1.在业务场景中,有关联的数据列通过简单的运算,将计算结果存储为新的特征列。
2.发现有用的、高贡献的特征,对核心特征重点进行衍生尝试。
import pandas as pd
data=[[1,1],[2,77],[3,60]]
data = pd.DataFrame(data)
data.columns=['x1','x2']
data['x1+x2'] = data['x1']+data['x2']
data['x1-x2'] = data['x1']-data['x2']
data['x2-x1'] = data['x2']-data['x1']
data['x1*x2'] = data['x1']*data['x2']
data['x1/x2'] = data['x1']/data['x2']
data['x2/x1'] = data['x2']/data['x1']
print(data)
'''Out:
x1 x2 x1+x2 x1-x2 x2-x1 x1*x2 x1/x2 x2/x1
0 1 1 2 0 0 1 1.000000 1.0
1 2 77 79 -75 75 154 0.025974 38.5
2 3 60 63 -57 57 180 0.050000 20.0
'''
将两个变量的值进行幂运算(取0次幂、1次幂、2次幂、3次幂,),并完成组合得到新的特征。
通过调用PolynomialFeatures评估器函数生成多项式计算结果
PolynomialFeatures(degree,interaction_only=False,includeb_bias=True)
*degree: 阶数(幂次)
*interaction_only:默认为False ,仅考虑两项交叉的到的新特征
*includeb_bias: 默认为True,考率计算特征的0次方
from sklearn.preprocessing import PolynomialFeatures
data=[[1,2],[3,4],[5,6]]
data = pd.DataFrame(data)
colname=['x1','x2']
data.columns=colname
degree =2 #最大阶数
col_name_list=[] #新生成特征名称
#两层循环生成新变量名称
for d in range(2,degree+1):
for i in range(d+1):
col_name_str=colname[0]+'^'+str(d-i) +'*'+colname[1]+'^'+str(i)
col_name_list.append(col_name_str)
print(col_name_list)
'''Out:
['x1^2*x2^0', 'x1^1*x2^1', 'x1^0*x2^2']
'''
# 生成高阶多项式计算结果
res= PolynomialFeatures(degree=degree,include_bias=False,interaction_only=True).fit_transform(data)
df = pd.DataFrame(res)
df.columns=col_name_list
# 原始数据和生成特征合并
data = pd.concat([data,df],axis=1) # 横向合并
print(data)
'''Out:
x1 x2 x1^2*x2^0 x1^1*x2^1 x1^0*x2^2
0 1 2 1.0 2.0 2.0
1 3 4 3.0 4.0 12.0
2 5 6 5.0 6.0 30.0
'''
将不同离散变量的不同取值两两组合,创建出新特征。
这里需要注意如果某特征的取值内容过多,会导致生成的特征过于稀疏。
下列例子,使用诊断时病人的状态特征为例,每个特征的取值内容仅有两个,三个特征,两两成组生成3个新特征。
# 创建空列表用于存储衍生后的特征名称和特征
colNames_new_l = []
features_new_l = []
data=[['yes','no','yes'],['no','yes','yes'],['yes','yes','yes']]
data = pd.DataFrame(data)
col_names=['咳嗽','发烧','流涕']
data.columns=col_names
print(data)
# enumerate过程
for col_index, col_name in enumerate(col_names):
print(col_index, col_name)
# 衍生特征列名称
for col_index, col_name in enumerate(col_names):
for col_sub_index in range(col_index+1, len(col_names)):
newNames = col_name + '&' + col_names[col_sub_index]
print(newNames)
# 创建衍生特征列名称及特征本身
for col_index, col_name in enumerate(col_names):
for col_sub_index in range(col_index+1, len(col_names)):
newNames = col_name + '&' + col_names[col_sub_index]
colNames_new_l.append(newNames)
newDF = pd.Series(data[col_name].astype('str')
+ '&'
+ data[col_names[col_sub_index]].astype('str'),
name=col_name)
features_new_l.append(newDF)
features_new = pd.concat(features_new_l, axis=1)
features_new.columns = colNames_new_l
features_new