github代码地址:https://github.com/taichuai/d2l_zh_tensorflow2.0
tf2.0线性回归简单实现,前面数据都是和上一篇一样,就不一一解释了
主要内容总结:
1、创建模型:tf.kears.Sequential(), tf.keras.layer直接创建, 并且可以使用 tensorflow.initializers 进行参数初始化
2、损失函数:tf.losses.MSE(x, y) 等各种,直接进行矩阵计算,得到平均损失,等价于:tf.reduce_mean(tf.square(predicted_y - tf.reshape(desired_y, predicted_y.shape)))
3、优化算法(优化器): tf.keras.optimizers.SGD(learning_rate=0.01)直接定义优化算法
4、训练模型: tape.gradient(l, model.trainable_variables) 记录动态图梯度, trainer.apply_gradients(zip(grads, model.trainable_variables)) 进行梯度自动更新
5、查看参数: model.trainable_variables 查看模型参数
1、创建模型
2、损失函数:tf.losses.MSE(x, y) 等各种,直接进行矩阵计算,得到平均损失,等价于:tf.reduce_mean(tf.square(predicted_y - tf.reshape(desired_y, predicted_y.shape)))
3、优化算法(优化器): tf.keras.optimizers.SGD(learning_rate=0.01)直接定义优化算法
4、训练模型: tape.gradient(l, model.trainable_variables) 记录动态图梯度, trainer.apply_gradients(zip(grads, model.trainable_variables)) 进行梯度自动更新
5、查看参数: model.trainable_variables 查看模型参数
import tensorflow as tf
print(tf.__version__)
from tensorflow.python.client import device_lib
import os
os.environ['CUDA_VISIBLE_DEVICES'] = "0, 1"
gpus = tf.config.experimental.list_physical_devices(device_type='GPU')
cpus = tf.config.experimental.list_physical_devices(device_type='CPU')
print(gpus, cpus)
# 设置当前程序的可见设备范围
tf.config.experimental.set_visible_devices(devices=gpus, device_type='GPU')
# 设置仅在需要时申请:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
# 下面的方式是设置Tensorflow固定消耗GPU:0的2GB显存
tf.config.experimental.set_virtual_device_configuration(
gpus[0],
[tf.config.experimental.VirtualDeviceConfiguration(memory_limit=200)]
)
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
print(get_available_gpus())
with tf.device('/device:GPU:0'):
w = tf.constant([[2, -3.4]])
b = tf.constant([4.2])
x = tf.random.normal([1000, 2], mean=0, stddev=10)
e = tf.random.normal([1000, 2], mean=0, stddev=0.1)
W = tf.Variable(tf.constant([5, 1]))
B = tf.Variable(tf.constant([1]))
w
import random
from matplotlib import pyplot as plt
# 线性回归模型, y =
# 生成数据,生成1000组数据
num_inputs = 2
num_examples = 1000
true_y = tf.matmul(x, tf.transpose(w)) b
x, true_y
# 读取数据
def set_figsize(figsize=(3.5, 2.5)):
plt.rcParams['figure.figsize'] = figsize
set_figsize()
plt.scatter(x[: ,1], true_y, 1)
def data_scale(x, y):
return x, y
db = tf.data.Dataset.from_tensor_slices((x, true_y))
db_all = db.map(data_scale)
# 为了每个epchoes都打散,可以把下面 db 放到每轮内部去shuffle和batch
# db = db_all.shuffle(10)
# db_batch = db.batch(32)
# 查看一组数据
# print(next(iter(db_batch)))
# 构建模型(此处就不需要自己定义变量在进行矩阵计算了,直接调用包就好了)
# 导入模块
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow import initializers as init
# 使用Sequential模式创建
model = keras.Sequential()
model.add(layers.Dense(1, kernel_initializer=init.RandomNormal(stddev=0.01)))
# 定义损失函数
from tensorflow import losses
#均方损失
loss = losses.MeanSquaredError()
# 定义优化算法
from tensorflow.keras import optimizers
trainer = optimizers.SGD(learning_rate=0.001)
在使用Tensorflow训练模型时,我们通过调用tensorflow.GradientTape记录动态图梯度,执行tape.gradient获得动态图中各变量梯度。通过 model.trainable_variables 找到需要更新的变量,并用 trainer.apply_gradients 更新权重,完成一步训练。
# 训练模型
num_epoches = 3
for epoch in range(num_epoches):
batch_data = db_all.shuffle(10)
batch_data = batch_data.batch(32)
for n, (train_x, train_y) in enumerate(batch_data):
# print(x, y)
print('x.shape', x.shape)
with tf.GradientTape() as tape:
l = loss(model(train_x), train_y)
# 自动记录可训练变量
grads = tape.gradient(l, model.trainable_variables)
# 完成梯度更新
trainer.apply_gradients(zip(grads, model.trainable_variables))
# model.trainable_variables查看模型参数
print(n , '\n', model.trainable_variables[0])
# 通过 model.get_weights()[0]查看相关权重
print(model.get_weights())
# 每轮求一次全部的平均损失
l = loss(model(x), true_y)
print('\n epoch %d , loss: %f' % (epoch, l.numpy()))