您的位置:首页 > 编程语言 > Python开发

[CS231n@Stanford] Assignment1-Q3 (python) Softmax实现

2016-09-07 13:09 507 查看


softmax.py

import numpy as np
from random import shuffle

def softmax_loss_naive(W, X, y, reg):
"""
Softmax 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
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)

#############################################################################
# TODO: Compute the softmax loss and its gradient using explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################

num_classes = W.shape[1]
num_train = X.shape[0]
for i in xrange(num_train):
scores = X[i].dot(W)
shift_scores = scores - max(scores)
loss_i = -shift_scores[y[i]] + np.log(np.sum(np.exp(shift_scores)))
loss += loss_i
for j in xrange(num_classes):
softmax_output = np.exp(shift_scores[j])/np.sum(np.exp(shift_scores))
if j == y[i]:
dW[:,j] += (softmax_output-1) *X[i]
else:
dW[:,j] += softmax_output *X[i]

loss /= num_train
loss += 0.5* reg * np.sum(W * W)
dW = dW/num_train + reg* W

pass
#############################################################################
# END OF YOUR CODE #
#############################################################################

return loss, dW

def softmax_loss_vectorized(W, X, y, reg):
"""
Softmax loss function, vectorized version.

Inputs and outputs are the same as softmax_loss_naive.
"""
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)

#############################################################################
# TODO: Compute the softmax loss and its gradient using no explicit loops. #
# Store the loss in loss and the gradient in dW. If you are not careful #
# here, it is easy to run into numeric instability. Don't forget the #
# regularization! #
#############################################################################

num_classes = W.shape[1]
num_train = X.shape[0]
scores = X.dot(W)
shift_scores = scores - np.max(scores, axis = 1).reshape(-1,1)
softmax_output = np.exp(shift_scores)/np.sum(np.exp(shift_scores), axis = 1).reshape(-1,1)
loss = -np.sum(np.log(softmax_output[np.arange(num_train), y]))
loss /= num_train
loss += 0.5* reg * np.sum(W * W)

softmax_output[np.arange(num_train), y] += -1
dW = (X.T).dot(softmax_output)
dW = dW/num_train + reg* W

pass
#############################################################################
# END OF YOUR CODE #
#############################################################################

return loss, dW


linear_classifier.py 的实现参见:http://blog.csdn.net/zzhangjizhi/article/details/52457278


softmax.ipynb的部分代码实现

# 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 over 0.35 on the validation set.
from linear_classifier import Softmax
results = {}
best_val = -1
best_softmax = None
learning_rates = [1e-7, 5e-7]
regularization_strengths = [5e4, 1e8]

################################################################################
# TODO: #
# Use the validation set to set the learning rate and regularization strength. #
# This should be identical to the validation that you did for the SVM; save #
# the best trained softmax classifer in best_softmax. #
################################################################################

iters = 2000
for lr in learning_rates:
for reg in regularization_strengths:
softmax = Softmax()
softmax.train(X_train, y_train, learning_rate=lr, reg=reg, num_iters=iters)

y_train_pred = softmax.predict(X_train)
acc_train = np.mean(y_train == y_train_pred)

y_val_pred = softmax.predict(X_val)
acc_val = np.mean(y_val == y_val_pred)

results[(lr, reg)] = (acc_train, acc_val)

if best_val < acc_val:
best_val = acc_val
best_softmax = softmax

pass
################################################################################
# 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 5.000000e+04 train accuracy: 0.333633 val accuracy: 0.343000

lr 1.000000e-07 reg 1.000000e+08 train accuracy: 0.100265 val accuracy: 0.087000

lr 5.000000e-07 reg 5.000000e+04 train accuracy: 0.326980 val accuracy: 0.341000

lr 5.000000e-07 reg 1.000000e+08 train accuracy: 0.100265 val accuracy: 0.087000

best validation accuracy achieved during cross-validation: 0.343000

softmax on raw pixels final test set accuracy: 0.348000

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息