-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_classification_tensorflow_model_for_andriod_app.py
161 lines (128 loc) · 4.67 KB
/
image_classification_tensorflow_model_for_andriod_app.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
148
149
150
151
152
153
154
155
156
157
158
159
160
# -*- coding: utf-8 -*-
"""Image Classification TensorFlow Model for Andriod app.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1BlXxAgAt3gEH5e4apm76REFgv06V-L5G
"""
from google.colab import drive
drive.mount('/content/gdrive')
!unzip '/content/gdrive/MyDrive/data/data.zip'
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255, # Normalize pixel values between 0 and 1
rotation_range=10, # Rotate the image randomly between -10 and 10 degrees
shear_range=0.2, # Apply shear transformation with a shear intensity of 0.2
zoom_range=0.2, # Apply zoom randomly between 0.8 and 1.2
horizontal_flip=True # Flip the image horizontally
)
val_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'data/train', # Directory of training data
target_size=(224, 224), # Resize the image to 224 x 224
batch_size=200, # Number of images to process at once
class_mode='categorical' # Categorical classification (more than 2 classes)
)
validation_generator = val_datagen.flow_from_directory(
'data/val', # Directory of validation data
target_size=(224, 224),
batch_size=200,
class_mode='categorical'
)
test_generator = test_datagen.flow_from_directory(
'data/test', # Directory of validation data
target_size=(224, 224),
batch_size=200,
class_mode='categorical'
)
import tensorflow as tf
import matplotlib.pyplot as plt
img_height, img_width = 224,224
batch_size = 32
train_ds = tf.keras.utils.image_dataset_from_directory(
"data/train",
image_size = (img_height, img_width),
batch_size = batch_size
)
val_ds = tf.keras.utils.image_dataset_from_directory(
"data/val",
image_size = (img_height, img_width),
batch_size = batch_size
)
test_ds = tf.keras.utils.image_dataset_from_directory(
"data/test",
image_size = (img_height, img_width),
batch_size = batch_size
)
class_names = ["apple","banana","cat","crow","daisy","dandelion","dog","kingfisher","orange","peacock","sunflower","tulip"]
plt.figure(figsize=(10,10))
for images, labels in train_ds.take(1):
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
plt.title(class_names[labels[i]])
plt.axis("off")
# model = tf.keras.Sequential([
# tf.keras.layers.Conv2D(32,3,activation='relu',input_shape=(224,224,3)),
# # tf.keras.layers.BatchNormalization(),
# tf.keras.layers.MaxPooling2D(2, 2),
# tf.keras.layers.Conv2D(64,3,activation='relu'),
# # tf.keras.layers.BatchNormalization(),
# tf.keras.layers.MaxPooling2D(2,2),
# tf.keras.layers.Conv2D(64,3,activation='relu'),
# # tf.keras.layers.BatchNormalization(),
# tf.keras.layers.MaxPooling2D(2,2),
# tf.keras.layers.Flatten(),
# tf.keras.layers.Dense(128, activation='relu'),
# tf.keras.layers.Dropout(0.5),
# tf.keras.layers.Dense(256, activation='relu'),
# tf.keras.layers.Dropout(0.2),
# tf.keras.layers.Dense(256,activation='relu'),
# tf.keras.layers.Dense(12, activation='softmax')
# ])
from keras.applications.vgg16 import VGG16
conv_base = VGG16(
weights='imagenet',
include_top = False,
input_shape=(224,224,3)
)
from keras import Sequential
from keras.layers import Dense,Flatten
model = Sequential()
model.add(conv_base)
model.add(Flatten())
model.add(Dense(256,activation='relu'))
model.add(Dense(12,activation='softmax'))
conv_base.trainable = False
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# Train the model
history = model.fit(train_generator,
epochs=10,
validation_data=validation_generator)
# model.save('model.h5')
model.evaluate(test_generator)
plt.plot(history.history['accuracy'], label='train acc')
plt.plot(history.history['val_accuracy'], label='val acc')
plt.legend()
plt.show()
plt.plot(history.history['loss'], label='train loss')
plt.plot(history.history['val_loss'], label='val loss')
plt.legend()
plt.show()
import numpy
plt.figure(figsize=(10,10))
for images, labels in test_ds.take(1):
classifications = model(images)
# print(classifications)
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype("uint8"))
index = numpy.argmax(classifications[i])
plt.title("Pred: " + class_names[index] + " | Real: " + class_names[labels[i]])
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open("model.tflite", 'wb') as f:
f.write(tflite_model)