0


机器学习3-特征工程个人笔记

特征缩放

主要导包

from sklearn import preprocessing

创建numpy二维数组进行后续特征类操作:

import numpy as np

arr = np.array([[1., -1., 2.], [3., 1., -2.], [2., 1., 1.]])

一、标准差标准化

函数语法格式:

preprocessing.StandardScaler(copy=True, with_mean=True, with_std=True)

参数解析:

    copy:默认True,若为False则表示在原数据上进行操作。

    with_mean:默认为True,若为False则表示将公式里的均值设为0。

    with_std:默认为True,若为False则表示将公式里的std值设为1。

StandardScaler的四个属性:

scale_每个特征对应的数据缩放比例mean_每个特征的均值var_每个特征的方差n_samples_seen_每个特征处理的样本数

详细实现代码:

# 原数据
print(arr)
# 定义规则StandardScaler并获取该规则所需的参数fit
std = preprocessing.StandardScaler().fit(arr)
# 输出每一列的均值
print(std.mean_)
# 输出每个特征的样本数
print(std.n_samples_seen_)
# 输出标准化后的数据
print(std.transform(arr))

#####
[[ 1. -1.  2.]
 [ 3.  1. -2.]
 [ 2.  1.  1.]]
#####
[2.         0.33333333 0.33333333]
#####
3
#####
[[-1.22474487 -1.41421356  0.98058068]
 [ 1.22474487  0.70710678 -1.37281295]
 [ 0.          0.70710678  0.39223227]]
  • fit()

      一个适配的过程,sklearn中封装的各种方法都需要这个过程的结果来进行下一步操作,得到要训练数据集的一些属性参数,如均值、方差、最值。
    
  • transform()

      通过调用的函数规则对原数据进行转换,以fit()为前提。
    
  • fit_stansform()

      fit()和transform()方法的结合,先fit再transform。
    

二、离差标准化(最小值最大值归一化)

    将训练集中的特征数值缩放到固定区间内(默认0-1),容易受噪声值影响。

函数语法格式:

preprocessing.MinMaxScaler(copy=True, feature_range=(0, 1))

参数解析:

    feature_range:默认(0, 1),指定缩放的区间。

MinMaxScaler的五个属性:

min_每个特征的最小调整scale_ 每个特征数据的缩放比例data_min_每个特征最小值data_max_每个特征最大值data_range_每个特征范围

详细实现代码:

std1 = preprocessing.MinMaxScaler().fit(arr)
# 输出每个特征列的最大值
print(std1.data_max_)
# 输出标准化后数据
print(std1.transform(arr))

#####
[3. 1. 2.]
#####
[[0.   0.   1.  ]
 [1.   1.   0.  ]
 [0.5  1.   0.75]]

三、正则归一化

函数语法格式:

preprocessing.Normalizer(norm="l2", copy=True)

参数解析:

    norm:默认为l2,表示对每个特征的每个元素都除以该样本的L1或L2范数。

详细实现代码:

std2 = preprocessing.Normalizer().fit(arr)
print(std2.transform(arr))

#####
[[ 0.40824829 -0.40824829  0.81649658]
 [ 0.80178373  0.26726124 -0.53452248]
 [ 0.81649658  0.40824829  0.40824829]]

四、二值化处理

    设置一个阈值,将所有大于阈值特征值转换为1,所有小于等于阈值的特征值转换为0。

函数语法格式:

preprocessing.Binarizer(threshold=0.0, copy=True)

参数解析:

    threshold:默认0.0,设置阈值。

详细实现代码:

std3 = preprocessing.Binarizer().fit(arr)
print(std3.transform(arr))

#####
[[1. 0. 1.]
 [1. 1. 0.]
 [1. 1. 1.]]

五、独热编码

    独热编码即One-Hot编码,类似于哑变量编码。

函数语法格式:

preprocessing.OneHotEnconder()

详细实现代码:

import pandas as pd

# 创建一个DataFrame对象
std4 = pd.DataFrame({'城市':['上海', '深圳', '广州', '重庆']}, index=[1, 2, 3, 4])
print(std4)
# 哑变量编码
print(pd.get_dummies(std4))
# 独热编码
std4['城市'] = preprocessing.LabelEncoder().fit_transform(std4['城市'])
print(std4)
# 格式转换
print(preprocessing.OneHotEncoder().fit_transform(std4))
print(preprocessing.OneHotEncoder().fit_transform(std4).toarray())

