深度學習原理與框架-神經網絡-線性回歸與神經網絡的效果對比 1.np.c_[將數據進行合並] 2.np.linspace(將數據拆成n等分) 3.np.meshgrid(將一維數據表示為二維的維度) 4.plt.contourf(畫出等高線圖,畫算法邊界)


1. np.c[a, b]  將列表或者數據進行合並,我們也可以使用np.concatenate

參數說明:a和b表示輸入的列表數據

2.np.linspace(0, 1, N) # 將0和1之間的數分成N份

參數說明:0表示起始數據,1表示末尾數據,N表示生成的分數

3.xx, yy = np.meshgrid(np.arange(x.min(), x.max(), N), np.arange(y.min(), y.max(), N))  對數據進行切分后,生成二維數據點

參數說明:np.arange(x.min(), x.max(), N) X軸的一維數據,np.arange(y.min(), y.max(), N) y軸一維數據, 

4. plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)  用於生成等高線圖

參數說明:xx和yy表示x軸方向的二維數據,yy表示y軸的二維方向的數據,Z表示顏色對應的標簽值, cmap表示顏色板

 

線性網絡和神經網絡的區別:

       第一:線性網絡只有一個w*x + b ,即線性變化層, 神經網絡可以有多個w*x + b , 且中間存在一個激活層relu 

線性回歸代碼解說:

第一步:使用np.c_[r*sin(t), r*cos(t)] 構造出二維的數據

第二步:前向傳播

               第一步:前向傳播np.dot(x, w) + b 計算得分scores

               第二步:使用e^scores / ∑e^scores 計算出概率值

               第三步:使用-np.log(probs[np.arange(num_sample, y)]) 計算交叉熵,並且使用np.sum計算總的交叉熵損失值

第三步:反向傳播

               第一步:計算softamx反向傳播的結果,即dout[np.arange(num_sample), y] -= 1 , dout /= num_samples 

               第二步:計算dx, dw, db, 這里的話也需要加上正則化懲罰項的求導,即w * reg  

第四步:更新參數  w = dw*step_size + w, b = db * step_size + b 

第五步:使用np.argmax()計算預測值, 利用pred_labels == y.mean() 計算准確率

第六步:使用plt.contourf 畫出等高線圖

  代碼:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0) # 隨機種子
N = 100 # 每類樣本的個數
K = 3  # 標簽值
D = 2  # 維度
X = np.zeros((N*K, D)) # 樣本初始化
y = np.zeros(N*K, dtype='int') # 標簽初始化
print(y.shape)
# 第一步:使用np.c_構造數據
for j in range(K):
    xi = np.arange(j*N, N*(j+1))
    r = np.linspace(0.0, 1, N)
    t = np.linspace(j*4, (j+1)*4, N) + np.random.randn(N) * 0.2
    X[xi] = np.c_[r*np.sin(t), r*np.cos(t)] # 構造樣本
    y[xi] = j # 構造標簽
# 初始化參數
W = np.random.randn(D, K) * 0.01
b = np.zeros((1, K))
reg = 1e-3
step_size = 1e-1

num_examples = X.shape[0]
for i in range(1000):
    # 第二步前向傳播
    # 前向傳播計算得分
    scores = np.dot(X, W) + b

    # 計算概率
    softmax_scores = np.exp(scores)
    probs = softmax_scores / np.sum(softmax_scores, axis=1, keepdims=True)
    # 計算損失值
    data_loss = -np.sum(np.log(probs[np.arange(num_examples), y])) / num_examples
    reg_loss = 1 / 2 * np.sum(W*W)
    loss = data_loss + reg_loss
    if i == 100:
        print(loss)
    # 第三步:計算反向傳播
    dout = probs
    # 求出softmax的反向傳播
    dout[np.arange(num_examples), y] -= 1
    dout /= num_examples
    # 求出dW和db
    dW = np.dot(X.T, dout)
    db = np.sum(dout, axis=0)
    # 正則化懲罰項的求導
    dW += W * reg
    # 第四步:進行參數的更新操作
    W = W - step_size * dW
    b = b - step_size * db

    scores = np.dot(X, W) + b

# 第五步:使用得分,獲得最終的准確率
pred_labels = np.argmax(scores, axis=1)
print('accucacy %.2f'%(np.array([pred_labels==y]).mean()))

# 第六步:使用plt.contourf畫出等高線圖
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))

Z = np.dot(np.c_[xx.ravel(), yy.ravel()], W) + b
Z = np.argmax(Z, axis=1)

Z = Z.reshape(xx.shape)

fig = plt.figure()
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.show()

             准確率為0.49 

