Repository navigation
Expand file tree
/
Copy pathmodel.py
More file actions
75 lines (65 loc) · 2.84 KB
/
Copy pathmodel.py
File metadata and controls
75 lines (65 loc) · 2.84 KB
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
import tensorflow as tf
import os
import shutil
import random
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
from tensorflow.keras.models import Model,Input
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.optimizers import Adam
# Define the training and test data directories
train_dir = 'rice_split/train'
test_dir = 'rice_split/test'
# Define the data generators for training and validation
train_datagen = ImageDataGenerator(rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_dir,
target_size=(224, 224),
batch_size=32,
class_mode='categorical',
subset='training',
seed =42)
test_generator = test_datagen.flow_from_directory(test_dir,
target_size=(224, 224),
batch_size=32,
class_mode='categorical',
subset='validation',
shuffle=False,
seed=42)
# Define the MobileNetV2 model as the base model
base_model = MobileNetV2(
input_shape=(224, 224, 3),
include_top=False,
weights='imagenet'
)
base_model.trainable = False
# Freeze the base model layers
for layer in base_model.layers:
layer.trainable = False
# Combine the base model with the new layers
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dropout(rate=0.2)(x)
outputs = Dense(units=36, activation="softmax")(x)
model = Model(inputs=base_model.input, outputs=outputs)
# Compile the model
LEARNING_RATE = 0.001
model.compile(optimizer=Adam(learning_rate=LEARNING_RATE),
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
history = model.fit(train_generator,
epochs=3,
validation_data=test_generator)
# Evaluate the model on the test set
test_loss, test_acc = model.evaluate(test_generator)
print('Test accuracy:', test_acc)
# Saving the model
model.save('rice_image_classification.h5')