2015-11-18 54 views
0

https://gist.github.com/marcelcaraciolo/1321585把一個線性迴歸溶液一起

從這個代碼,我試圖找到的θ係數的數據的集合,我目前具有在numpy的陣列。我已將訓練數組保存到名爲'foo.csv'的csv。我通過使用熊貓庫從另一個csv文件轉換我的代碼,目前我的訓練集是10886行×12列。我的第一列是我想要預測的Y或值,其他所有列都是我希望獲得theta值的變量。

這應該意味着我最終得到一個12乘1的θ值矩陣,因爲有12個因變量。

現在我對Python比較陌生。我目前正在運行iPython,並且想要提供測試數組的名稱,因爲我將它保存爲名爲'foo.csv'的csv文件。我希望能夠寫[1] MVLR.calctheta(foo.csv)並且輸出是一個12乘1的矩陣。但我不明白。我不斷收到一個:

AttributeError: 'module' object has no attribute 'calctheta' 

但我已經清楚地保存calctheta作爲一個功能,我不理解爲什麼我不能調用它。我是否錯誤地聲明瞭這個方法? 我假設我可以評估theta值,然後運行for循環,以便使用這些theta值和因變量評估每個測試行。

我遇到問題的是這個calctheta函數,我已經從上面的github改變了。我想它,所以我可以叫calctheta與

def calctheta(name): 
    data = genfromtxt (name, delimiter=",") 
    y = data[:,0] 
    X = data[:,1:11] 


    #number of training samples 
    m = y.size 

    y.shape = (m, 1) 

    #Scale features and set them to zero mean 
    x, mean_r, std_r = feature_normalize(X) 

    #Add a column of ones to X (interception data) 
    it = ones(shape=(m, 12)) 
    it[:, 1:12] = x 

    #Some gradient descent settings 
    iterations = 100 
    alpha = 0.01 

    #Init Theta and Run Gradient Descent 
    theta = zeros(shape=(11, 1)) 

    theta, J_history = gradient_descent(it, y, theta, alpha, iterations) 
    print theta 
    plot(arange(iterations), J_history) 
    xlabel('Iterations') 
    ylabel('Cost Function') 
    show() 

csv文件在一個側面說明,這種多變量線性迴歸的問題,有許多因變量。我的一些變量是根據0級的等級確定的 - >有多少個選項。

例如如果有3個選項用於該列選擇,那麼將通過訓練集確定分佈,但是對於其他列,這是原始值,所以平均值就是這樣(例如那是一個溫度列)

我的問題是,當計算theta值,變量排名選項不同的事實不會失去使用多變量線性迴歸的資格。如果我們假設你試圖衡量的最終目標通常是相對於其投入而分配的,我認爲它不會。

編輯:

我將此添加到我的代碼的頂部和縮進我的代碼的其餘部分用:

class MVLR: 

現在我越來越

NameError: name 'calctheta' is not defined 

編輯2:

我的代碼

類MVLR:

from numpy import loadtxt, zeros, ones, array, genfromtxt, linspace, logspace, mean, std, arange 
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
from pylab import plot, show, xlabel, ylabel 

#Evaluate the linear regression 

def __init__(self, name): 
    self.name = name 

def feature_normalize(self.X): 
    mean_r = [] 
    std_r = [] 
    X_norm = X 
    n_c = X.shape[1] 
    for i in range(n_c): 
     m = mean(X[:, i]) 
     s = std(X[:, i]) 
     mean_r.append(m) 
     std_r.append(s) 
     X_norm[:, i] = (X_norm[:, i] - m)/s 
    return X_norm, mean_r, std_r 


def compute_cost(self, X, y, theta): 
    ''' 
    Comput cost for linear regression 
    ''' 
    #Number of training samples 
    m = y.size 

    predictions = X.dot(theta) 

    sqErrors = (predictions - y) 

    J = (1.0/(2 * m)) * sqErrors.T.dot(sqErrors) 

    return J 


