Tensorflow学习Demo-C/F温度转换

2019-03-19  本文已影响0人  P_Zhi

此案例为Udacity的Tensorflow课程案例,摄氏度与华氏度转换模型。
Source:
https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_for_deep_learning/l02c01_celsius_to_fahrenheit.ipynb#scrollTo=_F00_J9duLBD

1. 导入依赖

import tensorflow as tf
import numpy as np

2. 设置训练数据

celsius_q    = np.array([-40, -10,  0,  8, 15, 22,  38],  dtype=float)
fahrenheit_a = np.array([-40,  14, 32, 46, 59, 72, 100],  dtype=float)

for i,c in enumerate(celsius_q):
  print("{} degrees Celsius = {} degrees Fahrenheit".format(c, fahrenheit_a[i]))

3. 创建模型

(1)构建层
l0 = tf.keras.layers.Dense(units=1, input_shape=[1]) 
(2)将层导入到模型中
model = tf.keras.Sequential([l0])

3. 编译模型

model.compile(loss='mean_squared_error',
          optimizer=tf.keras.optimizers.Adam(0.1))

4. 训练模型

history = model.fit(celsius_q, fahrenheit_a, epochs=500, verbose=False)
print("Finished training the model")

5. 图像化显示

import matplotlib.pyplot as plt
plt.xlabel('Epoch Number')
plt.ylabel("Loss Magnitude")
plt.plot(history.history['loss'])

6. 通过模型预测结果

print(model.predict([100.0]))

7. 查看层的权重

print("These are the layer variables: {}".format(l0.get_weights()))

8. 相关术语

上一篇 下一篇

猜你喜欢

热点阅读