人工智能深度学习TensorFlow通过感知器实现鸢尾花数据集分类

一.iris数据集简介

iris数据集的中文名是安德森鸢尾花卉数据集,英文全称是Anderson’s Iris data set。iris包含150个样本,对应数据集的每行数据。每行数据包含每个样本的四个特征和样本的类别信息,所以iris数据集是一个150行5列的二维表。

通俗地说,iris数据集是用来给花做分类的数据集,每个样本包含了花萼长度、花萼宽度、花瓣长度、花瓣宽度四个特征(前4列),我们需要建立一个分类器,分类器可以通过样本的四个特征来判断样本属于山鸢尾、变色鸢尾还是维吉尼亚鸢尾(这三个名词都是花的品种)。

二、数据来源

https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data

三、感知器表示R,评价E,优化O

参阅 深度学习与TensorFlow实战P45-47页

四、TensorFlow通过感知器实现鸢尾花数据集分类的python代码

import tensorflow as tf

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

from sklearn.model_selection import train_test_split

from sklearn import preprocessing

def init_weights(shape):

return tf.Variable(tf.random_normal(shape,stddev=0.01))

#创建分割线

def plotLine(slope,bias):

x = np.arange(-3,3,0.5)

y = x*slope+bias

plt.plot(x,y)

if __name__ == "__main__":

#导入数据,这里用了pandas库

df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)

features = df.iloc[1:len(df.index),[0,2]].values

labels = df.iloc[1:len(df.index),4].values

#调节数据,这一步很关键

scaler = preprocessing.StandardScaler().fit(features)

features_standard = scaler.transform(features)

#选取两种花的两类特征

for index,label in enumerate(labels):

if label == "Iris-setosa":

plt.scatter(features[index,0], features[index,1], color='red', marker='o', label='setosa')

else:

plt.scatter(features[index,0], features[index,1], color='blue', marker='x', label='versicolor')

plt.xlabel('petal len')

plt.ylabel('sepal len')

plt.show()

#转换一下标签

labels=np.where(labels=="Iris-setosa",1,-1)

#使用sklearn类库快速分割数据集

features_train, features_test, lables_train, labels_test=train_test_split(features_standard,labels,test_size=0.33)

#定义placeholder容器,第9章将会描述

X= tf.placeholder(tf.float32)

Y= tf.placeholder(tf.float32)

#初始化模型参数

w= init_weights([2,1])

b= tf.Variable(tf.zeros([1,1]))

#创建感知模型

predict_Y= tf.sign(tf.matmul(X,w)+b)

#定义损失函数

loss = tf.reduce_mean(tf.square(predict_Y-lables_train))

#定义优化方法

optimizer = tf.train.GradientDescentOptimizer(0.01)

train_step = optimizer.minimize(loss)

#初始化变量,运行模型

init = tf.global_variables_initializer()

sess = tf.Session()

sess.run(init)

#开始训练

for i in range(300):

sess.run(train_step,feed_dict = {X:features_train, Y:lables_train})

#提取训练好的模型

w1= sess.run(w).flatten()[0]

w2= sess.run(w).flatten()[1]

b= sess.run(b).flatten()

#将测试数据和感知器分割线显示出来

for index, label in enumerate(labels_test):

if label ==1:

plt.scatter(features_test[index, 0], features_test[index,1],color='red', marker='o', label='setosa')

else:

plt.scatter(features_test[index, 0], features_test[index,1],color='blue', marker='x', label='versicolor')

plt.xlabel('petal len')

plt.ylabel('sepal len')

plotLine(-w1/w2, -b/w2)

plt.show()

看看执行效果界面:

猜你喜欢

转载自blog.csdn.net/bysjlwdx/article/details/83817833