我似乎无法获得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()
答案 0 :(得分:1)
您处在正确的轨道上,只是在规范化数据和构建模型时缺少一些关键点。
只有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))
(注意:我们正在重塑x,y以适合(1,0)numpy数组)
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)
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以显示实际数据,而不是Scaled版本)
所有最终代码:
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()