from tensorflow.keras.applications import VGG16
pre_trained_model = VGG16(include_top=False,
weights = "imagenet",
input_shape=(224,224,3))
pre_trained_model.summary()#모델층의 요약정보
cnn_model2 = Sequential()
cnn_model2.add(pre_trained_model)
cnn_model2.add(Flatten())
cnn_model2.add(Dense(units=128,activation='relu'))
cnn_model2.add(Dense(units=64,activation='relu'))
cnn_model2.add(Dense(units=2,activation='softmax'))
# 특성추출방식
pre_trained_model.trainable = False
cnn_model2.summary()
cnn_model2.compile(loss="sparse_categorical_crossentropy",
optimizer="Adam",
metrics=['accuracy'])
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2, random_state=425)
cnn_model2.fit(X_train,y_train,epochs=20)
pre = cnn_model2.predict(X_test)
from sklearn.metrics import classification_report
print(classification_report(y_test,np.argmax(pre,axis=1)))
미세조정방식으로 할 경우 아래처럼 수정하면 된다.
pre_trained_model = VGG16(include_top=False,
weights = "imagenet",
input_shape=(224,224,3))
#미세조정방식
for layer in pre_trained_model.layers :
#print(layer.name)
if layer.name == "block5_conv3" :
layer.trainable = True
else :
layer.trainable = False
from tensorflow.keras.preprocessing.image import ImageDataGenerator
aug = ImageDataGenerator(rotation_range=90,
zoom_range=0.2,
horizontal_flip=True,
height_shift_range=0.2)
from tensorflow.keras.applications import MobileNetV2
pre_trained_model = MobileNetV2(include_top=False,
weights = "imagenet",
input_shape=(224,224,3))
pre_trained_model.trainable=False
pre_trained_model.summary()
from tensorflow.keras.layers import AveragePooling2D
cnn_model4 = Sequential()
cnn_model4.add(pre_trained_model)
cnn_model4.add(AveragePooling2D())
cnn_model4.add(Flatten())
cnn_model4.add(Dense(units=128,activation='relu'))
cnn_model4.add(Dense(units=64,activation='relu'))
cnn_model4.add(Dense(units=2,activation='softmax'))
from sklearn import metrics
cnn_model4.compile(loss="sparse_categorical_crossentropy",
optimizer='Adam',
metrics=['accuracy'])
cnn_model4.fit(aug.flow(X_train,y_train),
epochs=50)