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

此案例为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. 相关术语

  • 特征:模型的输入
  • 样本:用于训练流程的输入/输出对
  • 标签:模型的输出
  • 层级:神经网络中相互连接的节点集合。
  • 模型:神经网络的表示法
  • 密集全连接层 (FC):一个层级中的每个节点都与上个层级中的每个节点相连。
  • 权重和偏差:模型的内部变量
  • 损失:期望输出和真实输出之间的差值
  • MSE:均方误差,一种损失函数,它会将一小部分很大的差值视作比大量很小的差值更糟糕。
  • 梯度下降法:每次小幅调整内部变量,从而逐渐降低损失函数的算法。
  • 优化器:梯度下降法的一种具体实现方法。(有很多算法。在这门课程中,我们将仅使用“Adam”优化器,它是 ADAptive with Momentum 的简称,并且被视为最佳优化器。)
  • 学习速率:梯度下降过程中的损失改进“步长”。
  • 批次:在训练神经网络的过程中使用的一组样本。
  • 周期:完全经过整个训练数据集一轮
  • 前向传播:根据输入计算输出值
  • 反向传播:根据优化器算法计算内部变量的调整幅度,从输出层级开始,并往回计算每个层级,直到抵达输入层。
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容