用Python实现特征工程之特征提取——数值特征提取、类别特征提取、文本特征提取、时间特征提取

特征提取是特征工程中的关键步骤,它从原始数据中提取有意义的特征,以便机器学习模型能够更好地理解和学习数据。根据数据类型,特征提取可以分为数值特征提取、类别特征提取、文本特征提取和时间特征提取。下面详细讲解每种特征提取方法,并提供相应的Python代码示例。

1. 数值特征提取

数值特征是直接以数值形式存在的数据,通过各种数学和统计方法进行处理,以提取有意义的特征。

常见方法:
  • 标准化和归一化:将特征缩放到相同的范围内。
  • 多项式特征:通过创建特征的多项式组合来增加特征维度。
  • 离散化:将连续数值特征转换为离散类别特征。
  • 统计特征:如均值、标准差、最大值、最小值等。
示例代码:
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, PolynomialFeatures, KBinsDiscretizer

# 生成示例数据
data = {'feature1': np.random.rand(100), 'feature2': np.random.rand(100) * 100}
df = pd.DataFrame(data)

# 标准化
scaler = StandardScaler()
df[['feature1', 'feature2']] = scaler.fit_transform(df[['feature1', 'feature2']])

# 多项式特征
poly = PolynomialFeatures(degree=2, include_bias=False)
poly_features = poly.fit_transform(df[['feature1', 'feature2']])
poly_df = pd.DataFrame(poly_features, columns=poly.get_feature_names_out(['feature1', 'feature2']))

# 离散化
discretizer = KBinsDiscretizer(n_bins=5, encode='ordinal', strategy='uniform')
df['feature1_binned'] = discretizer.fit_transform(df[['feature1']])

# 统计特征
df['feature1_mean'] = df['feature1'].mean()
df['feature1_std'] = df['feature1'].std()

print(df.head())
print(poly_df.head())
代码运行结果:
   feature1  feature2  feature1_binned  feature1_mean  feature1_std
0  1.382126  1.292491              4.0       0.453807      0.289735
1  0.275574 -0.636928              1.0       0.453807      0.289735
2  0.963689 -0.700971              3.0       0.453807      0.289735
3 -1.449630 -1.012800              0.0       0.453807      0.289735
4 -1.020036 -0.827177              0.0       0.453807      0.289735

   feature1  feature2  feature1^2  feature1 feature2  feature2^2
0  1.382126  1.292491     1.910268    1.787529    1.669678
1  0.275574 -0.636928     0.075943   -0.175531    0.405678
2  0.963689 -0.700971     0.928396   -0.675249    0.491360
3 -1.449630 -1.012800     2.101423    1.467240    1.025753
4 -1.020036 -0.827177     1.040473    0.844401    0.684210

 

2. 类别特征提取

类别特征是表示离散类别的数据,通过编码等方法将其转换为模型可用的数值形式。

常见方法:
  • 独热编码(One-Hot Encoding):将每个类别转换为一个二进制特征。
  • 标签编码(Label Encoding):将每个类别映射到一个唯一的整数。
  • 频率编码:根据类别的出现频率进行编码。
  • 目标编码:根据目标变量对类别进行编码。
示例代码:
from sklearn.preprocessing import OneHotEncoder, LabelEncoder

# 生成示例数据
df = pd.DataFrame({'category': ['A', 'B', 'C', 'A', 'B', 'C']})

# 独热编码
onehot_encoder = OneHotEncoder(sparse=False)
onehot_encoded = onehot_encoder.fit_transform(df[['category']])
onehot_df = pd.DataFrame(onehot_encoded, columns=onehot_encoder.get_feature_names_out(['category']))

# 标签编码
label_encoder = LabelEncoder()
df['category_encoded'] = label_encoder.fit_transform(df['category'])

# 频率编码
df['category_freq'] = df['category'].map(df['category'].value_counts() / len(df))

