Regressor
按照莫烦的博客一步一步实施:
代码
import numpy as np
np.random.seed(1337) #for reproducibility
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
# creat some data
X = np.linspace(-1,1,200)
np.random.shuffle(X) #randomize the data
Y = 0.5*X + 2 + np.random.normal(0, 0.05, (200,))
# plot the data
plt.scatter(X, Y)
plt.show()
X_train, Y_train = X[:160], Y[:160] #first 160 data points for training
X_test, Y_test = X[160:], Y[160:] # last 40 data points for testing
# build a neural network from the 1st layer to the last layer
model = Sequential()
model.add(Dense(output_dim=1, input_dim=1))
# choose loss function and optimizing method
model.compile(loss='mse', optimizer='sgd')
# training
print ('Training--------------------------------------')
for step in range(301):
cost = model.train_on_batch(X_train, Y_train)
if step % 100 == 0:
print 'train cost : ', cost
#test
print ('\n Testing---------------------------------------')
cost = model.evaluate(X_test, Y_test, batch_size=40)
print 'test cost : ', cost
W, b = model.layers[0].get_weights()
print 'Weights =', W,
print 'biases = ', b
# plotting the prediction
Y_pred = model.predict(X_test)
plt.scatter(X_test, Y_test)
plt.plot(X_test, Y_pred)
plt.show()
注意
- 当生成数据图时需要关闭数据图才会出结果,我第一次傻得一直等没有结果,最后才知道。
- 莫烦博客里用的是Python3,而我用的是Python2.7,所以print函数的代码有所区别,要不加括号的。