手写单层回归神经网络(regression)

1.create data

2.分训练集,测试集

3.构建模型

4.往模型中添加神经层

5.激活模型

6.训练

7.测试

8预测

9可视化输出预测

import numpy as np
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
#1.create data
#创建x数据集
x = np.linspace(-1,1,200)
#将x随机打乱
np.random.shuffle(x)
#定义对应的y,并给y一个噪声
y = 0.5*x + 2 + np.random.normal(0,0.05,(200,))

#2分训练集,测试集
x_train,y_train = x[:160],y[:160]
x_test,y_test = x[160:],y[160:]

#3.构建模型
model = Sequential()
#4往模型中添加层
model.add(Dense(output_dim=1,input_dim=1))
#5激活模型
model.compile(loss='mse',optimizer='sgd')
#6训练
print('train...')
for step in range(301):
    cost = model.train_on_batch(x_train,y_train)
    if step % 100 == 0:
        print('cost:',cost)
#7测试
print('test....')
cost = model.evaluate(x_test,y_test,batch_size=40)
print('cost:',cost)
w, b =model.layers[0].get_weights()
print('w:',w,'\nb:',b)

#8预测
y_predict = model.predict(x_test)
#9可视化输出
plt.figure()
plt.scatter(x_test,y_test)
plt.plot(x_test,y_predict)
plt.show()

result:
train...
cost: 4.107647
cost: 0.08906002
cost: 0.007561464
cost: 0.0034376974
test....
40/40 [==============================] - 0s
cost: 0.0034449086524546146
w: [[0.44640157]] 
b: [1.9982066]

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值