gpt4 book ai didi

pandas - 用于方差分析和回归的 Pandas 中的分类变量用法?

转载 作者:行者123 更新时间:2023-12-04 12:38:53 24 4
gpt4 key购买 nike

准备一个小玩具示例:

import pandas as pd
import numpy as np

high, size = 100, 20
df = pd.DataFrame({'perception': np.random.randint(0, high, size),
'age': np.random.randint(0, high, size),
'outlook': pd.Categorical(np.tile(['positive', 'neutral', 'negative'], size//3+1)[:size]),
'smokes': pd.Categorical(np.tile(['lots', 'little', 'not'], size//3+1)[:size]),
'outcome': np.random.randint(0, high, size)
})
df['age_range'] = pd.Categorical(pd.cut(df.age, range(0, high+5, size//2), right=False,
labels=["{0} - {1}".format(i, i + 9) for i in range(0, high, size//2)]))
np.random.shuffle(df['smokes'])

这会给你类似的东西:
In [2]: df.head(10)
Out[2]:
perception age outlook smokes outcome age_range
0 13 65 positive little 22 60 - 69
1 95 21 neutral lots 95 20 - 29
2 61 53 negative not 4 50 - 59
3 27 98 positive not 42 90 - 99
4 55 99 neutral little 93 90 - 99
5 28 5 negative not 4 0 - 9
6 84 83 positive lots 18 80 - 89
7 66 22 neutral lots 35 20 - 29
8 13 22 negative lots 71 20 - 29
9 58 95 positive not 77 90 - 99

目标:找出 outcome 的可能性, 给定 {perception, age, outlook, smokes} .

次要目标:找出每列在确定 outcome 中的重要性.

第三个目标:证明关于分布的属性(这里我们是随机生成的,所以随机分布应该意味着 null hypothesis 是真的?)

显然,这些都是可以通过 statistical hypothesis testing 找到的问题。 .在 Pandas 中回答这些问题的正确方法是什么?

最佳答案

找出 outcome 的可能性给定的列和特征重要性(1 和 2)

分类数据

由于数据集包含分类值,我们可以使用 LabelEncoder() 将分类数据转换为数值数据。

from sklearn.preprocessing import LabelEncoder

enc = LabelEncoder()
df['outlook'] = enc.fit_transform(df['outlook'])
df['smokes'] = enc.fit_transform(df['smokes'])

结果

df.head()

perception age outlook smokes outcome age_range
0 67 43 2 1 78 0 - 9
1 77 66 1 1 13 0 - 9
2 33 10 0 1 1 0 - 9
3 74 46 2 1 22 0 - 9
4 14 26 1 2 16 0 - 9

无需创建任何模型,我们就可以使用 chi-squared test , p-valuecorrelation matrix来确定关系。

相关矩阵

import matplotlib.pyplot as plt
import seaborn as sns

corr = df.iloc[:, :-1].corr()
sns.heatmap(corr,
xticklabels=corr.columns,
yticklabels=corr.columns)
plt.show()

Correlation matrix

卡方检验和 p 值

from sklearn.feature_selection import chi2

res = chi2(df.iloc[:, :4], df['outcome'])
features = pd.DataFrame({
'features': df.columns[:4],
'chi2': res[0],
'p-value': res[1]
})

结果

features.head()

features chi2 p-value
0 perception 1436.012987 1.022335e-243
1 age 1416.063117 1.221377e-239
2 outlook 61.139303 9.805304e-01
3 smokes 57.147404 9.929925e-01

随机生成的数据,所以零假设为真。我们可以通过尝试将正态曲线拟合到 outcome 来验证这一点。 .

经销

import scipy as sp

sns.distplot(df['outcome'], fit=sp.stats.norm, kde=False)
plt.show()

Distribution

从图中我们可以得出结论,数据不符合正态分布(因为它是随机生成的。)

注:由于数据都是随机生成的,因此您的结果可能会因数据集的大小而异。

引用文献
  • Hypothesis testing
  • Feature selection
  • 关于pandas - 用于方差分析和回归的 Pandas 中的分类变量用法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56267110/

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