线性回归:ValueError:操作数无法与形状一起广播 (3,) (1338,)

数据挖掘 机器学习 Python 线性回归 执行
2022-02-25 17:52:49

我尝试对保险数据使用线性回归。但是在尝试使用 features 参数调用函数时出错。这是我的代码:

def h(x):
    global w
    return np.sum(np.transpose(w)*x)
    raise NotImplementedError()

当尝试使用简单的数据时,它工作正常,

w, x = [1,2,3], [2,3,4]
h(x)

输出为:20

但是当尝试使用数据集时,它会出错:

features = dataset.drop(["charges"], axis=1).values
h(features )

它返回错误:

ValueError: operands could not be broadcast together with shapes (3,) (1338,) 

所以功能看起来像这样:

array([[0.1173913 , 0.        , 0.35698144, 0.        , 1.        ],
       [0.1       , 1.        , 0.48331988, 1.        , 0.        ],
       [0.27391304, 1.        , 0.46674738, 3.        , 0.        ],
       ...,
       [0.1       , 0.        , 0.5496099 , 0.        , 0.        ],
       [0.15217391, 0.        , 0.3117837 , 0.        , 0.        ],
       [0.84782609, 0.        , 0.38216303, 0.        , 1.        ]])

我使用的数据是来自 kaggle.com 的 insurance.csv

1个回答

看起来您正在尝试逐点乘以矩阵和向量。这种操作没有定义。我认为你应该使用X.dot(w), whereX是一个特征并且是 wights可以处理不同性质的对象(如矩阵和向量)。所以我会写另外,我只会用矩阵来调用它(为了一致性),即使有一个对象,在这种情况下它也会是仔细观察进入函数的对象的形状。matrixwvectornp.dothreturn X.dot(w)XXR1×d