- 首页 > 人文 > >
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岁男孩挑食被母亲呵斥
-
【iPhone】面对疫情,苹果公布新政策,除中国市场,果粉可享140元补贴
-
「微信」微信“新规定”确认,两大功能不再免费,网友:逼我放弃?
-
华为mate▲华为P50Pro概念图:这就是四曲真全屏,比华为Mate40更值得期待
-
海外网|旅美大熊猫美香幼崽体重曝光 性别将在数周后公布
-
硬拳大卫君|印度官员依旧云淡风轻,国际权威雷霆发声,灾难性局面已经酿成
-
河南省|刚喝完“秋天的第一杯奶茶”,第一家同名公司就成立了?
-
中国足球|李霄鹏:蒿俊闵伤情比较严重,或缺席鲁能此后比赛
-
PAPI最时尚|你喜欢的品牌在什么位置呢,腕表王国官位表
-
爱疯电子峰哥苹果史上最耐用的手机,虽降价幅度大,但市场份额不降反增
-
三体|真实感扑面而来,炸裂震撼!《流浪地球2》绝不辜负你我的期待
-
-
-
营收|中国纸巾“第一品牌”,年营收225亿,维达和洁柔都不是对手
-
花朵|3种花人见人爱,植株低矮小巧,花开一整年,超级好养
-
水镜晓先生|俄3万吨潜艇启动测试,可引发超级海啸吞没城市,威力远超核导弹
-
「搞笑男人心」加入双电侧滑门,1.5T+7DCT,7.98万起,别克GL8碰到对手
-
张艺谋|《满江红》中五个谋女郎均没有以往的惊艳感,张艺谋看走眼了?
-
-