使用Python / Numpy实现正规方程

我编写了一些初学者代码,使用正规方程计算简单线性模型的系数。

# Modulesimport numpy as np# Loading data setX, y = np.loadtxt('ex1data3.txt', delimiter=',', unpack=True)data = np.genfromtxt('ex1data3.txt', delimiter=',')def normalEquation(X, y):    m = int(np.size(data[:, 1]))    # This is the feature / parameter (2x2) vector that will    # contain my minimized values    theta = []    # I create a bias_vector to add to my newly created X vector    bias_vector = np.ones((m, 1))    # I need to reshape my original X(m,) vector so that I can    # manipulate it with my bias_vector; they need to share the same    # dimensions.    X = np.reshape(X, (m, 1))    # I combine these two vectors together to get a (m, 2) matrix    X = np.append(bias_vector, X, axis=1)    # Normal Equation:    # theta = inv(X^T * X) * X^T * y    # For convenience I create a new, tranposed X matrix    X_transpose = np.transpose(X)    # Calculating theta    theta = np.linalg.inv(X_transpose.dot(X))    theta = theta.dot(X_transpose)    theta = theta.dot(y)    return thetap = normalEquation(X, y)print(p)

使用此处找到的小数据集:

http://www.lauradhamilton.com/tutorial-linear-regression-with-octave

我使用上述代码得到的系数是: [-0.34390603; 0.2124426 ],而不是: [24.9660; 3.3058]。谁能帮我解释一下我哪里做错了?


回答:

你的实现是正确的。你只是交换了 Xy(仔细看他们是如何定义 xy 的),这就是你得到不同结果的原因。

调用 normalEquation(y, X) 会得到 [ 24.96601443 3.30576144],正如它应该的那样。

Related Posts

Keras Dense层输入未被展平

这是我的测试代码: from keras import…

无法将分类变量输入随机森林

我有10个分类变量和3个数值变量。我在分割后直接将它们…

如何在Keras中对每个输出应用Sigmoid函数?

这是我代码的一部分。 model = Sequenti…

如何选择类概率的最佳阈值?

我的神经网络输出是一个用于多标签分类的预测类概率表: …

在Keras中使用深度学习得到不同的结果

我按照一个教程使用Keras中的深度神经网络进行文本分…

‘MatMul’操作的输入’b’类型为float32,与参数’a’的类型float64不匹配

我写了一个简单的TensorFlow代码,但不断遇到T…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注