原理

逻辑回归的推理过程能够參考这篇文章: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. wrote a programming language

    https://medium.freecodecamp.org/the-programming-language-pipeline-91d3f449c919

  2. C#引用类型转换的几种方式

    本篇体验引用类型转换:子类转换成父类,父类转换成子类,以及不是子父级关系类之间的转换. □ 隐式转换:子类转换成父类 public class Animal { public int _age; pu ...

  3. unity 质量设置 Quality Settings

    Unity allows you to set the level of graphical quality it will attempt to render. Generally speaking ...

  4. 通过@Value注解读取.properties配置内容

    @Controller @RequestMapping("/value") public class ValuePropertyController extends Applica ...

  5. Glusterfs初试

    Gluster的模式及介绍在此不表,这里只记录安装及配置过程. 1.整体环境 server1 : gfs1.cluster.com server2 : gfs2.cluster.com Client: ...

  6. Python3.6学习笔记(三)

    面向对象编程 面向对象编程 Object Oriented Programming 简称 OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数. 面向过程的程 ...

  7. 跟我学Spring3(9.1):Spring的事务之数据库事务概述

    原文出处: 张开涛 9.1 数据库事务概述 事务首先是一系列操作组成的工作单元,该工作单元内的操作是不可分割的,即要么所有操作都做,要么所有操作都不做,这就是事务. 事务必需满足ACID(原子性.一致 ...

  8. Flask 学习(二)路由

    Flask  路由 在说明什么是 Flask 路由之前,详细阐述下 Flask “Hello World” 这一 最小应用的代码. Flask “Hello World” from flask imp ...

  9. 【TYVJ 五月图论专项有奖比赛】

    最短路+TSP+最小生成树+倍增LCA+TreeDP 第一题 其实是个TSP问题(然而我没发现),但是关键点很少,只有5个,所以用dij+heap分别预处理出来这五个点为源的最短路…… 然后枚举起点 ...

  10. Qt Quick 和qml介绍

    很多人不了解Qt Quick和Qml,还有很多人对其存在偏见.这篇文章就是来向这些有困惑的人介绍一下其是什么,有什么特点. 首先,这两个是一个东西吗? 答案:是的.但是,具体来说,Qt Quick是框 ...