我之前仅使用床位数量进行了预测(运行正常),现在,我想通过添加第二个输入(平方英尺)来改进房价预测。
我添加了如下代码:
import tensorflow as tfimport numpy as npfrom tensorflow import kerasmodel = keras.Sequential([keras.layers.Dense(units=1, input_shape=[2])])xs = np.stack([[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [100, 150, 200, 250, 300, 350]], axis=1)ys = np.array([100000, 150000, 200000, 250000, 300000, 350000], dtype=float)model.fit(xs, ys, epochs=100)print(model.predict([[7.0], [400.0]])) # [7.0] number of beds / [400] square feet
但我收到了以下错误:
ValueError: Input 0 of layer sequential_57 is incompatible with the layer: expected axis -1 of input shape to have value 2 but received input with shape [None, 1]
请支持我修复这个问题并使其正常工作。
此致,
回答:
我对你的代码做了以下更改:
- 在训练模型之前,你需要编译模型(请看我下面的代码中的
model.compile('adam', 'mae')
) - 你想要预测的输入数组维度错误。它的维度是
(2,1)
,我将其改为(1,2)
。
如果我更改了这两点,代码对我来说是可以工作的。
model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[2])])xs = np.stack([[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], [100, 150, 200, 250, 300, 350]], axis=1)ys = np.array([100000, 150000, 200000, 250000, 300000, 350000], dtype = float)model.compile('adam', 'mae')model.fit(xs, ys, epochs=100)print(model.predict(np.array([[7.0, 400.0]]))) # [7.0] number of beds / [400] square feet #