深度學習筆記(11):初識TensorFlow 2.0
2 min readApr 5, 2020
本文將帶您透過tf.keras完成第一個TensorFlow 2.0的深度學習程式。
我們將建立一個線性回歸的方程式,將輸入的華式溫度,透過深度學習,算出攝氏溫度值。
值得一提的是,我們並沒有告訴電腦說華式和攝氏溫度的轉換公式,完全是透過我們的Input Data學習而來的。
引入模組
import tensorflow as tf
import numpy as np
建立訓練資料
華氏溫度與攝氏溫度,資料型態為float浮點數
fahrenheit_a = np.array([-40, 14, 32, 46, 59, 72, 100], dtype=float)celsius_q = np.array([-40, -10, 0, 8, 15, 22, 38], dtype=float)
建立模型
#定義Layer;units為神經層數目;input_shape為資料尺度
l0 = tf.keras.layers.Dense(units=1, input_shape=[1])
model = tf.keras.Sequential([l0]) #將Layer放入Model中
編譯模型
model.compile(loss='mean_squared_error',
optimizer=tf.keras.optimizers.Adam(0.01))#loss function用MSE;Optimizer用Adam,Learning是0.01
訓練模型
history = model.fit(fahrenheit_a, celsius_q, epochs=2000, verbose=True)
print("Finished training the model")# epochs代表本次訓練要執行幾個Cycle;verbose代表是否顯示訓練Output
視覺化訓練過程
import matplotlib.pyplot as plt
plt.xlabel('Epoch Number')
plt.ylabel("Loss Magnitude")
plt.plot(history.history['loss'])
進行預測
print(model.predict([212])) #預測212˚F時,攝氏會是幾度(Answer:100˚C)