概述
机器学习中,重复值不需要处理
特征工程
特征抽取
one-hot 编码
from sklearn.feature_extraction import DictVectorizer
dict_vec = DictVectorizer(sparse=False)# #sparse=False意思是不产生稀疏矩阵
X_train = dict_vec.fit_transform(X_train.to_dict(orient='record'))
X_test = dict_vec.transform(X_test.to_dict(orient='record'))
print(dict_vec.feature_names_)#查看转换后的列名
print(X_train)#查看转换后的训练集
['age','pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=female', 'sex=male']
[[31.19418104 0. 0. 1. 0. 1. ]
[31.19418104 1. 0. 0. 1. 0. ]
[31.19418104 0. 0. 1. 0. 1. ]
...
[12. 0. 1. 0. 1. 0. ]
[18. 0. 1. 0. 0. 1. ]
[31.19418104 0. 0. 1. 1. 0. ]]
方法2 pd.get_dummies
def countvec():
"""
对文本进行特征值化
:return: None
"""
cv = CountVectorizer()
data = cv.fit_transform(["人生 苦短,我 喜欢 python", "人生漫长,不用 python"])
print(cv.get_feature_names())
print(data.toarray())
return None
def cutword():
con1 = jieba.cut("今天很残酷,明天更残酷,后天很美好,但绝对大部分是死在明天晚上,所以每个人不要放弃今天。")
con2 = jieba.cut("我们看到的从很远星系来的光是在几百万年之前发出的,这样当我们看到宇宙时,我们是在看它的过去。")
con3 = jieba.cut("如果只用一种方式了解某样事物,你就不会真正了解它。了解事物真正含义的秘密取决于如何将其与我们所了解的事物相联系。")
# 转换成列表
content1 = list(con1)
content2 = list(con2)
content3 = list(con3)
# 吧列表转换成字符串
c1 = ' '.join(content1)
c2 = ' '.join(content2)
c3 = ' '.join(content3)
return c1, c2, c3
def hanzivec():
"""
中文特征值化
:return: None
"""
c1, c2, c3 = cutword()
print(c1, c2, c3)
cv = CountVectorizer()
data = cv.fit_transform([c1, c2, c3])
print(cv.get_feature_names())
print(data.toarray())
return None
def tfidfvec():
"""
中文特征值化
:return: None
"""
c1, c2, c3 = cutword()
print(c1, c2, c3)
tf = TfidfVectorizer()
data = tf.fit_transform([c1, c2, c3])
print(tf.get_feature_names())
print(data.toarray())
return None
特征预处理
归一化
什么时候需要用归一化?一般计算距离类的模型需要用标准化/归一化,其他模型用只能提升运算速度,LR模型一般用标准化
归一化使得各个特征对结果的影响程度相同,某一特征不会对结果造成更大的影响
会影响归一化结果
解决办法:使用标准化
def mm():
"""
归一化处理
:return: NOne
"""
mm = MinMaxScaler(feature_range=(2, 3))
data = mm.fit_transform([[90,2,10,40],[60,4,15,45],[75,3,13,46]])
print(data)
return None
def stand():
"""
标准化缩放
:return:
"""
std = StandardScaler()
data = std.fit_transform([[ 1., -1., 3.],[ 2., 4., 2.],[ 4., 6., -1.]])
print(data)
return None
def im():
"""
缺失值处理
:return:NOne
"""
# NaN, nan
im = SimpleImputer(missing_values=np.nan, strategy='mean',verbose=0)
data = im.fit_transform([[1, 2], [np.nan, 3], [7, 6]])
print(data)
return None