2014-09-02 92 views
1

我是python和編程的新手,正在通過「機器學習:算法透視」的方式工作。我被告知要對數據進行規範化處理,將其分爲訓練和測試數據,恢復測試向量,然後使用總和最小平方誤差。我一直得到,AttributeError:函數'object has no attribute'linreg'

文件 「/用戶/ shaune /升降梭箱/ Shaune博士/ auto-mpg.py」,第34行,在 的β= linreg.linreg(賴寧,traintgt)

AttributeError的:「功能

import os 
import pylab as pl 
import numpy as np 

from pylab import * 
from numpy import * 
import linreg 

os.chdir('/Users/shaune/Dropbox/Shaune PhD') 
auto=np.loadtxt('auto-mpg.data.txt',comments='"') 

#normalise the data 
auto=(auto-auto.mean(axis=0))/auto.var(axis=0) 

#seperate the training and testing data 
trainin=auto[::2,:8] 
testin=auto[1::2,:8] 
traintgt=auto[::2,1:2] 
testtgt=auto[1::2,1:2] 

#recover the beta vector 
def linreg(trainin,traintgt): 
    trainin=np.concatenate((trainin,-np.ones((np.shape(trainin)[0],1))),axis=1) 
    beta=np.dot(np.dot(np.linalg.inv(np.dot(np.transpose(trainin),trainin)),np.transpose(trainin)),traintgt) 
    traintgt=np.dot(trainin, beta) 

#sum of squares error to get predicted values on test set (want small values) 
beta=linreg.linreg(trainin,traintgt) 
testin=concatenate((testin,-np.ones((np.shape(testin)[0],1))),axis=1) 
testout=dot(testin,beta) 
error=sum((testout-testtgt)**2) 
print error 

請幫助:運行以下時,'對象有沒有屬性 'linreg'

!謝謝。

回答

1

此功能

def linreg(trainin,traintgt): 

的定義覆蓋掉你

import linreg 

進口重命名功能名稱linreg。評論說recover the beta vector,所以也許更好的名字是recover_beta。也就是說,def聲明改爲

def recover_beta(trainin,traintgt): 

你可能會想一個return語句添加到功能,而你在這。目前它不會返回任何東西。

+0

非常感謝你。這工作!但我不明白現在發生了什麼。我以爲我在用linreg來分離數據。當我更改名稱時,似乎並沒有再次引用這些行。它給了我什麼?我也試過返回,但它說:SyntaxError:'return'外部函數。 – Shaune 2014-09-03 00:38:07

相關問題