使用正规方程的线性回归

时间:2018-02-25 00:57:25

标签: python numpy matrix machine-learning regression

我试图对Andrew Ng的机器学习课程http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex2/ex2.html的练习#2中的高度与年龄数据进行线性回归。

x和y训练样例以两个.dat文件的形式给出,只有一个特征用于描述每个样本。 以年为单位的年龄和以英尺为单位的身高数据以此格式的换行符分隔

高度-X
2.0658746
2.3684087
2.5399929
2.5420804

年龄-γ
7.7918926
9.1596757
9.0538354
9.0566138

根据惯例,

x0 = 1用于截距。问题是通过使用正规方程找到参数theta:theta = inv(X ^ T * X)* X ^ T * y

我程序的输出给出参数[[nan],[0。]],而它应该是theta0 = 0.7502,theta1 = 0.0639。我不确定我做错了什么。我的代码如下。

import numpy as np

X_array = np.fromfile('ex2x.dat', dtype=float)

y_array = np.fromfile('ex2y.dat', dtype=float)

def normal_equation(X, y):

    m = len(X)

    bias_vector = np.ones((m,1))

    X = np.reshape(X, (m, 1))

    X = np.append(bias_vector, X, axis=1)

    y = np.reshape(y, (m, 1))

    X_transpose = X.T

    theta = np.linalg.inv(X_transpose.dot(X))
    theta = theta.dot(X_transpose)
    theta = theta.dot(y)

    return theta

theta = normal_equation(X_array, y_array)
print(theta)

0 个答案:

没有答案
相关问题