VGG16を使った画像分類について

python

from google.colab import drive drive.mount('/content/drive') %cd '/content/drive/MyDrive/test' import os import cv2 import numpy as np import glob as glob from sklearn.model_selection import train_test_split from keras.utils import np_utils #フォルダ名をクラス名にするpath = "./images"folders = os.listdir(path)classes = [f for f in folders if os.path.isdir(os.path.join(path, f))]n_classes = len(classes) #画像とラベルの格納X = []Y = [] for label,class_name in enumerate(classes): files = glob.glob("./images/" + class_name +"/*.jpg") for file in files: img = cv2.imread(file) img = cv2.resize(img,dsize = (224,224)) X.append(img) Y.append(label) X = np.array(X)X = X.astype('float32')X /= 255.0X[0] #ラベルの変換Y = np.array(Y)Y = np_utils.to_categorical(Y,n_classes)Y[:5] #学習データとテストデータに分けるX_train, X_test, y_train, y_test = train_test_split(X, Y,test_size = 0.2)print(X_train.shape)print(X_test.shape)print(y_train.shape)print(y_test.shape) from keras.applications.vgg16 import VGG16 from keras.models import Sequential from keras.models import model_from_json from keras.models import Model from keras.layers import Input, Activation, Dense, Flatten, Dropout from keras.optimizers import Adam #vgg16input_tensor = Input(shape=(224, 224, 3))base_model = VGG16(weights='imagenet', input_tensor=input_tensor,include_top=False) #後付けtop_model = Sequential()top_model.add(Flatten(input_shape=base_model.output_shape[1:]))top_model.add(Dense(n_classes, activation='softmax')) #結合model = Model(inputs=base_model.input, outputs = top_model(base_model.output)) #学習させない層for layer in model.layers[:15]: layer.trainable = False print('# layers = ', len(model. layers)) model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])model.summary() #trainデータで学習model.fit(X_train,y_train,epochs = 20,batch_size = 16) #テストデータで精度確認score = model.evaluate(X_test,y_test,batch_size = 16) import pickle #クラス名の保存pickle.dump(classes,open("classes.sav","wb"))#モデルの保存model.save("./cnn.h5") from keras.models import load_model import pickle import cv2 #モデルとクラス名の読み込みmodel = load_model("./cnn.h5")classes = pickle.load(open("classes.sav","rb")) #sample画像の前処理img = cv2.imread('sample.jpg')img = cv2.resize(img,dsize = (224,224))img = img.astype('float32')img /= 225.0img = img[None, ...]result = model.predict(img) np.set_printoptions(precision = 3, suppress = True)result*100 #確率が一番大きいクラスpred = result.argmax()pred #クラス名の呼び出しclasses[pred]

コメントを投稿

0 コメント