You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

训练测试集列数一致仍遇matmul维度不匹配及数组维度错误

问题分析与解决思路

我知道训练数据集列数为3、测试数据集列数为2时会触发错误,但现在训练集与测试集列数完全一致,执行以下代码时仍报错:

y_pred = lr.predict(x_test)
from sklearn.metrics import r2_score
r2_score(y_test,y_pred)

先是弹出1D数组错误,我把数据reshape成(-1,1)后,又出现新错误:

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

完整报错堆栈如下:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-176-ed3d22f24031> in <module>
----> 1 y_pred = lr.predict(x_test)
      2 from sklearn.metrics import r2_score
      3 r2_score(y_test,y_pred)

~\anaconda3\lib\site-packages\sklearn\linear_model\_base.py in predict(self, X)
    234             Returns predicted values.
    235         """
--> 236         return self._decision_function(X)
    237 
    238     _preprocess_data = staticmethod(_preprocess_data)

~\anaconda3\lib\site-packages\sklearn\linear_model\_base.py in _decision_function(self, X)
    216         check_is_fitted(self)
    217 
--> 218         X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
    219         return safe_sparse_dot(X, self.coef_.T,
    220                                dense_output=True) + self.intercept_

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in inner_f(*args, **kwargs)
     70                           FutureWarning)
     71         kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
--> 72         return f(**kwargs)
     73     return inner_f
     74 

~\anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator)
    617             # If input is 1D raise error
    618             if array.ndim == 1:
--> 619                 raise ValueError(
    620                     "Expected 2D array, got 1D array instead:\narray={}.\n"
    621                     "Reshape your data either using array.reshape(-1, 1) if "

ValueError: Expected 2D array, got 1D array instead:
array=[6.63 7.25 7.36 5.95 7.93 8.35 7.3  6.22 7.32 7.87 5.11 5.88 8.21 6.59
 7.84 7.09 5.84 7.37 5.58 7.56 6.06 6.84 7.57 6.79 7.6  5.61 4.26 6.51
 7.33 5.84 8.31 6.94 8.2  6.97 6.3  7.62 6.1  7.14 9.06 6.94].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

问题根源与解决方法

  • 第一个错误(1D数组):scikit-learn的predict方法要求输入特征矩阵是2D数组,你需要确保对x_test本身做reshape转换,而非其他数据。
  • 第二个错误(维度不匹配):size 160 is different from 40说明训练时的特征数(模型coef_的维度)和测试时的特征数不匹配,检查以下几点:
    1. 对比x_train.shape[1]和x_test.reshape(-1,1).shape[1],确保两者特征数完全一致。
    2. 确认是否对训练集做了额外特征处理(如标准化、特征选择),但未同步应用到测试集。
    3. 查看lr.coef_.shape,该值必须等于测试集的特征列数。

正确处理示例:

# 确保x_test是2D数组,且特征数与训练集一致
x_test = x_test.reshape(-1, x_train.shape[1])
# 若为单特征场景,可直接写为:x_test = x_test.reshape(-1, 1)

# 重新执行预测与评估
y_pred = lr.predict(x_test)
r2_score(y_test, y_pred)

内容的提问来源于stack exchange,提问作者Priyanshu-Ganwani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:15:32