使用pywebio时LinearRegression predict()特征数不匹配报错的解决
修复线性回归predict()的特征数量不匹配错误
我用pywebio给机器学习程序做了个小界面,不用界面的时候跑线性回归的predict()没问题。界面从用户那获取age(年龄)和salary(薪资)两个数值,存成numpy数组后转成二维数组(之前踩过数组形状的坑),但现在调用predict()时报错:ValueError: X has 1 features, but LinearRegression is expecting 2 features as input。求修复方法。
UI代码
age = int(input("Enter your age:", type=NUMBER)) salary = int(input("Enter your salary:", type=NUMBER)) entry = np.array([age, salary]) reshaped_entry = entry.reshape(-1, 1) estimate = regr.predict(reshaped_entry)
错误信息
ValueError Traceback (most recent call last) Input In [21], in <cell line: 22>() Input In [21], in retirement_ui() File ~\anaconda3\lib\site-packages\sklearn\linear_model\_base.py:362, in LinearModel.predict(self, X) 348 def predict(self, X): 349 """ 350 Predict using the linear model. 351 (...) 360 Returns predicted values. 361 """ --> 362 return self._decision_function(X) File ~\anaconda3\lib\site-packages\sklearn\linear_model\_base.py:345, in LinearModel._decision_function(self, X) 342 def _decision_function(self, X): 343 check_is_fitted(self) --> 345 X = self._validate_data(X, accept_sparse=["csr", "csc", "coo"], reset=False) 346 return safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ File ~\anaconda3\lib\site-packages\sklearn\base.py:585, in BaseEstimator._validate_data(self, X, y, reset, validate_separately, **check_params) 582 out = X, y 584 if not no_val_X and check_params.get("ensure_2d", True): --> 585 self._check_n_features(X, reset=reset) 587 return out File ~\anaconda3\lib\site-packages\sklearn\base.py:400, in BaseEstimator._check_n_features(self, X, reset) 397 return 399 if n_features != self.n_features_in_: --> 400 raise ValueError( 401 f"X has {n_features} features, but {self.__class__.__name__} " 402 f"is expecting {self.n_features_in_} features as input." 403 ) ValueError: X has 1 features, but LinearRegression is expecting 2 features as input.
修复方法
问题出在数组重塑的方向上:
- 当前
entry.reshape(-1, 1)会把[age, salary]这个长度为2的一维数组变成2行1列的二维数组,模型会判定这是2个样本、每个样本1个特征,和训练时要求的2个特征不匹配。 - 正确做法是把数组塑造成1行2列的二维数组,对应1个样本、2个特征,和训练数据的特征数量一致。
修改后的代码:
age = int(input("Enter your age:", type=NUMBER)) salary = int(input("Enter your salary:", type=NUMBER)) entry = np.array([age, salary]) # 改成reshape(1, -1),让numpy自动计算列数 reshaped_entry = entry.reshape(1, -1) # 或者一步到位直接创建二维数组:entry = np.array([[age, salary]]) estimate = regr.predict(reshaped_entry)
解释:
reshape(1, -1)会生成形状为(1,2)的数组,正好符合模型需要的「1个样本、2个特征」输入格式。- 直接用
np.array([[age, salary]])创建二维数组,省去重塑步骤,逻辑更直观。
内容的提问来源于stack exchange,提问作者Cold_and_sunny
相关产品推荐
相关产品推荐

