Keras神经网络多分类鸢尾花分类

利用keras搭积木,快速搭建出一个神经网络模型,训练鸢尾花分类

代码

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
from sklearn.model_selection import train_test_split
import keras
from keras.models import Sequential
from keras.layers import Dense
# 导入数据
path = '../Data/iris.data'
data = pd.read_csv(path, names=['Sepal.Length','Sepal.Width','Petal.Length','Petal.Width','Species'])
data.head(10)

Keras神经网络多分类鸢尾花分类_第1张图片

# 映射函数iris_type: 将string的label映射至数字label
def iris_type(s):
    class_label = {'Iris-setosa':0, 'Iris-versicolor':1, 'Iris-virginica':2}
    return class_label[s]
Data = pd.read_csv(path,names=['Sepal.Length','Sepal.Width','Petal.Length','Petal.Width','Species'], converters = {4:iris_type})
Data.head(10)

Keras神经网络多分类鸢尾花分类_第2张图片

# 变量初始化
# 最后一列为y,其余为x
cols = Data.shape[1] #列数 shape[0]行数 [1]列数
X = Data.iloc[:,0:cols-1]       #取前cols-1列,即输入向量
y = Data.iloc[:,cols-1:cols]    #取最后一列,即目标变量
X = np.array(X)
y = np.array(y)
y = y.flatten()       # 对y进行降维
def realdata(y,k):
    real = np.zeros(shape=(k,len(y)))
    for i in range(0,k):
        y_i = np.array([1 if label == i else 0 for label in y])
        real[i] = y_i
    return real.T
y = realdata(y,3)
y

Keras神经网络多分类鸢尾花分类_第3张图片

X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3)
#y_train=y_train.T
X_train.shape,y_train.shape
# 搭建神经网络
# 搭建神经网络
model = Sequential()
model.add(Dense(units=5, activation='relu',input_dim = 4))   # 输入层,5个激活单元,激活函数为relu,输入数据维度为(4,)
model.add(Dense(units=5, activation='relu'))                 # 隐藏层,5个激活单元,激活函数为relu
model.add(Dense(units=3, activation='softmax'))              # 输出层,3个输出单元,激活函数为softmax)
model.compile(loss='categorical_crossentropy', optimizer='sgd',metrics=['accuracy'])
model.fit(X_train,y_train,batch_size=1,epochs = 20)

Keras神经网络多分类鸢尾花分类_第4张图片

result = model.predict(X_test)
np.round(result,2)

Keras神经网络多分类鸢尾花分类_第5张图片

score = model.evaluate(X_test,y_test)
print('loss值为:',score[0])
print('准确率为:',score[1])

你可能感兴趣的:(神经网络,深度学习,python,tensorflow,机器学习)