基于python中theano库的线性回归

yipeiwu_com5年前Python基础

theano库是做deep learning重要的一部分,其最吸引人的地方之一是你给出符号化的公式之后,能自动生成导数。本文使用梯度下降的方法,进行数据拟合,现在把代码贴在下方

代码块

import numpy as np 
import theano.tensor as T 
import theano 
import time 

class Linear_Reg(object): 
  def __init__(self,x): 
    self.a = theano.shared(value = np.zeros((1,), dtype=theano.config.floatX),name = 'a') 
    self.b = theano.shared(value = np.zeros((1,), 
dtype=theano.config.floatX),name = 'b') 
    self.result = self.a * x + self.b 
    self.params = [self.a,self.b] 
  def msl(self,y): 
    return T.mean((y - self.result)**2) 

def regrun(rate,data,labels): 

  X = theano.shared(np.asarray(data, 
                 dtype=theano.config.floatX),borrow = True) 
  Y = theano.shared(np.asarray(labels, 
                 dtype=theano.config.floatX),borrow = True) 

  index = T.lscalar() #定义符号化的公式
  x = T.dscalar('x')  #定义符号化的公式
  y = T.dscalar('y')  #定义符号化的公式

  reg = Linear_Reg(x = x) 
  cost = reg.msl(y) 


  a_g = T.grad(cost = cost,wrt = reg.a) #计算梯度 
  b_g = T.grad(cost = cost, wrt = reg.b) #计算梯度

  updates=[(reg.a,reg.a - rate * a_g),(reg.b,reg.b - rate * b_g)] #更新参数
  train_model = theano.function(inputs=[index], outputs = reg.msl(y),updates = updates,givens = {x:X[index], y:Y[index]}) 

  done = True 
  err = 0.0 
  count = 0 
  last = 0.0 
  start_time = time.clock() 
  while done: 
    #err_s = [train_model(i) for i in xrange(data.shape[0])] 
    for i in xxx:
      err_s = [train_model(i) ]
      err = np.mean(err_s)  

    #print err 
    count = count + 1 
    if count > 10000 or err <0.1: 
      done = False 
    last = err 
  end_time = time.clock() 
  print 'Total time is :',end_time -start_time,' s' # 5.12s 
  print 'last error :',err 
  print 'a value : ',reg.a.get_value() # [ 2.92394467]  
  print 'b value : ',reg.b.get_value() # [ 1.81334458] 

if __name__ == '__main__':  
  rate = 0.01 
  data = np.linspace(1,10,10) 
  labels = data * 3 + np.ones(data.shape[0],dtype=np.float64) +np.random.rand(data.shape[0])
  regrun(rate,data,labels) 

其基本思想是随机梯度下降。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python SELENIUM上传文件或图片实现过程

Python SELENIUM上传文件或图片实现过程

逛网站的时候经常会遇到需要上传图片的操作,这里主要来说下selenium操作上传文件的操作。 前提条件:定位的元素必须是type 属性是file类型。即type="file",如下图:...

python 根据pid杀死相应进程的方法

用python语言实现根据pid杀死相应进程 kill_process.py代码如下 #! /usr/bin/python # -*- coding: utf-8 -*- impo...

python 实现将小图片放到另一个较大的白色或黑色背景图片中

python 实现将小图片放到另一个较大的白色或黑色背景图片中

将图片放入到白色或黑色背景图中,前提是图片小于背景图片的尺寸,原图为如下,长为192,宽为64。 1.将图片放入到白色背景图(224,224)中 import cv2 import...

Python正则表达式教程之三:贪婪/非贪婪特性

之前已经简单介绍了Python正则表达式的基础与捕获,那么在这一篇文章里,我将总结一下正则表达式的贪婪/非贪婪特性。  贪婪 默认情况下,正则表达式将进行贪婪匹配。所谓“贪婪”...

用python生成1000个txt文件的方法

用python生成1000个txt文件的方法

问题,用python生成如下所示的1000个txt文件? 解答: import os for i in range(0,1001): os.mknod("./a/%04d.txt...