当前位置:   article > 正文

Python线性判别分析(LDA)——数据降维_pythonlda降维

pythonlda降维

附:
Pandas文档链接
sklearn文档链接

手动实现LDA

读取数据

采用鸢尾花数据

数据链接https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data
在这里插入图片描述
数据集共3类,共有150条花的基本数据,三种花各50条,每条数据包括萼片长度,萼片宽度,花瓣长度,花瓣宽度4种特征

使用pandas读取数据集,代码:

import pandas as pd

# 显示所有列
pd.set_option('display.max_columns', None)
# 显示所有行
pd.set_option('display.max_rows', None)
# 增加每行的宽度
pd.set_option('display.width', 1000)

df = pd.read_csv(
    filepath_or_buffer='iris.data',
    header=None,
    sep=',',
)

# 自定义列名
feature_dict = {
   
    i: label for i, label in zip(
        range(4),
        (
            'sepal length in cm',
            'sepal width in cm',
            'petal length in cm',
            'petal width in cm',
        )
    )
}

# 指定列名
df.columns = [l for i, l in sorted(feature_dict.items())] + ['class label']
print(df.head(150))  # 返回前n行数据
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

输出如下:
在这里插入图片描述

转换标签

from sklearn.preprocessing import LabelEncoder

X = df[['sepal length in cm',
        'sepal width in cm',
        'petal length in cm',
        'petal width in cm']].values
y = df['class label'].values
# 制作标签 {1:'Setosa', 2:'Versicolor', 3:'Virginica'}
enc = LabelEncoder()
label_encoder = enc.fit(y)
y = label_encoder.transform(y) + 1
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

使用sklearn中的LabelEncoder完成标签转换,分两步走,先fittransform,转换结果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/712215
推荐阅读
相关标签
  

闽ICP备14008679号