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

使用MLPRegressor时遭遇KeyError问题求助

MLPRegressor时遭遇KeyError问题求助

我在尝试运行一个MLP回归模型时遇到了KeyError,其他类似案例我都能解决,但这个问题难住我了。我试过调整axis参数和reshape,但都没用。

运行代码后出现如下错误:

Traceback (most recent call last):
File "c:\BAULO\PYTHON\ESTRUCTURAS\P_ML\UNIDAD6\Book16.py", line 14, in <module>
data_y = msu_df[w]
File "C:\Users\Mauri\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\frame.py", line 3810, in __getitem__
indexer = self.columns._get_indexer_strict(key, "columns")[1]
File "C:\Users\Mauri\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\base.py", line 6111, in _get_indexer_strict
self._raise_if_missing(keyarr, indexer, axis_name)
File "C:\Users\Mauri\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\indexes\base.py", line 6171, in _raise_if_missing
raise KeyError(f"None of [{key}] are in the [{axis_name}]")
KeyError: "None of [Index([('N_Applications',)], dtype='object')] are in the [columns]"

我的代码如下:

import pandas as pd
import numpy as np
from sklearn.neural_network import MLPRegressor

msu_df = pd.read_csv('MSU applications.csv')
msu_df.set_index('Year', drop=True, inplace=True)

X = ['P_Football_Performance','SMAn2']
y = 'N_Applications'

w = np.reshape(y, (1,-1))
data_X = msu_df[X]
data_y = msu_df[w]

mlp = MLPRegressor(hidden_layer_sizes=6, max_iter=100000)
print(mlp.predict(mlp.fit(data_X, data_y)))

问题出在哪?

你这错误核心是对目标列名的处理搞复杂啦!原本y就是个普通的字符串列名'N_Applications',结果你用np.reshape(y, (1,-1))把它转成了一个二维数组。当你拿这个数组去取DataFrame的列时,pandas会把它当成一个带元组的索引来找列,但你的DataFrame里哪有这种奇怪的列名呀,自然就抛出KeyError了。

怎么改?

完全不需要给列名做reshape操作,scikit-learn的模型对pandas的Series兼容性很好,直接用原始列名取数就行。修正后的代码如下:

import pandas as pd
import numpy as np
from sklearn.neural_network import MLPRegressor

msu_df = pd.read_csv('MSU applications.csv')
msu_df.set_index('Year', drop=True, inplace=True)

X = ['P_Football_Performance','SMAn2']
y = 'N_Applications'

# 删掉那个多余的reshape步骤!
data_X = msu_df[X]
data_y = msu_df[y]

mlp = MLPRegressor(hidden_layer_sizes=6, max_iter=100000)
# 分开写拟合和预测会更清晰,当然你原来的写法也能跑,但可读性差一点
mlp.fit(data_X, data_y)
print(mlp.predict(data_X))

额外小提示

如果之后真的需要把目标变量改成二维数组(比如某些小众模型有要求),那也得先拿到列数据再reshape,比如:

data_y = msu_df[y].values.reshape(-1, 1)

不过对于MLPRegressor来说,一维的Series或者数组都能正常用,所以这步其实没必要做~

备注:内容来源于stack exchange,提问作者Mauricio Luis Vega

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 15:43:17