I made a classifier for iris while referring to this course, so it is a memorandum. [Must-see for beginners! Completely capture neural networks and deep learning with Python]
Mac OS Catalina 10.15.7 Spyder 4.1.4 Anaconda 3 Python 3.7.9 Keras 2.3.1
This is the code I created.
iris.py
from sklearn.datasets import load_iris#Get iris data
iris = load_iris()
from sklearn.model_selection import train_test_split as split #Tool to separate datasets
X_train,X_test,y_train,y_test = split(iris.data, iris.target, train_size = 0.8) #80 of the dataset%For learning, 20%For experimentation
import keras
#Creating a neural network
#Dense:Neural network definition class
#Activateion:Activation function class
from keras.layers import Dense, Activation
model = keras.models.Sequential()#Make a model Make a container
model.add(Dense(units =32,input_dim = 4 )) #32 intermediate layers, 4 input layers
model.add(Activation('relu'))#Activation function Relu
model.add(Dense(units = 3))#Output layer:Three
model.add(Activation('softmax'))#Activation function softmax
#compile
model.compile(
loss = 'sparse_categorical_crossentropy', optimizer = 'sgd', metrics = ['accuracy'])
#Execution of learning
model.fit(X_train,y_train,epochs = 100)#100 times iterative learning
#Perform evaluation
#Check the correct answer rate of test data
score = model.evaluate(X_test,y_test,batch_size = 1)#loss in score(loss) ,accuracy(accuracy)Vector
#Reference: https://aidiary.hatenablog.com/category/Keras?page=1478696865
accuracy = score[1]
print('accuracy="',str(accuracy))#To combine numbers and strings with print, str()Make a string with
#Reference: https://www.javadrive.jp/python/string/index9.html
#Check only one data
import numpy as np
x = np.array([[5.1,3.5,1.4,0.2]])#X_Create an array in the same format as train
r = model.predict(x)#Probability vector
print('Probability per label=',r)
print('Label with the highest probability=',r.argmax())#argmax()Returns the largest label in the vector
#Output data
json_string = model.to_json()
#If you want to import a model
#from keras.models import model_fromjson #model = model_from_json/json_string)
#Save learning parameters
#Install h5py first
model.save_weights('param.hdf5')
#When reading
#model.load_weight('param.hdf5')
Execution result
accuracy=" 0.9666666388511658
Probability per label= [[0.9405338 0.05598015 0.00348606]]
Label with the highest probability= 0
Recommended Posts