python分类器svm_SVM分类器python实现

本作业的目标如下:

implement a fully-vectorized loss function for the SVM

implement the fully-vectorized expression for its analytic gradient

check your implementation using numerical gradient

use a validation set to tune the learning rate and regularization strength

optimize the loss function with SGD

visualize the final learned weights

归一化图片

mean_image = np.mean(X_train, axis=0)

print mean_image[:10] # print a few of the elements

plt.figure(figsize=(4,4))

plt.imshow(mean_image.reshape((32,32,3)).astype('uint8')) # visualize the mean image

plt.show()

X_train -= mean_image

X_val -= mean_image

X_test -= mean_image

X_dev -= mean_image

损失函数与梯度计算

def svm_loss_naive(W, X, y, reg):

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, :] # compute the correct_class gradients

dW[:, j] += X[i, :] # compute the wrong_class gradients

# 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

dW /= num_train

dW += 2 * reg * W

# Add regularization to the loss.

loss += 0.5 * reg

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值