tensorflow2.0教程与操作示例( 二 )

示例代码import tensorflow as tfprint(tf.__version__)# 设定cpu或者gputf.debugging.set_log_device_placement (True)cpus = tf.config.list_physical_devices(device_type='CPU')print('cpus',cpus)tf.config.set_visible_devices (cpus)A = tf.constant([[1,2],[3,4]])print('A',A,type(A),A.numpy(),dir(A))B = tf.constant([[5,6],[7,8]])C = tf.matmul(A,B)print(C,type(C),C.shape,vars(C))# 临时指定cpu或者gpuwith tf.device('/cpu:0'):A = tf.constant([[1,2],[3,4]])B = tf.constant([[5,6],[7,8]])C = tf.matmul(A,B)print(C,type(C),C.shape,C.device)# 张量,标量随机数random_float = tf.random.uniform(shape=())print('random_float',random_float)# 定义一个有2个元素的零向量zero_vector = tf.zeros(shape=(2))print('zero_vector',zero_vector)# 自动求导机制x = tf.Variable(initial_value=http://kandian.youth.cn/index/3.)with tf.GradientTape() as tape:y = tf.square(x)y_grad = tape.gradient(y,x)print('y_grad',y_grad)print('tape',tape,type(tape))X = tf.constant([[1.,2.],[3.,4.]])y = tf.constant([[1.],[2.]])w = tf.Variable(initial_value=http://kandian.youth.cn/index/[[1.],[2.]])b = tf.Variable(initial_value=1.)with tf.GradientTape() as tape:L = tf.reduce_sum(tf.square(tf.matmul(X, w) + b - y))w_grad,b_grad = tape.gradient(L,[w,b])print(w_grad,b_grad)tensorflow2线性模型步骤
  • 使用 tf.keras.datasets 获得数据集并预处理
  • 使用 tf.keras.Model 和 tf.keras.layers 构建模型
  • 构建模型训练流程 , 使用 tf.keras.losses 计算损失函数 , 并使用 tf.keras.optimizer 优化模型
  • 构建模型评估流程 , 使用 tf.keras.metrics 计算评估指标
源代码# Dataimport numpy as npimport tensorflow as tf# dataX_raw = np.array([2013, 2014, 2015, 2016, 2017], dtype=np.float32)y_raw = np.array([12000, 14000, 15000, 16500, 17500], dtype=np.float32)# 归一化X = (X_raw - X_raw.min()) / (X_raw.max() - X_raw.min())y = (y_raw - y_raw.min()) / (y_raw.max() - y_raw.min())X = tf.constant(X)y = tf.constant(y)a = tf.Variable(initial_value=http://kandian.youth.cn/index/0.)b = tf.Variable(initial_value=0.)variables = [a, b]num_epoch = 10000optimizer = tf.keras.optimizers.SGD(learning_rate=5e-4)for e in range(num_epoch):# 使用tf.GradientTape()记录损失函数的梯度信息with tf.GradientTape() as tape:y_pred = a * X + bloss = tf.reduce_sum(tf.square(y_pred - y))# TensorFlow自动计算损失函数关于自变量(模型参数)的梯度grads = tape.gradient(loss, variables)# TensorFlow自动根据梯度更新参数optimizer.apply_gradients(grads_and_vars=zip(grads, variables))print(a, b)# 方法2 kerasX = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])y = tf.constant([[10.0], [20.0]])class Linear(tf.keras.Model):def __init__(self,):super().__init__()self.dense = tf.keras.layers.Dense(units=1,use_bias=True,activation=tf.nn.relu,kernel_regularizer=tf.zeros_initializer(),bias_regularizer=tf.zeros_initializer)def call(self,input):output = self.dense(input)return outputmodel = Linear()optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)for i in range(100):with tf.GradientTape() as tape:y_pred = model(X)loss = tf.reduce_mean(tf.square(y_pred-y))grads = tape.gradient(loss,model.variables)optimizer.apply_gradients(grads_and_vars=zip(grads,model.variables))print(model.variables)# 模型的评估sparse_categorical_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()num_batches = int(data_loader.num_test_data // batch_size)for batch_index in range(num_batches):start_index, end_index = batch_index * batch_size, (batch_index + 1) * batch_sizey_pred = model.predict(data_loader.test_data[start_index: end_index])sparse_categorical_accuracy.update_state(y_true=data_loader.test_label[start_index: end_index], y_pred=y_pred)print("test accuracy: %f" % sparse_categorical_accuracy.result())


推荐阅读