欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

鸢尾花(Iris)数据集

发布时间:2023/12/20 编程问答 54 豆豆
生活随笔 收集整理的这篇文章主要介绍了 鸢尾花(Iris)数据集 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

鸢尾花数据集

  • 1. 鸢尾花数据集下载
  • 2. Pandas库基础操作
  • 3. 数据可视化

1. 鸢尾花数据集下载

  • 下载鸢尾花数据集
tf.keras.utils.get_file(fname,origin,cache_dir) 参数说明
fname下载后的文件名
origin文件的URL地址
cache_dir下载后文件的存储位置
TRAIN_URL="http://download.tensorflow.org/data/iris_training.csv" train_path=tf.keras.utils.get_file("iris_training.csv",TRAIN_URL)

iris_training.csv训练数据集,120条样本数据;iris_test.csv测试数据集,30条数据。本文只用到训练数据集,其中有花萼长度(Sepal Length)、花萼宽度(Sepal Width)、花瓣长度(Petal Length)、花瓣宽度(Petal Width)四个属性。标签0、1、2分别表示山鸢尾(Setosa)、变色鸢尾(Versicolor)、维吉尼亚鸢尾(Virginical)。

  • split()函数(知识扩充):通过指定的分隔符对字符串进行切片,并返回一个列表。
TRAIN_URL.split("/") #表示以 / 作分隔符 TRAIN_URL="http://download.tensorflow.org/data/iris_training.csv" train_path=tf.keras.utils.get_file(TRAIN_URL.split('/')[-1],TRAIN_URL)

2. Pandas库基础操作

用于数据统计和分析、可以高效、方便地操作大型数据集。

  • 导入Pandas库
import pandas as pd
  • 读取csv数据集文件
#文件名参数 pd.read_csv(filepath_or_buffer,header,names) #header=0(默认)设置第一行数据作为列标题,header=None表示没有列标题 column_names=['SepalLength','SepalWidth','PetalLength','Species'] df_iris=pd.read_csv(train_path,header=0,names=column_names) df_iris.head() #读取前n行数据,参数为空时,默认读取而是为数据表中的前5行数据

输出结果如下:

  • head()函数
    读取前n行数据,参数为空时,默认读取而是为数据表中的前5行数据。
  • tail()函数
    读取后n行数据,参数为空时,默认读取而是为数据表中的后5行数据
  • 索引和切片访问数据
    df_iris[n:m]表示读取行号n到行号m-1的数据样本
  • describe()函数
    显示二维数据的统计信息,输出总数、平均值、标准差、最小值等信息。
df_iris.describe()

输出结果如下:

  • DataFrame的常用属性
属性描述
nmid数据表的维数
shape数据表的形状
size数据表元素的总个数
df_iris=pd.read_csv(train_path)print(df_iris.ndim) #2 print(df_iris.shape) #(120, 4) print(df_iris.size) #480
  • 转化为NumPy数组
iris=np.array(df_iris) print(type(df_iris)) #<class 'pandas.core.frame.DataFrame'> print(type(iris)) #<class 'numpy.ndarray'>

转化为NumPy数组后,可以利用索引和切片访问数组元素,比如iris[0:6]表示读取前6行数据,iris[0:6,0:4]表示读取前6行数据的前4列。

3. 数据可视化

循环输出所有属性关系图

import tensorflow as tf import pandas as pd import numpy as np import matplotlib.pyplot as pltTRAIN_URL="http://download.tensorflow.org/data/iris_training.csv" train_path=tf.keras.utils.get_file(TRAIN_URL.split('/')[-1],TRAIN_URL)column_names=['SepalLength','SepalWidth','PetalLength','PetalWidth','Species'] df_iris=pd.read_csv(train_path,header=0,names=column_names)iris=np.array(df_iris)fig=plt.figure('Iris Data',figsize=(15,15))plt.suptitle("Andreson's Iris Dara Set\n(Blue->Setosa|Red->Versicolor|Green->Virginical)")for i in range(4):for j in range(4):plt.subplot(4,4,4*i+(j+1))if(i==j):plt.text(0.3,0.4,column_names[i],fontsize=15)else:plt.scatter(iris[:,j],iris[:,i],c=iris[:,4],cmap='brg')if(i==0):plt.title(column_names[j])if(j==0):plt.ylabel(column_names[i])plt.show()

输出结果如下:

总结

以上是生活随笔为你收集整理的鸢尾花(Iris)数据集的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。