我正在尝试使用Numpy和Pandas在Python中实现简单的线性回归。但是我得到了一个ValueError:矩阵不是对齐的错误,因为调用点函数实质上是计算矩阵乘法,正如文档所说的那样。下面是代码片段:
import numpy as np
import pandas as pd
#initializing the matrices for X, y and theta
#dataset = pd.read_csv("data1.csv")
dataset = pd.DataFrame([[6.1101,17.592],[5.5277,9.1302],[8.5186,13.662],[7.0032,11.854],[5.8598,6.8233],[8.3829,11.886],[7.4764,4.3483],[8.5781,12]])
X = dataset.iloc[:, :-1]
y = dataset.iloc[:, -1]
X.insert(0, "x_zero", np.ones(X.size), True)
print(X)
print(f"\n{y}")
theta = pd.DataFrame([[0],[1]])
temp = pd.DataFrame([[1],[1]])
print(X.shape)
print(theta.shape)
print(X.dot(theta))
这是相同的输出:
x_zero 0
0 1.0 6.1101
1 1.0 5.5277
2 1.0 8.5186
3 1.0 7.0032
4 1.0 5.8598
5 1.0 8.3829
6 1.0 7.4764
7 1.0 8.5781
0 17.5920
1 9.1302
2 13.6620
3 11.8540
4 6.8233
5 11.8860
6 4.3483
7 12.0000
Name: 1, dtype: float64
(8, 2)
(2, 1)
Traceback (most recent call last):
File "linear.py", line 16, in <module>
print(X.dot(theta))
File "/home/tejas/.local/lib/python3.6/site-packages/pandas/core/frame.py", line 1063, in dot
raise ValueError("matrices are not aligned")
ValueError: matrices are not aligned
由于您可以看到这两个属性的形状属性的输出,第二个轴具有相同的维数(2),点函数应该返回一个8*1 DataFrame。那么,为什么会出错呢?
发布于 2020-03-17 18:59:09
这种错位不是来自形状,而是来自熊猫指数。您有两个解决问题的选项:
调整theta
分配:
theta = pd.DataFrame([[0],[1]], index=X.columns)
所以你所乘的索引是匹配的。
通过将第二个df
移动到numpy
,删除索引关联
X.dot(theta.to_numpy())
这个功能在pandas
中实际上是有用的--如果它试图匹配智能索引,那么当它变得适得其反时,您的情况就是非常具体的;)
https://stackoverflow.com/questions/60726146
复制相似问题