利用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)
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)
cols = Data.shape[1]
X = Data.iloc[:,0:cols-1]
y = Data.iloc[:,cols-1:cols]
X = np.array(X)
y = np.array(y)
y = y.flatten()
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
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3)
X_train.shape,y_train.shape
model = Sequential()
model.add(Dense(units=5, activation='relu',input_dim = 4))
model.add(Dense(units=5, activation='relu'))
model.add(Dense(units=3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='sgd',metrics=['accuracy'])
model.fit(X_train,y_train,batch_size=1,epochs = 20)
result = model.predict(X_test)
np.round(result,2)
score = model.evaluate(X_test,y_test)
print('loss值为:',score[0])
print('准确率为:',score[1])