机器学习算法那些事 | 60个“特征工程”计算函数(Python代码)

本文来源公众号“机器学习算法那些事”,仅用于学术分享,侵权删,干货满满。

原文链接:60个“特征工程”计算函数(Python代码)

近期一些朋友询问我关于如何做特征工程的问题,有没有什么适合初学者的有效操作。

特征工程的问题往往需要具体问题具体分析,当然也有一些暴力的策略,可以在竞赛初赛前期可以带来较大提升,而很多竞赛往往依赖这些信息就可以拿到非常好的效果,剩余的则需要结合业务逻辑以及很多其他的技巧,此处我们将平时用得最多的聚合操作罗列在下方。

最近刚好看到一篇文章汇总了非常多的聚合函数,就摘录在下方,供许多初入竞赛的朋友参考。

聚合特征汇总

pandas自带的聚合函数

  1. ​​​​​​​​mean(): Compute mean of groups
  2. sum(): Compute sum of group values
  3. size(): Compute group sizes
  4. count(): Compute count of group
  5. std(): Standard deviation of groups
  6. var(): Compute variance of groups
  7. sem(): Standard error of the mean of groups
  8. first(): Compute first of group values
  9. last(): Compute last of group values
  10. nth() : Take nth value, or a subset if n is a list
  11. min(): Compute min of group values
  12. max(): Compute max of group values

其它重要聚合函数

其它重要聚合函数&分类分别如下。

