TensorFlow 示例摄氏度到华氏度的转换(一)

TensorFlow 实现神经网络模型来进行摄氏度到华氏度的转换,可以将其作为一个回归问题来处理。我们可以通过神经网络来拟合这个简单的转换公式。

[1. 数据准备与预处理](#1. 数据准备与预处理)

[2. 构建模型](#2. 构建模型)

[3. 编译模型](#3. 编译模型)

[4. 训练模型](#4. 训练模型)

[5. 评估模型](#5. 评估模型)

[6. 模型应用与预测](#6. 模型应用与预测)

[7. 保存与加载模型](#7. 保存与加载模型)

[8. 完整代码](#8. 完整代码)


1. 数据准备与预处理

你提供了摄氏度和华氏度的数据,并进行了标准化。标准化是为了使数据适应神经网络的训练,因为标准化可以加快训练过程并提高模型性能。

复制代码
import numpy as np
import tensorflow as tf

# 温度数据:摄氏度到华氏度的转换
celsius = np.array([-50,-40, -10, 0, 8, 22, 35, 45, 55, 65, 75, 95], dtype=float)
fahrenheit = np.array([-58.0,-40.0,14.0,32.0,46.4,71.6,95.0,113.0,131.0,149.0,167.0,203.0], dtype=float)

# 数据标准化:计算均值和标准差
celsius_mean = np.mean(celsius)
celsius_std = np.std(celsius)

fahrenheit_mean = np.mean(fahrenheit)
fahrenheit_std = np.std(fahrenheit)

# 标准化输入和输出数据
celsius_normalized = (celsius - celsius_mean) / celsius_std
fahrenheit_normalized = (fahrenheit - fahrenheit_mean) / fahrenheit_std

2. 构建模型

在构建模型时,使用了一个简单的神经网络结构。神经网络包含了一个隐藏层和一个输出层。隐藏层使用了ReLU激活函数,输出层使用了线性激活函数,适合回归任务。

复制代码
# 创建模型
model = tf.keras.Sequential([
    # 隐藏层,增加神经元数量,激活函数使用 ReLU
    tf.keras.layers.Dense(16, input_dim=1, activation='relu'),
    # 输出层,线性激活函数用于回归任务
    tf.keras.layers.Dense(1, activation='linear')
])

3. 编译模型

选择了Adam优化器,它在处理回归任务时表现较好,损失函数使用均方误差(MSE),这是回归问题中常用的损失函数。

复制代码
# 编译模型,使用 Adam 优化器和均方误差损失函数
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='mean_squared_error')

4. 训练模型

模型通过 fit() 方法进行训练,设置训练轮数(epochs)为5000轮。根据数据的复杂性和模型的表现,增加训练轮数可以帮助模型更好地收敛。

复制代码
# 训练模型,设置训练轮数(epochs)增加到5000
model.fit(celsius_normalized, fahrenheit_normalized, epochs=5000)

5. 评估模型

训练完成后,你可以对模型进行评估。这里使用了一个测试集(test_celsius),并通过预测得到标准化的结果,然后将其恢复为原始的华氏度值。

复制代码
# 测试模型
test_celsius = np.array([0, 20, 100], dtype=float)
test_celsius_normalized = (test_celsius - celsius_mean) / celsius_std
predictions_normalized = model.predict(test_celsius_normalized)

# 将预测结果从标准化值恢复到原始华氏度范围
predictions = predictions_normalized * fahrenheit_std + fahrenheit_mean

6. 模型应用与预测

最后,你可以输出预测的华氏度值。模型会对每个输入的摄氏度值返回预测的华氏度

复制代码
# 输出预测结果
print("预测华氏度:")
for c, f in zip(test_celsius, predictions):
    print(f"{c} 摄氏度 => {f[0]} 华氏度")

7. 保存与加载模型

保存模型可以让你在之后加载并进行预测而不需要重新训练。在TensorFlow中,你可以使用 model.save() 来保存模型,使用 tf.keras.models.load_model() 来加载模型。

复制代码
# 保存模型
model.save('temperature_conversion_model.h5')

# 加载模型
loaded_model = tf.keras.models.load_model('temperature_conversion_model.h5')

8. 完整代码

最终的完整代码如下:

复制代码
import numpy as np
import tensorflow as tf

# 温度数据:摄氏度到华氏度的转换
celsius = np.array([-50,-40, -10, 0, 8, 22, 35, 45, 55, 65, 75, 95], dtype=float)
fahrenheit = np.array([-58.0,-40.0,14.0,32.0,46.4,71.6,95.0,113.0,131.0,149.0,167.0,203.0], dtype=float)

# 数据标准化:计算均值和标准差
celsius_mean = np.mean(celsius)
celsius_std = np.std(celsius)

fahrenheit_mean = np.mean(fahrenheit)
fahrenheit_std = np.std(fahrenheit)

# 标准化输入和输出数据
celsius_normalized = (celsius - celsius_mean) / celsius_std
fahrenheit_normalized = (fahrenheit - fahrenheit_mean) / fahrenheit_std

# 创建模型
model = tf.keras.Sequential([
    # 隐藏层,增加神经元数量,激活函数使用 ReLU
    tf.keras.layers.Dense(16, input_dim=1, activation='relu'),
    # 输出层,线性激活函数用于回归任务
    tf.keras.layers.Dense(1, activation='linear')
])

# 编译模型,使用 Adam 优化器和均方误差损失函数
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), loss='mean_squared_error')

# 训练模型,设置训练轮数(epochs)增加到5000
model.fit(celsius_normalized, fahrenheit_normalized, epochs=5000)

# 测试模型
test_celsius = np.array([0, 20, 100], dtype=float)
test_celsius_normalized = (test_celsius - celsius_mean) / celsius_std
predictions_normalized = model.predict(test_celsius_normalized)

# 将预测结果从标准化值恢复到原始华氏度范围
predictions = predictions_normalized * fahrenheit_std + fahrenheit_mean

# 输出预测结果
print("预测华氏度:")
for c, f in zip(test_celsius, predictions):
    print(f"{c} 摄氏度 => {f[0]} 华氏度")

# 保存模型
model.save('temperature_conversion_model.h5')

# 加载模型
loaded_model = tf.keras.models.load_model('temperature_conversion_model.h5')
相关推荐
deepdata_cn几秒前
从弱AI到强AI:符号推理是实现通用人工智能AGI的关键钥匙
人工智能·agi·符号推理
richard_first1 分钟前
第5章 Attention 的思想
人工智能·深度学习·transformer
AI英德西牛仔1 分钟前
秘塔 导出word指令之外:AI导出鸭电脑版的底层逻辑与批量交付哲学
人工智能·word·excel·deepseek·ai导出鸭
老白说数智化升级6 分钟前
AI与人工如何并行,Operation Agent Brain如何让制造运营持续优化?
人工智能·制造
小小测试开发6 分钟前
AI 安全测试:腾讯开源 A.I.G 平台拆解——2000+ CVE 规则与 LLM 审计的双引擎协作
人工智能·开源
guwentian13 分钟前
从0到1手写 AI Agent Harness:为什么护城河不在模型,而在工程外壳
人工智能·python·安全·deepseek·harness
独隅14 分钟前
从 Copilot 到 Agent:AI 驱动下的开发工作流重构实战
人工智能·重构·copilot
Summer-Bright14 分钟前
独立 AI 浏览器之死与「内嵌化」之生:Atlas 关停、Comet 免费化、豆包虚拟桌面,入口之争的终局
人工智能·ai·ai 浏览器
FYKJ_201016 分钟前
django学习成绩预警系统10905
java·javascript·spring boot·python·spark·django·php
淳悦qiqi16 分钟前
2026依托技术优势高准确率语音识别软件多场景让信息整理更省事更清晰
人工智能·语音识别