深度学习:keras实现线性回归

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()


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值