在tensorflow 2.0里面如何实现老师在2.6小节里给x,y,w的赋值呢?
来源:2-6 数据处理与模型图构建(2)
幕布斯3050947
2019-11-19
写回答
1回答
-
正十七
2020-02-16
同学你好,抱歉回复的晚了。在tensorflow中就没有placeholder和sess的概念了,取而代之的是更加python化的使用方式,即直接将模型当做一个函数来使用,把数据输入给封装好的模型就可以了。
下面是一个例子,感兴趣的话可以关注我的另一门课:《tensorflow2.0》https://coding.imooc.com/class/344.html
import matplotlib as mpl import matplotlib.pyplot as plt %matplotlib inline import numpy as np import sklearn import pandas as pd import os import sys import time import tensorflow as tf from tensorflow import keras print(tf.__version__) print(sys.version_info) for module in mpl, np, pd, sklearn, tf, keras: print(module.__name__, module.__version__) from sklearn.datasets import fetch_california_housing housing = fetch_california_housing() print(housing.DESCR) print(housing.data.shape) print(housing.target.shape) from sklearn.model_selection import train_test_split x_train_all, x_test, y_train_all, y_test = train_test_split( housing.data, housing.target, random_state = 7) x_train, x_valid, y_train, y_valid = train_test_split( x_train_all, y_train_all, random_state = 11) from sklearn.preprocessing import StandardScaler scaler = StandardScaler() x_train_scaled = scaler.fit_transform(x_train) x_valid_scaled = scaler.transform(x_valid) x_test_scaled = scaler.transform(x_test) # 1. batch 遍历训练集 metric # 1.1 自动求导 # 2. epoch结束 验证集 metric epochs = 100 batch_size = 32 steps_per_epoch = len(x_train_scaled) // batch_size optimizer = keras.optimizers.SGD() metric = keras.metrics.MeanSquaredError() def random_batch(x, y, batch_size=32): idx = np.random.randint(0, len(x), size=batch_size) return x[idx], y[idx] model = keras.models.Sequential([ keras.layers.Dense(30, activation='relu', input_shape=x_train.shape[1:]), keras.layers.Dense(1), ]) for epoch in range(epochs): metric.reset_states() for step in range(steps_per_epoch): x_batch, y_batch = random_batch(x_train_scaled, y_train, batch_size) with tf.GradientTape() as tape: y_pred = model(x_batch) y_pred = tf.squeeze(y_pred, 1) loss = keras.losses.mean_squared_error(y_batch, y_pred) metric(y_batch, y_pred) grads = tape.gradient(loss, model.variables) grads_and_vars = zip(grads, model.variables) optimizer.apply_gradients(grads_and_vars) print("\rEpoch", epoch, " train mse:", metric.result().numpy(), end="") y_valid_pred = model(x_valid_scaled) y_valid_pred = tf.squeeze(y_valid_pred, 1) valid_loss = keras.losses.mean_squared_error(y_valid_pred, y_valid) print("\t", "valid mse: ", valid_loss.numpy())
00
相似问题
X与W内积相加,为啥不把1也算上?
回答 2
关于tensorflow的配置问题
回答 1