基于python中theano庫的線性回歸
theano庫是做deep learning重要的一部分,其最吸引人的地方之一是你給出符號(hào)化的公式之后,能自動(dòng)生成導(dǎo)數(shù)。本文使用梯度下降的方法,進(jìn)行數(shù)據(jù)擬合,現(xiàn)在把代碼貼在下方
代碼塊
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() #定義符號(hào)化的公式
x = T.dscalar('x') #定義符號(hào)化的公式
y = T.dscalar('y') #定義符號(hào)化的公式
reg = Linear_Reg(x = x)
cost = reg.msl(y)
a_g = T.grad(cost = cost,wrt = reg.a) #計(jì)算梯度
b_g = T.grad(cost = cost, wrt = reg.b) #計(jì)算梯度
updates=[(reg.a,reg.a - rate * a_g),(reg.b,reg.b - rate * b_g)] #更新參數(shù)
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)
其基本思想是隨機(jī)梯度下降。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
MySQLdb ImportError: libmysqlclient.so.18解決方法
這篇文章主要介紹了MySQLdb ImportError: libmysqlclient.so.18解決方法,需要的朋友可以參考下2014-08-08
使用Python操作Redis所有數(shù)據(jù)類型的方法
當(dāng)今互聯(lián)網(wǎng)時(shí)代,數(shù)據(jù)處理已經(jīng)成為了一個(gè)非常重要的任務(wù),而Redis作為一款高性能的NoSQL數(shù)據(jù)庫,越來越受到了廣大開發(fā)者的喜愛,本篇博客將介紹如何使用Python操作Redis的所有類型,以及一些高級(jí)用法,需要的朋友可以參考下2023-11-11
Python?socket之TCP通信及下載文件的實(shí)現(xiàn)
本文主要介紹了Python?socket之TCP通信及下載文件的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
python 讀入多行數(shù)據(jù)的實(shí)例
下面小編就為大家分享一篇python 讀入多行數(shù)據(jù)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04
python unittest實(shí)現(xiàn)api自動(dòng)化測(cè)試
這篇文章主要為大家詳細(xì)介紹了python unittest實(shí)現(xiàn)api自動(dòng)化測(cè)試的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-04-04
pymysql之cur.fetchall() 和cur.fetchone()用法詳解
這篇文章主要介紹了pymysql之cur.fetchall() 和cur.fetchone()用法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-05-05

