# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import numpy as np
import pandas as pd
from keras.applications import mobilenet_v2
import tensorflow as tf

conv_base = mobilenet_v2.MobileNetV2(include_top=False, weights='imagenet',input_shape=(224, 224, 3))
conv_base.trainable = False


conv_base.summary()

import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator

from keras import models
from keras import layers
from keras import optimizers
model = models.Sequential()
model.add(conv_base)
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dropout(0.4))
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dropout(0.2))
model.add(layers.Dense(2, activation = 'softmax'))

# +
#train_datagen = ImageDataGenerator(rescale=1./255,rotation_range=40,width_shift_range=0.2,
#height_shift_range=0.2,shear_range=0.2,zoom_range=0.2,horizontal_flip=True,fill_mode='nearest')

train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_directory("train",target_size=(224 , 224),batch_size=10)

validation_generator = test_datagen.flow_from_directory("validation",target_size=(224, 224),batch_size=10)

model.compile(loss='categorical_crossentropy',optimizer=optimizers.RMSprop(lr=2e-5),metrics=['acc'])

history = model.fit_generator(train_generator,steps_per_epoch=25,epochs=10,validation_data=validation_generator,validation_steps=5)
# -

a = conv_base.layers
set_trainable= False
for layer in a:
    print(layer.name)
    if (layer.name == 'batch_16_expand' or 'batch_15_expand' or 'batch_14_expand' or 'batch_12_expand' or 'batch_13_expand'):
        set_trainable=True
    if set_trainable:
        layer.trainable = True
    else:
        layer.trainable = False

# +
model.compile(loss='categorical_crossentropy',optimizer=optimizers.RMSprop(lr=1e-5),metrics=['acc'])

history = model.fit_generator(train_generator,steps_per_epoch=25,epochs=10,validation_data=validation_generator,validation_steps=5)
# -

predict_datagen = ImageDataGenerator(rescale=1/255)
predict_generator = predict_datagen.flow_from_directory('predict',target_size=(224,224),batch_size=10)
label_true = predict_generator.classes
stp = len(predict_generator)
label_predict = model.predict_generator(predict_generator , steps=stp)

predict = []
label_predict
for i in label_predict:
    if i[0]>i[1]:
        predict.append(0)
    else:
        predict.append(1)

predict = np.array(predict)
predict.shape


# +
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score

accuracy = accuracy_score(label_true,predict)
print('acc: %f' % accuracy)
precision = precision_score(label_true,predict)
print('precision: %f' % precision)
recall = recall_score(label_true,predict)
print('recall : %f' % recall)
f1 = f1_score(label_true,predict)
print('f1_score: %f' % f1)
# -

import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()





StarcoderdataJupyterScriptsDedupFiltered