# -*- coding: utf-8 -*-
"""
Created on Sat Aug 26 18:25:28 2017
线性回归拟合直线
@author: Han
"""
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt
# 创建一个等差数列
trX = np.linspace(-1 , 1 , 100)
trY = 3 * trX + np.random.randn(*trX.shape) * 0.33
# 绘制数据
plt.scatter(trX , trY)
plt.show()
# 分训练集和测试集
X_train , y_train = trX[:80] , trY[:80]
X_test , y_test = trX[80:] , trY[80:]
model = Sequential()
model.add(Dense(input_dim = 1 , output_dim = 1 , init = 'uniform' , activation='linear'))
# 选择损失函数和优化方法
model.compile(optimizer='sgd' , loss='mse')
model.fit(X_train , y_train , epochs=200 , verbose=1)
# 获取参数
W , b = model.layers[0].get_weights()
print('Linear regression model is initialized with weights w: %.2f, b: %.2f' % (W, b))
# 测试
Y_pred = model.predict(X_test)
plt.scatter(X_test , y_test)
plt.plot(X_test , Y_pred)
plt.show()
# 保存权重
model.save_weights('my_model.h5')
model.load_weights('my_model.h5')
keras线性回归拟合直线
最新推荐文章于 2023-10-31 22:48:38 发布