加载数据集
# Load the raw CIFAR-10 data.
cifar10_dir = 'cs231n/datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = load_CIFAR10(cifar10_dir)
# As a sanity check, we print out the size of the training and test data.
print('Training data shape: ', X_train.shape)
print('Training labels shape: ', y_train.shape)
print('Test data shape: ', X_test.shape)
print('Test labels shape: ', y_test.shape)
结果:
Training data shape: (50000, 32, 32, 3)
Training labels shape: (50000,)
Test data shape: (10000, 32, 32, 3)
Test labels shape: (10000,)
分割数据集
# Split the data into train, val, and test sets. In addition we will
# create a small development set as a subset of the training data;
# we can use this for development so our code runs faster.
num_training = 49000
num_validation = 1000
num_test = 1000
num_dev = 500
# Our validation set will be num_validation points from the original
# training set.
mask = range(num_training, num_training + num_validation)
X_val = X_train[mask]
y_val = y_train[mask]
#
# Our training set will be the first num_train points from the original
# training set.
mask = range(num_training)
X_train = X_train[mask]
y_train = y_train[mask]
# We will also make a development set, which is a small subset of
# the training set.
mask = np.random.choice(num_training, num_dev, replace=False)
X_dev = X_train[mask]
y_dev = y_train[mask]
# We use the first num_test points of the original test set as our
# test set.
mask = range(num_test)
X_test = X_test[mask]
y_test = y_test[mask]
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)
结果:
Train data shape: (49000, 32, 32, 3)
Train labels shape: (49000,)
Validation data shape: (1000, 32, 32, 3)
Validation labels shape: (1000,)
Test data shape: (1000, 32, 32, 3)
Test labels shape: (1000,)
将32323展开成3072*1
# Preprocessing: reshape the image data into rows
X_train = np.reshape(X_train, (X_train.shape[0], -1))
X_val = np.reshape(X_val, (X_val.shape[0], -1))
X_test = np.reshape(X_test, (X_test.shape[0], -1))
X_dev = np.reshape(X_dev, (X_dev.shape[0], -1))
# As a sanity check, print out the shapes of the data
print('Training data shape: ', X_train.shape)
print('Validation data shape: ', X_val.shape)
print('Test data shape: ', X_test.shape)
print('dev data shape: ', X_dev.shape)
结果:
Training data shape: (49000, 3072)
Validation data shape: (1000, 3072)
Test data shape: (1000, 3072)
dev data shape: (500, 3072)
接下来对图像数据进行中心化操作,这里不再赘述。
naive implementation of the loss
def svm_loss_naive(W, X, y, reg):
"""
Structured SVM loss function, naive implementation (with loops).
Inputs have dimension D, there are C classes, and we operate on minibatches
of N examples.
Inputs:
- W: A numpy array of shape (D, C) containing weights.
- X: A numpy array of shape (N, D) containing a minibatch of data.
- y: A numpy array of shape (N,) containing training labels; y[i] = c means
that X[i] has label c, where 0 <= c < C.
- reg: (float) regularization strength
Returns a tuple of:
- loss as single float
- gradient with respect to weights W; an array of same shape as W
"""
dW = np.zeros(W.shape) # initialize the gradient as zero
# compute the loss and the gradient
num_classes = W.shape[1]
num_train = X.shape[0]
loss = 0.0
for i in xrange(num_train):
scores = X[i].dot(W)
correct_class_score = scores[y[i]] # 选取正确的分数
for j in xrange(num_classes):
if j == y[i]:
continue
margin = scores[j] - correct_class_score + 1 # note delta = 1
if margin > 0:
loss += margin
dW[:,y[i]] += -X[i,:].T
dW[:,j] += X[i,:].T
# Right now the loss is a sum over all training examples, but we want it
# to be an average instead so we divide by num_train.
loss /= num_train
# Add regularization to the loss.
loss += reg * np.sum(W * W)
dW /= num_train
dW += reg * W
#############################################################################
# TODO: #
# Compute the gradient of the loss function and store it dW. #
# Rather that first computing the loss and then computing the derivative, #
# it may be simpler to compute the derivative at the same time that the #
# loss is being computed. As a result you may need to modify some of the #
# code above to compute the gradient. #
#############################################################################
return loss, dW
检查numeric gradient
和analytic gradient
是否相同,结果如下:
numerical: -21.154820 analytic: -21.154820, relative error: 2.156955e-11
numerical: -15.646956 analytic: -15.646956, relative error: 1.701945e-12
numerical: -12.570585 analytic: -12.570585, relative error: 1.765923e-11
numerical: 1.132944 analytic: 1.132944, relative error: 1.340921e-10
numerical: 6.988271 analytic: 6.988271, relative error: 4.883998e-11
numerical: -5.636565 analytic: -5.636565, relative error: 3.185107e-11
numerical: -19.290815 analytic: -19.290815, relative error: 1.324725e-11
numerical: -39.458206 analytic: -39.458206, relative error: 1.499212e-12
numerical: 29.654785 analytic: 29.654785, relative error: 7.468480e-12
numerical: 8.850677 analytic: 8.850677, relative error: 1.820948e-11
numerical: -1.873331 analytic: -1.869115, relative error: 1.126408e-03
numerical: -11.970316 analytic: -11.965054, relative error: 2.198217e-04
numerical: 27.541778 analytic: 27.547150, relative error: 9.752253e-05
numerical: -13.284015 analytic: -13.294164, relative error: 3.818578e-04
numerical: 17.315594 analytic: 17.306512, relative error: 2.622948e-04
numerical: -11.626487 analytic: -11.632282, relative error: 2.491471e-04
numerical: 44.386078 analytic: 44.385843, relative error: 2.647647e-06
numerical: -15.492639 analytic: -15.492624, relative error: 5.021475e-07
numerical: -19.645482 analytic: -19.651773, relative error: 1.600740e-04
numerical: 7.485944 analytic: 7.491883, relative error: 3.965264e-04
Inline Question 1
It is possible that once in a while a dimension in the gradcheck will not match exactly. What could such a discrepancy be caused by? Is it a reason for concern? What is a simple example in one dimension where a gradient check could fail? Hint: the SVM loss function is not strictly speaking differentiable
Your Answer: Maybe because SVM loss function is not strictly speaking differentiable. At original point(0,0), the funtion is not differentiable, so the gradient check could fail.
svm_loss_vectorized
def svm_loss_vectorized(W, X, y, reg):
"""
Structured SVM loss function, vectorized implementation.
Inputs and outputs are the same as svm_loss_naive.
"""
loss = 0.0
dW = np.zeros(W.shape) # initialize the gradient as zero
#############################################################################
# TODO: #
# Implement a vectorized version of the structured SVM loss, storing the #
# result in loss. #
#############################################################################
num_train = X.shape[0]
scores = X.dot(W)
correct_scores = scores[np.arange(num_train), y]
# 一行五百个(500,)
# arrange生成一个0-num_train的序列,步长为1
correct_scores = np.reshape(correct_scores, (num_train, -1))
# (500,1)
margins = scores - correct_scores + 1
margins = np.maximum(0, margins)
margins[range(num_train), y] = 0
loss += np.sum(margins) / num_train
loss += reg * np.sum(W * W)
#############################################################################
# END OF YOUR CODE #
#############################################################################
#############################################################################
# TODO: #
# Implement a vectorized version of the gradient for the structured SVM #
# loss, storing the result in dW. #
# #
# Hint: Instead of computing the gradient from scratch, it may be easier #
# to reuse some of the intermediate values that you used to compute the #
# loss. #
#############################################################################
margins[margins > 0] = 1
row_sum = np.sum(margins, axis = 1)
print(row_sum)
margins[np.arange(num_train), y] = -row_sum.T
# 只有对应位的被设成-9之类的,其余还是1
print(margins)
dW = np.dot(X.T, margins)
dW /= num_train
dW += reg * W
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, dW
结果:
Naive loss: 9.101681e+00 computed in 0.174625s
(500,)
(500, 1)
Vectorized loss: 9.101681e+00 computed in 0.000000s
difference: -0.000000
Stochastic Gradient Descent
def train(self, X, y, learning_rate=1e-3, reg=1e-5, num_iters=100,
batch_size=200, verbose=False):
"""
Train this linear classifier using stochastic gradient descent.
用随机梯度下降法训练
Inputs:
- X: A numpy array of shape (N, D) containing training data; there are N
training samples each of dimension D.
- y: A numpy array of shape (N,) containing training labels; y[i] = c
means that X[i] has label 0 <= c < C for C classes.
- learning_rate: (float) learning rate for optimization.
- reg: (float) regularization strength.
- num_iters: (integer) number of steps to take when optimizing
- batch_size: (integer) number of training examples to use at each step.
- verbose: (boolean) If true, print progress during optimization.
Outputs:
A list containing the value of the loss function at each training iteration.
"""
num_train, dim = X.shape
num_classes = np.max(y) + 1 # assume y takes values 0...K-1 where K is number of classes
# 种类
if self.W is None:
# lazily initialize W
self.W = 0.001 * np.random.randn(dim, num_classes)
# Run stochastic gradient descent to optimize W
loss_history = []
for it in xrange(num_iters):
X_batch = None
y_batch = None
#########################################################################
# TODO: #
# Sample batch_size elements from the training data and their #
# corresponding labels to use in this round of gradient descent. #
# Store the data in X_batch and their corresponding labels in #
# y_batch; after sampling X_batch should have shape (dim, batch_size) #
# and y_batch should have shape (batch_size,) #
# #
# Hint: Use np.random.choice to generate indices. Sampling with #
# replacement is faster than sampling without replacement. #
#########################################################################
index = np.random.choice(num_train, batch_size)
X_batch = X[index,:]
y_batch = y[index]
#########################################################################
# END OF YOUR CODE #
#########################################################################
# evaluate loss and gradient
loss, grad = self.loss(X_batch, y_batch, reg)
loss_history.append(loss)
# perform parameter update
#########################################################################
# TODO: #
# Update the weights using the gradient and the learning rate. #
#########################################################################
self.W += -grad*learning_rate
#########################################################################
# END OF YOUR CODE #
#########################################################################
if verbose and it % 100 == 0:
print('iteration %d / %d: loss %f' % (it, num_iters, loss))
return loss_history
loss图:
predict function
def predict(self, X):
"""
Use the trained weights of this linear classifier to predict labels for
data points.
Inputs:
- X: A numpy array of shape (N, D) containing training data; there are N
training samples each of dimension D.
Returns:
- y_pred: Predicted labels for the data in X. y_pred is a 1-dimensional
array of length N, and each element is an integer giving the predicted
class.
"""
y_pred = np.zeros(X.shape[0])
###########################################################################
# TODO: #
# Implement this method. Store the predicted labels in y_pred. #
###########################################################################
y_pred = np.argmax(X.dot(self.W),axis= 1)
# argmax返回数组a中最大数的索引
###########################################################################
# END OF YOUR CODE #
###########################################################################
return y_pred
结果:
training accuracy: 0.384122
validation accuracy: 0.382000
选择最好的超参数
# Use the validation set to tune hyperparameters (regularization strength and
# learning rate). You should experiment with different ranges for the learning
# rates and regularization strengths; if you are careful you should be able to
# get a classification accuracy of about 0.4 on the validation set.
learning_rates = [1e-7, 5e-5]
regularization_strengths = [2.5e4, 5e4]
# results is dictionary mapping tuples of the form
# (learning_rate, regularization_strength) to tuples of the form
# (training_accuracy, validation_accuracy). The accuracy is simply the fraction
# of data points that are correctly classified.
results = {}
best_val = -1 # The highest validation accuracy that we have seen so far.
best_svm = None # The LinearSVM object that achieved the highest validation rate.
################################################################################
# TODO: #
# Write code that chooses the best hyperparameters by tuning on the validation #
# set. For each combination of hyperparameters, train a linear SVM on the #
# training set, compute its accuracy on the training and validation sets, and #
# store these numbers in the results dictionary. In addition, store the best #
# validation accuracy in best_val and the LinearSVM object that achieves this #
# accuracy in best_svm. #
# #
# Hint: You should use a small value for num_iters as you develop your #
# validation code so that the SVMs don't take much time to train; once you are #
# confident that your validation code works, you should rerun the validation #
# code with a larger value for num_iters. #
################################################################################
# 提示:num_iters先用较小的值,这样可以不用花太多时间在训练上,一旦确定了组合是奏效的,再调高num_iters的值
for learning_rate in learning_rates:
for regularization_strength in regularization_strengths:
svm = LinearSVM()
loss_hist = svm.train(X_train, y_train, learning_rate = learning_rate, reg = regularization_strength,
num_iters = 1500, verbose=True)
y_train_pred = svm.predict(X_train)
train_accuracy = np.mean(y_train_pred == y_train)
y_val_pred = svm.predict(X_val)
val_accuracy = np.mean(y_val == y_val_pred)
results[(learning_rate, regularization_strength)] = [train_accuracy, val_accuracy]
if val_accuracy > best_val:
best_val = val_accuracy
best_svm = svm
################################################################################
# END OF YOUR CODE #
################################################################################
# Print out results.
for lr, reg in sorted(results):
train_accuracy, val_accuracy = results[(lr, reg)]
print('lr %e reg %e train accuracy: %f val accuracy: %f' % (
lr, reg, train_accuracy, val_accuracy))
print('best validation accuracy achieved during cross-validation: %f' % best_val)
结果:
lr 1.000000e-07 reg 2.500000e+04 train accuracy: 0.382837 val accuracy: 0.381000
lr 1.000000e-07 reg 5.000000e+04 train accuracy: 0.368592 val accuracy: 0.380000
lr 5.000000e-05 reg 2.500000e+04 train accuracy: 0.144918 val accuracy: 0.130000
lr 5.000000e-05 reg 5.000000e+04 train accuracy: 0.058224 val accuracy: 0.075000
best validation accuracy achieved during cross-validation: 0.381000
画图结果:
最好的超参在测试集上的结果为:
linear SVM on raw pixels final test set accuracy: 0.370000
观察learned weights
Inline question 2:
Describe what your visualized SVM weights look like, and offer a brief explanation for why they look they way that they do.
Your answer: :They look like obsure signals, which is because they learned all the pitures in the data set.