【问题标题】:ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 13 is different from 1)ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 13 is different from 1)
【发布时间】:2021-01-11 10:04:39
【问题描述】:

我正在使用 sklearn 通过线性回归解决波士顿房价问题。 途中发生了这样的错误:

ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 13 is different from 1)

代码:

import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression

X = boston.data
y = boston.data

dfX = pd.DataFrame(X, columns = boston.feature_names)
dfy = pd.DataFrame(y, columns = ["Price"] )
df = pd.concat([dfX,dfy],axis =1)

reg = LinearRegression()
reg.fit(X,y)

x_12 = np.array(dfX["LSTAT"]).reshape(-1,1)  # 12th data in boston.data
y = np.array(dfy["Price"]).reshape(-1,1)

predict = reg.predict(x_12) > Error code

【问题讨论】:

    标签: python scikit-learn linear-regression


    【解决方案1】:

    该错误似乎是由于LinearRegression 的函数fit 用于load_boston 数据集的所有13 个特征,但在使用predict 时,您只使用1 个特征(LSTAT)。这似乎会导致训练模型和predict 输入数据之间发生冲突。您可能需要更新您的 fit 函数,使其仅接受 LSTAT 功能,以便在使用 predict 时只期望一个功能作为输入数据

    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_boston
    from sklearn.linear_model import LinearRegression
    
    boston = load_boston()
    X, y = load_boston(return_X_y=True)
    
    # X will now have only data from "LSTAT" column
    X = X[:, np.newaxis, boston.feature_names.tolist().index("LSTAT")]
    
    dfX = pd.DataFrame(X, columns = ["LSTAT"] )
    dfy = pd.DataFrame(y, columns = ["Price"] )
    df = pd.concat([dfX,dfy],axis =1)
    
    reg = LinearRegression()
    reg.fit(X, y)
    
    x_12 = np.array(dfX["LSTAT"]).reshape(-1, 1)  # 12th data in boston.data
    y = np.array(dfy["Price"]).reshape(-1, 1)
    
    predict = reg.predict(x_12)
    

    【讨论】:

      猜你喜欢
      • 2021-09-23
      • 2021-10-09
      • 1970-01-01
      • 2020-09-29
      • 2018-10-21
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      相关资源
      最近更新 更多