python - 线性回归 - 使用 MinMaxScaler() 获取特征重要性 - 极大的系数
问题描述
我正在尝试获取回归模型的特征重要性。我有 58 个自变量和 1 个因变量。大多数自变量是数值的,有些是二进制的。
首先我用这个:
X = dataset.drop(['y'], axis=1)
y = dataset[['y']]
# define the model
model = LinearRegression()
# fit the model
model.fit(X, y)
# get importance
importance = model.coef_[0]
print(model.coef_)
print(importance)
# summarize feature importance
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
pyplot.bar([x for x in range(len(importance))], importance)
pyplot.show()
并得到以下结果: 特征重要性图
然后我在拟合模型之前使用 MinMaxScaler() 来缩放数据:
scaler = MinMaxScaler()
dataset[dataset.columns] = scaler.fit_transform(dataset[dataset.columns])
print(dataset)
X = dataset.drop(['y'], axis=1)
y = dataset[['y']]
# define the model
model = LinearRegression()
# fit the model
model.fit(X, y)
# get importance
importance = model.coef_[0]
print(model.coef_)
print(importance)
# summarize feature importance
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
pyplot.bar([x for x in range(len(importance))], importance)
pyplot.show()
这导致了以下情节: 使用 MinMaxScaler 后的特征重要性图
正如您在左上角看到的那样,它是 1e11,这意味着最大值为负 600 亿。我在这里做错了什么?它甚至是使用 MinMaxScaler 的正确方法吗?
解决方案
在回归分析中,系数的大小不一定与其重要性相关。确定回归分析中自变量重要性的最常见标准是 p 值。小 p 值意味着高水平的重要性,而高 p 值意味着变量在统计上不显着。当您的模型惩罚变量时,您应该只使用系数的大小作为特征重要性的度量。也就是说,当优化问题具有 L1 或 L2 惩罚时,例如 lasso 或 ridge 回归。
sklearn
虽然不报告 p 值。我建议使用statsmodels.OLS
. 对于所有其他模型,包括树、集成、神经网络等,您应该使用它feature_importances_
来确定每个自变量的个体重要性。
通过model.coef_
用作特征重要性的度量,您只考虑了 beta 的大小。如果这确实是您感兴趣的内容,请尝试numpy.abs(model.coef_[0])
,因为 beta 也可能是负数。
至于您的使用min_max_scaler()
,您使用正确。但是,您正在转换整个数据集,而实际上,您只应该重新调整自变量。
X = dataset.drop(['y'], axis=1)
y = dataset['y']
scaler = MinMaxScaler()
X = scaler.fit_transform(X)
print(X)
通过使用scaler.fit_transform(dataset[dataset.columns])
,您正在重新调整dataset
对象中的所有列,包括您的因变量。实际上,您的代码等效于scaler.fit_transform(dataset)
,因为您选择了 中的所有列dataset
。
通常,仅当您怀疑异常值影响您的估算器时,您才应该重新缩放数据。通过重新缩放您的数据,beta 系数不再是可解释的(或至少不那么直观)。发生这种情况是因为给定的贝塔不再表示因相应自变量的边际变化引起的因变量的变化。
最后,这应该不是问题,但为了安全起见,请确保缩放器不会更改您的二进制自变量。