- 首页 > 人文 > >
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())
推荐阅读
-
-
-
封神榜 接引道人,接引道人和准提道人,封神之后都成了谁--
-
-
-
Intel|游戏性能回来了 11代酷睿喜加一:《杀手3》免费送
-
『5g手机』小米又大跳水,5G双模+128GB+120Hz刷新率,上架半个月直降400元
-
安卓|消息称iPhone15全系将采用叹号屏 你会买单?苹果全面屏手机/平板加速到来
-
数控|这两只精选层股票股价接近翻番:汇添富、嘉实、金长川等10家战投赚了
-
雨沐网络孟琬|之前你买过吗,《绝地求生》再无千元以上服饰,
-
医务工作者小贾|指甲上有竖纹,是生病了吗?听听医生怎么说
-
周到|比利时国宴冰淇淋在这未展先销,打造“永不落幕的进博会”,这一主阵地今年还有大变化
-
爱龙爱炫车|突然全身瘫痪,靠轮椅生活,马上要成为湖南台“一姐”
-
最新!紧凑型车“油耗”榜单更新,冠军不足5L,轩逸比朗逸省油
-
大众报业·海报新闻|财鑫闻丨首批200亿科创50ETF本周袭来!科创板50指数值得投吗?
-
香酥|1碗面粉加2个鸡蛋,教你做香酥小饼干,酥香脆爽,比面包还好吃
-
公司|[公司]ST八菱:股票交易异常波动 无未披露重要事项
-
擦肩而过 “擦肩而过”的TCL与华为,终会“相遇”
-
感言|沈梦辰发布视频版淘汰感言:最对不住“大碗宽面”组的伙伴
-
上单|上单霸主老夫子,进阶攻略,进可攻,退可守,上分如喝水