特征工程(五)length

本文介绍了一种文本预处理方法,通过统计文本中单词的长度,为后续的自然语言处理任务提供基础特征。使用Python pandas库读取训练和测试数据集,定义函数get_word_len来获取每个单词的长度,最后将结果保存为CSV文件。
'''
将原始数据的word的长度特征,并将结果保存到本地

article特征可做类似处理

'''
df_train=pd.read_csv('train_set.csv')
df_test=pd.read_csv('test_set.csv')


def get_word_len(df_series):
	word_len=[]
	for row in df_series:
    	word_len.append(len(row.split(' ')))
    return word_len

df_train_word = pd.DataFrame({'id':df_train['id'].values.tolist(),'word_len':get_word_len(df_train['word_seg'])})
df_test_word = pd.DataFrame({'id':df_test['id'].values.tolist(),'word_len':get_word_len(df_test['word_seg'])})


df_train_word.to_csv('./train_word_len.csv',index=False)
df_test_word.to_csv('./test_word_len.csv',index=False)
### 特征工程示例代码 在机器学习项目中,特征工程是一个至关重要的环节。以下是基于 `scikit-learn` 的特征预处理和特征选择的完整示例代码。 #### 数据加载与初始化 首先导入必要的库并加载鸢尾花数据集: ```python import numpy as np import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn.compose import ColumnTransformer from sklearn.ensemble import RandomForestClassifier from sklearn.feature_selection import SelectKBest, f_classif # 加载鸢尾花数据集 data = load_iris() X = pd.DataFrame(data.data, columns=data.feature_names) y = data.target # 添加一些分类特征和缺失值 np.random.seed(0) missing_indices = np.random.choice(X.index, size=10, replace=False) X.loc[missing_indices, 'sepal length (cm)'] = None X['category_feature'] = np.random.choice(['A', 'B', 'C'], size=len(X)) ``` #### 预处理管道 创建一个预处理管道来处理数值特征和分类特征: ```python numeric_features = ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'] categorical_features = ['category_feature'] numeric_transformer = Pipeline(steps=[ ('imputer', SimpleImputer(strategy='mean')), ('scaler', StandardScaler()) ]) categorical_transformer = Pipeline(steps=[ ('onehot', OneHotEncoder(handle_unknown='ignore')) ]) preprocessor = ColumnTransformer( transformers=[ ('num', numeric_transformer, numeric_features), ('cat', categorical_transformer, categorical_features) ]) ``` #### 特征选择 通过统计检验方法(如 F 检验)进行特征选择: ```python selector = SelectKBest(score_func=f_classif, k=3) pipeline = Pipeline(steps=[ ('preprocessor', preprocessor), ('feature_selector', selector), ('classifier', RandomForestClassifier(random_state=42)) ]) ``` #### 训练与评估模型 将数据拆分为训练集和测试集,并训练随机森林分类器: ```python X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) pipeline.fit(X_train, y_train) score = pipeline.score(X_test, y_test) print(f"Model Accuracy: {score:.2f}") ``` 以上代码展示了如何使用 `scikit-learn` 进行完整的特征预处理、特征选择以及建模过程[^1]。 --- ### 数据降维示例 如果需要进一步降低维度,可以引入主成分分析(PCA),这是常见的无监督降维技术之一: ```python from sklearn.decomposition import PCA pca = PCA(n_components=2) X_pca = pca.fit_transform(preprocessor.transform(X)) df_pca = pd.DataFrame(X_pca, columns=['PC1', 'PC2']) print(df_pca.head()) ``` 此部分利用了 `PCA` 将高维数据降至二维空间以便可视化或简化后续计算[^2]。 --- ### 可视化异常检测 为了识别潜在的异常值,还可以借助箱线图完成初步探索: ```python import matplotlib.pyplot as plt plt.figure(figsize=(8, 6)) X.boxplot(column=numeric_features) plt.title('Box Plot of Numeric Features') plt.show() ``` 上述代码片段能够帮助快速定位可能存在的离群点[^3]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值