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

附:
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行数据

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

转换标签

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

使用sklearn中的LabelEncoder完成标签转换,分两步走,先fittransform,转换结果如下:
在这里插入图片描述

  • 3
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值