Theano Logistic Regression
原理
逻辑回归的推理过程能够參考这篇文章:http://blog.csdn.net/zouxy09/article/details/20319673,当中包括了关于逻辑回归的推理,梯度下降以及python源代码,讲的有点多。能够直接看核心部分
对于这篇文章补充一个就是其缺少的正则化内容:
能够查看知乎上的一个回答,算是比較完整
https://www.zhihu.com/question/35508851/answer/63093225
Theano 代码
#!/usr/bin/env python
# -*- encoding:utf-8 -*-
'''
This is done by Vincent.Y
mainly modified from deep learning tutorial
'''
import numpy as np
import theano
import theano.tensor as T
from theano import function
from sklearn.datasets import make_moons
import matplotlib.pyplot as plt
class LogisticRegression():
def __init__(self,X,n_in,n_out):
self.W = theano.shared(
value=np.zeros(
(n_in,n_out),
dtype=theano.config.floatX
),
name='W',
borrow=True
)
self.b=theano.shared(
value=np.zeros(
(n_out,),
dtype=theano.config.floatX
),
name='b',
borrow=True
)
self.p_y_given_x=T.nnet.softmax(T.dot(X,self.W)+self.b)
self.y_pred=T.argmax(self.p_y_given_x,axis=1)
self.params=[self.W,self.b]
self.X=X
def negative_log_likelihood(self,y):
return -T.mean(T.log(self.p_y_given_x)[T.arange(y.shape[0]),y])
def errors(self,y):
if y.ndim != self.y_pred.ndim:
raise TypeError(
'y should have the same shape as self.y_pred',
('y',y.type,'y_pred',self.y_pred.type)
)
if y.dtype.startswith('int'):
return T.mean(T.neq(self.y_pred,y))
else:
return NotImplementedError()
def load_data():
#we generate data from sklearn
np.random.seed(0)
X, y = make_moons(800, noise=0.20)
print "xxxxx",X.shape
#return train validate test sets
return [(X[0:600,],y[0:600,]),(X[600:800,],y[600:800,])]
def sgd_optimization(learing_rate=0.12,n_epochs=300):
datasets=load_data()
train_set_x,train_set_y=datasets[0]
test_set_x,test_set_y=datasets[1]
index=T.lscalar()
x = T.matrix('x')
y = T.lvector('y')
classifier=LogisticRegression(X=x,n_in=2,n_out=2)
cost=classifier.negative_log_likelihood(y)
test_model=function(
inputs=[x,y],
outputs=classifier.errors(y)
)
g_W=T.grad(cost=cost,wrt=classifier.W)
g_b=T.grad(cost=cost,wrt=classifier.b)
updates=[(classifier.W,classifier.W-learing_rate*g_W),
(classifier.b,classifier.b-learing_rate*g_b)]
train_model=function(
inputs=[x,y],
outputs=classifier.errors(y),
updates=updates
)
epoch=0
while(epoch<n_epochs):
epoch=epoch+1
avg_cost=train_model(train_set_x,train_set_y)
test_cost=test_model(test_set_x,test_set_y)
print "epoch is %d,train error %f, test error %f"%(epoch,avg_cost,test_cost)
predict_model=function(
inputs=[x],
outputs=classifier.y_pred
)
plot_decision_boundary(lambda x:predict_model(x),train_set_x,train_set_y)
def plot_decision_boundary(pred_func,train_set_x,train_set_y):
x_min, x_max = train_set_x[:, 0].min() - .5, train_set_x[:, 0].max() + .5
y_min, y_max = train_set_x[:, 1].min() - .5, train_set_x[:, 1].max() + .5
h = 0.01
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = pred_func(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
plt.scatter(train_set_x[:, 0], train_set_x[:, 1], c=train_set_y, cmap=plt.cm.Spectral)
plt.show()
if __name__=="__main__":
sgd_optimization()
效果
Theano Logistic Regression的更多相关文章
- 用 theano 求解 Logistic Regression (SGD 优化算法)
1. model 这里待求解的是一个 binary logistic regression,它是一个分类模型,参数是权值矩阵 W 和偏置向量 b.该模型所要估计的是概率 P(Y=1|x),简记为 p, ...
- Deep Learning Tutorial - Classifying MNIST digits using Logistic Regression
Deep Learning Tutorial 由 Montreal大学的LISA实验室所作,基于Theano的深度学习材料.Theano是一个python库,使得写深度模型更容易些,也可以在GPU上训 ...
- 逻辑回归Logistic Regression 之基础知识准备
0. 前言 这学期 Pattern Recognition 课程的 project 之一是手写数字识别,之二是做一个网站验证码的识别(鸭梨不小哇).面包要一口一口吃,先尝试把模式识别的经典问题—— ...
- 逻辑回归 Logistic Regression
逻辑回归(Logistic Regression)是广义线性回归的一种.逻辑回归是用来做分类任务的常用算法.分类任务的目标是找一个函数,把观测值匹配到相关的类和标签上.比如一个人有没有病,又因为噪声的 ...
- logistic regression与SVM
Logistic模型和SVM都是用于二分类,现在大概说一下两者的区别 ① 寻找最优超平面的方法不同 形象点说,Logistic模型找的那个超平面,是尽量让所有点都远离它,而SVM寻找的那个超平面,是只 ...
- Logistic Regression - Formula Deduction
Sigmoid Function \[ \sigma(z)=\frac{1}{1+e^{(-z)}} \] feature: axial symmetry: \[ \sigma(z)+ \sigma( ...
- SparkMLlib之 logistic regression源码分析
最近在研究机器学习,使用的工具是spark,本文是针对spar最新的源码Spark1.6.0的MLlib中的logistic regression, linear regression进行源码分析,其 ...
- [OpenCV] Samples 06: [ML] logistic regression
logistic regression,这个算法只能解决简单的线性二分类,在众多的机器学习分类算法中并不出众,但它能被改进为多分类,并换了另外一个名字softmax, 这可是深度学习中响当当的分类算法 ...
- Stanford机器学习笔记-2.Logistic Regression
Content: 2 Logistic Regression. 2.1 Classification. 2.2 Hypothesis representation. 2.2.1 Interpretin ...
随机推荐
- vim选择命令
最近在做一些无聊的客户化OSD,发现结合vim的一些命令更简单. 1.全选:ggVG(V:shift+v) 解释是:gg 让光标移到首行,在vim才有效,vi中无效:V 是进入Visual(可视)模式 ...
- [MySql]默认密码的查找与修改
摘要 在安装成功后,怎么找到mysql的默认密码,折腾很长时间,最后发现在安装的过程中,产生了一个默认的随机密码. 密码 在mysql安装目录生成的data文件下,查找xxx.err的文件如图: 用记 ...
- Remon Spekreijse CSerialPort用法
在程序中如果要用到多个串口,而且还要做很多复杂的处理,那么最好不用MSComm通讯控件,如果这时你还不愿意自己编写底层,就用这个类:CserialPort类.作者是 Remon Spekreijse ...
- 七问C#关键字const和readonly
const和readonly经常被用来修饰类的字段,两者有何异同呢? const 1.声明const类型变量一定要赋初值吗? --一定要赋初值 public class Student { publi ...
- MVC打印表格,把表格内容放到部分视图打印
假设在一个页面上有众多内容,而我们只想把该页面上的表格内容打印出来,window.print()方法会把整个页面的内容打印出来,如何做到只打印表格内容呢? 既然window.print()只会打印整页 ...
- [转载] C-MEX程序编写
原作者,胡荣春 2006-10-11 1 MEX文件简介 在MATLAB中可调用的C或Fortran语言程序称为MEX文件.MATLAB可以直接把MEX文件视为它的内建函数进行调用.MEX文件是动态 ...
- java hashcode()和equal()方法比较
通常equals,toString,hashCode,在应用中都会被复写,建立具体对象的特有的内容. 之所以有hashCode方法,是因为在批量的对象比较中,hashCode要比equals来得快,很 ...
- 转: gob编解码
要让数据对象能在网络上传输或存储,我们需要进行编码和解码.现在比较流行的编码方式有JSON,XML等.然而,Go在gob包中为我们提供了另一种方式,该方式编解码效率高于JSON.gob是Golang包 ...
- 第二章 ActionScript 3.0学习之画星星(鼠标及键盘事件)
今天觉得学到的比较有趣,所以记录之......~~~ 下面这段就是画出星星的代码:StarShape.as package { import flash.display.Shape; import f ...
- poj 2284 That Nice Euler Circuit 解题报告
That Nice Euler Circuit Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 1975 Accepted ...