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()

效果

时间: 2024-08-02 03:02:10

Theano Logistic Regression的相关文章

logistic regression using Theano 注释版

Theano是一个可以让你定义,优化,计算数学表达式的一个python库.多种机器学习方法可以很方便的用Theano实现.下面是用Theano实现logistic regression (逻辑回归)的例子. 摘自Theano官网的tutorial里面. 主要步骤分为下面几步 1. 定义逻辑回归模型 2. 定义建立数据集方法 3.定义训练逻辑回归模型方法 4. 训练 代码下载地址: http://deeplearning.net/tutorial/logreg.html#logreg ""

Deep Learning Tutorial - Classifying MNIST digits using Logistic Regression

Deep Learning Tutorial 由 Montreal大学的LISA实验室所作,基于Theano的深度学习材料.Theano是一个python库,使得写深度模型更容易些,也可以在GPU上训练深度模型.所以首先得了解python和numpy.其次,阅读Theano basic tutorial. Deep Learning Tutorial 包括: 监督学习算法: Logistic Regression - using Theano for something simple Multi

Logistic Regression to do Binary Classification

使用python的theano编写Logistic Regression进行二分类学习,使用到的数据集可以到这里下载. 我们知道Logistic Regression是在一个多元线性函数的基础上加了一个非线性函数,常用的非线性函数是Sigmoid函数.加上sigmoid之后的输出我们认为是对应分类为1的概率,所以需要学习的参数就是线性加权的系数和截距(bias). h(x) = wx + b g(x) = 1 / ( 1 + exp(-h(x)) ) = 1 / ( 1 + exp( -wx-b

Logistic Regression & Classification (1)

一.为什么不使用Linear Regression 一个简单的例子:如果训练集出现跨度很大的情况,容易造成误分类.如图所示,图中洋红色的直线为我们的假设函数 .我们假定,当该直线纵轴取值大于等于0.5时,判定Malignant为真,即y=1,恶性肿瘤:而当纵轴取值小于0.5时,判定为良性肿瘤,即y=0. 就洋红色直线而言,是在没有最右面的"×"的训练集,通过线性回归而产生的.因而这看上去做了很好的分类处理,但是,当训练集中加入了右侧的"×"之后,导致整个线性回归的结

对Logistic Regression 的初步认识

线性回归 回归就是对已知公式的未知参数进行估计.比如已知公式是y=a∗x+b,未知参数是a和b,利用多真实的(x,y)训练数据对a和b的取值去自动估计.估计的方法是在给定训练样本点和已知的公式后,对于一个或多个未知参数,机器会自动枚举参数的所有可能取值,直到找到那个最符合样本点分布的参数(或参数组合).也就是给定训练样本,拟合参数的过程,对y= a*x + b来说这就是有一个特征x两个参数a b,多个样本的话比如y=a*x1+b*x2+...,用向量表示就是y =  ,就是n个特征,n个参数的拟

Coursera台大机器学习课程笔记9 -- Logistic Regression

这一节课主要讲如何用logistic regression做分类. 在误差衡量问题上,选取了最大似然函数误差函数,这一段推导是难点. 接下来是如何最小化Ein,采用的是梯度下降法,这个比较容易. 参考:http://beader.me/mlnotebook/section3/logistic-regression.html http://www.cnblogs.com/ymingjingr/p/4330304.html

logistic regression编程练习

本练习以<机器学习实战>为基础, 重现书中代码, 以达到熟悉算法应用为目的 1.梯度上升算法 新建一个logRegres.py文件, 在文件中添加如下代码: from numpy import * #加载模块 numpy def loadDataSet(): dataMat = []; labelMat = [] #加路径的话要写作:open('D:\\testSet.txt','r') 缺省为只读 fr = open('testSet.txt') #readlines()函数一次读取整个文件

最详细的基于R语言的Logistic Regression(Logistic回归)源码,包括拟合优度,Recall,Precision的计算

这篇日志也确实是有感而发,我对R不熟悉,但实验需要,所以简单学了一下.发现无论是网上无数的教程,还是书本上的示例,在讲Logistic Regression的时候就是给一个简单的函数及输出结果说明.从来都没有讲清楚几件事情: 1. 怎样用训练数据训练模型,然后在测试数据上进行验证(测试数据和训练数据可能有重合)? 2. 怎样计算预测的效果,也就是计算Recall,Precision,F-measure等值? 3. 怎样计算Nagelkerke拟合优度等评价指标? 发现这些书本和一些写博客的朋友,

深度学习 Deep LearningUFLDL 最新Tutorial 学习笔记 2:Logistic Regression

1 Logistic Regression 简述 Linear Regression 研究连续量的变化情况,而Logistic Regression则研究离散量的情况.简单地说就是对于推断一个训练样本是属于1还是0.那么非常easy地我们会想到概率,对,就是我们计算样本属于1的概率及属于0的概率,这样就能够依据概率来预计样本的情况,通过概率也将离散问题变成了连续问题. Specifically, we will try to learn a function of the form: P(y=1