原理

逻辑回归的推理过程能够參考这篇文章: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的更多相关文章

  1. 用 theano 求解 Logistic Regression (SGD 优化算法)

    1. model 这里待求解的是一个 binary logistic regression,它是一个分类模型,参数是权值矩阵 W 和偏置向量 b.该模型所要估计的是概率 P(Y=1|x),简记为 p, ...

  2. Deep Learning Tutorial - Classifying MNIST digits using Logistic Regression

    Deep Learning Tutorial 由 Montreal大学的LISA实验室所作,基于Theano的深度学习材料.Theano是一个python库,使得写深度模型更容易些,也可以在GPU上训 ...

  3. 逻辑回归Logistic Regression 之基础知识准备

    0. 前言   这学期 Pattern Recognition 课程的 project 之一是手写数字识别,之二是做一个网站验证码的识别(鸭梨不小哇).面包要一口一口吃,先尝试把模式识别的经典问题—— ...

  4. 逻辑回归 Logistic Regression

    逻辑回归(Logistic Regression)是广义线性回归的一种.逻辑回归是用来做分类任务的常用算法.分类任务的目标是找一个函数,把观测值匹配到相关的类和标签上.比如一个人有没有病,又因为噪声的 ...

  5. logistic regression与SVM

    Logistic模型和SVM都是用于二分类,现在大概说一下两者的区别 ① 寻找最优超平面的方法不同 形象点说,Logistic模型找的那个超平面,是尽量让所有点都远离它,而SVM寻找的那个超平面,是只 ...

  6. Logistic Regression - Formula Deduction

    Sigmoid Function \[ \sigma(z)=\frac{1}{1+e^{(-z)}} \] feature: axial symmetry: \[ \sigma(z)+ \sigma( ...

  7. SparkMLlib之 logistic regression源码分析

    最近在研究机器学习,使用的工具是spark,本文是针对spar最新的源码Spark1.6.0的MLlib中的logistic regression, linear regression进行源码分析,其 ...

  8. [OpenCV] Samples 06: [ML] logistic regression

    logistic regression,这个算法只能解决简单的线性二分类,在众多的机器学习分类算法中并不出众,但它能被改进为多分类,并换了另外一个名字softmax, 这可是深度学习中响当当的分类算法 ...

  9. Stanford机器学习笔记-2.Logistic Regression

    Content: 2 Logistic Regression. 2.1 Classification. 2.2 Hypothesis representation. 2.2.1 Interpretin ...

随机推荐

  1. C语言每日小练(四)——勇者斗恶龙

    勇者斗恶龙 你的王国里有一条n个头的恶龙,你希望雇佣一些骑士把它杀死(砍掉全部的头). 村里有m个骑士能够雇佣.一个能力值为x的骑士能够砍掉恶龙一个致敬不超过x的头,且须要支付x个金币. 怎样雇佣骑士 ...

  2. js单例模式详解实例

    这篇文章主要介绍了什么是单例单例模式.使用场景,提供了3个示例给大家参考 什么是单例? 单例要求一个类有且只有一个实例,提供一个全局的访问点.因此它要绕过常规的控制器,使其只能有一个实例,供使用者使用 ...

  3. VS中运行HTTP 无法注册URL

    参考资料 http://www.java123.net/detail/view-449670.html http://www.cnblogs.com/jiewei915/archive/2010/06 ...

  4. Android Binder分析二:Natvie Service的注冊

    这一章我们通过MediaPlayerService的注冊来说明怎样在Native层通过binder向ServiceManager注冊一个service,以及client怎样通过binder向Servi ...

  5. RobotFramework自动化3-搜索案例

    前言 RF系列主要以案例为主,关键字不会的可以多按按F5,里面都有很详细的介绍,要是纯翻译的话,就没太大意义了,因为小编本来英语就很差哦! 前面selenium第八篇介绍过定位一组搜索结果,是拿百度搜 ...

  6. Uber分布式追踪系统Jaeger使用介绍和案例

    原文:Uber分布式追踪系统Jaeger使用介绍和案例[PHP Hprose Go] 前言   随着公司的发展,业务不断增加,模块不断拆分,系统间业务调用变得越复杂,对定位线上故障带来很大困难.整个调 ...

  7. JAVA常见算法题(三十三)---求子串在字符串中出现的次数

    计算某字符串中子串出现的次数. public static void main(String[] args) { String s1 = "adcdcjncdfbcdcdcd"; ...

  8. PASCAL VOC数据集The PASCAL Object Recognition Database Collection

    The PASCAL Object Recognition Database Collection News 04-Apr-07: The VOC2007 challenge development ...

  9. C++ vector 删除符合条件的元素

    C++ vector中实际删除元素使用的是容器vecrot中std::vector::erase()方法. C++ 中std::remove()并不删除元素,因为容器的size()没有变化,只是元素的 ...

  10. IOS中键盘隐藏几种方式

    在ios开发中,经常需要输入信息.输入信息有两种方式: UITextField和UITextView.信息输入完成后,需要隐藏键盘,下面为大家介绍几种隐藏键盘的方式. <一> 点击键盘上的 ...