#####
   城市
1  上海
2  深圳
3  广州
4  重庆
#####哑变量
   城市_上海  城市_广州  城市_深圳  城市_重庆
1      1      0      0      0
2      0      0      1      0
3      0      1      0      0
4      0      0      0      1
#####对应哑变量编码之后的索引值
   城市
1   0
2   2
3   1
4   3
#####输出有值的行列值
  (0, 0)    1.0
  (1, 2)    1.0
  (2, 1)    1.0
  (3, 3)    1.0
#####转换为数组列表
[[1. 0. 0. 0.]
 [0. 0. 1. 0.]
 [0. 1. 0. 0.]
 [0. 0. 0. 1.]]

特征降维

    两个角度理解降维
  • 数据角度:减少数据列数
  • 空间角度:将高维度映射到低维度

主要导包

from sklearn import decomposition

一、PCA(主要成分分析)

    将n维特征映射到m维上(m<n),其中m维称特征为主成分,并非直接去除其他n-m维特征得到的,PCA为无监督学习。

语法格式:

decomposition.PCA(n_components=None, copy=True, whiten=False, svd_solver='auto')

参数解析:

n_components:指定主成分的维度数量。

whiten:白化,默认False,是否让每个特征都具有相同的方差。

svd_solver:svd策略,默认auto,可选auto、full、arpack、randomized。

主要属性:

components_降维后各主成分方向,并按方差值大小排序explained_variance_降维后各主成分的方差值explained_variance_ratio_降维后各主成分方差值占比singular_values_最大奇异值

详细代码:

# 使用sklearn内置数据集,鸢尾花数据集
from sklearn import datasets
iris = datasets.load_iris()
# 获取数据特征值
x = iris.data
# 获取数据目标值
y = iris.target
print(x)
print(y)

#####
[[5.1 3.5 1.4 0.2]
 [4.9 3.  1.4 0.2]
 [4.7 3.2 1.3 0.2]
 [4.6 3.1 1.5 0.2]
 [5.  3.6 1.4 0.2]
 [5.4 3.9 1.7 0.4]
[...]...]
#####
 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
 2 2]
    可以看到鸢尾花的数据集是四维数据,分别代表花瓣的长度宽度、花萼的长度宽度,使用PCA将特征值降维到二维,具体如下:
# 定义PCA降维规则
pca = decomposition.PCA(n_components=2)
# 将规则实现到特征值上
pca_x = pca.fit_transform(x)
print(pca_x)

#####
[[-2.68412563  0.31939725]
 [-2.71414169 -0.17700123]
 [-2.88899057 -0.14494943]
 [-2.74534286 -0.31829898]
 [-2.72871654  0.32675451]
 [-2.28085963  0.74133045]
[...]...]

二、ICA(独立成分分析)

    从多变量统计数据中找到隐含的因素,常用于还原混淆信号中的不同源信号。

代码实操:

    全部导包:
import numpy as np
# 用于生成信号
from scipy import signal
# 通过pca对ica进行比较
from sklearn.decomposition import PCA
from sklearn.decomposition import FastICA
# 作图,直观展示
import matplotlib.pyplot as plt
    ICA还原已混淆信号操作,首先创建混淆信号:
# 设置随机种子,使得随机数固定生成
np.random.seed(0)
# 生成0到8之间数量为2000的等差数列
time = np.linspace(0, 8, 2000)
# 生成3种源信号
waft1 = np.sin(2 * time)  # 正弦信号
waft2 = np.sign(np.sin(3 * time))  # 方波信号
waft3 = signal.sawtooth(2 * np.pi * time)  # 锯齿信号
print('正弦信号为:\n', waft1, '\n',
      '方波信号为:\n', waft2, '\n',
      '锯齿信号为:\n', waft3)