def median(x):return np.median(x)def variation_coefficient(x):mean = np.mean(x)if mean != 0:return np.std(x) / meanelse:return np.nandef variance(x):return np.var(x)def skewness(x):if not isinstance(x, pd.Series):x = pd.Series(x)return pd.Series.skew(x)def kurtosis(x):if not isinstance(x, pd.Series):x = pd.Series(x)return pd.Series.kurtosis(x)def standard_deviation(x):return np.std(x)def large_standard_deviation(x):if (np.max(x)-np.min(x)) == 0:return np.nanelse:return np.std(x)/(np.max(x)-np.min(x))def variation_coefficient(x):mean = np.mean(x)if mean != 0:return np.std(x) / meanelse:return np.nandef variance_std_ratio(x):y = np.var(x)if y != 0:return y/np.sqrt(y)else:return np.nandef ratio_beyond_r_sigma(x, r):if x.size == 0:return np.nanelse:return np.sum(np.abs(x - np.mean(x)) > r * np.asarray(np.std(x))) / x.sizedef range_ratio(x):mean_median_difference = np.abs(np.mean(x) - np.median(x))max_min_difference = np.max(x) - np.min(x)if max_min_difference == 0:return np.nanelse:return mean_median_difference / max_min_differencedef has_duplicate_max(x):return np.sum(x == np.max(x)) >= 2def has_duplicate_min(x):return np.sum(x == np.min(x)) >= 2def has_duplicate(x):return x.size != np.unique(x).sizedef count_duplicate_max(x):return np.sum(x == np.max(x))def count_duplicate_min(x):return np.sum(x == np.min(x))def count_duplicate(x):return x.size - np.unique(x).sizedef sum_values(x):if len(x) == 0:return 0return np.sum(x)def log_return(list_stock_prices):return np.log(list_stock_prices).diff() def realized_volatility(series):return np.sqrt(np.sum(series**2))def realized_abs_skew(series):return np.power(np.abs(np.sum(series**3)),1/3)def realized_skew(series):return np.sign(np.sum(series**3))*np.power(np.abs(np.sum(series**3)),1/3)def realized_vol_skew(series):return np.power(np.abs(np.sum(series**6)),1/6)def realized_quarticity(series):return np.power(np.sum(series**4),1/4)def count_unique(series):return len(np.unique(series))def count(series):return series.size#drawdons functions are mine
def maximum_drawdown(series):series = np.asarray(series)if len(series)<2:return 0k = series[np.argmax(np.maximum.accumulate(series) - series)]i = np.argmax(np.maximum.accumulate(series) - series)if len(series[:i])<1:return np.NaNelse:j = np.max(series[:i])return j-kdef maximum_drawup(series):series = np.asarray(series)if len(series)<2:return 0series = - seriesk = series[np.argmax(np.maximum.accumulate(series) - series)]i = np.argmax(np.maximum.accumulate(series) - series)if len(series[:i])<1:return np.NaNelse:j = np.max(series[:i])return j-kdef drawdown_duration(series):series = np.asarray(series)if len(series)<2:return 0k = np.argmax(np.maximum.accumulate(series) - series)i = np.argmax(np.maximum.accumulate(series) - series)if len(series[:i]) == 0:j=kelse:j = np.argmax(series[:i])return k-jdef drawup_duration(series):series = np.asarray(series)if len(series)<2:return 0series=-seriesk = np.argmax(np.maximum.accumulate(series) - series)i = np.argmax(np.maximum.accumulate(series) - series)if len(series[:i]) == 0:j=kelse:j = np.argmax(series[:i])return k-jdef max_over_min(series):if len(series)<2:return 0if np.min(series) == 0:return np.nanreturn np.max(series)/np.min(series)def mean_n_absolute_max(x, number_of_maxima = 1):""" Calculates the arithmetic mean of the n absolute maximum values of the time series."""assert (number_of_maxima > 0), f" number_of_maxima={number_of_maxima} which is not greater than 1"n_absolute_maximum_values = np.sort(np.absolute(x))[-number_of_maxima:]return np.mean(n_absolute_maximum_values) if len(x) > number_of_maxima else np.NaNdef count_above(x, t):if len(x)==0:return np.nanelse:return np.sum(x >= t) / len(x)def count_below(x, t):if len(x)==0:return np.nanelse:return np.sum(x <= t) / len(x)#number of valleys = number_peaks(-x, n)
def number_peaks(x, n):"""Calculates the number of peaks of at least support n in the time series x. A peak of support n is defined as asubsequence of x where a value occurs, which is bigger than its n neighbours to the left and to the right."""x_reduced = x[n:-n]res = Nonefor i in range(1, n + 1):result_first = x_reduced > _roll(x, i)[n:-n]if res is None:res = result_firstelse:res &= result_firstres &= x_reduced > _roll(x, -i)[n:-n]return np.sum(res)def mean_abs_change(x):return np.mean(np.abs(np.diff(x)))def mean_change(x):x = np.asarray(x)return (x[-1] - x[0]) / (len(x) - 1) if len(x) > 1 else np.NaNdef mean_second_derivative_central(x):x = np.asarray(x)return (x[-1] - x[-2] - x[1] + x[0]) / (2 * (len(x) - 2)) if len(x) > 2 else np.NaNdef root_mean_square(x):return np.sqrt(np.mean(np.square(x))) if len(x) > 0 else np.NaNdef absolute_sum_of_changes(x):return np.sum(np.abs(np.diff(x)))def longest_strike_below_mean(x):if not isinstance(x, (np.ndarray, pd.Series)):x = np.asarray(x)return np.max(_get_length_sequences_where(x < np.mean(x))) if x.size > 0 else 0def longest_strike_above_mean(x):if not isinstance(x, (np.ndarray, pd.Series)):x = np.asarray(x)return np.max(_get_length_sequences_where(x > np.mean(x))) if x.size > 0 else 0def count_above_mean(x):m = np.mean(x)return np.where(x > m)[0].sizedef count_below_mean(x):m = np.mean(x)return np.where(x < m)[0].sizedef last_location_of_maximum(x):x = np.asarray(x)return 1.0 - np.argmax(x[::-1]) / len(x) if len(x) > 0 else np.NaNdef first_location_of_maximum(x):if not isinstance(x, (np.ndarray, pd.Series)):x = np.asarray(x)return np.argmax(x) / len(x) if len(x) > 0 else np.NaNdef last_location_of_minimum(x):x = np.asarray(x)return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaNdef first_location_of_minimum(x):if not isinstance(x, (np.ndarray, pd.Series)):x = np.asarray(x)return np.argmin(x) / len(x) if len(x) > 0 else np.NaN# Test non-consecutive non-reoccuring values ?
def percentage_of_reoccurring_values_to_all_values(x):if len(x) == 0:return np.nanunique, counts = np.unique(x, return_counts=True)if counts.shape[0] == 0:return 0return np.sum(counts > 1) / float(counts.shape[0])def percentage_of_reoccurring_datapoints_to_all_datapoints(x):if len(x) == 0:return np.nanif not isinstance(x, pd.Series):x = pd.Series(x)value_counts = x.value_counts()reoccuring_values = value_counts[value_counts > 1].sum()if np.isnan(reoccuring_values):return 0return reoccuring_values / x.sizedef sum_of_reoccurring_values(x):unique, counts = np.unique(x, return_counts=True)counts[counts < 2] = 0counts[counts > 1] = 1return np.sum(counts * unique)def sum_of_reoccurring_data_points(x):unique, counts = np.unique(x, return_counts=True)counts[counts < 2] = 0return np.sum(counts * unique)def ratio_value_number_to_time_series_length(x):if not isinstance(x, (np.ndarray, pd.Series)):x = np.asarray(x)if x.size == 0:return np.nanreturn np.unique(x).size / x.sizedef abs_energy(x):if not isinstance(x, (np.ndarray, pd.Series)):x = np.asarray(x)return np.dot(x, x)def quantile(x, q):if len(x) == 0:return np.NaNreturn np.quantile(x, q)# crossing the mean ? other levels ? 
def number_crossing_m(x, m):if not isinstance(x, (np.ndarray, pd.Series)):x = np.asarray(x)# From https://stackoverflow.com/questions/3843017/efficiently-detect-sign-changes-in-pythonpositive = x > mreturn np.where(np.diff(positive))[0].sizedef absolute_maximum(x):return np.max(np.absolute(x)) if len(x) > 0 else np.NaNdef value_count(x, value):if not isinstance(x, (np.ndarray, pd.Series)):x = np.asarray(x)if np.isnan(value):return np.isnan(x).sum()else:return x[x == value].sizedef range_count(x, min, max):return np.sum((x >= min) & (x < max))def mean_diff(x):return np.nanmean(np.diff(x.values))
base_stats = ['mean','sum','size','count','std','first','last','min','max',median,skewness,kurtosis]
higher_order_stats = [abs_energy,root_mean_square,sum_values,realized_volatility,realized_abs_skew,realized_skew,realized_vol_skew,realized_quarticity]
additional_quantiles = [quantile_01,quantile_025,quantile_075,quantile_09]
other_min_max = [absolute_maximum,max_over_min]
min_max_positions = [last_location_of_maximum,first_location_of_maximum,last_location_of_minimum,first_location_of_minimum]
peaks = [number_peaks_2, mean_n_absolute_max_2, number_peaks_5, mean_n_absolute_max_5, number_peaks_10, mean_n_absolute_max_10]
counts = [count_unique,count,count_above_0,count_below_0,value_count_0,count_near_0]
reoccuring_values = [count_above_mean,count_below_mean,percentage_of_reoccurring_values_to_all_values,percentage_of_reoccurring_datapoints_to_all_datapoints,sum_of_reoccurring_values,sum_of_reoccurring_data_points,ratio_value_number_to_time_series_length]
count_duplicate = [count_duplicate,count_duplicate_min,count_duplicate_max]
variations = [mean_diff,mean_abs_change,mean_change,mean_second_derivative_central,absolute_sum_of_changes,number_crossing_0]
ranges = [variance_std_ratio,ratio_beyond_01_sigma,ratio_beyond_02_sigma,ratio_beyond_03_sigma,large_standard_deviation,range_ratio]

