Python Keras神经网络实现iris鸢尾花分类预测

Keras卷积神经网络实现iris鸢尾花分类预测,正确率超过99%

1、鸢尾花数据iris.csv

在这里插入图片描述

iris数据集是机器学习中一个经典的数据集,由英国统计学家Ronald Fisher在1936年收集整理而成。该数据集包含了3种不同品种的鸢尾花(Iris Setosa,Iris Versicolour,Iris Virginica)各50个样本,每个样本包含了花萼长度(sepal length)、花萼宽度(sepal width)、花瓣长度(petal length)、花瓣宽度(petal width)四个特征。

iris数据集的主要应用场景是分类问题,在机器学习领域中被广泛应用。通过使用iris数据集作为样本集,我们可以训练出一个分类器,将输入的新鲜鸢尾花归类到三种品种中的某一种。iris数据集的特征数据已经被广泛使用,也是许多特征选择算法和模型选择算法的基础数据集之一。

在这里插入图片描述
总共150条数据
在这里插入图片描述
数据分布均匀,每种分类50条数据。

2 引入iris鸢尾花数据集

2.1 使用本地iris.csv文件

# -*- coding:utf-8 -*-
import pandas as pd
from keras.utils import np_utils

# 导入iris数据集
df = pd.read_csv("iris.csv")
label_dict = {'setosa': 0, 'versicolor': 1, 'virginica': 2}
df['species'] = df['species'].apply(lambda x: label_dict[x])
X = df.iloc[:, :4].values
labels = df.iloc[:, 4].values
print(labels)

# 将标签进行one-hot编码
y = np_utils.to_categorical(labels)

2.2 下载iris数据集

from sklearn.datasets import load_iris
from sklearn.preprocessing import LabelEncoder, OneHotEncoder

# 读入数据集
iris = load_iris()
X = iris.data
y = iris.target

# 对标签进行编码
le = LabelEncoder()
y = le.fit_transform(y)
y = y.reshape(-1, 1)

# 对标签进行独热编码
ohe = OneHotEncoder()
y = ohe.fit_transform(y).toarray()

3、引入依赖库

# -*- coding:utf-8 -*-
import random         # 导入 random 模块,用于随机数生成
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from keras.utils import np_utils
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense

4、设置随机种子

# 设置随机种子,让模型每次输出的结果都一样
seed_value = 42
random.seed(seed_value)                         # 设置 random 模块的随机种子
np.random.seed(seed_value)                      # 设置 numpy 模块的随机种子
tf.random.set_seed(seed_value)                 # 设置 Tensorflow 中随机种子

5、拆分训练集和测试集

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=seed_value)

6、构建网络模型

# 构建模型
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=X.shape[1]))
model.add(Dense(units=32, activation='relu'))
model.add(Dense(units=8, activation='relu'))
model.add(Dense(units=3, activation='softmax'))

7、编译模型

# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

8、训练模型

# 训练模型
model.fit(X_train, y_train, epochs=100, batch_size=15, verbose=0)

9、测试模型

loss, acc = model.evaluate(X_test, y_test, verbose=0)
print(f'Test accuracy: {acc}')

10、控制台输出

2023-05-01 19:05:45.366554: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudart64_110.dll
2023-05-01 19:05:49.516863: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set
2023-05-01 19:05:49.518720: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library nvcuda.dll
2023-05-01 19:05:49.548524: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 0 with properties: 
pciBusID: 0000:01:00.0 name: GeForce GTX 1650 Ti computeCapability: 7.5
coreClock: 1.485GHz coreCount: 16 deviceMemorySize: 4.00GiB deviceMemoryBandwidth: 178.84GiB/s
2023-05-01 19:05:49.549051: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudart64_110.dll
2023-05-01 19:05:49.556327: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cublas64_11.dll
2023-05-01 19:05:49.556633: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cublasLt64_11.dll
2023-05-01 19:05:49.560389: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cufft64_10.dll
2023-05-01 19:05:49.563796: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library curand64_10.dll
2023-05-01 19:05:49.573391: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cusolver64_10.dll
2023-05-01 19:05:49.577156: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cusparse64_11.dll
2023-05-01 19:05:49.578818: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudnn64_8.dll
2023-05-01 19:05:49.579140: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1862] Adding visible gpu devices: 0
2023-05-01 19:05:49.579558: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2023-05-01 19:05:49.580604: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 0 with properties: 
pciBusID: 0000:01:00.0 name: GeForce GTX 1650 Ti computeCapability: 7.5
coreClock: 1.485GHz coreCount: 16 deviceMemorySize: 4.00GiB deviceMemoryBandwidth: 178.84GiB/s
2023-05-01 19:05:49.581317: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudart64_110.dll
2023-05-01 19:05:49.582061: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cublas64_11.dll
2023-05-01 19:05:49.582709: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cublasLt64_11.dll
2023-05-01 19:05:49.583159: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cufft64_10.dll
2023-05-01 19:05:49.583596: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library curand64_10.dll
2023-05-01 19:05:49.584036: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cusolver64_10.dll
2023-05-01 19:05:49.584477: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cusparse64_11.dll
2023-05-01 19:05:49.584942: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudnn64_8.dll
2023-05-01 19:05:49.585440: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1862] Adding visible gpu devices: 0
2023-05-01 19:05:50.037470: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1261] Device interconnect StreamExecutor with strength 1 edge matrix:
2023-05-01 19:05:50.037807: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1267]      0 
2023-05-01 19:05:50.037974: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1280] 0:   N 
2023-05-01 19:05:50.038283: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1406] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 2903 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1650 Ti, pci bus id: 0000:01:00.0, compute capability: 7.5)
2023-05-01 19:05:50.039434: I tensorflow/compiler/jit/xla_gpu_device.cc:99] Not creating XLA devices, tf_xla_enable_xla_devices not set
2023-05-01 19:05:50.198406: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:116] None of the MLIR optimization passes are enabled (registered 2)
2023-05-01 19:05:50.499869: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cublas64_11.dll
2023-05-01 19:05:50.890828: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cublasLt64_11.dll
Test accuracy: 1.0

Test accuracy: 1.0
测试准确率100%

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值