keras速度复习-非线性回归

import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense,Activation#激活函数
from keras.optimizers import SGD

#生成200个随机点,区间[-0.5,0.5]
x_data=np.linspace(-0.5,0.5,200)
noise=np.random.normal(0,0.02,x_data.shape)
y_data=np.square(x_data)+noise

#显示随机点
plt.scatter(x_data,y_data)
plt.show()

#构建一个顺序模型
model=Sequential()
#在模型中添加一个全连接层(输出一维,输入一维)
#1-10-1,还要再加激活函数!超强大的sigmod!
model.add(Dense(units=10,input_dim=1))#第一层10出1进
model.add(Activation('tanh'))#这是第一种激活函数写法,下面第二种
model.add(Dense(units=1,activation='tanh'))#第二层1出10进(不写input会自动连接上一层输出)

#定义优化算法(learning ratio学习率改为0.3)
sgd=SGD(lr=0.3)
#sgd:随机梯度下降法stochastic gradient descent
#mse:均方误差mean squared error
model.compile(optimizer=sgd,loss='mse')

#训练3001个批次,每次都重复使用x_data,y_data中的数据
for step in range(3001):
    #每次训练一个批次,随机梯度每次都更新(批量梯度要全部扫一次)
    cost=model.train_on_batch(x_data,y_data)
    #每五百个batch打印一次cost值观察拟合程度
    if step%500==0:
        print("cost:",cost)
        
#打印权值和偏置值:
W,b=model.layers[0].get_weights()
print('W:',W,'b:',b)
    
#x_data输入网络中,得到预测值y_pred
y_pred=model.predict(x_data)
 
#显示随机点:X坐标,Y坐标
plt.scatter(x_data,y_data)
#显示预测结果:X坐标,Y坐标,颜色red,线粗3
plt.plot(x_data,y_pred,'r-',lw=3)
plt.show()

猜你喜欢

转载自blog.csdn.net/cj1064789374/article/details/88184103