参考文献:

https://www.kaggle.com/code/lucasmorin/amex-feature-engineering-2-aggreg-functions

THE END !

文章结束,感谢阅读。您的点赞,收藏,评论是我继续更新的动力。大家有推荐的公众号可以评论区留言,共同学习,一起进步。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/12932.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【无标题】进程池/Linux

#include <iostream> #include <vector> #include <unistd.h> #include <cassert> #include <sys/types.h> #include <string> #include <sys/wait.h> // using namespace std; #include "Tash.hpp" class channel//封装文…

三分钟快速上手SpringSecurity框架

导入依赖框架 web 框架(spring-boot-starter-web) <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency> springSecurity 框架(spring-boot-starter-security) <de…

递归-常规问题详解

目录 前言 递归经典题目 子集 77. 组合 46. 全排列 前言 递归在计算机算法中有很重要的地位&#xff0c;它可以解决条件具有重复性的问题。我们在快速排序和归并排序&#xff0c;都是利用了递归去解决问题的。写好一个递归代码不是太容易&#xff0c;很容易造成死循环最终…

基于单片机的空气质量检测系统设计(51+4G版)-设计说明书

设计摘要&#xff1a; 本设计是基于单片机的空气质量检测系统设计涉及以下主要功能&#xff0c;旨在监测甲烷和一氧化碳的浓度&#xff0c;并在浓度过高时采取相应措施&#xff0c;以确保室内空气质量的安全。该系统使用传感器对甲烷和一氧化碳的浓度进行检测。传感器将收集到…

