1.keras-構建基本簡單網絡實現線性迴歸

構建基本簡單網絡實現線性迴歸網絡

1.建立數據繪製散點圖dom

import keras
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
import tensorflow as tf

# 建立數據繪製散點圖
x_data = np.random.rand(100)
noise = np.random.normal(0,0.01,x_data.shape)
y_data = x_data * 0.1 + 0.2 + noise

plt.scatter(x_data,y_data)
plt.show()

2.構建模型spa

# 構建順序模型
model = Sequential()
# 在模型中添加一個全鏈接模型
model.add(Dense(units=1,input_dim=1)) #units=1,input_dim=1輸入和輸出都是一維的
model.compile(optimizer='sgd',
              loss= 'mse')
for step in range(3000):
    # 每次訓練一個batch
    cost = model.train_on_batch(x_data,y_data)
    if step % 500 ==0:
        print('step:',step)
        print('cost',cost)
# 打印權值和偏移項
W,b = model.layers[0].get_weights()
print('W:',W,'b',b)

out:code

step: 0
cost 0.026886607
step: 500
cost 0.0005393094
step: 1000
cost 0.00020998158
step: 1500
cost 0.0001274022
step: 2000
cost 0.000106695006
step: 2500
cost 0.00010150281
W: [[0.1016009]] b [0.19795756]orm

3.預測並繪製預測結果blog

# 進行預測值
y_pred = model.predict(x_data)

# 顯示隨機點
plt.scatter(x_data,y_data)
plt.plot(x_data,y_pred,'r-',lw=3)
plt.show()

相關文章
相關標籤/搜索