2017-07-26 10 views
0

を出力:単変量線形回帰私は現在のpythonの単変量線形回帰の実装を書いているのNaN

# implementation of univariate linear regression 
import numpy as np 


def cost_function(hypothesis, y, m): 
    return (1/(2 * m)) * ((hypothesis - y) ** 2).sum() 


def hypothesis(X, theta): 
    return X.dot(theta) 


def gradient_descent(X, y, theta, m, alpha): 
    for i in range(1500): 
    temp1 = theta[0][0] - alpha * (1/m) * (hypothesis(X, theta) - y).sum() 
    temp2 = theta[1][0] - alpha * (1/m) * ((hypothesis(X, theta) - y) * X[:, 1]).sum() 
    theta[0][0] = temp1 
    theta[1][0] = temp2 

    return theta 

if __name__ == '__main__': 
    data = np.loadtxt('data.txt', delimiter=',') 

    y = data[:, 1] 
    m = y.size 
    X = np.ones(shape=(m, 2)) 
    X[:, 1] = data[:, 0] 
    theta = np.zeros(shape=(2, 1)) 
    alpha = 0.01 

    print(gradient_descent(X, y, theta, m, alpha)) 

このコードシータのための出力NaNは、無限大に行くの後になります - 私は何が起こっているのかを把握することはできません間違っていますが、それは確かに私の勾配降下関数におけるthetaの変更に関係しています。

私が使用しているデータは、私がオンラインになった単純な線形回帰ペアのデータセットであり、正しくロードされます。

誰でも正しい方向に向けることができますか?

答えて

0

あなたが見ている問題は、X[:,1]またはdata[:,1]を実行すると、シェイプ(m、)のオブジェクトが表示されることです。シェイプのマトリクスと形状(M)のオブジェクトを掛けると(mは、1)は、(あなたが Y = y.reshapeを行う場合サイズの行列(M、M)

a = np.array([1,2,3]) 
b = np.array([[4],[5],[6]]) 
(a*b).shape #prints (3,3) 

を得ます(M、1)あなたは

X_1 = X[:,1].reshape((m,1)) 

を行う) あなたif __name__ブロックで、あなたgradient_descent関数内では、問題を修正する必要があります。今起こっていることは、あなたがしたときにそうなることです。

((hypothesis(X, theta) - y) * X[:, 1]) 

これはあなたが望むものではありません。

私がテストに使用される完全なコードは次のとおりです。

# implementation of univariate linear regression 
import numpy as np 


def cost_function(hypothesis, y, m): 
    return (1/(2 * m)) * ((hypothesis - y) ** 2).sum() 


def hypothesis(X, theta): 
    return X.dot(theta) 


def gradient_descent(X, y, theta, m, alpha): 
    X_1 = X[:,1] 
    X_1 = X_1.reshape((m,1)) 
    for i in range(1500): 
    temp1 = theta[0][0] - alpha * (1/m) * (hypothesis(X, theta) - y).sum() 
    temp2 = theta[1][0] - alpha * (1/m) * ((hypothesis(X, theta) - y) * X_1).sum() 
    theta[0][0] = temp1 
    theta[1][0] = temp2 

    return theta 

if __name__ == '__main__': 
    data= np.random.normal(size=(100,2)) 

    y = 30*data[:,0] + data[:, 1] 
    m = y.size 
    X = np.ones(shape=(m, 2)) 
    y = y.reshape((m,1)) 
    X[:, 1] = data[:, 0] 
    theta = np.zeros(shape=(2, 1)) 
    alpha = 0.01 

    print(gradient_descent(X, y, theta, m, alpha)) 
+0

残念ながら、これは問題を解決していないようだ - 同じ出力前と同じように。 – bag

+0

また、X [:、1]の形を変える必要があります。私は編集します –

+0

まだ運がない!以前と同じ出力。 if __name__ブロックのmの宣言の直後に、y = y.reshape((m、1))を挿入しました。また、x1 = X [:, 1] .reshape((m、1)) gradient_descent。 – bag

関連する問題