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 ...
随机推荐
- 使用Lazy<T>实现对客户订单的延迟加载
"延迟加载"是指在需要的时候再加载数据.比如获得一个Customer信息,并不会把该Customer的Orders信息一下加载出来,当需要显示Orders的时候再加载.简单来说,就 ...
- datagrid在MVC中的运用02-结合搜索
本文接着上一篇,来体验给datagrid加上搜索功能.主要涉及到: ※ 把一个div与datagrid相关起来 ※ datagrid接收查询参数 ※ 查询参数的封装 效果图: 查询参数封装 分页相关的 ...
- C#编程(三)
原文链接:http://blog.csdn.net/shanyongxu/article/details/46398713 C#中的常量 定义常量所需要的关键字:const,语法结果:const 变量 ...
- EF实体框架处理实体之间关联关系与EF延迟机制(下)
在数据库中,表与表之间可能存在多种联系,比如,一对多,多对多的关系.当我们使用逻辑外键在数据库建立两张表之间的关系的时候,我们使用EF实体框架 必然也会将这种关系映射到我们的实体关系中来.所以,在我们 ...
- 使用命名参数处理 CallableStatement
简介:JDBC 中的语句处理 在 JDBC 应用程序中,JDBC 语句对象用于将 SQL 语句发送到数据库服务器.一个语句对象与一个连接相关联,应用程序与数据库服务器之间的通信由语句对象来处理. JD ...
- 手机网站和PC网站兼容的响应式网页设计
今天跟大家介绍的这个网站叫 媒体查询 官网域名:http://mediaqueri.es/ 该酷站收集了很多响应式设计的案例.全部都是收集的一些励志精美而时尚的网站,使用媒体查询和响应的网页设计. ...
- easyui datagrid 计算
转载,至高吴上(Alfa.wu) !谢谢! /******************************************************** 主要用于 明细表格 字段间的计算 Sta ...
- C语言:结构体和联合体(共用体)
结构体:struct 1.结构体变量的首地址能够被其最宽基本类型成员的大小所整除. 2.结构体每个成员相对于结构体首地址的偏移量(offset)都是成员的整数倍. 3.结构体的总大小为结构体最宽基本类 ...
- Objective-C:保留计数器思想的详解(对象的保留和所有权的释放)
对象的保留和所有权的释放: int main(int agrs,char *argv[]) { @autoreleasepool{ Person *person = [[Person alloc]in ...
- [Usaco2006 Nov]Roadblocks第二短路
贝茜把家搬到了一个小农场,但她常常回到FJ的农场去拜访她的朋友.贝茜很喜欢路边的风景,不想那么快地结束她的旅途,于是她每次回农场,都会选择第二短的路径,而不象我们所习惯的那样,选择最短路. 贝茜所在的 ...