使用Keras實現(xiàn)簡單線性回歸模型操作
神經(jīng)網(wǎng)絡(luò)可以用來模擬回歸問題 (regression),實質(zhì)上是單輸入單輸出神經(jīng)網(wǎng)絡(luò)模型,例如給下面一組數(shù)據(jù),用一條線來對數(shù)據(jù)進行擬合,并可以預測新輸入 x 的輸出值。

一、詳細解讀
我們通過這個簡單的例子來熟悉Keras構(gòu)建神經(jīng)網(wǎng)絡(luò)的步驟:
1.導入模塊并生成數(shù)據(jù)
首先導入本例子需要的模塊,numpy、Matplotlib、和keras.models、keras.layers模塊。Sequential是多個網(wǎng)絡(luò)層的線性堆疊,可以通過向Sequential模型傳遞一個layer的list來構(gòu)造該模型,也可以通過.add()方法一個個的將layer加入模型中。layers.Dense 意思是這個神經(jīng)層是全連接層。
2.建立模型
然后用 Sequential 建立 model,再用 model.add 添加神經(jīng)層,添加的是 Dense 全連接神經(jīng)層。參數(shù)有兩個,(注意此處Keras 2.0.2版本中有變更)一個是輸入數(shù)據(jù)的維度,另一個units代表神經(jīng)元數(shù),即輸出單元數(shù)。如果需要添加下一個神經(jīng)層的時候,不用再定義輸入的緯度,因為它默認就把前一層的輸出作為當前層的輸入。在這個簡單的例子里,只需要一層就夠了。
3.激活模型
model.compile來激活模型,參數(shù)中,誤差函數(shù)用的是 mse均方誤差;優(yōu)化器用的是 sgd 隨機梯度下降法。
4.訓練模型
訓練的時候用 model.train_on_batch 一批一批的訓練 X_train, Y_train。默認的返回值是 cost,每100步輸出一下結(jié)果。
5.驗證模型
用到的函數(shù)是 model.evaluate,輸入測試集的x和y,輸出 cost,weights 和 biases。其中 weights 和 biases 是取在模型的第一層 model.layers[0] 學習到的參數(shù)。從學習到的結(jié)果你可以看到, weights 比較接近0.5,bias 接近 2。
Weights= [[ 0.49136472]]
biases= [ 2.00405312]
6.可視化學習結(jié)果
最后可以畫出預測結(jié)果,與測試集的值進行對比。

二、完整代碼
import numpy as np
np.random.seed(1337)
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
# 生成數(shù)據(jù)
X = np.linspace(-1, 1, 200) #在返回(-1, 1)范圍內(nèi)的等差序列
np.random.shuffle(X) # 打亂順序
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, )) #生成Y并添加噪聲
# plot
plt.scatter(X, Y)
plt.show()
X_train, Y_train = X[:160], Y[:160] # 前160組數(shù)據(jù)為訓練數(shù)據(jù)集
X_test, Y_test = X[160:], Y[160:] #后40組數(shù)據(jù)為測試數(shù)據(jù)集
# 構(gòu)建神經(jīng)網(wǎng)絡(luò)模型
model = Sequential()
model.add(Dense(input_dim=1, units=1))
# 選定loss函數(shù)和優(yōu)化器
model.compile(loss='mse', optimizer='sgd')
# 訓練過程
print('Training -----------')
for step in range(501):
cost = model.train_on_batch(X_train, Y_train)
if step % 50 == 0:
print("After %d trainings, the cost: %f" % (step, cost))
# 測試過程
print('\nTesting ------------')
cost = model.evaluate(X_test, Y_test, batch_size=40)
print('test cost:', cost)
W, b = model.layers[0].get_weights()
print('Weights=', W, '\nbiases=', b)
# 將訓練結(jié)果繪出
Y_pred = model.predict(X_test)
plt.scatter(X_test, Y_test)
plt.plot(X_test, Y_pred)
plt.show()
三、其他補充
1. numpy.linspace
numpy.linspace(start, stop, num=50, endpoint=True,retstep=False,dtype=None)
返回等差序列,序列范圍在(start,end),生成num個元素的np數(shù)組,如果endpoint為False,則生成num+1個但是返回num個,retstep=True則在其后返回步長.
>>> np.linspace(2.0, 3.0, num=5) array([ 2. , 2.25, 2.5 , 2.75, 3. ]) >>> np.linspace(2.0, 3.0, num=5, endpoint=False) array([ 2. , 2.2, 2.4, 2.6, 2.8]) >>> np.linspace(2.0, 3.0, num=5, retstep=True) (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)
以上這篇使用Keras實現(xiàn)簡單線性回歸模型操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用wxPython實現(xiàn)Windows11任務欄通知功能
這篇文章主要為大家詳細介紹了如何使用 wxPython 模塊,在 Windows 11 中實現(xiàn)任務欄通知功能,文中的示例代碼簡潔易懂,感興趣的小伙伴可以跟隨小編一起學習一下2023-10-10
Python實現(xiàn)視頻畫質(zhì)增強的示例代碼
這篇文章主要為大家詳細介紹了如何利用Python語言實現(xiàn)對視頻進行畫質(zhì)增強功能,文中的示例代碼講解詳細,感興趣的小伙伴可以嘗試一下2022-04-04
關(guān)于阿里云oss獲取sts憑證 app直傳 python的實例
今天小編就為大家分享一篇關(guān)于阿里云oss獲取sts憑證 app直傳 python的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08