人物介绍模板 PSD 源文件免费获取

免费获取 下载链接在最后&#xff01; 下载链接在最后&#xff01; 下载链接在最后&#xff01; 下载链接在最后&#xff01; 下载链接在最后&#xff01; 链接&#xff1a;https://pan.baidu.com/s/1sq3e6djMdZt76Sh_uqVxWg 提取码&#xff1a;naun

AniPortrait详细讲解以及完整搭建流程(有问题留言)

AniPortrait是一款真实感人像动画的音频驱动合成的AI程序。 下面是它的github源码: GitHub - Zejun-Yang/AniPortrait: AniPortrait: Audio-Driven Synthesis of Photorealistic Portrait AnimationAniPortrait: Audio-Driven Synthesis of Photorealistic Portrait Animati…

TiDB学习1:TiDB体系架构概览

目录 1. TiDB体系结构 2. TiDBsever 3. TiKV 4. PD(Placement Driver) 5. TiFlash 1. TiDB体系结构 水平扩容或者缩容金融级高可用实时 HTAP云原生的分布式数据库兼容MySQ 5.7 协议 2. TiDBsever 处理客户端的连接SQL语句的解析和编译关系型数据与 kv 的转化(insert语句)S…

线上3D博物馆搭建简单吗?有何优势?有哪些应用场景?

随着科技的飞速发展&#xff0c;传统的博物馆参观方式正在经历一场前所未有的变革&#xff0c;在科技的“加持”下&#xff0c;不少博物馆凭借强大的技术、创意和美学实践&#xff0c;频频“出圈”&#xff0c;线上3D博物馆逐渐崛起&#xff0c;这不仅丰富了人们的文化体验&…

Mirror从入门到入神(二)

文章目录 SpawnSpawnObject NetworkIdentityAwakeInitializeNetworkBehavioursValidateComponents NetworkBehaviourNetworkServerSpawnObjectOnStartServerRebuildObserversRebuildObserversDefaultAddAllReadyServerConnectionsToObservers NetworkIdentityAddObserver Netwo…

C++|多态性与虚函数(1)功能绑定|向上转换类型|虚函数

目录 什么是多态性&#xff1f; 概念 分类 向上类型转换 功能的早绑定和晚绑定 绑定 绑定与多态的联系 编译时多态&#xff08;功能的早绑定&#xff09; 运行时多态&#xff08;功能的晚绑定&#xff09; 一般而言 实现功能晚绑定——虚函数 虚函数定义的说明 什么…

springboot jar包下config logback外配置文件不生效

描述 与jar 包同级的config目录下放置配置文件 检查1 确定配置配置文件名称为logback-spring.xml 检查2 确定logback-spring.xml 内容正确 检查3 开发环境为 生产环境&#xff08;外配置环境下&#xff09;

