日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人工智能 > pytorch >内容正文

pytorch

深度学习-Tensorflow2.2-Eager模式与自定义训练{4}-微分运算训练练习-16

發布時間:2024/9/15 pytorch 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 深度学习-Tensorflow2.2-Eager模式与自定义训练{4}-微分运算训练练习-16 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Eager模式簡介

Tensorflow 發布了新的 TF 2.0 Beta 版本我們可以通過以下命令安裝:pip install tensorflow==2.0.0-beta1

TensorFlow的eager模式是一個命令式編程環境,它使得我們可以立即評估操作產生的結果,而無需構建計 算圖。

Eager模式極大的方便我們使用TensorFlow、調試模型,增加了網絡調試的靈活程度和tensorflow對于初學者友好性。

在這里我們可以叫它 tensorflow的交互模式。

與Tensorflow 1.x版本不同,tensorflow 2.0 默認使用 eager 模式。
執行tf.executing_eagerly() 返回 True

Eager模式提供了一個靈活的研究和實驗機器學習平臺,提供直觀的界面 - 自然地構建代碼并使用Python數據結構。快速迭代小型模型和小型數據。

更容易調試 -在交互式環境中直接檢查、運行模型、測試變化。這個過程中代碼會即時錯誤報告。

自然控制流 - eager模式下使用Python控制流而不是圖控制流,簡化了動態模型的創建。

Eager模式支持大多數TensorFlow操作和GPU加速。

eager模式下,TensorFlow操作會立即執行并將其值返回給Python。

tf.Tensor對象引用具體值而不是計算圖中節點的符號句柄。

Eager模式運行特點

由于在會話中沒有構建和運行的計算圖,因此使用print()語句或調試器很容易檢查結果、評估輸出,打印和檢查張量值,而不影響計算梯度的過程。

Eager模式下Tensorflow可與NumPy很好地協作。

TensorFlow 數學運算可將Python對象和NumPy數組轉換為tf.Tensor對象。

而 tf.Tensor.numpy方法將對象的值作NumPy返回ndarray。

Eager模式中梯度的計算

在Eager模式中,使用tf.GradientTape跟蹤計算梯度的操作

由于在每次執行可能發生不同的操作,所有前向傳遞操作都被記錄到Tape上。要計算漸變,就往后播放磁帶
然后丟棄。

特定的tf.GradientTape只能計算一個梯度; 后續調用會引發運行時錯誤。

也可以設置可重復調用

張量


自動微分


自定義訓練

import tensorflow as tf (train_image,train_labels),_=tf.keras.datasets.mnist.load_data() train_image.shape,train_labels

train_image = tf.expand_dims(train_image,-1)# 擴充維度 train_image.shape

# 改變數據類型 train_image = tf.cast(train_image/255,tf.float32) # 歸一化并改變數據類型 train_labels = tf.cast(train_labels,tf.int64) dataset = tf.data.Dataset.from_tensor_slices((train_image,train_labels)) # 建立數據集 dataset

dataset = dataset.shuffle(10000).batch(32) # 對數據進行洗牌 亂序 dataset

# 建立模型 model = tf.keras.Sequential([tf.keras.layers.Conv2D(16,[3,3],activation="relu",input_shape=(28,28,1)),tf.keras.layers.Conv2D(32,[3,3],activation="relu"),tf.keras.layers.GlobalAveragePooling2D(),tf.keras.layers.Dense(10) # 未激活 ]) # 自定義循環(編譯) optimizers = tf.keras.optimizers.Adam() # 優化函數 loss_func = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) # 損失函數 features,labels = next (iter(dataset)) features.shape,labels.shape

predictions = model(features) predictions.shape

tf.argmax(predictions,axis=1)

labels

def loss(model,x,y):y_ = model(x)return loos_func(y,y_) def train_step(model,images,labels):with tf.GradientTape() as t:loss_step = loss(model,images,labels)grads = t.gradient(loss_step,model.trainable_variables)optimizers.apply_gradients(zip(grads,model.trainable_variables)) def train():for epoch in range(10):for (batch,(images,labels)) in enumerate(dataset):train_step(model,images,labels)print("epoch{} is finshed".format(epoch)) train()



代碼如下:

import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 修改警告級別,不顯示警告(train_image,train_labels),_=tf.keras.datasets.mnist.load_data() print(train_image.shape,train_labels) train_image = tf.expand_dims(train_image,-1)# 擴充維度 print(train_image.shape) # 改變數據類型 train_image = tf.cast(train_image/255,tf.float32) # 歸一化并改變數據類型 train_labels = tf.cast(train_labels,tf.int64) dataset = tf.data.Dataset.from_tensor_slices((train_image,train_labels)) # 建立數據集 dataset = dataset.shuffle(10000).batch(32) # 對數據進行洗牌 print(dataset) # 建立模型 model = tf.keras.Sequential([tf.keras.layers.Conv2D(16,[3,3],activation="relu",input_shape=(28,28,1)),tf.keras.layers.Conv2D(32,[3,3],activation="relu"),tf.keras.layers.GlobalAveragePooling2D(),tf.keras.layers.Dense(10) # 未激活 ]) # 自定義循環(編譯) optimizers = tf.keras.optimizers.Adam() # 優化函數 loss_func = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) # 損失函數 features,labels = next (iter(dataset)) print(features.shape,labels.shape) predictions = model(features) print(predictions.shape) tf.argmax(predictions,axis=1) print(labels)def loss(model,x,y):y_ = model(x)return loss_func(y,y_)train_loss = tf.keras.metrics.Mean("train_loss") train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy("train_accuracy")def train_step(model,images,labels):with tf.GradientTape() as t:pred = model(images)loss_step = loss_func(labels,pred)grads = t.gradient(loss_step,model.trainable_variables)optimizers.apply_gradients(zip(grads,model.trainable_variables))train_loss(loss_step)train_accuracy(labels,pred) def train():for epoch in range(10):for (batch,(images,labels)) in enumerate(dataset):train_step(model,images,labels)print("epoch{} loss is {},acc is {}".format(epoch,train_loss.result(),train_accuracy.result()))train_loss.reset_states()# 重置狀態train_accuracy.reset_states()train()

總結

以上是生活随笔為你收集整理的深度学习-Tensorflow2.2-Eager模式与自定义训练{4}-微分运算训练练习-16的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。