如果我们使用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()
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,如果center参数为真,则为len(y) - 2,否则为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])