催产素(Oxytocin ) ELISA检测试剂盒

催产素(Oxytocin )是一种神经生理肽&#xff0c;在下丘脑室旁核产生并储存在垂体后部。该分子由9个氨基酸组成&#xff0c;用一个[1-6]二硫键和一个半灵活的羧基酰胺化尾巴连接。催产素是一种曾经被认为仅限于女性平滑肌生殖生理的激素&#xff0c;目前的研究结果已经确定&…

寻求发展+兼顾陪读|企业高管赴美国乔治梅森大学做访问学者

E经理拟去美国访学&#xff0c;想达到3个目的&#xff1a;结合本专业方向&#xff0c;扩展至跨学科研究领域&#xff1b;考察市场&#xff0c;寻求新的发展契机&#xff1b;携孩子出国读书&#xff0c;兼顾陪读&#xff0c;并希望尽早出国。最终我们为其落实的乔治梅森大学访问…

会员网站如何创建具有不同仪表盘结构的用户帐户页面

用户帐户页面是中央用户仪表盘&#xff0c;用户可以在其中添加和编辑信息、发布和编辑帖子以及保存收藏夹项目。本教程介绍如何使用“内容”和“重写”模板模式设置帐户页面、为帐户页面创建子页面以及设置个人资料菜单等。 在本教程中&#xff0c;我们将介绍如何使用招聘网站…

PSAI超强插件来袭:一键提升设计效率!

无需魔法&#xff0c;直接在PS中完成图生图、局部重绘、线稿上色、无损放大、扩图等操作。无论你是Windows还是Mac用户&#xff0c;都能轻松驾驭这款强大的AI绘图工具&#xff0c;这款PSAI插件让你的设计工作直接起飞&#xff01; 在之前的分享中&#xff0c;我为大家推荐过两…

Wiley数据库文献哪里比较全?去哪里下载比较高效

Wiley出版社1807年创建于美国&#xff0c;是一家具有超过200年历史的全球知名的出版机构&#xff0c;面向专业人士、科研人员、教育工作者、学生、终身学习者提供必需的知识和服务。 Wiley及旗下的子品牌出版了超过500位诺贝尔奖得主的作品。Wiley Online Library为全学科期刊全…

从0开始搭建一个react项目 第一 二 三天

从0开始搭建一个react项目 今天接到一个任务让我把原来用ext.js写的前端换成react写的&#xff0c;我好慌的&#xff0c;因为我就是一个小白&#xff0c;之前只做过简单的二次开发功能。唉&#xff0c;我只是一个领着微薄薪水的小实习生&#xff0c;为什么要有这个任务&#x…

价格战开卷!字节发布豆包大模型,比行业便宜99.3%

豆包大模型正式亮相 5月15日&#xff0c;在2024春季火山引擎Force原动力大会上&#xff0c;字节跳动自研豆包大模型正式亮相。 &#xff08;图源&#xff1a;证券时报&#xff09; 火山引擎是字节跳动旗下云服务平台&#xff0c;据火山引擎总裁谭待介绍&#xff0c;豆包大模型…

海外媒体发稿:如何在日本媒体投放新闻通稿-大舍传媒

导言 在全球化的时代背景下&#xff0c;海外媒体宣发对于企业来说非常重要。通过在海外媒体投放新闻通稿&#xff0c;企业能够拓展海外市场&#xff0c;增强知名度和影响力。本文将探讨如何在海外媒体投放新闻通稿&#xff0c;以帮助企业进行有效的海外宣传。 挖掘海外媒体资…

Dubbo2.x迁移3.x过程及原理

Dubbo2.x迁移3.x过程及原理 1.Dubbo2.x迁移3.x1.1 快速升级步骤1.2 Provider 端升级过程详解1.2.1 双注册带来的资源消耗 1.3 Consumer 端升级过程1.3.1 APPLICATION_FIRST策略1.3.2 双订阅带来的资源消耗1.3.3 消费端更细粒度的控制 1.4 迁移状态的收敛1.4.1 不同的升级策略影…