text_plain_output_1.png
from keras.preprocessing.image import array_to_img

from keras.preprocessing.image import img_to_array

from keras.preprocessing.image import load_img

from sklearn.metrics import classification_report

from tensorflow.keras.layers import Conv2D, MaxPooling2D,GlobalAveragePooling2D

from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten

from tensorflow.keras.models import Sequential

from tensorflow.keras.preprocessing.image import load_img,img_to_array

import matplotlib.pyplot as plt

import numpy as np

import os

import tensorflow as tf

stored_data_path = '../input/magnetictiledefect'
CLASS_NAME = ['Blowhole', 'Free', 'Break', 'Fray', 'Uneven', 'Crack']
CLASS_NAME_NUM = [0, 1, 2, 3, 4, 5]

file_path = '../input/magneticTileDefect/'
X_all_raw = []
y_all = []
for ani_class in CLASS_NAME:
    for filename in os.listdir(file_path + ani_class):
        for subfilename in os.listdir(file_path + ani_class + '/' + filename + '/Imgs'):
            img = load_img(file_path + ani_class + '/' + filename + '/Imgs/' + subfilename, target_size=(224, 224))
            img_array = img_to_array(img)
            X_all_raw.append(img_array)
            y_all.append(CLASS_NAME.index(ani_class))
X_all_raw = np.array(X_all_raw)
X_all_raw.shape

y_all = np.array(y_all)
y_all

X_train_raw = X_train_raw.astype('float32')
X_test_raw = X_test_raw.astype('float32')
X_train_raw /= 255
X_test_raw /= 255
y_train = tf.keras.utils.to_categorical(y_train, len(CLASS_NAME))
y_test = tf.keras.utils.to_categorical(y_test, len(CLASS_NAME))

BATCH_SIZE = 64
EPOCH = 50

model = Sequential()
model.add(Conv2D(64, (3, 3), input_shape=(224, 224, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(len(CLASS_NAME)))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
history = model.fit(X_train_raw, y_train, batch_size=BATCH_SIZE, epochs=EPOCH, validation_data=(X_test_raw, y_test), shuffle=True)
y_pred = model.predict(X_test_raw)

plt.figure(figsize=[20, 8])
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy', size=25, pad=20)
plt.ylabel('Accuracy', size=15)
plt.xlabel('Epoch', size=15)
plt.legend(['train', 'test'], loc='upper left')
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss', size=25, pad=20)
plt.ylabel('Loss', size=15)
plt.xlabel('Epoch', size=15)
plt.legend(['train', 'test'], loc='upper left')
plt.show()