神經網絡代碼解說:

第一步:使用np.c_[r*sin(t), r*cos(t)] 構造出二維的數據

第二步:前向傳播

               第一步:前向傳播np.dot(x, w1) + b1計算第一層 

               第二步:np.maximum(np.dot(x1, w2) + b2) 加上一個relu激活函數作為第二層  

               第三步:使用np.exp(scores) / ∑np.exp(scores) 獲得概率值

               第四步:使用-np.log(probs[np.arange(num_sample, y)]) 計算交叉熵,並且使用np.sum計算總的交叉熵損失值

第三步:反向傳播

               第一步:計算softamx反向傳播的結果,即dout[np.arange(num_sample), y] -= 1 , dout /= num_samples 

               第二步:計算dh1, dw2, db2, 這里的話也需要加上正則化懲罰項的求導,即w * reg

               第三步:計算relu激活層的反向傳播,即dout[x<0] = 0 

                第四步:計算dw1和db1

                第五步:在dw1和dw2的基礎上,加上正則化懲罰項的求導,reg * W   

第四步:更新參數  w = dw*step_size + w, b = db * step_size + b 

第五步:使用np.argmax()計算預測值, 利用pred_labels == y.mean() 計算准確率

第六步:使用plt.contourf 畫出等高線圖

代碼:

import numpy as np
import matplotlib.pyplot as plt

# 隨機種子
np.random.seed(0)
N = 100  # 每個樣本的個數
K = 3  # 樣本的類別
D = 2  # 表示兩個維度

X = np.zeros((N*K, D))
y = np.zeros(N*K, dtype='int')
# 第一步:構造數據
for j in range(K):
    ix = np.arange(j*N, (j+1)*N)
    r = np.linspace(0.0, 1, N)
    t = np.linspace((4*j), (j+1)*4, N) + np.random.randn(N) * 0.2
    X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
    y[ix] = j
# 初始化權重參數
W1 = np.random.rand(D, 100) * 0.01
b1 = np.zeros((1, 100))
W2 = np.random.randn(100, K) * 0.01
b2 = np.zeros((1, K))

reg = 1e-3  # 正則化的概率
step_size = 1 # 學習率
num_samples = X.shape[0] # 樣本的個數
for i in range(2000):
    # 第二步:循環,進行前向傳播
    # 第一層得分值的獲得
    h1 = np.dot(X, W1) + b1
    # 使用relu激活層
    relu_h1 = np.maximum(0, h1)
    # 進行第二層的前向傳播
    scores = np.dot(relu_h1, W2) + b2

    # 計算概率值
    probs = np.exp(scores)
    probs = probs / np.sum(probs, axis=1, keepdims=True)
    # 計算損失值
    data_loss = -np.sum(np.log(probs[np.arange(num_samples), y])) / num_samples
    # 正則化懲罰項的損失值
    reg_loss = 1 / 2 * np.sum(W1*W1)*reg + 1/2 * np.sum(W2*W2)*reg
    loss = data_loss + reg_loss

    # 進行反向傳播
    # softmax的反向傳播結果
    dout = probs.copy()
    dout[np.arange(num_samples), y] -= 1
    dout /= num_samples
    # 第二層反向傳播的結果
    dh1 = np.dot(dout, W2.T)
    dw2 = np.dot(relu_h1.T, dout)
    db2 = np.sum(dout, axis=0)
    # relu層反向傳播的結果
    drelu = dh1.copy()
    drelu[h1 < 0] = 0
    # 第一層方向傳播的結果
    dw1 = np.dot(X.T, drelu)
    db1 = np.sum(drelu, axis=0)
    # 在獲得梯度權重的基礎上加上正則化的梯度值
    dw2 += reg * W2
    dw1 += reg * W1
    # 第四步:進行參數的更新
    W2 -= dw2 * step_size
    b2 -= db2 * step_size
    W1 -= dw1 * step_size
    b1 -= db1 * step_size

    if i%100 == 0:
        print(loss)

# 第五步:根據得分值,計算准確率
predict_labels = np.argmax(scores, axis=1)
print('accuracy:%.2f'%np.array([predict_labels==y]).mean())


# 第六步:進行畫圖操作
h = 0.02
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                     np.arange(y_min, y_max, h))

# 計算出對應的類別值
Z = np.dot(np.maximum(np.dot(np.c_[xx.ravel(), yy.ravel()], W1) + b1, 0), W2) + b2
Z = np.argmax(Z, axis=1)

Z = Z.reshape(xx.shape)

fig = plt.figure()
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.show()

                                准確率0.95 

          


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM