机器学习特征工程:从原始数据到模型输入
机器学习特征工程从原始数据到模型输入1. 引言“数据和特征决定了机器学习的上限。” 好的特征工程可以让简单模型超越复杂模型。特征工程流程原始数据 → 数据清洗 → 特征提取 → 特征变换 → 特征选择 → 模型输入2. 数值特征处理2.1 标准化与归一化fromsklearn.preprocessingimportStandardScaler,MinMaxScaler,RobustScaler# 标准化均值0方差1适合正态分布scalerStandardScaler()X_scaledscaler.fit_transform(X)# 归一化缩放到 [0, 1]scalerMinMaxScaler()X_normalizedscaler.fit_transform(X)# 鲁棒标准化用中位数和四分位距适合有异常值scalerRobustScaler()X_robustscaler.fit_transform(X)2.2 对数变换importnumpyasnp# 处理右偏分布如收入、房价X_lognp.log1p(X)# log(1 x)避免 log(0)# Box-Cox 变换fromscipy.statsimportboxcox X_boxcox,lambda_optboxcox(X1)# Yeo-Johnson 变换支持负数fromsklearn.preprocessingimportPowerTransformer ptPowerTransformer(methodyeo-johnson)X_yeojohnsonpt.fit_transform(X)3. 类别特征编码3.1 常用编码fromsklearn.preprocessingimportLabelEncoder,OrdinalEncoder,OneHotEncoder# 标签编码有序类别leLabelEncoder()encodedle.fit_transform([低,中,高,中])# [0, 1, 2, 1]# One-Hot 编码无序类别oheOneHotEncoder(sparseFalse)encodedohe.fit_transform([[红],[蓝],[红],[绿]])# [[1,0,0], [0,1,0], [1,0,0], [0,0,1]]# 目标编码高基数类别fromcategory_encodersimportTargetEncoder teTargetEncoder()encodedte.fit_transform(X_categorical,y)3.2 高基数类别处理# 频率编码freqX[city].value_counts(normalizeTrue)X[city_freq]X[city].map(freq)# 目标编码带交叉验证防止过拟合fromcategory_encodersimportTargetEncoder teTargetEncoder(smoothing10)X[city_target]te.fit_transform(X[city],y)# 嵌入编码深度学习importtorch.nnasnn embeddingnn.Embedding(num_categories100,embedding_dim8)4. 时间特征importpandasaspddefextract_time_features(df,time_col):提取时间特征df[time_col]pd.to_datetime(df[time_col])# 基础特征df[year]df[time_col].dt.year df[month]df[time_col].dt.month df[day]df[time_col].dt.day df[hour]df[time_col].dt.hour df[minute]df[time_col].dt.minute df[dayofweek]df[time_col].dt.dayofweek# 0周一df[dayofyear]df[time_col].dt.dayofyear df[week]df[time_col].dt.isocalendar().week# 周期编码sin/cosdf[month_sin]np.sin(2*np.pi*df[month]/12)df[month_cos]np.cos(2*np.pi*df[month]/12)df[hour_sin]np.sin(2*np.pi*df[hour]/24)df[hour_cos]np.cos(2*np.pi*df[hour]/24)df[dayofweek_sin]np.sin(2*np.pi*df[dayofweek]/7)df[dayofweek_cos]np.cos(2*np.pi*df[dayofweek]/7)# 布尔特征df[is_weekend]df[dayofweek].isin([5,6]).astype(int)df[is_month_start]df[time_col].dt.is_month_start.astype(int)df[is_month_end]df[time_col].dt.is_month_end.astype(int)returndf5. 文本特征fromsklearn.feature_extraction.textimportTfidfVectorizerfromtransformersimportAutoTokenizer,AutoModel# TF-IDFtfidfTfidfVectorizer(max_features10000,ngram_range(1,2))X_tfidftfidf.fit_transform(texts)# Sentence-BERT 嵌入tokenizerAutoTokenizer.from_pretrained(all-MiniLM-L6-v2)modelAutoModel.from_pretrained(all-MiniLM-L6-v2)defget_embedding(text):inputstokenizer(text,return_tensorspt,truncationTrue,max_length512)withtorch.no_grad():outputmodel(**inputs)returnoutput.last_hidden_state.mean(dim1).squeeze().numpy()6. 交互特征# 数学组合X[ratio]X[feature_a]/(X[feature_b]1e-8)X[product]X[feature_a]*X[feature_b]X[difference]X[feature_a]-X[feature_b]# 多项式特征fromsklearn.preprocessingimportPolynomialFeatures polyPolynomialFeatures(degree2,interaction_onlyTrue)X_polypoly.fit_transform(X)# 分桶X[age_bin]pd.cut(X[age],bins[0,18,35,50,65,100],labels[少年,青年,中年,老年,高龄])7. 特征选择7.1 过滤法fromsklearn.feature_selectionimportSelectKBest,f_classif,mutual_info_classif# 方差过滤删除方差为 0 的特征fromsklearn.feature_selectionimportVarianceThreshold selectorVarianceThreshold(threshold0.01)X_filteredselector.fit_transform(X)# 相关性过滤correlationsX.corrwith(y).abs()selectedcorrelations[correlations0.05].index# SelectKBestselectorSelectKBest(f_classif,k50)X_selectedselector.fit_transform(X,y)7.2 包装法fromsklearn.feature_selectionimportRFEfromsklearn.ensembleimportRandomForestClassifier# 递归特征消除modelRandomForestClassifier(n_estimators100)rfeRFE(model,n_features_to_select20,step5)X_selectedrfe.fit_transform(X,y)print(f选中的特征:{X.columns[rfe.support_].tolist()})7.3 嵌入法fromsklearn.ensembleimportGradientBoostingClassifier# 基于树模型的特征重要性modelGradientBoostingClassifier()model.fit(X,y)importancespd.Series(model.feature_importances_,indexX.columns)top_featuresimportances.nlargest(20)print(top_features)8. 特征工程 Pipelinefromsklearn.pipelineimportPipelinefromsklearn.composeimportColumnTransformer# 定义不同列的处理方式numeric_features[age,income,score]categorical_features[city,gender,education]preprocessorColumnTransformer([(num,Pipeline([(scaler,StandardScaler()),]),numeric_features),(cat,Pipeline([(encoder,OneHotEncoder(handle_unknownignore)),]),categorical_features),])# 完整 PipelinepipelinePipeline([(preprocessor,preprocessor),(feature_selection,SelectKBest(f_classif,k50)),(classifier,GradientBoostingClassifier()),])pipeline.fit(X_train,y_train)scorepipeline.score(X_test,y_test)9. 总结特征工程的核心数值特征标准化/归一化是基础对数变换处理偏态类别特征低基数用 One-Hot高基数用目标编码时间特征周期编码sin/cos比直接用数值更好特征选择先过滤快速再包装精确最后嵌入模型驱动Pipeline把所有步骤封装为可复现的流水线

相关新闻

终极指南:三步快速上手开源制造执行系统openMES

终极指南:三步快速上手开源制造执行系统openMES

终极指南:三步快速上手开源制造执行系统openMES 【免费下载链接】openMES A MES system designed based on ISA88&ISA95/一个参考ISA88&ISA95标准来设计的MES系统 项目地址: https://gitcode.com/gh_mirrors/op/openMES openMES是一款基于国际ISA88和…

2026/6/24 10:03:59阅读更多 →
5个Vue Vben Admin高效开发技巧:从权限管理到主题定制

5个Vue Vben Admin高效开发技巧:从权限管理到主题定制

5个Vue Vben Admin高效开发技巧:从权限管理到主题定制 【免费下载链接】vue-vben-admin A modern vue admin panel built with Vue3, Shadcn UI, Vite, TypeScript, and Monorepo. Its fast! 项目地址: https://gitcode.com/GitHub_Trending/vu/vue-vben-admin …

2026/6/24 9:58:58阅读更多 →
如何15分钟掌握OpenRocket:免费开源火箭设计与仿真工具实战指南

如何15分钟掌握OpenRocket:免费开源火箭设计与仿真工具实战指南

如何15分钟掌握OpenRocket:免费开源火箭设计与仿真工具实战指南 【免费下载链接】openrocket Model-rocketry aerodynamics and trajectory simulation software 项目地址: https://gitcode.com/GitHub_Trending/op/openrocket 你是否对火箭设计充满好奇&…

2026/6/24 9:58:58阅读更多 →
星流AI设计智能体:替代停运Lovart的本地化Agent解决方案

星流AI设计智能体:替代停运Lovart的本地化Agent解决方案

1. Lovart 打不开不是你的问题,是它根本没“活”过最近在几个设计类社群里频繁看到有人发问:“Lovart 为什么打不开?”“点开就是白屏/404/加载转圈半小时”“注册邮箱收不到验证链接”……我一开始以为是网络波动或浏览器兼容性问题&#xf…

2026/6/24 11:24:34阅读更多 →
Android Java登录注册UI模板:Material Design规范,AS直接导入运行

Android Java登录注册UI模板:Material Design规范,AS直接导入运行

本文还有配套的精品资源,点击获取 简介:提供一套开箱即用的Android登录与注册页面源码,基于Android Studio环境开发,纯Java编写,严格遵循Material Design设计语言。包含TextInputLayout、MaterialButton、ImageView…

2026/6/24 11:24:34阅读更多 →
OpenVAS漏洞扫描实战:从零部署到自动化安全评估

OpenVAS漏洞扫描实战:从零部署到自动化安全评估

1. 项目概述:为什么我们需要一个“服务器体检医生”?在运维和安全的日常里,服务器就像我们身体,平时看着活蹦乱跳,但内部有没有“暗疾”,光靠肉眼是看不出来的。一次未打补丁的系统漏洞、一个配置不当的开放…

2026/6/24 11:24:34阅读更多 →
Qwen3.5-35B-A3B-FP8:多模态模型轻量化落地实践

Qwen3.5-35B-A3B-FP8:多模态模型轻量化落地实践

1. 项目概述:一场被低估的模型轻量化实战突破最近在几个技术群和模型社区里,反复看到有人发截图问:“Qwen3.5-35B-A3B-FP8到底是不是真的?比Qwen3-VL快多少?显存能省多少?”——这问题背后藏着一个非常现实…

2026/6/24 11:24:34阅读更多 →
OpenClaw零代码AI漫剧工作流:阿里云+本地GPU协同实践

OpenClaw零代码AI漫剧工作流:阿里云+本地GPU协同实践

1. 这不是“零代码”,而是把AI漫剧生产链路里最硬的骨头全给你啃下来了 2026年4月,我用OpenClaw在阿里云ECS上搭起了一套能稳定生成10分钟AI漫剧的流水线——从角色设定、分镜脚本、语音合成到画面生成,全程没写一行Python或JavaScript。但“…

2026/6/24 11:24:34阅读更多 →
Postman接口自动化测试实战:从原理到CI/CD集成

Postman接口自动化测试实战:从原理到CI/CD集成

1. 项目概述:为什么我们需要Postman接口自动化测试? 如果你是一名后端开发、测试工程师,或者正在学习API开发,那么“Postman接口自动化测试”这个标题对你来说,绝不仅仅是一个工具的使用教程。它背后代表着一整套提升研…

2026/6/24 11:19:33阅读更多 →
【人工智能】一文搞定到底什么是智能体

【人工智能】一文搞定到底什么是智能体

【人工智能】一文搞定到底什么是智能体 一文搞定到底什么是智能体【人工智能】一文搞定到底什么是智能体一. LM,WorkFlow,Agent分别有什么么不同二. Agent的思考过程是怎样的三. Agent的五个核心部分1)LLM2)Prompt3)Me…

2026/6/24 7:33:03阅读更多 →
嵌入式GUI控件实战:ROTARY、SCROLLBAR、SLIDER原理与应用

嵌入式GUI控件实战:ROTARY、SCROLLBAR、SLIDER原理与应用

1. 嵌入式GUI控件:从原理到实战的深度解析在嵌入式系统开发中,图形用户界面(GUI)的设计与实现往往是项目从“能用”到“好用”的关键一跃。不同于资源充沛的PC或移动平台,嵌入式设备的GUI需要在有限的CPU性能、内存空间…

2026/6/24 2:12:09阅读更多 →
Google AI Studio 300美元额度的真相与实战指南

Google AI Studio 300美元额度的真相与实战指南

1. 这300美金不是“送钱”,而是Google埋下的第一道技术门槛 你看到标题里那个醒目的“$300美金”时,第一反应可能是:又一个免费额度?领完就完事?我亲手试过——这300美金根本不是红包,而是一张入场券&…

2026/6/24 7:37:00阅读更多 →
TaskJuggler脚本编程入门:用代码实现自动化项目管理

TaskJuggler脚本编程入门:用代码实现自动化项目管理

TaskJuggler脚本编程入门:用代码实现自动化项目管理 【免费下载链接】TaskJuggler TaskJuggler - Project Management beyond Gantt chart drawing 项目地址: https://gitcode.com/gh_mirrors/ta/TaskJuggler TaskJuggler是一款强大的开源项目管理工具&#…

2026/6/24 0:02:41阅读更多 →
终极教程:使用angular-mobile-nav实现流畅的移动页面过渡效果

终极教程:使用angular-mobile-nav实现流畅的移动页面过渡效果

终极教程:使用angular-mobile-nav实现流畅的移动页面过渡效果 【免费下载链接】angular-mobile-nav An angular navigation service for mobile applications 项目地址: https://gitcode.com/gh_mirrors/an/angular-mobile-nav angular-mobile-nav是一款专为…

2026/6/24 0:02:41阅读更多 →
Wan2.1-Fun-V1.1-1.3B-InP Web UI使用教程:无需代码的AI视频创作

Wan2.1-Fun-V1.1-1.3B-InP Web UI使用教程:无需代码的AI视频创作

Wan2.1-Fun-V1.1-1.3B-InP Web UI使用教程:无需代码的AI视频创作 【免费下载链接】Wan2.1-Fun-V1.1-1.3B-InP 项目地址: https://ai.gitcode.com/hf_mirrors/PAI/Wan2.1-Fun-V1.1-1.3B-InP Wan2.1-Fun-V1.1-1.3B-InP是一款强大的AI视频创作工具,…

2026/6/24 0:02:41阅读更多 →