# -*- coding: utf-8 -*-
from keras.models import Sequential
from keras.layers import Dense
from keras.models import load_model
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1) # for reproducibility
X = np.random.rand(200)
np.random.shuffle(X) # randomize the data
Y = X + np.random.normal(0, 0.05, (200,))
X_train, Y_train = X[:160], Y[:160] # first 160 data points
X_test, Y_test = X[160:], Y[160:] # last 40 data points
model = Sequential()
model.add(Dense(output_dim=1, input_dim=1))
model.compile(loss='mse', optimizer='sgd')
print('test before save: ', model.predict(X_test[0:1]))
for step in range(10000):
# cost = model.train_on_batch(X_train, Y_train)
cost = model.fit(X_train, Y_train, nb_epoch=1, batch_size=160)
# save model
model.save('my_model.h5') # HDF5 file, you have to pip3 install h5py if don't have it
del model # deletes the existing model
# load model
model = load_model('my_model.h5')
print('test after load: ', model.predict(X_test[0:1]))
# 模型预测值
predictY = model.predict(X[:])
predictY= np.asarray(predictY)
predictY = np.reshape(predictY,(200))
# 绘图
plt.figure('Accuracy')
plt.plot(X,Y,'ro') # plot绘制折线图
plt.plot(X,predictY,'b^')
plt.draw() # 显示绘图
plt.pause(20) #显示20秒
plt.savefig("Accuracy.jpg") #保存图象
plt.close() #关闭图表
红色的点是真实的数据分布,绿色的点是模型预测出来的数据,迭代300轮效果:
800轮:
1500轮:
3000轮:
另一个非线性回归的例子
# -*- coding: utf-8 -*-
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Activation
from keras.optimizers import SGD
from keras.utils import plot_model
import matplotlib.pyplot as plt
import numpy as np
# 生成数据
np.random.seed(0)
X_train=np.linspace(-0.5,0.5,200)
noise=np.random.normal(0,0.02,X_train.shape)
Y_train=np.square(X_train)+noise
# 搭建模型
model = Sequential()
model.add(Dense(units=20,input_dim=1))
model.add(Activation('tanh')) #增加非线性激活函数
model.add(Dense(units=1)) #默认连接上一层input_dim=20
model.add(Activation('relu'))
# 优化器
defsgd=SGD(lr=0.1)
model.compile(loss='mse', optimizer=defsgd)
# 绘制网络结构图
plot_model(model, to_file='model_logistic_regression.png',show_shapes=True)
# 执行训练
for step in range(2000):
cost = model.fit(X_train, Y_train)
if step % 20 ==0:
# 模型预测值
predictY = model.predict(X_train[:])
predictY = np.asarray(predictY)
predictY = np.reshape(predictY, (200))
# 绘图
plt.figure('Accuracy')
plt.plot(X_train, Y_train, 'ro') # plot绘制折线图
plt.plot(X_train, predictY, 'b^')
plt.draw() # 显示绘图
plt.pause(0.0001) # 显示xx秒
plt.cla()
# save model
model.save('model_logistic_regression.h5') # HDF5 file
del model # deletes the existing model
定义的简单模型框图:
拟合效果: