gpt4 book ai didi

python - 用于特征选择的单变量线性回归测试?

转载 作者:太空宇宙 更新时间:2023-11-03 21:46:22 30 4
gpt4 key购买 nike

我一直在阅读有关 scikit 的 feature_selection 包下提供的 f_regression 函数的信息。根据我读到并引用的内容,它说:

Linear model for testing the individual effect of each of many regressors. This is a scoring function to be used in a feature seletion procedure, not a free standing feature selection procedure.

This is done in 2 steps:

  • The correlation between each regressor and the target is computed, that is, ((X[:, i] - mean(X[:, i])) * (y - mean_y)) / (std(X[:, i]) * std(y)).
  • It is converted to an F score then to a p-value.

因此,在第一部分中,我认为他们正在计算相关系数,但我找不到如何将这些相关系数转换为 F 分数,然后转换为 p 值的部分。有人可以举一些分析示例来了解如何执行该过程吗?

谢谢

最佳答案

如果我们使用 this example :

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_selection import f_regression
from scipy import stats

np.random.seed(0)
X = np.random.rand(1000, 3)
y = X[:, 0] + np.sin(6 * np.pi * X[:, 1]) + 0.1 * np.random.randn(1000)

y = x1 + sin(6 * pi * x2) + 0.1 * N(0, 1),即第三个特征完全不相关。

f_test, p_values = f_regression(X, y)
f_test_norm = f_test/np.max(f_test)

plt.figure(figsize=(25, 5))
for i in range(3):
plt.subplot(1, 3, i + 1)
plt.scatter(X[:, i], y, edgecolor='black', s=20)
plt.xlabel("$x_{}$".format(i + 1), fontsize=14)
if i == 0:
plt.ylabel("$y$", fontsize=14)
plt.title("Normalized F-test={:.2f},F-test={:.2f}, p-value={:.2f}".format(f_test_norm[i],f_test[i],p_values[i]),
fontsize=16)
plt.show()

enter image description here

F 检验和 p 值的值如下:

>>> f_test, p_values
(array([187.42118421, 52.52357392, 0.47268298]),
array([3.19286906e-39, 8.50243215e-13, 4.91915197e-01]))

让我们首先计算相关性:

df = pd.DataFrame(X)
df['y'] = y
0 1 2 y
0 0.548814 0.715189 0.602763 1.004714
1 0.544883 0.423655 0.645894 0.900226
2 0.437587 0.891773 0.963663 -0.919160
...

>>> df.corr()['y']
0 0.397624
1 -0.223601
2 0.021758
y 1.000000

corr = df.corr()['y'][:3]

然后根据this ,他们计算degrees_of_freedom ,如len(y) - 2如果center参数为 true 且 len(y) - 1否则:

degrees_of_freedom = y.size - (2 if center else 1)

F-统计量的计算方式为

F = corr ** 2 / (1 - corr ** 2) * degrees_of_freedom在我们的例子中给出:

0    187.421184
1 52.523574
2 0.472683
Name: y, dtype: float64

然后使用 survival function 计算 p 值:

pv = stats.f.sf(F, 1, degrees_of_freedom)
>>> pv
array([3.19286906e-39, 8.50243215e-13, 4.91915197e-01])

关于python - 用于特征选择的单变量线性回归测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52461893/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com