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

  1. Softmax回归

    Reference: http://ufldl.stanford.edu/wiki/index.php/Softmax_regression http://deeplearning.net/tutor ...

  2. Softmax回归(Softmax Regression)

    转载请注明出处:http://www.cnblogs.com/BYRans/ 多分类问题 在一个多分类问题中,因变量y有k个取值,即.例如在邮件分类问题中,我们要把邮件分为垃圾邮件.个人邮件.工作邮件 ...

  3. DeepLearning之路(二)SoftMax回归

    Softmax回归   1. softmax回归模型 softmax回归模型是logistic回归模型在多分类问题上的扩展(logistic回归解决的是二分类问题). 对于训练集,有. 对于给定的测试 ...

  4. Machine Learning 学习笔记 (3) —— 泊松回归与Softmax回归

    本系列文章允许转载,转载请保留全文! [请先阅读][说明&总目录]http://www.cnblogs.com/tbcaaa8/p/4415055.html 1. 泊松回归 (Poisson ...

  5. Softmax 回归原理介绍

    考虑一个多分类问题,即预测变量y可以取k个离散值中的任何一个.比如一个邮件分类系统将邮件分为私人邮件,工作邮件和垃圾邮件.由于y仍然是一个离散值,只是相对于二分类的逻辑回归多了一些类别.下面将根据多项 ...

  6. UFLDL教程(四)之Softmax回归

    关于Andrew Ng的machine learning课程中,有一章专门讲解逻辑回归(Logistic回归),具体课程笔记见另一篇文章. 下面,对Logistic回归做一个简单的小结: 给定一个待分 ...

  7. 机器学习 —— 基础整理(五)线性回归;二项Logistic回归;Softmax回归及其梯度推导;广义线性模型

    本文简单整理了以下内容: (一)线性回归 (二)二分类:二项Logistic回归 (三)多分类:Softmax回归 (四)广义线性模型 闲话:二项Logistic回归是我去年入门机器学习时学的第一个模 ...

  8. LR多分类推广 - Softmax回归*

    LR是一个传统的二分类模型,它也可以用于多分类任务,其基本思想是:将多分类任务拆分成若干个二分类任务,然后对每个二分类任务训练一个模型,最后将多个模型的结果进行集成以获得最终的分类结果.一般来说,可以 ...

  9. Logistic回归(逻辑回归)和softmax回归

    一.Logistic回归 Logistic回归(Logistic Regression,简称LR)是一种常用的处理二类分类问题的模型. 在二类分类问题中,把因变量y可能属于的两个类分别称为负类和正类, ...

  10. 手写数字识别 ----Softmax回归模型官方案例注释(基于Tensorflow,Python)

    # 手写数字识别 ----Softmax回归模型 # regression import os import tensorflow as tf from tensorflow.examples.tut ...

随机推荐

  1. poj1845 数论

    //Accepted 204K 16MS //约数和 //n=p1^e1*p2^e2***pk^ek //约数和为:(p1^0+p1^1+..+p1^e1)*(p2^0+p2^1+..+p2^e2)* ...

  2. DirectX 总结和DirectX 9.0 学习笔记

    转自:http://www.cnblogs.com/graphics/archive/2009/11/25/1583682.html DirectX 总结 DDS DirectXDraw Surfac ...

  3. (转)Sencha Touch和jQuery Mobile的比较

    原文:http://extjs.org.cn/node/664 Sencha Touch和jQuery Mobile的比较 Posted 周三, 08/07/2013 - 10:07 by admin ...

  4. 使用免费内测托管平台fir.im测试

    1,使用Xcode先行把项目导成ipa文件.登录http://fir.im/ 2.点击左上角的苹果标志,把准备好的ipa文件拖入即可.4.填写相关材料即可开始上传5,让飞机灰一会即可.6.接着会看见: ...

  5. 转:【More Effective C#】Lambda表达式优化

    http://www.cnblogs.com/kongyiyun/archive/2010/10/19/1855274.html 使用Lambda表达式将会造成Lambda表达式主题部分的代码重复. ...

  6. 表视图控制器(TableViewController)(三) 、 表视图搜索

    1 乐库的设置界面 1.1 问题 tableView分为静态(static)和动态(dynamic),之前使用的都是动态的tableView,表视图的有多少分区.有多少行以及每一行显示的内容都不是固定 ...

  7. Fix VNC Desktop Sharing on Ubuntu Desktop 14.04

    Solution 1 sudo apt-get -y install dconf-tools dconf write /org/gnome/desktop/remote-access/require- ...

  8. C++学习笔记15:操作符重载的函数原型列表(推荐)

    //普通四则运算 friend A operator +(const A & lhs, const A & rhs); friend A operator -(const A & ...

  9. 解密Redis持久化

    原文 http://blog.nosqlfan.com/html/3813.html 本文内容来源于Redis作者博文,Redis作者说,他看到的所有针对Redis的讨论中,对Redis持久化的误解是 ...

  10. sql server中NULL导入decimal字段时报错

    sql server中NULL导入decimal字段时报错 在导入CSV文件时,如果decimal字段为null值,导致文本文件入库时失败. 错误现象 构造例子 新建一张表,包含decimal字段. ...