Softmax回归(使用theano)
# coding:utf8
import numpy as np
import cPickle
import theano
import os
import theano.tensor as T class SoftMax:
def __init__(self,MAXT=50,step=0.15,landa=0):
self.MAXT = MAXT
self.step = step
self.landa = landa #在此权重衰减项未能提升正确率 def load_theta(self,datapath):
self.theta = cPickle.load(open(datapath,'rb')) def process_train(self,data,label,typenum,batch_size=500):
valuenum=data.shape[1]
batches = data.shape[0] / batch_size
data = theano.shared(np.asarray(data,dtype=theano.config.floatX))
label = T.cast(theano.shared(np.asarray(label,dtype=theano.config.floatX)), 'int32')
x = T.matrix('x')
y = T.ivector('y')
index = T.lscalar()
theta = theano.shared(value=0.001*np.zeros((valuenum,typenum),
dtype=theano.config.floatX),
name='theta',borrow=True)
hx=T.nnet.softmax(T.dot(x,theta))
cost = -T.mean(T.log(hx)[T.arange(y.shape[0]), y]) +0.5*self.landa*T.sum(theta ** 2) #权重衰减项
g_theta = T.grad(cost, theta)
updates = [(theta, theta - self.step * g_theta)]
train_model = theano.function(
inputs=[index],outputs=cost,updates=updates,givens={
x: data[index * batch_size: (index + 1) * batch_size],
y: label[index * batch_size: (index + 1) * batch_size]
},allow_input_downcast=True
)
lastcostJ = np.inf
stop = False
epoch = 0
costj=[]
while (epoch < self.MAXT) and (not stop):
epoch = epoch + 1
for minibatch_index in xrange(batches):
costj.append(train_model(minibatch_index))
if np.mean(costj)>=lastcostJ:
print "costJ is increasing !!!"
stop=True
else:
lastcostJ=np.mean(costj)
print(( 'epoch %i, minibatch %i/%i,averange cost is %f') %
(epoch,minibatch_index + 1,batches,lastcostJ))
self.theta=theta
if not os.path.exists('data/softmax.pkl'):
f= open("data/softmax.pkl",'wb')
cPickle.dump(self.theta.get_value(),f)
f.close()
return self.theta.get_value() def process_test(self,data,label,batch_size=500):
batches = label.shape[0] / batch_size
data = theano.shared(np.asarray(data,dtype=theano.config.floatX))
label = T.cast(theano.shared(np.asarray(label,dtype=theano.config.floatX)), 'int32')
x = T.matrix('x')
y = T.ivector('y')
index = T.lscalar()
hx=T.nnet.softmax(T.dot(x,self.theta))
predict = T.argmax(hx, axis=1)
errors=T.mean(T.neq(predict, y))
test_model = theano.function(
inputs=[index],outputs=errors,givens={
x: data[index * batch_size: (index + 1) * batch_size],
y: label[index * batch_size: (index + 1) * batch_size]
},allow_input_downcast=True
)
test_losses=[]
for minibatch_index in xrange(batches):
test_losses.append(test_model(minibatch_index))
test_score = np.mean(test_losses)
print(( 'minibatch %i/%i, test error of model %f %%') %
(minibatch_index + 1,batches,test_score * 100.)) def h(self,x):
m = np.exp(np.dot(x,self.theta))
sump = np.sum(m,axis=1)
return m/sump def predict(self,x):
return np.argmax(self.h(x),axis=1) if __name__ == '__main__':
f = open('mnist.pkl', 'rb')
training_data, validation_data, test_data = cPickle.load(f)
training_inputs = [np.reshape(x, 784) for x in training_data[0]]
data = np.array(training_inputs)
training_inputs = [np.reshape(x, 784) for x in validation_data[0]]
vdata = np.array(training_inputs)
f.close()
softmax = SoftMax()
softmax.process_train(data,training_data[1],10)
softmax.process_test(vdata,validation_data[1])
#minibatch 20/20, test error of model 7.530000 %
Softmax回归(使用theano)的更多相关文章
- Softmax回归
Reference: http://ufldl.stanford.edu/wiki/index.php/Softmax_regression http://deeplearning.net/tutor ...
- Softmax回归(Softmax Regression)
转载请注明出处:http://www.cnblogs.com/BYRans/ 多分类问题 在一个多分类问题中,因变量y有k个取值,即.例如在邮件分类问题中,我们要把邮件分为垃圾邮件.个人邮件.工作邮件 ...
- DeepLearning之路(二)SoftMax回归
Softmax回归 1. softmax回归模型 softmax回归模型是logistic回归模型在多分类问题上的扩展(logistic回归解决的是二分类问题). 对于训练集,有. 对于给定的测试 ...
- Machine Learning 学习笔记 (3) —— 泊松回归与Softmax回归
本系列文章允许转载,转载请保留全文! [请先阅读][说明&总目录]http://www.cnblogs.com/tbcaaa8/p/4415055.html 1. 泊松回归 (Poisson ...
- Softmax 回归原理介绍
考虑一个多分类问题,即预测变量y可以取k个离散值中的任何一个.比如一个邮件分类系统将邮件分为私人邮件,工作邮件和垃圾邮件.由于y仍然是一个离散值,只是相对于二分类的逻辑回归多了一些类别.下面将根据多项 ...
- UFLDL教程(四)之Softmax回归
关于Andrew Ng的machine learning课程中,有一章专门讲解逻辑回归(Logistic回归),具体课程笔记见另一篇文章. 下面,对Logistic回归做一个简单的小结: 给定一个待分 ...
- 机器学习 —— 基础整理(五)线性回归;二项Logistic回归;Softmax回归及其梯度推导;广义线性模型
本文简单整理了以下内容: (一)线性回归 (二)二分类:二项Logistic回归 (三)多分类:Softmax回归 (四)广义线性模型 闲话:二项Logistic回归是我去年入门机器学习时学的第一个模 ...
- LR多分类推广 - Softmax回归*
LR是一个传统的二分类模型,它也可以用于多分类任务,其基本思想是:将多分类任务拆分成若干个二分类任务,然后对每个二分类任务训练一个模型,最后将多个模型的结果进行集成以获得最终的分类结果.一般来说,可以 ...
- Logistic回归(逻辑回归)和softmax回归
一.Logistic回归 Logistic回归(Logistic Regression,简称LR)是一种常用的处理二类分类问题的模型. 在二类分类问题中,把因变量y可能属于的两个类分别称为负类和正类, ...
- 手写数字识别 ----Softmax回归模型官方案例注释(基于Tensorflow,Python)
# 手写数字识别 ----Softmax回归模型 # regression import os import tensorflow as tf from tensorflow.examples.tut ...
随机推荐
- poj1647
转自:http://woodjohn.blog.sohu.com/231905679.html 题意是比较简单的:假定你是国际象棋中的白方,现在棋盘上只剩下白王.黑王和白后(王和后的走法规则就不赘述了 ...
- 获取一个 app 的 URL Scheme 的方法:
获取一个 app 的 URL Scheme 的方法: 上这个网站 URL Schemes 查一下相应的 app 的 URL Scheme 是否有被收录 第一种方法没找到的话,把相应的 app 的 ip ...
- FreebuF黑客专访系列之吴翰清(刺):接下来几年,有两样东西必定会火
注:吴翰清——中国网络安全圈最具影响力的人物之一.西安交大少年班毕业,大学期间创办民间组织幻影,阿里巴巴集团最年轻的高级安全专家,创新工场安全宝任联合副总裁,热门公众微信“道哥的黑板报”幕后作 ...
- WebGrid Enterprise免费下载
WebGrid.NET Enterprise是一个为ASP.NET平台下WEB开发而设计的高级数据表格控件.WebGrid.NET为复杂的分层次导航交互式企业级信息传输提供了全面而先进的功能,它允许用 ...
- iOS之《 Human Interface Guidelines:from Concept to Product 》<界面设计指南 二>:从概念到产品的实现
开发之前需要想到的: 1.列出所有用户可能喜欢的功能. 例子:食谱 (1)创建一个总的食谱菜单 (2)食谱的获取方法 (3)比较价格 (4)当地的食材店 (5)食谱每道菜的注释 (6)能够获取和使用 ...
- Nodejs创建https服务器(Windows 7)
为了实验一下WebRTC,搭了个简单的https服务器.说说步骤: 生成OpenSSL证书 使用Nodejs的https模块建立服务器 OpenSSL 证书 我机子Windows 7,安装了Cygwi ...
- iOS-代理
1.协议是一组通讯协议,一般用作两个类之间的通信. 2.协议声明了一组所有类对象都可以实现的接口. 3.协议不是类,用@protocol关键字声明一个协议. 4.与协议有关的两个对象,代理者和委托者. ...
- curl 发送带有Authorization的post请求命令
curl --user user:password -d "param1=111¶m2=222" "http://127.0.0.1/cmd"
- Git工作常用
工作时,最好每次都创建一个本地分支,这样就会减少错误修改远程代码的机会. 基于远程dev分支创建分支并切到本地分支: git checkout -b <local_dev> -t orig ...
- OpenHCI - Data Transfer Types
There are four data transfer types defined in USB(USB中有4种数据传输类型). Each type is optimized to match th ...