赞
踩
采用鸢尾花数据
数据链接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完成标签转换,分两步走,先fit
再transform
,转换结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。