我正在尝试对Andrew Ng机器学习课程练习#2中找到的身高与年龄数据进行线性回归,相关数据可以在http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex2/ex2.html找到。
x和y的训练样本分别存储在两个.dat文件中,每个样本仅使用一个特征描述。年龄(以年为单位)和身高(以英尺为单位)的数据通过换行符分隔,格式如下:
身高-x
2.0658746
2.3684087
2.5399929
2.5420804
年龄-y
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 npX_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 thetatheta = normal_equation(X_array, y_array)print(theta)
回答:
你读取文件的方式有误。查看文件,你会发现只有50行,但你的代码中m
的值是106。原因是当你使用np.fromfile()
而不指定分隔符时,默认会按二进制读取。但对于这些文件,你可能并不希望这样做。
尝试将你的导入代码改为:
array = np.fromfile('path/to/ex2x.dat', sep=' ', dtype=float)
来自numpy文档:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html
sep : str 如果文件是文本文件,则为项目之间的分隔符。空分隔符(””)表示文件应被视为二进制。分隔符中的空格(” “)匹配零个或多个空白字符。仅由空格组成的分隔符必须至少匹配一个空白字符。
做出此更改后,你的代码现在返回:
[[ 0.75016254][ 0.06388117]]