毕业设计练习_01——用keras实现鸢尾花分类

鸢尾花数据集介绍

3种鸢尾花类别,每个类别有50个样本,每个样本中包括4种鸢尾花的属性特征和鸢尾花的品种(sepal length, sepal width, petal length, petal width, species )花萼长度,花萼宽度,花瓣长度,花瓣宽度,品种
Species
0——山鸢花setosa
1——变色鸢尾 versicolour
2——维吉尼亚鸢尾 virginica

用keras构建神经网络八股

import相关模块

import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn import datasets#从sklearn包datasets中读入数据集

数据集读入与处理

x_data = datasets.load_iris().data#返回iris数据集所有输入特征
y_data= datasets.load_iris().target#返回iris数据集所有标签
print(x_data.shape)
print(y_data.shape)

输出看一下数据和标签的shape

(150, 4)
(150,)

将数据集乱序和数据集划分,其中seed括号中的数值可以任意给定

np.random.seed(116)#输入特征和标签仍一一对应 只要括号中设置的数字相同 取出的随机数就相同
np.random.shuffle(x_train)#np.random.shuffle()函数将x_data数据集中的数据自身打乱
np.random.seed(116)
np.random.shuffle(y_train)
tf.random.set_seed(116)
#数据集分成永不相见的训练集和测试集 训练集前120个,测试集前30个
x_train = x_data[:-30]#输入数据集中前120个数据
y_train = y_data[:-30]
x_test = x_data[-30:]
y_test = y_data[-30:]

搭建网络模型

由于数据集较为简单,选择一层全连接层搭建网络结构,注意由于是3分类,最后一层全连接的输出是3,为了防止过拟合,选择了l2正则化方法

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(3,activation='softmax',kernel_regularizer=tf.keras.regularizers.l2())
])
#生成神经网络的参数,4个输入特征,所以输入层为4个输入节点;因为3分类,所以输出层为3个神经元。
#全连接层,3个神经元,非线性函数softmax,正则选tf.keras.regularizers.l2()

配置训练方法

对于多分类问题,选择交叉熵损失函数,对于回归问题,选择mean squared error(均方差)损失函数,由于前面进行了softmax概率分布,所以参数是false

model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.1),
             loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
             metrics=['sparse_categorical_accuracy'])
#优化器选择sgd 损失函数   y_是数值,y是独热码

训练模型

history = model.fit(x_train,y_train,batch_size=32,epochs=100,validation_data=(x_test,y_test),validation_freq=1)

训练结果可视化

import matplotlib.pyplot as plt
acc = history.history['sparse_categorical_accuracy']
val_acc = history.history['val_sparse_categorical_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))

plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'g', label='Validation accuracy')
plt.title('Training and validation accuracy')

plt.figure()

plt.plot(epochs, loss, 'r', label='Training Loss')
plt.plot(epochs, val_loss, 'g', label='Validation Loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()

绿色代表测试集,红色代表训练集

在这里插入图片描述

result = model.predict(x_test)
np.round(result,2)
array([[0.06, 0.78, 0.16],
       [0.96, 0.04, 0.  ],
       [0.05, 0.76, 0.19],
       [0.03, 0.73, 0.24],
       [0.02, 0.65, 0.33],
       [0.  , 0.23, 0.77],
       [0.04, 0.68, 0.28],
       [0.06, 0.84, 0.1 ],
       [0.03, 0.65, 0.32],
       [0.05, 0.79, 0.16],
       [0.94, 0.06, 0.  ],
       [0.92, 0.08, 0.  ],
       [0.96, 0.04, 0.  ],
       [0.94, 0.06, 0.  ],
       [0.92, 0.08, 0.  ],
       [0.03, 0.72, 0.25],
       [0.02, 0.69, 0.29],
       [0.95, 0.05, 0.  ],
       [0.03, 0.68, 0.3 ],
       [0.92, 0.08, 0.  ],
       [0.08, 0.83, 0.1 ],
       [0.02, 0.76, 0.22],
       [0.  , 0.07, 0.92],
       [0.01, 0.37, 0.62],
       [0.92, 0.08, 0.  ],
       [0.  , 0.09, 0.91],
       [0.96, 0.04, 0.  ],
       [0.95, 0.05, 0.  ],
       [0.  , 0.1 , 0.9 ],
       [0.04, 0.8 , 0.17]], dtype=float32)
print(y_test)
[1 0 1 1 1 2 1 1 1 1 0 0 0 0 0 1 1 0 1 0 1 1 2 2 0 2 0 0 2 1]

可以发现在测试集的30个样本均训练正确

补充

本例是直接使用keras内部的数据集,标签直接是0、1、2,不再是文字,不用再进行编码,否则可以使用以下代码。

from sklearn.preprocessing import LabelEncoder # 将标签转化成一个整数
encoder = LabelEncoder()
Y_encoded = encoder.fit_transform(Y) # Y是没经处理的文字标签
Y_onehot = np_utils.to_categorical(Y_encoded) # 该行代码是将0、1、2等数字转化为独热编码
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值