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的更多相关文章

  1. CS231n 2016 通关 第三章-SVM 作业分析

    作业内容,完成作业便可熟悉如下内容: cell 1  设置绘图默认参数 # Run some setup code for this notebook. import random import nu ...

  2. 【cs231n作业笔记】二:SVM分类器

    可以参考:cs231n assignment1 SVM 完整代码 231n作业   多类 SVM 的损失函数及其梯度计算(最好)https://blog.csdn.net/NODIECANFLY/ar ...

  3. CS231n -Assignments 1 Q1 and Q2

    前言 最近在youtube 上学习CS231n的课程,并尝试完成Assgnments,收获很多,这里记录下过程和结果以及过程中遇到的问题,我并不是只是完成需要补充的代码段,对于自己不熟悉的没用过的库函 ...

  4. python调用py中rar的路径问题。

    1.python调用py,在py中的os.getcwd()获取的不是py的路径,可以通过os.path.split(os.path.realpath(__file__))[0]来获取py的路径. 2. ...

  5. Python导入其他文件中的.py文件 即模块

    import sys sys.path.append("路径") import .py文件

  6. import renumber.py in pymol

    cp renumber.py /usr/local/lib/python2.7/dist-packages/pymol import renumber or run /path/to/renumber ...

  7. python gettitle.py

    #!/usr/bin/env python # coding=utf-8 import threading import requests import Queue import sys import ...

  8. 解决 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 ...

  9. caffe机器学习自带图片分类器classify.py实现输出预测结果的概率及caffe的web_demo例子运行实例

    caffe机器学习环境搭建及python接口编译参见我的上一篇博客:机器学习caffe环境搭建--redhat7.1和caffe的python接口编译 1.运行caffe图片分类器python接口 还 ...

随机推荐

  1. 以goroutine为例看协程的相关概念

    转自  http://wangzhezhe.github.io/blog/2016/02/17/golang-scheduler/ 基本上是网上相关文章的梳理,初衷主要是想了解下golang中的gor ...

  2. Net is as typeof 运行运算符详解 net 自定义泛型那点事

    Net is as typeof 运行运算符详解   概述 在了解运行运算符的前提我们需要了解什么是RTTI ,在任何一门面向对象的语言中,都有RTTI这个概念(即 运行时). RTTI(Run-Ti ...

  3. 【每日Scrum】第三天(4.24) TD学生助手Sprint2站立会议

    站立会议 组员 昨天 今天 困难 签到 刘铸辉 (组长) 今天主要看了多事件处理的内容然后改了下界面, 和小楠重写架构,使代码更加简洁,并增加了几个界面 架构太难,数据库字段总出问题 Y 刘静 添加事 ...

  4. linux之return和exit引发的大问题(vfork和fork)

    在coolshell.cn上看到的一个问题.为此拿来研究一下. 首先 看看return和exit的差别 在linux上分别跑一下这个代码 int main() { return 0; //exit(0 ...

  5. 为公司做crm资产管理

    一.实现会议室预定 二.实现调查问卷 三.项目背景初始化分析 四.简单的登陆注册 五.学生管理 六.老师管理 七.销售管理 八.客户关系管理 九.抢单管理 十.微信发消息发邮件管理 补充:数据表设计. ...

  6. mysql 数据类型+约束+关联

    1.什么是存储引擎存储引擎就是表的类型,针对不同的存储引擎,mysql会有不同的处理逻辑 2.存储引擎介绍InnoDB| DEFAULT | Supports transactions, row-le ...

  7. mysql判断是否等于某个值

    需要在其后面加.toString()方法,其中 flag为字符串类型

  8. EasyDarwin开源流媒体服务器实现RTSP直播同步输出MP4、RTMP、HLS的方案思路

    背景 近期跟开源团队商量,想在EasyDarwin上继续做一些功能扩展,目前EasyDarwin开源流媒体服务器只能够实现高效的RTSP推流直播转发/分发功能,输入与输出都是RTSP/RTP流,不能够 ...

  9. EasyIPCamera通过RTSP协议接入海康、大华等摄像机,摒弃私有SDK接入弊端

    本文转自博客:http://blog.csdn.net/xinlanbobo/article/details/53156742 近期工作中需要开发一套视频监控系统,实现WEB端.手机APP端预览局域网 ...

  10. Ubuntu Firefox没有声音的解决方案

    安装ubuntu-restricted-extras sudo apt-get install ubuntu-restricted-extras 参考博文:解决ubuntu中firefox没有声音的问 ...