import numpy as np # 随机数
np.random.seed(1271)
from keras.models import Sequential #深度学习的模型
from keras.layers import Dense #层的输入输出
import matplotlib.pyplot as plt #绘图
x = np.linspace(-1, 1, 200) # -1, 1之间切割200份
np.random.shuffle(x) # 打乱顺序
print(x)
y = 0.5 * x + 2 + np.random.normal(0, 0.05, (200, )) # y与x,插入一个随机数矩阵
print(y)
# plt.scatter(x, y)
# plt.show()
x_train, y_train = x[:160], y[: 160] # 切割, 测试, 训练
x_test, y_test = x[160:], y[160:]
model = Sequential() # 建立模型
model.add(Dense(input_dim = 1, output_dim = 1)) # 输入为1, 输出为1
model.compile(loss="mse", optimizer="sgd") # 设定损失函数,设定优化
print("训练-----------")
for step in range(301):
cost = model.train_on_batch(x_train, y_train)
if step % 100 ==0:
print("训练结果", cost)
print("测试-----------")
cost = model.evaluate(x_test, y_test, batch_size=40)
print("测试结果", cost)
w, b = model.layers[0].get_weights()
print("w=", w, "b=", b)
y_new = model.predict(x_test) # 测试预测
plt.scatter(x_test, y_test) # 测试数据散点图
plt.plot(x_test, y_new) # 预测的直线图
plt.show()
深度学习:keras实现线性回归
最新推荐文章于 2023-09-12 12:42:25 发布