-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinception.py
147 lines (115 loc) · 3.95 KB
/
inception.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# -*- coding: utf-8 -*-
"""inception.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1hZ9vibzTcZTkSP8uf8E55Jl2VNIKAz1w
"""
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import seaborn as sns
from sklearn.metrics import confusion_matrix
from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing.image import ImageDataGenerator
from keras.utils.np_utils import to_categorical
from keras.callbacks import TensorBoard
from keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from keras.models import Sequential
import tensorflow as tf
import pickle
import random
import cv2
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from google.colab import files
! pip install - q kaggle
files.upload()
!gdown - -id 1gR5-Tzr-HZicaORJEHg6uVOOcPy0YY49
!unzip rooms_dataset.zip
! mkdir ~/.kaggle
! cp kaggle.json ~/.kaggle/
! chmod 600 ~/.kaggle/kaggle.json
!kaggle datasets download - d crowww/a-large-scale-fish-dataset
!unzip a-large-scale-fish-dataset.zip
# Dataset path
dataset_path = '/content/Fish_Dataset/Fish_Dataset'
fish_classes = os.listdir(dataset_path)
print(fish_classes)
# Loading the dataset
training_data = []
IMG_SIZE = 75
def create_training_data():
for fish_class in fish_classes:
path = os.path.join(dataset_path, fish_class)
class_num = fish_classes.index(fish_class)
for img in os.listdir(path):
try:
img_array = cv2.imread(
os.path.join(path, img), cv2.IMREAD_COLOR)
new_array = cv2.resize(
img_array, (IMG_SIZE, IMG_SIZE), interpolation=cv2.INTER_AREA)
training_data.append([new_array, class_num])
except Exception as e:
pass
create_training_data()
print(len(training_data))
# Shuffling the dataset
random.shuffle(training_data)
for sample in training_data[:10]:
print(sample[1])
# Splitting the dataset into features and labels
X = []
y = []
for features, label in training_data:
X.append(features)
y.append(label)
# Converting the features and labels into numpy arrays
X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 3)
y = np.array(y)
# Normalizing the features
X = X / 255.0
# One hot encoding the labels
y = to_categorical(y, num_classes=9)
# Splitting the dataset into training set and test set
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0)
# Building the inceptionV3 model
inceptionV3 = InceptionV3(
weights="imagenet", include_top=False, input_shape=(IMG_SIZE, IMG_SIZE, 3))
# Adding the layers to the inceptionV3 model
model = Sequential()
model.add(inceptionV3)
model.add(Flatten())
model.add(Dense(256, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(9, activation="softmax"))
# Compiling the inceptionV3 model
model.compile(loss="categorical_crossentropy",
optimizer="adam", metrics=["accuracy"])
# Fitting the inceptionV3 model to the training set
model.fit(X_train, y_train, batch_size=32, epochs=20,
validation_data=(X_test, y_test))
# Saving the inceptionV3 model
model.save("inceptionV3.model")
# Loading the inceptionV3 model
model = tf.keras.models.load_model("inceptionV3.model")
# Evaluating the inceptionV3 model
loss, accuracy = model.evaluate(X_test, y_test)
print("Loss: ", loss)
print("Accuracy: ", accuracy)
# Predicting the test set results
y_pred = model.predict(X_test)
y_pred = np.argmax(y_pred, axis=1)
y_test = np.argmax(y_test, axis=1)
# Printing the name of the fish class
print(fish_classes[y_pred[0]])
# Confusion matrix
cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize=(6, 5))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.title('Confusion Matrix')
plt.xlabel('Predicted Label')
plt.ylabel('True Label')
plt.show()
print(classification_report(y_test, y_pred, target_names=fish_classes))