• -为Softmax分类器实现完全矢量化的损失函数
  • -实现解析梯度完全矢量化的表达式
  • 使用数值梯度检查实现结果
  • 使用验证集调整学习率和正则化强度
  • 使用SGD优化损失函数
  • 可视化最终学习的权重

softmax.ipynb

库、绘图设置和数据的导入和SVM一样

Train data shape:  (49000, 3073)
Train labels shape: (49000,)
Validation data shape: (1000, 3073)
Validation labels shape: (1000,)
Test data shape: (1000, 3073)
Test labels shape: (1000,)
dev data shape: (500, 3073)
dev labels shape: (500,)

Softmax Classifier

 `cs231n/classifiers/softmax.py`
首先完成带嵌套循环的softmax_loss_naive
def softmax_loss_naive(W, X, y, reg):
# Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W) #创建一个与W具有相同形状的全零数组。 N = X.shape[0]
for i in range(N):
score = X[i].dot(W) #长度为C?
exp_score = np.exp(score - np.max(score)) #防止溢出
loss += -np.log(exp_score[y[i]]/np.sum(exp_score)) / N #复刻公式
#loss += (-np.log(exp_score[y[i]])+ np.log(np.sum(exp_score))) / N #展开
dexp_score = np.zeros_like(exp_score)
dexp_score[y[i]] -= 1/exp_score[y[i]]/N
dexp_score += 1 /np.sum(exp_score) / N
dscore = dexp_score *exp_score
dW += X[[i]].T.dot([dscore])
loss +=reg*np.sum(W**2)
dW += 2*reg*W
# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** return loss, dW

注意使用exp避免数值溢出之后要用本地梯度乘上游梯度得到梯度值。

向量化的softmax_loss_vectorized

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

    # Initialize the loss and gradient to zero.
loss = 0.0
dW = np.zeros_like(W)
# scores = X.dot(W)
#exp_score = np.exp(score - np.max(score))
scores -= np.max(scores, axis=1, keepdims=True)#保持dim
exp_scores = np.exp(scores) probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # Compute the loss
N = X.shape[0] #有点不熟悉这个维度012的顺序
loss = np.sum(-np.log(probs[np.arange(N), y])) / N
loss += reg * np.sum(W * W) #正则化强度的系数其实无所谓?只要不太小应该效果都差不多 # Compute the gradient
dscores = probs
dscores[np.arange(N), y] -= 1
dscores /= N dW = X.T.dot(dscores)
dW += reg * W return loss, dW

超参数调试

# 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 cs231n.classifiers import Softmax
results = {}
best_val = -1
best_softmax = None ################################################################################
# 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. #
################################################################################ # Provided as a reference. You may or may not want to change these hyperparameters
learning_rates = [3e-7,4e-7,5e-7]
regularization_strengths = [0.5e4, 1e4,1.5e4,2e4] # *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # Iterate over all hyperparameter combinations
for lr in learning_rates:
for reg in regularization_strengths:
# Create a new Softmax classifier
softmax = Softmax() # Train the classifier on the training set
softmax.train(X_train, y_train, learning_rate=lr, reg=reg, num_iters=1000) # Evaluate the classifier on the training and validation sets
train_accuracy = np.mean(softmax.predict(X_train) == y_train)
val_accuracy = np.mean(softmax.predict(X_val) == y_val) # Save the results for this hyperparameter combination
results[(lr, reg)] = (train_accuracy, val_accuracy) # Update the best validation accuracy and best classifier
if val_accuracy > best_val:
best_val = val_accuracy
best_softmax = softmax # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)***** # 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 5.000000e-07 reg 5.000000e+03 train accuracy: 0.386000 val accuracy: 0.392000

最后看看在test上的准确率

# evaluate on test set
# Evaluate the best softmax on test set
y_test_pred = best_softmax.predict(X_test)
test_accuracy = np.mean(y_test == y_test_pred)
print('softmax on raw pixels final test set accuracy: %f' % (test_accuracy, ))
softmax on raw pixels final test set accuracy: 0.384000

对比一下不同步数的权重图像差异

100 500 1000

1500 3000 5000

(多整了一些)噪点的减少还是非常明显的,虽然1500之后准确率没太大区别

