我的模型在完成训练后出现了很高的错误。正确选择节点和层数是否非常关键,还是我需要选择更慢的学习率或更多的 epoch?我原以为为这个方程式训练模型不会有什么大不了的。
# f(x) = 0.22*x*x*x-0.6*x*x+0.4*x-0.5
import tensorflow as tf
import numpy as np
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
x = np.array([-5,-4.8,-4.6,-4.4,-4.2,-4,-3.8,-3.6,-3.4,-3.2,-3,-2.8,-2.6,-2.4,-2.2,-2,-1.8,-1.6,-1.4,-1.2,-1,-0.8,-0.6,-0.4,-0.2,0,0.2,0.4,0.6,0.8,1,1.2,1.4,1.6,1.8,2,2.2,2.4,2.6,2.8,3,3.2,3.4,3.6,3.8,4,4.2,4.4,4.6,4.8,5], dtype=float)
y = np.array([-45,-40.57424,-36.44992,-32.61648,-29.06336,-25.78,-22.75584,-19.98032,-17.44288,-15.13296,-13.04,-11.15344,-9.46272,-7.95728,-6.62656,-5.46,-4.44704,-3.57712,-2.83968,-2.22416,-1.72,-1.31664,-1.00352,-0.77008,-0.60576,-0.5,-0.44224,-0.42192,-0.42848,-0.45136,-0.48,-0.50384,-0.51232,-0.49488,-0.44096,-0.34,-0.18144,0.04528,0.350720000000001,0.745439999999999,1.24,1.84496,2.57088,3.42832,4.42784,5.58,6.89536,8.38448,10.05792,11.92624,14], dtype=float)
for i,c in enumerate(x):
print("x = {}, y = {}".format(x[i], y[i]))
l0 = tf.keras.layers.Dense(units=4, input_shape=[1])
l1 = tf.keras.layers.Dense(units=10)
l2 = tf.keras.layers.Dense(units=1)
model = tf.keras.Sequential([l0, l1, l2])
model.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.1))
history = model.fit(x, y, epochs=50000, verbose=False)
print("Finished training the model")
import matplotlib.pyplot as plt
plt.xlabel('Epoch Number')
plt.ylabel("Loss Magnitude")
plt.plot(history.history['loss'])
扬帆大鱼
相关分类