第十二篇:《機器學習之神經網絡(實戰篇)》

本篇接第九篇:《機器學習之神經網絡(實戰篇)》

這是一個比較完整的實戰項目

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline


# 放置數據的點
np.random.seed(0)
N = 100 # 每類點數
D = 2 # 維度
K = 3 # 類別數目
X = np.zeros((N*K,D))
y = np.zeros(N*K, dtype='uint8')
for j in range(K):
  ix = range(N*j,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 # theta
  X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
  y[ix] = j

fig = plt.figure(figsize=(11,11))
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.show()
h = 200 # 隱藏層大小
W = 0.01 * np.random.randn(D,h)# x:300*2  2*100
b = np.zeros((1,h))
W2 = 0.01 * np.random.randn(h,K)
b2 = np.zeros((1,K))

# 一些超參數
step_size = 1e-0
reg = 1e-3 # 正則化強度

# 梯度下降環
num_examples = X.shape[0]


# 進行迭代訓練模型
for i in range(10000):
  # 評價班級成績, [N x K]
  hidden_layer = np.maximum(0, np.dot(X, W) + b) # note, ReLU activation hidden_layer:300*100
  #print hidden_layer.shape
  scores = np.dot(hidden_layer, W2) + b2  #scores:300*3
  #print scores.shape

  # 計算類概率
  exp_scores = np.exp(scores)

  probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K]

  #print probs.shape

  # 計算損耗:平均交叉熵損失與正則化

  corect_logprobs = -np.log(probs[range(num_examples),y])

  data_loss = np.sum(corect_logprobs)/num_examples

  reg_loss = 0.5*reg*np.sum(W*W) + 0.5*reg*np.sum(W2*W2)

  loss = data_loss + reg_loss

  if i % 1000 == 0:
    print ("訓練第 %d 次: 誤差 %f" % (i, loss))

  # 計算分數的梯度
  dscores = probs
  dscores[range(num_examples),y] -= 1
  dscores /= num_examples

  # 反向傳播 參數的梯度
  # 首先 反向傳播 into parameters W2 and b2
  dW2 = np.dot(hidden_layer.T, dscores)
  db2 = np.sum(dscores, axis=0, keepdims=True)
  # 然後 反向傳播 into hidden layer
  dhidden = np.dot(dscores, W2.T)
  # 反向傳播 the ReLU non-linearity
  dhidden[hidden_layer <= 0] = 0
  # 最後 into W,b
  dW = np.dot(X.T, dhidden)
  db = np.sum(dhidden, axis=0, keepdims=True)

  # 添加正則化梯度貢獻
  dW2 += reg * W2
  dW += reg * W

  # 執行參數更新
  W += -step_size * dW
  b += -step_size * db
  W2 += -step_size * dW2
  b2 += -step_size * db2



hidden_layer = np.maximum(0, np.dot(X, W) + b)
scores = np.dot(hidden_layer, W2) + b2
predicted_class = np.argmax(scores, axis=1)
print ('訓練後的準確度: %.2f' % (np.mean(predicted_class == y)))


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(0, np.dot(np.c_[xx.ravel(), yy.ravel()], W) + b), W2) + b2
Z = np.argmax(Z, axis=1)
Z = Z.reshape(xx.shape)

fig = plt.figure(figsize=(9,9))
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)

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

訓練的情況

最後的效果圖

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章