import keras import numpy as np import matplotlib.pyplot as plt #Sequential 按顺序构成的模型 from keras.models import Sequential#Sequential是模型结构,输入层,隐藏层,输出层 #Dense 全连接层 from keras.layers import Dense #使用numpy生成100个随机点 x_data=np.random.rand(100) noise=np.random.normal(0,0.01,x_data.shape)#生成和x_data形状一样的噪声 y_data=x_data*0.1+0.2+noise #显示随机点 #plt.scatter(x_data,y_data) #plt.show() #构建一个顺序模型 model=Sequential() #在模型中添加一个全连接层 model.add(Dense(units=1,input_dim=1))#units是输出维度,输出y,input_dim是输入维度,输入x model.compile(optimizer='sgd',loss='mse')#编译这个模型,sgd是随机梯度下降法,优化器.mse是均方误差 #训练模型 for step in range(3001): #每次训练一个批次 cost=model.train_on_batch(x_data,y_data)#代价函数的值,其实就是loss #每500个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) #显示随机点s plt.scatter(x_data,y_data) #显示预测结果 plt.plot(x_data,y_pred,'r-',lw=3)#r-表示红色的线,lw表示线宽 plt.show()
结果:
Using TensorFlow backend.
2019-02-16 16:43:05.823017: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
cost: 1.2237755
cost: 0.031610813
cost: 0.007897568
cost: 0.002027363
cost: 0.00057419395
cost: 0.00021446131
cost: 0.00012540948
W: [[0.08398207]] b: [0.20809509]