# 生成混淆信号
waft = np.c_[waft1, waft2, waft3]
waft += 0.2 * np.random.normal(size=waft.shape)  # 增加噪声
waft /= waft.std(axis=0)  # 数据标准化
arr = np.array([[1, 1, 1], [0.5, 2, 1.0], [1.5, 1.0, 2.0]])  # 混淆矩阵
mix_waft = np.dot(waft, arr.T)  # 生成的混淆信号
print('混淆信号为:\n', mix_waft)

#####
正弦信号为:
 [ 0.          0.00800392  0.01600732 ... -0.27253687 -0.28022907
 -0.28790332] 
 方波信号为:
 [ 0.  1.  1. ... -1. -1. -1.] 
 锯齿信号为:
 [-1.       -0.991996 -0.983992 ...  0.983992  0.991996 -1.      ]
混淆信号为:
 [[-0.74486315 -0.91401507 -1.81570038]
 [ 0.03932519  1.06492993 -1.58715033]
 [-0.40766041  0.39786915 -1.90998106]
 ...
 [ 0.23856791 -0.28486909  1.38619226]
 [-0.00653213 -0.99317023  1.48134842]
 [-3.00301507 -3.62816891 -4.8258685 ]]
    对mix_waft混淆信号进行降维操作:
# 创建ica规则
ica = FastICA(n_components=3).fit(mix_waft)

# 使用ICA还原信号
waft_ica = ica.transform(mix_waft)
# 使用PCA还原信号
waft_pca = PCA(n_components=3).fit_transform(mix_waft)
# 绘制结果
plt.figure(figsize=[12, 6])  # 设置画布大小
# 设置中文字体格式
plt.rcParams['font.sans-serif'] = 'SimHei'
# 设置正负号正常显示
plt.rcParams['axes.unicode_minus'] = False
models = [mix_waft, waft, waft_ica, waft_pca]
names = ['混淆信号',
         '实际源信号',
         'ICA复原信号',
         'PCA复原信号']
colors = ['red', 'steelblue', 'orange']
for i, (model, name) in enumerate(zip(models, names), 1):
    # 创建子图
    plt.subplot(4, 1, i)
    # 设置标题,对应上面定义过的names
    plt.title(name)
    # 设置三个信号在图形中的数据值和颜色
    for sig, color in zip(model.T, colors):
        plt.plot(sig, color=color)
# 设置每个子图之间的边距
plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.46)
# 展示
plt.show()

     可以看出,对于复原信号来说,ICA复原的信号比PCA复原的信号更明显更接近实际数据。

三、LDA

    LDA是一种监督学习的降维技术,主要功能是将高维度数据在低维度上进行投影展示,其中同一类别的各数据投影点较近,不同类别的数据投影点中心之间距离尽可能大。LDA可用于降维,也可用于分类。

LDA与PCA的区别

    LDA和PCA都是将多维数据降为低维数据,但PCA的降维不容易区分数据属于哪个类别,即不做分类调整,而LDA则会将不同类别的数据以他们的中心点做分类处理,更容易区分类别之间的差异。

代码实现:

import matplotlib.pyplot as plt
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn import decomposition
from sklearn import datasets

iris = datasets.load_iris()
x = iris.data
y = iris.target
# 构建并训练lda和pca模型,获取到降维结果
x_lda = LinearDiscriminantAnalysis(n_components=2).fit_transform(x, y)
x_pca = decomposition.PCA(n_components=2).fit_transform(x)
# 创建画布
plt.figure()
# 图表正常显示
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
# 设置每个特征在图形展示的颜色
colors = ['r', 'g', 'b']
# 设置图形形状
markers = ['*', '.', 'd']
# 绘制PCA散点图
for color, i, marker in zip(colors, [0, 1, 2], markers):
    plt.scatter(x_pca[y == i, 0], x_pca[y == i, 1], color=color, marker=marker)
plt.title('PCA结果展示')
plt.show()
# 绘制LDA散点图
plt.figure()
for color, i, marker in zip(colors, [0, 1, 2], markers):
    plt.scatter(x_lda[y == i, 0], x_lda[y == i, 1], color=color, marker=marker)
plt.title('LDA结果展示')
plt.show()


本文转载自: https://blog.csdn.net/Jun_257/article/details/125022260
版权归原作者 落系 所有, 如有侵权,请联系我们删除。

“机器学习3-特征工程个人笔记”的评论:

还没有评论