ニューラルネットワークを実現するためにnumpyを使用する


まずnumpyを用いてこのニューラルネットワークを実現した.numpyは、n次元配列オブジェクトと、これらの配列を操作する多くの関数を提供します.numpyは汎用的な科学計算の枠組みである.計算図、深さ学習、勾配の概念はありません.しかし、numpyの操作を使用して、順方向伝播と逆方向伝播を手動で実現し、ランダムデータをフィットさせる2層のネットワークを容易に実現することができます.
import numpy as np

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random input and output data
x = np.random.randn(N, D_in)
y = np.random.randn(N, D_out)

# Randomly initialize weights
w1 = np.random.randn(D_in, H)
w2 = np.random.randn(H, D_out)

learning_rate = 1e-6

for t in range(500):
    # Forward pass: compute predicted y
    h = x.dot(w1)
    h_relu = np.maximum(h, 0)
    y_pred = h_relu.dot(w2)

    # Compute and print loss
    loss = np.square(y_pred - y).sum()
    print(t, loss)

    # Backprop to compute gradients of w1 and w2 with respect to loss
    grad_y_pred = 2.0 * (y_pred - y)
    grad_w2 = h_relu.T.dot(grad_y_pred)
    grad_h_relu = grad_y_pred.dot(w2.T)
    grad_h = grad_h_relu.copy()
    grad_h_relu[h<0] = 0
    grad_w1 = x.T.dot(grad_h)

    # update weights
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * grad_w2

作者:MaosongRanリンク:https://www.jianshu.com/p/52684285e335 出典:簡書簡書の著作権は著者の所有であり、いかなる形式の転載も著者に連絡して授権を得て出典を明記してください.