python - 在张量流中训练模型时的时代问题
问题描述
所以我是 Tensorflow 2.0 的新手,我正在尝试训练一个简单的模型,它将摄氏温度转换为华氏温度。这是代码:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
c = np.array([-40, -10, 0, 8, 15, 22, 38], dtype = float)
f = np.array([-40, 14, 32, 46, 59, 72, 100], dtype = float)
lyr = tf.keras.layers.Dense(units = 1, input_shape = [1])
mod = tf.keras.Sequential([lyr])
mod.compile(loss = "mean_squared_error", optimzer = tf.keras.optimizers.Adam(0.1))
hist = mod.fit(c, f, epochs = 5000, verbose = False)
plt.xlabel("Epoch Number")
plt.ylabel("Loss Magnitude")
plt.plot(hist.history["loss"])
plt.show()
print(mod.predict([100.0]))
该模型应该只用 500 个 epoch 就可以产生一个精确的值,但至少需要 5000 个 epoch 才能得到一个准确的值。发生这种情况的原因可能是什么?
解决方案
您的代码在方法中有epochs=10000
一个参数。model.fit
请使用以下代码:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
c = np.array([-40, -10, 0, 8, 15, 22, 38], dtype = float)
f = np.array([-40, 14, 32, 46, 59, 72, 100], dtype = float)
lyr = tf.keras.layers.Dense(units = 1, input_shape = [1])
mod = tf.keras.Sequential([lyr])
mod.compile(loss = "mean_squared_error", optimzer = tf.keras.optimizers.Adam(0.1))
hist = mod.fit(c, f, epochs = 5000, verbose = False)
plt.xlabel("Epoch Number")
plt.ylabel("Loss Magnitude")
plt.plot(hist.history["loss"])
plt.show()
print(mod.predict([100.0]))
推荐阅读
- html - 如何使用存储在 Firestore 中的图像 url
- laravel - Laravel Spatie Query Builder:使用 Axios 使用 API 的正确方法
- c++ - 对构造函数语法的一点误解
- php - in_array() 期望参数 2 是数组,布尔值在行中给出
- dsl - Xtext 验证器 - 检查所有元素 X 以进行元素 Y 验证
- python - 根据索引位置替换列表组件
- android - AsyncTask 上未显示进度对话框
- opengl - Z 实际上应该是透视除法的什么值?
- html - 在 iOS 和 MacOS 上的 Safari 中,溢出属性工作异常
- git - 来自 gitlab 的新分支不会出现在 git bash 中