【實戰演練】機器學習系列02-安裝tensorflow與keras搭建線性迴歸神經網絡

keras是一個深度學習的框架,能夠快速地搭建神經網絡而且進行巡檢與測試,是一個能夠快速入門神經網絡的軟件。
python

使用keras前,須要先安裝tensorflow。linux


一、安裝tensorflow算法

先更新pip,pip與linux的yum差很少,若是源不夠新,可能安裝軟件的時候會致使依賴關係不全,安裝軟件失敗。bash

管理員身份運行cmd窗口網絡

pip install msgpack
python –m pip install –upgrade pip
pip install -U --ignore-installed wrapt
pip install --upgrade tensorflow
pip install tensorflow


二、安裝keras框架

pip install kerasdom


三、搭建線性迴歸神經網絡ide

使用jupyter notebook運行以下代碼嘗試。函數

3.1生成數據學習

import numpy as np
np.random.seed(1337)                
from keras.models import Sequential     #採用一層一層的神經網絡
from keras.layers import Dense   #神經網絡神經元全鏈接
import matplotlib.pyplot as plt         #圖形庫
# 生成數據
X = np.linspace(-1, 1, 200) #在返回(-1, 1)範圍內的等差序列
np.random.shuffle(X)    # 打亂順序
Y = 0.5 * X + 2 + np.random.normal(0, 0.05, (200, ))    #生成Y並添加噪聲
# plot
plt.scatter(X, Y)
plt.show()

001.png

3.2指定訓練集與測試集

X_train, Y_train = X[:160], Y[:160]     # 前160組數據爲訓練數據集
X_test, Y_test = X[160:], Y[160:]      #後40組數據爲測試數據集


3.3構建神經網絡

model = Sequential()
model.add(Dense(input_dim=1, units=1))
# 選定loss函數和優化器
model.compile(loss='mse', optimizer='sgd')

這裏的loss與optimizer有不少不一樣的可選,這些不一樣的函數,會採用不一樣的算法,致使咱們模型學習的快慢,以及準確率。

3.4訓練模型

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))

3.5測試模型

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)

3.6繪製結果

Y_pred = model.predict(X_test)
plt.scatter(X_test, Y_test)
plt.plot(X_test, Y_pred)
plt.show()

002.png

通過線性迴歸結合梯度降低算法後,神經網絡自動將生成的散點數據,擬合成爲一條直線。

相關文章
相關標籤/搜索