手写单层回归神经网络(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]

手写单层回归神经网络(regression)_第1张图片

你可能感兴趣的:(mask-rcnn,regression,maskrcnn)