def gradient_descent(self, X, y, theta, alpha, num_iters): 
    ''' 
    Performs gradient descent to learn theta 
    by taking num_items gradient steps with learning 
    rate alpha 
    ''' 
    m = y.size 
    J_history = zeros(shape=(num_iters, 1)) 

    for i in range(num_iters): 

     predictions = X.dot(theta) 

     theta_size = theta.size 

     for it in range(theta_size): 

      temp = X[:, it] 
      temp.shape = (m, 1) 

      errors_x1 = (predictions - y) * temp 

      theta[it][0] = theta[it][0] - alpha * (1.0/m) * errors_x1.sum() 

     J_history[i, 0] = compute_cost(X, y, theta) 

    return theta, J_history 

#Load the dataset 



#Plot the data 
''' 
fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 
n = 100 
for c, m, zl, zh in [('r', 'o', -50, -25)]: 
    xs = data[:, 0] 
    ys = data[:, 1] 
    zs = data[:, 2] 
    ax.scatter(xs, ys, zs, c=c, marker=m) 
ax.set_xlabel('Size of the House') 
ax.set_ylabel('Number of Bedrooms') 
ax.set_zlabel('Price of the House') 
plt.show() 
''' 

def calctheta(self, name): 
    data = genfromtxt (name, delimiter=",") 
    y = data[:,0] 
    X = data[:,1:11] 


    #number of training samples 
    m = y.size 

    y.shape = (m, 1) 

    #Scale features and set them to zero mean 
    x, mean_r, std_r = feature_normalize(X) 

    #Add a column of ones to X (interception data) 
    it = ones(shape=(m, 12)) 
    it[:, 1:12] = x 

    #Some gradient descent settings 
    iterations = 100 
    alpha = 0.01 

    #Init Theta and Run Gradient Descent 
    theta = zeros(shape=(11, 1)) 

    theta, J_history = gradient_descent(it, y, theta, alpha, iterations) 
    print theta 
    plot(arange(iterations), J_history) 
    xlabel('Iterations') 
    ylabel('Cost Function') 
    show() 
+0

你可以發佈整個文件嗎?爲了做'MVLR.calctheta(foo.cv)',你實際上需要一個叫做MVLR的類,它有calctheta方法。可悲的是,僅僅在文件中使用該方法是不夠的。 – Proghero

+0

我將此添加到我的代碼的頂部和縮進我的代碼,其餘: 類MVLR: 現在我越來越 NameError:名字「calctheta」沒有定義 – user3042850

+0

什麼是你的源的名稱文件?如果它是'multlin.py',你應該可以在IPython中輸入:'import multlin; multlin.calctheta( 'foo.csv')'。 – yuzeh

回答

0

你應該考慮設計使用類代碼。你可以讓你的文件看起來像這樣(從你的問題採取了部分代碼):

from numpy import loadtxt, zeros, ones, array, genfromtxt, linspace, logspace, mean, std, arange 
from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt 
from pylab import plot, show, xlabel, ylabel 

class MyClass(object): 
    def __init__(self, name): 
     self.name = name 

    def calculate_theta(self, name): 
     # code calculating theta here 
     return theta 

    def feature_normalize(self.X): 
     mean_r = [] 
     std_r = [] 
     X_norm = X 
     n_c = X.shape[1] 
     for i in range(n_c): 
      m = mean(X[:, i]) 
      s = std(X[:, i]) 
      mean_r.append(m) 
      std_r.append(s) 
      X_norm[:, i] = (X_norm[:, i] - m)/s 
     return X_norm, mean_r, std_r 

if __name__ == '__main__': 
    my_class = MyClass(some_input_x) 
    my_class.calculate_theta(some_input_y) 

Here你可以得到如何創建類一個更好的例子。

+0

我將這添加到我的代碼的頂部和縮進我的代碼的其餘部分: 類MVLR: 現在我越來越 NameError:名字「calctheta」沒有定義 – user3042850

+0

奇怪,我沒有得到這個錯誤。是否有你的代碼比你在這裏發佈?也許calctheta被稱爲別的地方? (注意:我對我的回答做了一些小修改) – Proghero

+0

我添加了我的代碼,可以看一下嗎? – user3042850