CS231N Assignment1 softmax 笔记的更多相关文章

  1. cs231n assignment1 KNN

    title: cs231n assignment1 KNN tags: - KNN - cs231n categories: - 机器学习 date: 2019年9月16日 17:03:13 利用KN ...

  2. 笔记:CS231n+assignment1(作业一)

    CS231n的课后作业非常的好,这里记录一下自己对作业一些笔记. 一.第一个是KNN的代码,这里的trick是计算距离的三种方法,核心的话还是python和machine learning中非常实用的 ...

  3. 【cs231n】神经网络笔记笔记2

    ) # 对数据进行零中心化(重要) cov = np.dot(X.T, X) / X.shape[0] # 得到数据的协方差矩阵 数据协方差矩阵的第(i, j)个元素是数据第i个和第j个维度的协方差. ...

  4. 【cs231n】最优化笔记

    ): W = np.random.randn(10, 3073) * 0.0001 # generate random parameters loss = L(X_train, Y_train, W) ...

  5. cs231n官方note笔记

    本文记录官方note中比较新颖和有价值的观点(从反向传播开始) 一 反向传播 1 “反向传播是一个优美的局部过程.在整个计算线路图中,每个门单元都会得到一些输入并立即计算两个东西:1. 这个门的输出值 ...

  6. [基础]斯坦福cs231n课程视频笔记(三) 训练神经网络

    目录 training Neural Network Activation function sigmoid ReLU Preprocessing Batch Normalization 权重初始化 ...

  7. 【Python 代码】CS231n中Softmax线性分类器、非线性分类器对比举例(含python绘图显示结果)

    1 #CS231n中线性.非线性分类器举例(Softmax) #注意其中反向传播的计算 # -*- coding: utf-8 -*- import numpy as np import matplo ...

  8. CS231n 2017 学习笔记01——KNN(K-Nearest Neighbors)

    本博客内容来自 Stanford University CS231N 2017 Lecture 2 - Image Classification 课程官网:http://cs231n.stanford ...

  9. 【cs231n】图像分类笔记

    前言 首先声明,以下内容绝大部分转自知乎智能单元,他们将官方学习笔记进行了很专业的翻译,在此我会直接copy他们翻译的笔记,有些地方会用红字写自己的笔记,本文只是作为自己的学习笔记.本文内容官网链接: ...

  10. [基础]斯坦福cs231n课程视频笔记(一) 图片分类之使用线性分类器

    线性分类器的基本模型: f = Wx Loss Function and Optimization 1. LossFunction 衡量在当前的模型(参数矩阵W)的效果好坏 Multiclass SV ...

随机推荐

  1. 六一儿童节,看我用ModelArts让8090梦回童年

    [本期推荐] 8岁小朋友的儿童节,有点硬核,一起来认识这些小小程序员,看他们如何coding出一个与众不同的童年. 摘要: 如果还能再过一次儿童节-- 本文分享自华为云社区<"梦回童年 ...

  2. ​五大不良 coding 习惯,你占了几样?

    在之前的文章中,我们一起解读了2021年数据成本报告.根据 IBM 和 Ponemon Institute 2021年的报告,全球平均数据泄露成本约为424万美元.为了降低数据泄露造成的成本,企业可以 ...

  3. SpringBoot Docker 发布

    本文是手动模式,可以移步 Intellij IDEA 集成 Docker 发布 使用 Intellij 集成Docker 发布,比较方便 pom 文件 <groupId>com.vipso ...

  4. Flink异步IO

    本文讲解 Flink 用于访问外部数据存储的异步 I/O API. 对于不熟悉异步或者事件驱动编程的用户,建议先储备一些关于 Future 和事件驱动编程的知识. 对于异步 I/O 操作的需求 在与外 ...

  5. ChatGpt玩法(一):prompt使用的重要性

    前言 登录https://www.topgpt.one即可免费体验ChatGPT带来的强大魅力. ChatGpt是一个强大的自然语言处理工具,可以用于多种任务,如文本生成.问答系统以及对话生成等等.其 ...

  6. 【邀请有礼】全球视频云创新挑战赛邀请有礼:参与 100% 获得 “壕” 礼,更有机会获得 JBL 音箱、Cherry 机械键盘

    活动背景: 2021 年首届全球视频云创新挑战赛报名火热进行中,这里奖金池高达四十万,有业界顶尖专家指导,有展示自我技能的广阔舞台,还有入职阿里的绿色招聘通道.如果你有一点点心动,那请不要错过这场挑战 ...

  7. SELinux 入门 pt.2

    哈喽大家好,我是咸鱼 在<SELinux 入门 pt.1>中,咸鱼向各位小伙伴介绍了 SELinux 所使用的 MAC 模型.以及几个重要的概念(主体.目标.策略.安全上下文) 我们还讲到 ...

  8. 【C++第三方库】Windows下编译和使用 WebSocket++/WebSocketpp

    应用场景: 使用C++开发一个支持websocket协议的服务进程,可与HTML5(浏览器js文件)通信.来实现替换基于firebreath框架的跨浏览器插件开发. 当前,讲述websocketpp开 ...

  9. Codeforces Round #734 (Div. 3) A~D1 个人题解

    比赛链接:Here 1551A. Polycarp and Coins (签到) 题意: 我们有任意个面额为 \(1\) 和 \(2\) 的硬币去支付 \(n\) 元账单, 现在请问怎么去分配数额使得 ...

  10. 【网摘】SQL练习题

    原文链接:Here