# 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. SyntaxError: missing ; before statement 错误的解决

    今天jsp页面中报错:SyntaxError: missing ; before statement 简单的理解是语法错误,F12调试之后发现原来是我定义的一个js中的全局变量的问题. <scr ...

  2. hdoj-2025

    #include "stdio.h"#include "string.h"void sort(char ch[],int count[],int n,int f ...

  3. 在.net中实现在textbox中按ctrl+enter进行数据的提交

    textbox.Attributes.Add("onKeydown", "if(event.ctrlKey&&event.keyCode == 13){d ...

  4. java互斥方法

    synchronized,  lock/unlock,  volatile类型变量, atom类, 同步集合,  新类库中的构件: CountDownLatch\CyclicBarric\Semaph ...

  5. node 学习笔记

    以下笔记默认安装完成node 及npm 1.安装express 新版本的express-generator已经独立出来,全局安装这个包就ok. npm install express-generato ...

  6. Charlie's Change_完全背包&&路径记录

    Description Charlie is a driver of Advanced Cargo Movement, Ltd. Charlie drives a lot and so he ofte ...

  7. Qt Charts示例

    Qt 5.7 有一些变化,把原来商业版的几个模块用GPLv3协议放到了社区版本里: Qt Charts (GPLv3) Qt Data Visualization (GPLv3) Qt Virtual ...

  8. 根据存放位置数据的链表P打印链表L的元素

    题目:给定一个链表L和另一个链表P,它们包含以升序排列的整数.操作printLots打印L中那些由P所指定的位置上的元素.写出过程printLots(L,P).只可以使用公有的STL容器操作.该过程的 ...

  9. 17、SQL基础整理(事务)

    事务 事务==流程控制 确保流程只能成功或者失败,若出现错误会自动回到原点 例: begin tran insert into student values('111','王五','男','1999- ...

  10. Linux基础入门(新版)(实验五至实验八)

    实验五 环境变量与文件查找 (环境变量的作用与用法,及几种搜索文件的方法)   一.环境变量   1.变量 (1)常变量与值是一对一的关系 (2)变量的作用域即变量的有效范围(比如一个函数中.一个源文 ...