linear_classifier.py
import numpy as np
from cs231n.classifiers.linear_svm import *
from cs231n.classifiers.softmax import * class LinearClassifier(object): def __init__(self):
self.W = None 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. #
#########################################################################
# num_train = 49000 batch_size = 200
mask = np.random.choice(num_train, batch_size, replace=False)
X_batch = X[mask]
y_batch = y[mask]
#########################################################################
# 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 = self.W - learning_rate * grad
#########################################################################
# END OF YOUR CODE #
######################################################################### if verbose and it % 100 == 0:
print 'iteration %d / %d: loss %f' % (it, num_iters, loss) return loss_history def predict(self, X):
"""
Use the trained weights of this linear classifier to predict labels for
data points. Inputs:
- X: D x N array of training data. Each column is a D-dimensional point. 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[1])
###########################################################################
# TODO: #
# Implement this method. Store the predicted labels in y_pred. #
###########################################################################
#49000*3073 * 3073 * 10
y_pred = np.argmax(np.dot(X,self.W), axis=1)
###########################################################################
# END OF YOUR CODE #
###########################################################################
return y_pred def loss(self, X_batch, y_batch, reg):
"""
Compute the loss function and its derivative.
Subclasses will override this. Inputs:
- X_batch: A numpy array of shape (N, D) containing a minibatch of N
data points; each point has dimension D.
- y_batch: A numpy array of shape (N,) containing labels for the minibatch.
- reg: (float) regularization strength. Returns: A tuple containing:
- loss as a single float
- gradient with respect to self.W; an array of the same shape as W
"""
pass class LinearSVM(LinearClassifier):
""" A subclass that uses the Multiclass SVM loss function """ def loss(self, X_batch, y_batch, reg):
return svm_loss_vectorized(self.W, X_batch, y_batch, reg) class Softmax(LinearClassifier):
""" A subclass that uses the Softmax + Cross-entropy loss function """ def loss(self, X_batch, y_batch, reg):
return softmax_loss_vectorized(self.W, X_batch, y_batch, reg)
linear_classifier.py的更多相关文章
- CS231n 2016 通关 第三章-SVM 作业分析
作业内容,完成作业便可熟悉如下内容: cell 1 设置绘图默认参数 # Run some setup code for this notebook. import random import nu ...
- 【cs231n作业笔记】二:SVM分类器
可以参考:cs231n assignment1 SVM 完整代码 231n作业 多类 SVM 的损失函数及其梯度计算(最好)https://blog.csdn.net/NODIECANFLY/ar ...
- CS231n -Assignments 1 Q1 and Q2
前言 最近在youtube 上学习CS231n的课程,并尝试完成Assgnments,收获很多,这里记录下过程和结果以及过程中遇到的问题,我并不是只是完成需要补充的代码段,对于自己不熟悉的没用过的库函 ...
- python调用py中rar的路径问题。
1.python调用py,在py中的os.getcwd()获取的不是py的路径,可以通过os.path.split(os.path.realpath(__file__))[0]来获取py的路径. 2. ...
- Python导入其他文件中的.py文件 即模块
import sys sys.path.append("路径") import .py文件
- import renumber.py in pymol
cp renumber.py /usr/local/lib/python2.7/dist-packages/pymol import renumber or run /path/to/renumber ...
- python gettitle.py
#!/usr/bin/env python # coding=utf-8 import threading import requests import Queue import sys import ...
- 解决 odoo.py: error: option --addons-path: The addons-path 'local-addons/' does not seem to a be a valid Addons Directory!
情况说明 odoo源文件路径-/odoo-dev/odoo/: 我的模块插件路径 ~/odoo-dev/local-addons/my-module 在my-module中创建了__init__.py ...
- caffe机器学习自带图片分类器classify.py实现输出预测结果的概率及caffe的web_demo例子运行实例
caffe机器学习环境搭建及python接口编译参见我的上一篇博客:机器学习caffe环境搭建--redhat7.1和caffe的python接口编译 1.运行caffe图片分类器python接口 还 ...
随机推荐
- 深入struts2.0(七)--ActionInvocation接口以及3DefaultActionInvocation类
1.1.1 ActionInvocation类 ActionInvocation定义为一个接口.主要作用是表现action的运行状态.它拥有拦截器和action的实例.通过重复的运行inv ...
- shell脚本编写-自动部署及监控
1.编写脚本自动部署反向代理.web.nfs: I.部署nginx反向代理两个web服务,调度算法使用加权轮询 II.所有web服务使用共享存储nfs,保证所有web都对其有读写权限,保证数据一致性: ...
- VMware虚拟机下如何安装一个64位的win7系统
原文地址:http://www.xitongcheng.com/jiaocheng/win7_article_21001.html VMware虚拟机软件可以在一台电脑上运行多个操作系统,一些网友想在 ...
- 浅析nodejs的buffer类
1.什么时候该用buffer,什么时候不该用 看一下如下的测试代码,分别是拼接各种不同长度的字符串,最后直接拼接了10MB的字符串 var string,string2,string3; var bu ...
- hdu5296(2015多校1)--Annoying problem(lca+一个公式)
Annoying problem Time Limit: 16000/8000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others ...
- C#文件操作与编程
一:驱动器System.IO 软盘,优盘,光盘,硬盘 DriveInfo/DriveType DriveInfo:确定有关驱动器的信息:盘符,类型,可用空间 DriveType:确定DriveInfo ...
- How to reset your password in Ubuntu
There are many reasons you might want to reset a password: Someone gave you a computer with Ubuntu i ...
- php时间12小时和24小时区别
date('Y-m-d H:i:s',$row1['time']) 大写H为24小时制 小写h为12小时制
- 使用 lstat 函数获取文件信息
前言 在之前的文章中,描述过如何用 fcntl 函数改变文件的状态标记.但,文件还有很多信息,如文件类型,权限设置,设备编号,访问时间等等.如果要获取这些信息,则使用函数 lstat 可以轻松达到这个 ...
- Win32对话框工程笔记
Main.cpp #include <Windows.h> #include "resource.h" INT_PTR CALLBACK dialogProc(HWND ...