我似乎无法让 tensorflow 构建一个与最简单的线性图相匹配的模型。 下面是代码和实际与模型结果。 我究竟做错了什么?
import numpy as np
import matplotlib.pyplot as plt
import keras
x = np.array([[1965.0], [1980.0]])
y = np.array([[320.0], [345.0]])
plt.plot(x, y)
model = keras.Sequential([keras.layers.Dense(1, activation='linear')])
model.compile(optimizer='adam',
loss="mean_squared_error")
model.fit(x=x, y=y, epochs=10000)
yHat = model.predict(x)
print("yHat ", yHat)
plt.plot(x, yHat)
plt.show()
请您参考如下方法:
您走在正确的轨道上,只是在规范化数据和构建模型时遗漏了一些关键点。
只有 2 个数据点被输入您的神经网络。使用
np.arange()来创建更大的数组。神经网络喜欢 0 到 1 之间的数据点(有助于学习收敛)。因此,让我们使用 sklearn.MinMaxScaler 转换 x 和 y 数组:
(这会将每个变量根据其值转换为 0 和 1 之间的数组的最小值和最大值)
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
x = scaler.fit_transform(np.arange(1965, 1990).reshape(-1,1))
y = scaler.fit_transform(np.arange(320, 345).reshape(-1,1))
(注意:我们正在 reshape x,y 以适应 (1,0) numpy 数组)
- 然后我们可以使用 1 个线性 Dense 层构建模型:
epochs = 20
model = keras.Sequential()
model.add(Dense( units=1, input_dim=1, activation="linear" ))
## Establishing optimizer so that we can modify the learning rate >= 1
sgd = keras.optimizers.SGD(lr=0.1, momentum=0.0, decay=0.0, nesterov=False)
model.compile( optimizer=sgd, loss="mean_squared_error" )
model.fit( x, y, batch_size=1, epochs=epochs)
- 最后我们可以绘制预测和实际 Y 变量:
predicted = model.predict(x)
predicted = predicted + .01 ## offset prediction so the two lines don't overlap
plt.plot(scaler.inverse_transform(y), label='actual_y')
plt.plot(scaler.inverse_transform(predicted), label='predicted_y')
plt.legend(loc='upper left')
plt.show()
(注意:我们正在反转 sklearn.tranform 以显示实际数据而不是缩放版本)
最终代码:
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.layers.core import Dense
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
epochs = 20
## Using np.arange() instead of np.array()
## Transforming x,y so that the model can understand the variables
x = scaler.fit_transform(np.arange(1965, 1990).reshape(-1,1))
y = scaler.fit_transform(np.arange(320, 345).reshape(-1,1))
model = keras.Sequential()
model.add(Dense( units=1, input_dim=1, activation="linear" ))
## Establishing optimizer so that we can modify the learning rate >= 1
sgd = keras.optimizers.SGD(lr=0.1, momentum=0.0, decay=0.0, nesterov=False)
model.compile( optimizer=sgd, loss="mean_squared_error" )
model.fit( x, y, batch_size=1, epochs=epochs)
predicted = model.predict(x)
predicted = predicted + .01 ## offset prediction so the two lines don't overlap
plt.plot(scaler.inverse_transform(y), label='actual_y')
plt.plot(scaler.inverse_transform(predicted), label='predicted_y')
plt.legend(loc='upper left')
plt.show()