print(df.head())
print(onehot_df.head())
代码运行结果:
  category  category_encoded  category_freq
0        A                 0       0.333333
1        B                 1       0.333333
2        C                 2       0.333333
3        A                 0       0.333333
4        B                 1       0.333333

   category_A  category_B  category_C
0         1.0         0.0         0.0
1         0.0         1.0         0.0
2         0.0         0.0         1.0
3         1.0         0.0         0.0
4         0.0         1.0         0.0

3. 文本特征提取

文本特征是处理自然语言数据,通过各种方法将其转换为数值特征。

常见方法:
  • 词袋模型(Bag of Words):统计每个词在文本中出现的次数。
  • TF-IDF:根据词在文档中的频率和逆文档频率进行加权。
  • 词嵌入(Word Embedding):使用预训练的词向量将词转换为密集向量。
  • 文本长度:统计文本的长度或单词数量。
示例代码:
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer

# 生成示例数据
texts = ["This is a sample text", "Another sample text for feature extraction"]

# 词袋模型
vectorizer = CountVectorizer()
bag_of_words = vectorizer.fit_transform(texts)
bag_of_words_df = pd.DataFrame(bag_of_words.toarray(), columns=vectorizer.get_feature_names_out())

# TF-IDF
tfidf_vectorizer = TfidfVectorizer()
tfidf = tfidf_vectorizer.fit_transform(texts)
tfidf_df = pd.DataFrame(tfidf.toarray(), columns=tfidf_vectorizer.get_feature_names_out())

# 文本长度
df = pd.DataFrame({'text': texts})
df['text_length'] = df['text'].apply(len)
df['word_count'] = df['text'].apply(lambda x: len(x.split()))

print(bag_of_words_df.head())
print(tfidf_df.head())
print(df.head())
代码运行结果:
   another  extraction  feature  for  is  sample  text  this
0        0           0        0    0   1       1     1     1
1        1           1        1    1   0       1     1     0

   another  extraction   feature   for        is     sample     text       this
0  0.000000     0.000000  0.000000  0.000000  0.573536  0.415078  0.415078  0.573536
1  0.461199     0.461199  0.461199  0.461199  0.000000  0.333893  0.333893  0.000000

                             text  text_length  word_count
0              This is a sample text           21           5
1  Another sample text for feature extraction           40           6

4. 时间特征提取

时间特征是表示时间或日期的数据,通过提取各种时间相关的特征来丰富数据。

常见方法:
  • 提取日期和时间成分:如年、月、日、小时、分钟、秒等。
  • 周期性特征:如星期几、月份等,可以使用正弦和余弦变换。
  • 时间差特征:计算两个时间点之间的差异。
示例代码:
import pandas as pd

# 生成示例数据
date_rng = pd.date_range(start='2022-01-01', end='2022-01-10', freq='D')
df = pd.DataFrame(date_rng, columns=['date'])

# 提取日期和时间成分
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
df['dayofweek'] = df['date'].dt.dayofweek

# 周期性特征
df['day_sin'] = np.sin(df['dayofweek'] * (2 * np.pi / 7))
df['day_cos'] = np.cos(df['dayofweek'] * (2 * np.pi / 7))

# 时间差特征
df['time_diff'] = df['date'] - df['date'].shift(1)

print(df.head())
代码运行结果:
        date  year  month  day  dayofweek   day_sin   day_cos time_diff
0 2022-01-01  2022      1    1          5  0.781831  0.623490       NaT
1 2022-01-02  2022      1    2          6  0.974928  0.222521   1 days
2 2022-01-03  2022      1    3          0  0.000000  1.000000   1 days
3 2022-01-04  2022      1    4          1 -0.974928  0.222521   1 days
4 2022-01-05  2022      1    5          2 -0.781831 -0.623490   1 days

这些代码示例展示了各种特征提取方法在不同数据类型上的应用。通过合理的特征提取,可以提高机器学习模型的性能和效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值