按照《程序员的AI书》中的示例,照猫画虎,可运行出错。问题出在model.fit,说是参数类型不对。示例中输入的是两个列表:
x_array = [1, 2, 3, 10, 2000, -2, -10, -100, -5,-20]
y= [1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0]
检查了一下,应该是软件的版本不一致造成的,目前的版本model.fit可以接收numpy.ndarray类型。
将上面的代码修为:
x_array = np.array( [1, 2, 3, 10, 2000, -2, -10, -100, -5,-20])
y= np.array([1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0])
程序可以通过了。
完整的代码如下:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np
model = Sequential()
model.add(Dense(units=8,activation='relu',input_dim=1))
model.add(Dense(units=1,activation='sigmoid'))
model.compile(loss='mean_squared_error',optimizer='sgd')
x_array = np.array( [1, 2, 3, 10, 2000, -2, -10, -100, -5,-20])
y= np.array([1.0,1.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0])
model.fit(x_array,y,epochs=10,batch_size=4)
test_x=np.array([30,40,-20,-60])
test_y=model.predict(test_x)
for i in range(0,len(test_x)):
print('input {} => predict:{}'.format(test_x[i],test_y[i]))