温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python中怎么使用theano库实现线性回归

发布时间:2021-06-15 16:18:56 来源:亿速云 阅读:155 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关python中怎么使用theano库实现线性回归,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

代码块

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中怎么使用theano库实现线性回归了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI