- 首页 > 人文 > >
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())
推荐阅读
-
翰林的小院子扔地里老死也没人要,难以相信,比红薯还强的抗癌野菜
-
央视新闻|秘鲁报告2例白喉死亡病例 政府发布国家级流行病警报
-
-
上王者撩雨泽|爆料:张飞新皮肤虎魄局内特效首次曝光!上架时间确定
-
洪欣|港媒曝洪欣已带儿子改姓,改为洪镐濂,网友呼吁洪镐濂保护好妈妈
-
深圳赛格大厦疑再发晃动 值班人员:专家正24小时实时监测
-
底线|看了《底线》40集大结局,我平复下复杂的心情,写下这篇文章
-
阿星说汽车|仅7万起日产感到危机重重,日产这次真怕了!轩逸看了心服口服
-
时尚氢气|少穿裤装多穿这款“裙子”,优雅知性还很吸睛,奔三奔四的女人
-
一个有颈椎病的大三学生,还能深入程序员的道路吗,很迷茫,求指点
-
-
好六网|先爆军神后出残香,提升4千亿,DNF:黑旭剑影双喜临门
-
ZAKER|乐歌股份遭两机构砸盘暴跌16%,董事长怒怼平安资管后
-
-
青年|一个54岁女人的自白当父母不在了,亲兄弟姐妹从此成了陌路人
-
-
被判刑|半年内3次被卖,4名罪犯被判刑,智障人士的人生活该不幸?
-
-
#牲口#消失农村老物件,你还记得多少,里面一定有几件让你泪目
-
中国乡村之声|却3人溺亡……这些“隐形杀手”,必须警惕,俩家长救孩子