作業一
作業內容:
實現k-NN,SVM分類器,Softmax分類器和兩層神經網絡,實踐一個簡單的圖像分類流程。
激活函數類型:
上圖左邊是Sigmoid非線性函數,將實數壓縮到[0,1]之間。右邊是tanh函數,將實數壓縮到[-1,1]。
然而現在sigmoid函數已經不太受歡迎,實際很少使用了,這是因爲它有***兩個主要缺點***:
- Sigmoid函數飽和使梯度消失
- Sigmoid函數的輸出不是零中心的
和sigmoid神經元一樣,tanh函數也存在飽和問題,但是和sigmoid神經元不同的是,它的輸出是零中心的。現在大多使用tanh
——————————————————————————————
左邊是ReLU(校正線性單元:Rectified Linear Unit)激活函數,當X=0時函數值爲0。當X>0時函數的斜率爲1。右邊是從 Krizhevsky等的論文中截取的圖表,指明使用ReLU比使用tanh的收斂快6倍。
使用ReLU有以下一些優缺點:
優點 - 相較於sigmoid和tanh函數,ReLU對於隨機梯度下降的收斂有巨大的加速作用
- sigmoid和tanh神經元含有指數運算等耗費計算資源的操作,而ReLU可以簡單地通過對一個矩陣進行閾值計算得到
缺點 - 在訓練的時候,ReLU單元比較脆弱並且可能“死掉”。舉例來說,當一個很大的梯度流過ReLU的神經元的時候,可能會導致梯度更新到一種特別的狀態,在這種狀態下神經元將無法被其他任何數據點再次激活。如果這種情況發生,那麼從此所以流過這個神經元的梯度將都變成0。也就是說,這個ReLU單元在訓練中將不可逆轉的死亡,因爲這導致了數據多樣化的丟失。
以上就是一些常用的神經元及其激活函數。
——————————————————————————————
Leaky ReLU。Leaky ReLU是爲解決“ReLU死亡”問題的嘗試。ReLU中當x<0時,函數值爲0。而Leaky ReLU則是給出一個很小的負數梯度值,比如0.01。
Maxout。一些其他類型的單元被提了出來,Maxout是對ReLU和leaky ReLU的一般化歸納,它的函數是:
eLU和Leaky ReLU都是這個公式的特殊情況(比如ReLU就是當W1,b1=0的時候)。這樣Maxout神經元就擁有ReLU單元的所有優點(線性操作和不飽和),而沒有它的缺點(死亡的ReLU單元)。然而和ReLU對比,它每個神經元的參數數量增加了一倍,這就導致整體參數的數量激增。
——————————————————————————————
最後需要注意一點:在同一個網絡中混合使用不同類型的神經元是非常少見的,雖然沒有什麼根本性問題來禁止這樣做。
數據預處理
- 均值減法:是預處理最常用的形式。它對數據中每個獨立特徵減去平均值,從幾何上可以理解爲在每個維度上都將數據雲的中心都遷移到原點.
- 歸一化:是指將數據的所有維度都歸一化,使其數值範圍都近似相等。有兩種常用方法可以實現歸一化。
一般數據預處理流程:左邊:原始的2維輸入數據。中間:在每個維度上都減去平均值後得到零中心化數據,現在數據雲是以原點爲中心的。右邊:每個維度都除以其標準差來調整其數值範圍。紅色的線指出了數據各維度的數值範圍,在中間的零中心化數據的數值範圍不同,但在右邊歸一化數據中數值範圍相同。 - PCA:是另一種預處理形式。在這種處理中,先對數據進行零中心化處理,然後計算協方差矩陣,它展示了數據中的相關性結構.
- 白化:白化操作的輸入是特徵基準上的數據,然後對每個維度除以其特徵值來對數值範圍進行歸一化。該變換的幾何解釋是:如果數據服從多變量的高斯分佈,那麼經過白化後,數據的分佈將會是一個均值爲零,且協方差相等的矩陣。確定誇大的噪聲。
權重初始化
- 錯誤:全零初始化。
讓我們從應該避免的錯誤開始。在訓練完畢後,雖然不知道網絡中每個權重的最終值應該是多少,但如果數據經過了恰當的歸一化的話,就可以假設所有權重數值中大約一半爲正數,一半爲負數。這樣,一個聽起來蠻合理的想法就是把這些權重的初始值都設爲0吧,因爲在期望上來說0是最合理的猜測。這個做法錯誤的!因爲如果網絡中的每個神經元都計算出同樣的輸出,然後它們就會在反向傳播中計算出同樣的梯度,從而進行同樣的參數更新。換句話說,如果權重被初始化爲同樣的值,神經元之間就失去了不對稱性的源頭。 - 小隨機數初始化:因此,權重初始值要非常接近0又不能等於0。解決方法就是將權重初始化爲很小的數值,以此來打破對稱性。
- 稀疏初始化:另一個處理非標定方差的方法是將所有權重矩陣設爲0,但是爲了打破對稱性,每個神經元都同下一層固定數目的神經元隨機連接(其權重數值由一個小的高斯分佈生成)。一個比較典型的連接數目是10個。
- 偏置(biases)的初始化:通常將偏置初始化爲0,這是因爲隨機小數值權重矩陣已經打破了對稱性。對於ReLU非線性激活函數,有研究人員喜歡使用如0.01這樣的小數值常量作爲所有偏置的初始值,這是因爲他們認爲這樣做能讓所有的ReLU單元一開始就激活,這樣就能保存並傳播一些梯度。然而,這樣做是不是總是能提高算法性能並不清楚(有時候實驗結果反而顯示性能更差),所以通常還是使用0來初始化偏置參數。
批量歸一化
批量歸一化是loffe和Szegedy提出的方法,該方法減輕瞭如何合理初始化神經網絡這個棘手問題帶來的頭痛:,其做法是讓激活數據在訓練開始前通過一個網絡,網絡處理數據使其服從標準高斯分佈。因爲歸一化是一個簡單可求導的操作,所以上述思路是可行的。在實現層面,應用這個技巧通常意味着全連接層與激活函數之間添加一個BatchNorm層。對於這個技巧本節不會展開講,因爲上面的參考文獻中已經講得很清楚了,需要知道的是在神經網絡中使用批量歸一化已經變得非常常見。在實踐中,使用了批量歸一化的網絡對於不好的初始值有更強的魯棒性。最後一句話總結:批量歸一化可以理解爲在網絡的每一層之前都做預處理,只是這種操作以另一種方式與網絡集成在了一起。
正則化 Regularization
- L2正則化可能是最常用的正則化方法了。可以通過懲罰目標函數中所有參數的平方將其實現。即對於網絡中的每個權重W
- L1正則化是另一個相對常用的正則化方法
- 最大範式約束另一種形式的正則化是給每個神經元中權重向量的量級設定上限,並使用投影梯度下降來確保這一約束。
- 隨機失活是一個簡單又極其有效的正則化方法。與L1正則化,L2正則化和最大範式約束等方法互爲補充。在訓練的時候,隨機失活的實現方法是讓神經元以超參數P的概率被激活或者被設置爲0。
梯度檢查
理論上將進行梯度檢查很簡單,就是簡單地把解析梯度和數值計算梯度進行比較。然而從實際操作層面上來說,這個過程更加複雜且容易出錯。下面是一些提示、技巧和需要仔細注意的事情:
使用中心化公式。在使用有限差值近似來計算數值梯度的時候,常見的公式是
該公式在檢查梯度的每個維度的時候,會要求計算兩次損失函數(所以計算資源的耗費也是兩倍),但是梯度的近似值會準確很多。
使用相對誤差來比較:
比較數值梯度和解析梯度的細節有哪些?如何得知此兩者不匹配?你可能會傾向於監測它們的差的絕對值或者差的平方值,然後定義該值如果超過某個規定閾值,就判斷梯度實現失敗。然而該思路是有問題的。想想,假設這個差值是1e-4,如果兩個梯度值在1.0左右,這個差值看起來就很合適,可以認爲兩個梯度是匹配的。然而如果梯度值是1e-5或者更低,那麼1e-4就是非常大的差距,梯度實現肯定就是失敗的了。因此,使用相對誤差總是更合適一些:
- 相對誤差>1e-2:通常就意味着梯度可能出錯。
- 1e-2>相對誤差>1e-4:要對這個值感到不舒服才行。
- 1e-4>相對誤差:這個值的相對誤差對於有不可導點的目標函數是OK的。但如果目標函數中沒有kink(使用tanh和softmax),那麼相對誤差值還是太高。
- 1e-7或者更小:好結果,可以高興一把了。
要知道的是網絡的深度越深,相對誤差就越高。所以如果你是在對一個10層網絡的輸入數據做梯度檢查,那麼1e-2的相對誤差值可能就OK了,因爲誤差一直在累積。相反,如果一個可微函數的相對誤差值是1e-2,那麼通常說明梯度實現不正確。
使用雙精度
一個常見的錯誤是使用單精度浮點數來進行梯度檢查。這樣會導致即使梯度實現正確,相對誤差值也會很高(比如1e-2)。在我的經驗而言,出現過使用單精度浮點數時相對誤差爲1e-2,換成雙精度浮點數時就降低爲1e-8的情況。
學習之前:合理性檢查的提示與技巧
在進行費時費力的最優化之前,最好進行一些合理性檢查:
- ***尋找特定情況的正確損失值。***在使用小參數進行初始化時,確保得到的損失值與期望一致。最好先單獨檢查數據損失(讓正則化強度爲0)。例如,對於一個跑CIFAR-10的Softmax分類器,一般期望它的初始損失值是2.302,這是因爲初始時預計每個類別的概率是0.1(因爲有10個類別),然後Softmax損失值正確分類的負對數概率:-ln(0.1)=2.302。對於Weston Watkins SVM,假設所有的邊界都被越過(因爲所有的分值都近似爲零),所以損失值是9(因爲對於每個錯誤分類,邊界值是1)。如果沒看到這些損失值,那麼初始化中就可能有問題。
- 第二個合理性檢查:提高正則化強度時導致損失值變大。
- 對小數據子集過擬合:最後也是最重要的一步,在整個數據集進行訓練之前,嘗試在一個很小的數據集上進行訓練(比如20個數據),然後確保能到達0的損失值。進行這個實驗的時候,最好讓正則化強度爲0,不然它會阻止得到0的損失。除非能通過這一個正常性檢查,不然進行整個數據集訓練是沒有意義的。但是注意,能對小數據集進行過擬合併不代表萬事大吉,依然有可能存在不正確的實現。比如,因爲某些錯誤,數據點的特徵是隨機的,這樣算法也可能對小數據進行過擬合,但是在整個數據集上跑算法的時候,就沒有任何泛化能力。
損失函數
訓練期間第一個要跟蹤的數值就是損失值,它在前向傳播時對每個獨立的批數據進行計算。下圖展示的是隨着損失值隨時間的變化,尤其是曲線形狀會給出關於學習率設置的情況:
左圖展示了不同的學習率的效果。過低的學習率導致算法的改善是線性的。高一些的學習率會看起來呈幾何指數下降,更高的學習率會讓損失值很快下降,但是接着就停在一個不好的損失值上(綠線)。這是因爲最優化的“能量”太大,參數在混沌中隨機震盪,不能最優化到一個很好的點上。右圖顯示了一個典型的隨時間變化的損失函數值,在CIFAR-10數據集上面訓練了一個小的網絡,這個損失函數值曲線看起來比較合理(雖然可能學習率有點小,但是很難說),而且指出了批數據的數量可能有點太小(因爲損失值的噪音很大)。
——————————————————————————————
訓練集和驗證集準確率
在訓練分類器的時候,需要跟蹤的第二重要的數值是驗證集和訓練集的準確率。這個圖表能夠展現知道模型過擬合的程度:
在訓練集準確率和驗證集準確率中間的空隙指明瞭模型過擬合的程度。在圖中,藍色的驗證集曲線顯示相較於訓練集,驗證集的準確率低了很多,這就說明模型有很強的過擬合。遇到這種情況,就應該增大正則化強度(更強的L2權重懲罰,更多的隨機失活等)或收集更多的數據。另一種可能就是驗證集曲線和訓練集曲線如影隨形,這種情況說明你的模型容量還不夠大:應該通過增加參數數量讓模型容量更大些。
每層的激活數據及梯度分佈
一個不正確的初始化可能讓學習過程變慢,甚至徹底停止。還好,這個問題可以比較簡單地診斷出來。其中一個方法是輸出網絡中所有層的激活數據和梯度分佈的柱狀圖。直觀地說,就是如果看到任何奇怪的分佈情況,那都不是好兆頭。比如,對於使用tanh的神經元,我們應該看到激活數據的值在整個[-1,1]區間中都有分佈。如果看到神經元的輸出全部是0,或者全都飽和了往-1和1上跑,那肯定就是有問題了。
第一層可視化
將神經網絡第一層的權重可視化的例子。左圖中的特徵充滿了噪音,這暗示了網絡可能出現了問題:網絡沒有收斂,學習率設置不恰當,正則化懲罰的權重過低。右圖的特徵不錯,平滑,乾淨而且種類繁多,說明訓練過程進行良好。
代碼
import numpy as np
import matplotlib.pyplot as plt
from cs231n.classifiers.neural_net import TwoLayerNet
%matplotlib inline
plt.rcParams['figure.figsize'] = (10.0, 8.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
%load_ext autoreload
%autoreload 2
# 矢量間的相對誤差計算
def rel_error(x, y):
""" returns relative error """
return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))
input_size = 4
hidden_size = 10
num_classes = 3
# 樣本 5*4
num_inputs = 5
def init_toy_model():
np.random.seed(0)
return TwoLayerNet(input_size, hidden_size, num_classes, std=1e-1)
def init_toy_data():
np.random.seed(1)
X = 10 * np.random.randn(num_inputs, input_size)
y = np.array([0, 1, 2, 2, 1])
return X, y
net = init_toy_model()
X, y = init_toy_data()
scores = net.loss(X)
print('Your scores:')
print(scores)
print()
print('correct scores:')
correct_scores = np.asarray([
[-0.81233741, -1.27654624, -0.70335995],
[-0.17129677, -1.18803311, -0.47310444],
[-0.51590475, -1.01354314, -0.8504215 ],
[-0.15419291, -0.48629638, -0.52901952],
[-0.00618733, -0.12435261, -0.15226949]])
print(correct_scores)
print()
# 差距應該 < 1e-7
print('Difference between your scores and correct scores:')
print(np.sum(np.abs(scores - correct_scores)))
# 加入正則化
loss, _ = net.loss(X, y, reg=0.05)
correct_loss = 1.30378789133
# s差距< 1e-12
print('Difference between your loss and correct loss:')
print(np.sum(np.abs(loss - correct_loss)))
from cs231n.gradient_check import eval_numerical_gradient
# 使用梯度檢測來檢驗反向傳播的梯度,W1,W2,b1和b2的每個分析梯度應小於1e-8
loss, grads = net.loss(X, y, reg=0.05)
for param_name in grads:
f = lambda W: net.loss(X, y, reg=0.05)[0]
param_grad_num = eval_numerical_gradient(f, net.params[param_name], verbose=False)
print('%s max relative error: %e' % (param_name, rel_error(param_grad_num, grads[param_name])))
net = init_toy_model()
stats = net.train(X, y, X, y,
learning_rate=1e-1, reg=5e-6,
num_iters=100, verbose=False)
print('Final training loss: ', stats['loss_history'][-1])
# 畫出損失曲線
plt.plot(stats['loss_history'])
plt.xlabel('iteration')
plt.ylabel('training loss')
plt.title('Training Loss history')
plt.show()
from cs231n.data_utils import load_CIFAR10
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000):
# 劃分數據集
# Load the raw CIFAR-10 data
cifar10_dir = 'cs231n/datasets/CIFAR10'
# Cleaning up variables to prevent loading data multiple times (which may cause memory issue)
try:
del X_train, y_train
del X_test, y_test
print('Clear previously loaded data.')
except:
pass
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# Subsample the data
mask = list(range(num_training, num_training + num_validation))
X_val = X_train[mask]
y_val = y_train[mask]
mask = list(range(num_training))
X_train = X_train[mask]
y_train = y_train[mask]
mask = list(range(num_test))
X_test = X_test[mask]
y_test = y_test[mask]
# Normalize the data: subtract the mean image
mean_image = np.mean(X_train, axis=0)
X_train -= mean_image
X_val -= mean_image
X_test -= mean_image
# Reshape data to rows
X_train = X_train.reshape(num_training, -1)
X_val = X_val.reshape(num_validation, -1)
X_test = X_test.reshape(num_test, -1)
return X_train, y_train, X_val, y_val, X_test, y_test
# Invoke the above function to get our data.
X_train, y_train, X_val, y_val, X_test, y_test = get_CIFAR10_data()
print('Train data shape: ', X_train.shape)
print('Train labels shape: ', y_train.shape)
print('Validation data shape: ', X_val.shape)
print('Validation labels shape: ', y_val.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
input_size = 32 * 32 * 3
hidden_size = 50
num_classes = 10
net = TwoLayerNet(input_size, hidden_size, num_classes)
# Train the network
stats = net.train(X_train, y_train, X_val, y_val,
num_iters=1000, batch_size=200,
learning_rate=1e-4, learning_rate_decay=0.95,
reg=0.25, verbose=True)
# Predict on the validation set
val_acc = (net.predict(X_val) == y_val).mean()
print('Validation accuracy: ', val_acc)
# 繪製損失函數,訓練、驗證集上的準確率
plt.subplot(2, 1, 1)
plt.plot(stats['loss_history'])
plt.title('Loss history')
plt.xlabel('Iteration')
plt.ylabel('Loss')
plt.subplot(2, 1, 2)
plt.plot(stats['train_acc_history'], label='train')
plt.plot(stats['val_acc_history'], label='val')
plt.title('Classification accuracy history')
plt.xlabel('Epoch')
plt.ylabel('Classification accuracy')
plt.legend()
plt.show()
from cs231n.vis_utils import visualize_grid
# 可視化網絡權重
def show_net_weights(net):
W1 = net.params['W1']
W1 = W1.reshape(32, 32, 3, -1).transpose(3, 0, 1, 2)
plt.imshow(visualize_grid(W1, padding=3).astype('uint8'))
plt.gca().axis('off')
plt.show()
show_net_weights(net)
best_net = None # store the best model into this
# 調參
results = {}
best_val = -1
learning_rates = [1e-3, 5e-4]
regularization_strengths = [0.25, 0.5]
input_size = 32 * 32 * 3
hidden_size = 100
num_classes = 10
net = TwoLayerNet(input_size, hidden_size, num_classes)
for learning_rate in learning_rates:
for regularization_strength in regularization_strengths:
net = TwoLayerNet(input_size, hidden_size, num_classes)
loss_hist = net.train(X_train, y_train, X_val, y_val,
num_iters=1000, batch_size=200,
learning_rate=learning_rate, learning_rate_decay=0.95,
reg=regularization_strength, verbose=False)
y_train_pred = net.predict(X_train)
training_accuracy = np.mean(y_train == y_train_pred)
y_val_pred = net.predict(X_val)
validation_accuracy = np.mean(y_val == y_val_pred)
results[(learning_rate, regularization_strength)] = (training_accuracy, validation_accuracy)
if best_val < validation_accuracy:
best_val = validation_accuracy
best_net = net
# 測試集上的精度
test_acc = (best_net.predict(X_test) == y_test).mean()
print('Test accuracy: ', test_acc)
neural_net.py
from __future__ import print_function
from builtins import range
from builtins import object
import numpy as np
import matplotlib.pyplot as plt
from past.builtins import xrange
class TwoLayerNet(object):
"""
A two-layer fully-connected neural network. The net has an input dimension of
N, a hidden layer dimension of H, and performs classification over C classes.
We train the network with a softmax loss function and L2 regularization on the
weight matrices. The network uses a ReLU nonlinearity after the first fully
connected layer.
In other words, the network has the following architecture:
input - fully connected layer - ReLU - fully connected layer - softmax
The outputs of the second fully-connected layer are the scores for each class.
"""
def __init__(self, input_size, hidden_size, output_size, std=1e-4):
"""
Initialize the model. Weights are initialized to small random values and
biases are initialized to zero. Weights and biases are stored in the
variable self.params, which is a dictionary with the following keys:
W1: First layer weights; has shape (D, H)
b1: First layer biases; has shape (H,)
W2: Second layer weights; has shape (H, C)
b2: Second layer biases; has shape (C,)
Inputs:
- input_size: The dimension D of the input data.
- hidden_size: The number of neurons H in the hidden layer.
- output_size: The number of classes C.
"""
self.params = {}
self.params['W1'] = std * np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_size)
self.params['W2'] = std * np.random.randn(hidden_size, output_size)
self.params['b2'] = np.zeros(output_size)
def loss(self, X, y=None, reg=0.0):
"""
Compute the loss and gradients for a two layer fully connected neural
network.
Inputs:
- X: Input data of shape (N, D). Each X[i] is a training sample.
- y: Vector of training labels. y[i] is the label for X[i], and each y[i] is
an integer in the range 0 <= y[i] < C. This parameter is optional; if it
is not passed then we only return scores, and if it is passed then we
instead return the loss and gradients.
- reg: Regularization strength.
Returns:
If y is None, return a matrix scores of shape (N, C) where scores[i, c] is
the score for class c on input X[i].
If y is not None, instead return a tuple of:
- loss: Loss (data loss and regularization loss) for this batch of training
samples.
- grads: Dictionary mapping parameter names to gradients of those parameters
with respect to the loss function; has the same keys as self.params.
"""
# Unpack variables from the params dictionary
W1, b1 = self.params['W1'], self.params['b1']
W2, b2 = self.params['W2'], self.params['b2']
N, D = X.shape
# Compute the forward pass
scores = None
#############################################################################
# TODO: Perform the forward pass, computing the class scores for the input. #
# Store the result in the scores variable, which should be an array of #
# shape (N, C). #
#############################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
z1 = X.dot(W1)+b1
a1 = np.maximum(0, z1)
scores = a1.dot(W2)+b2
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# If the targets are not given then jump out, we're done
if y is None:
return scores
# Compute the loss
loss = None
#############################################################################
# TODO: Finish the forward pass, and compute the loss. This should include #
# both the data loss and L2 regularization for W1 and W2. Store the result #
# in the variable loss, which should be a scalar. Use the Softmax #
# classifier loss. #
#############################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
exp_scores = np.exp(scores-np.max(scores, axis = 1, keepdims = True))
final_scores = exp_scores/np.sum(exp_scores, axis=1, keepdims = True)
loss = np.sum(-np.log(final_scores[np.arange(N),y]))/N
loss += reg*np.sum(np.square(W1))
loss += reg*np.sum(np.square(W2))
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# Backward pass: compute gradients
grads = {}
#############################################################################
# TODO: Compute the backward pass, computing the derivatives of the weights #
# and biases. Store the results in the grads dictionary. For example, #
# grads['W1'] should store the gradient on W1, and be a matrix of same size #
#############################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
dexp_scores = np.ones(exp_scores.shape)/np.sum(exp_scores, axis=1, keepdims = True)
dexp_scores[np.arange(N), y] -= 1/exp_scores[np.arange(N), y]
dexp_scores /= N
dscores = exp_scores*dexp_scores
db2 = np.sum(dscores,axis=0)
dW2 = a1.T.dot(dscores)
da1 = dscores.dot(W2.T)
dz1 = da1
dz1[z1 <= 0] = 0
db1 = np.sum(dz1, axis=0)
dW1 = X.T.dot(dz1)
dW1 += 2*reg*W1
dW2 += 2*reg*W2
grads['W1'] = dW1
grads['b1'] = db1
grads['W2'] = dW2
grads['b2'] = db2
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
return loss, grads
def train(self, X, y, X_val, y_val,
learning_rate=1e-3, learning_rate_decay=0.95,
reg=5e-6, num_iters=100,
batch_size=200, verbose=False):
"""
Train this neural network using stochastic gradient descent.
Inputs:
- X: A numpy array of shape (N, D) giving training data.
- y: A numpy array f shape (N,) giving training labels; y[i] = c means that
X[i] has label c, where 0 <= c < C.
- X_val: A numpy array of shape (N_val, D) giving validation data.
- y_val: A numpy array of shape (N_val,) giving validation labels.
- learning_rate: Scalar giving learning rate for optimization.
- learning_rate_decay: Scalar giving factor used to decay the learning rate
after each epoch.
- reg: Scalar giving regularization strength.
- num_iters: Number of steps to take when optimizing.
- batch_size: Number of training examples to use per step.
- verbose: boolean; if true print progress during optimization.
"""
num_train = X.shape[0]
iterations_per_epoch = max(num_train / batch_size, 1)
# Use SGD to optimize the parameters in self.model
loss_history = []
train_acc_history = []
val_acc_history = []
for it in range(num_iters):
X_batch = None
y_batch = None
#########################################################################
# TODO: Create a random minibatch of training data and labels, storing #
# them in X_batch and y_batch respectively. #
#########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
incides = np.random.choice(num_train,batch_size,replace = True)
X_batch = X[incides]
y_batch = y[incides]
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
# Compute loss and gradients using the current minibatch
loss, grads = self.loss(X_batch, y=y_batch, reg=reg)
loss_history.append(loss)
#########################################################################
# TODO: Use the gradients in the grads dictionary to update the #
# parameters of the network (stored in the dictionary self.params) #
# using stochastic gradient descent. You'll need to use the gradients #
# stored in the grads dictionary defined above. #
#########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
self.params['W1'] -= learning_rate*grads['W1']
self.params['W2'] -= learning_rate*grads['W2']
self.params['b1'] -= learning_rate*grads['b1']
self.params['b2'] -= learning_rate*grads['b2']
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
if verbose and it % 100 == 0:
print('iteration %d / %d: loss %f' % (it, num_iters, loss))
# Every epoch, check train and val accuracy and decay learning rate.
if it % iterations_per_epoch == 0:
# Check accuracy
train_acc = (self.predict(X_batch) == y_batch).mean()
val_acc = (self.predict(X_val) == y_val).mean()
train_acc_history.append(train_acc)
val_acc_history.append(val_acc)
# Decay learning rate
learning_rate *= learning_rate_decay
return {
'loss_history': loss_history,
'train_acc_history': train_acc_history,
'val_acc_history': val_acc_history,
}
def predict(self, X):
"""
Use the trained weights of this two-layer network to predict labels for
data points. For each data point we predict scores for each of the C
classes, and assign each data point to the class with the highest score.
Inputs:
- X: A numpy array of shape (N, D) giving N D-dimensional data points to
classify.
Returns:
- y_pred: A numpy array of shape (N,) giving predicted labels for each of
the elements of X. For all i, y_pred[i] = c means that X[i] is predicted
to have class c, where 0 <= c < C.
"""
y_pred = None
###########################################################################
# TODO: Implement this function; it should be VERY simple! #
###########################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
scores = np.maximum(X.dot(self.params['W1']) + self.params['b1'], 0).dot(self.params['W2']) + self.params['b2']
y_pred = np.argsort(scores,axis = 1)[:,-1]
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
return y_pred