CS231N Assignment1 softmax 笔记
- -为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
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 笔记的更多相关文章
- cs231n assignment1 KNN
title: cs231n assignment1 KNN tags: - KNN - cs231n categories: - 机器学习 date: 2019年9月16日 17:03:13 利用KN ...
- 笔记:CS231n+assignment1(作业一)
CS231n的课后作业非常的好,这里记录一下自己对作业一些笔记. 一.第一个是KNN的代码,这里的trick是计算距离的三种方法,核心的话还是python和machine learning中非常实用的 ...
- 【cs231n】神经网络笔记笔记2
) # 对数据进行零中心化(重要) cov = np.dot(X.T, X) / X.shape[0] # 得到数据的协方差矩阵 数据协方差矩阵的第(i, j)个元素是数据第i个和第j个维度的协方差. ...
- 【cs231n】最优化笔记
): W = np.random.randn(10, 3073) * 0.0001 # generate random parameters loss = L(X_train, Y_train, W) ...
- cs231n官方note笔记
本文记录官方note中比较新颖和有价值的观点(从反向传播开始) 一 反向传播 1 “反向传播是一个优美的局部过程.在整个计算线路图中,每个门单元都会得到一些输入并立即计算两个东西:1. 这个门的输出值 ...
- [基础]斯坦福cs231n课程视频笔记(三) 训练神经网络
目录 training Neural Network Activation function sigmoid ReLU Preprocessing Batch Normalization 权重初始化 ...
- 【Python 代码】CS231n中Softmax线性分类器、非线性分类器对比举例(含python绘图显示结果)
1 #CS231n中线性.非线性分类器举例(Softmax) #注意其中反向传播的计算 # -*- coding: utf-8 -*- import numpy as np import matplo ...
- CS231n 2017 学习笔记01——KNN(K-Nearest Neighbors)
本博客内容来自 Stanford University CS231N 2017 Lecture 2 - Image Classification 课程官网:http://cs231n.stanford ...
- 【cs231n】图像分类笔记
前言 首先声明,以下内容绝大部分转自知乎智能单元,他们将官方学习笔记进行了很专业的翻译,在此我会直接copy他们翻译的笔记,有些地方会用红字写自己的笔记,本文只是作为自己的学习笔记.本文内容官网链接: ...
- [基础]斯坦福cs231n课程视频笔记(一) 图片分类之使用线性分类器
线性分类器的基本模型: f = Wx Loss Function and Optimization 1. LossFunction 衡量在当前的模型(参数矩阵W)的效果好坏 Multiclass SV ...
随机推荐
- 手把手教你写一个spring IOC容器
摘要:spring框架的基础核心和起点毫无疑问就是IOC,IOC作为spring容器提供的核心技术,成功完成了依赖的反转:从主类的对依赖的主动管理反转为了spring容器对依赖的全局控制.今天就带大家 ...
- 打破“双十定律”,华为云AI推动超级抗菌药Drug X研发加速
摘要:学科交叉已经逐渐变成了科技创新的一个主要源泉,成为这个科学时代一个不可替代的研究范式.在科技与技术合力赋能之下,中国科研人创新奋斗再出新成果,人类与病菌的博弈因此有了新武器. 本文分享自华为云社 ...
- 列举GaussDB(DWS)常见的查询时索引失效场景
摘要:使用GaussDB(DWS)时,有时为了加快查询速度,需要对表建立索引.有时我们会遇到明明建立了索引,查询计划中却发现索引没有被使用的情况.本文将列举几种常见的场景和优化方法. 本文分享自华为云 ...
- ITS实现可滚动表格
一.ITS不支持TableControl 在ITS条码开发中,遇到需要滚动浏览表格的需求,但是在ITS中是不支持TableControl,并且已经验证在PDA中显示ALV行不通,因为ALV条目过多无法 ...
- .net 温故知新【17】:Asp.Net Core WebAPI 中间件
一.前言 到这篇文章为止,关于.NET "温故知新"系列的基础知识就完结了,从这一系列的系统回顾和再学习,对于.NET core.ASP.NET CORE又有了一个新的认识. 不光 ...
- #1016:Prime Ring Problem(经典DFS)
原题链接 题意:很容易理解,就是让你输出满足相邻的相加是素数的序列(注意不要重复) 思路就是深搜思想把每种情况遍历一次 代码实现: #include<iostream> #include& ...
- AtCoder ABC 165 D - Floor Function (Good, 手动模拟推出公式)
题目链接:Here 题意: 给出正整数 \(A,B,N (1\le A\le 1e6,1\le B,N\le1e12)\) ,对于 \(x\in [0,N]\) 求出 \(\left\lfloor\f ...
- Canvas实现画布的缩放
主要介绍三种方式: 首先创建一个index.html文件 <!DOCTYPE html> <html lang="en"> <head> < ...
- freeswitch上报信令到HOMER的配置方案
概述 HOMER是一款100%开源的针对SIP/VOIP/RTC的抓包工具和监控工具. 之前的文章中,我们介绍了HOMER的安装步骤,HOMER7的安装部署还是比较简单的,安装过程也比较顺利. 然后, ...
- Postman 接口测试配置 Pre-request Script
本文为博主原创,转载请注明出处: Pre-request Script 为Postman预置脚本,用于在postman 发送请求之前执行,封装计算或获取某些请求参数. 1. postman 脚本提供 ...





