- 首页 > 人文 > >
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())
推荐阅读
-
大嘴猴医生■汉人不叫“汉人”,有一个更厉害的称呼,延续两千年,汉朝之前
-
央视新闻客户端|江苏今晨发布大雾橙色预警 多条高速路一度封闭
-
「扎心」男人有车和没车有多大差距?看完对比后,网友:很扎心!
-
-
「我国」我国“最小”的省会,面积不如小县城,却被评世界新一
-
-
新学年将开始,香港政务司司长张建宗:须帮助学生培养国民身份认同及守法意识
-
影视剧中的人(尤其是女人)看见尸体会狂叫不止,现实中人看到尸体真的会那么恐惧吗
-
杨幂|鹅厂又一爱情剧未播先火,顶流女星搭档当红小生,网友:王炸预定
-
-
卡哇伊|哪几个生肖横财运旺盛,一生富贵双全,财运接连不断!,6月17~7月31
-
-
-
刘老二侃车|车宽1米9、车舱像奔驰,知名度拖了后腿?,宝马引擎踩一脚200匹
-
-
比亚迪|特斯拉Model 3国产强敌 比亚迪海豹预告:豪华、运动
-
-
向海而筑:佳兆业金沙湾滨海公园生态建筑国际设计竞赛启动|深晚报道| a8179
-
英国那些事儿|外网年轻人流行用指甲锉磨牙“正畸”,把正经牙医都急坏了!
-