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 | """TensorFlow code generated based on BUML."""
import tensorflow as tf
from keras import layers
from datetime import datetime
from sklearn.metrics import classification_report
from besser.generators.nn.utils_nn import compute_mean_std
# Define the network architecture
class NeuralNetwork(tf.keras.Model):
def __init__(self):
super().__init__()
self.l1 = layers.Conv2D(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='valid', dilation_rate=1, groups=1, use_bias=True, activation='relu')
self.l2 = layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding='valid')
self.l3 = layers.Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding='valid', dilation_rate=1, groups=1, use_bias=True, activation='relu')
self.l4 = layers.MaxPool2D(pool_size=(2, 2), strides=(2, 2), padding='valid')
self.l5 = layers.Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding='valid', dilation_rate=1, groups=1, use_bias=True, activation='relu')
self.l6 = layers.Flatten()
self.l7 = layers.Dense(units=64, use_bias=True, activation='relu')
self.l8 = layers.Dense(units=10, use_bias=True)
def call(self, x):
x = self.l1(x)
x = self.l2(x)
x = self.l3(x)
x = self.l4(x)
x = self.l5(x)
x = self.l6(x)
x = self.l7(x)
x = self.l8(x)
return x
def prepare_datasets():
"""Prepare training and testing datasets."""
IMAGE_SIZE = (32, 32)
# Function to load and preprocess images
scale, _, _ = compute_mean_std("dataset/cifar10/train", num_samples=100,
target_size=IMAGE_SIZE)
def preprocess_image(image, label, to_scale):
if to_scale:
image = tf.cast(image, tf.float32) / 255.0
return image, label
# Load dataset (resizes by default)
def load_dataset(directory, mode, image_size):
dataset = tf.keras.preprocessing.image_dataset_from_directory(
directory=directory,
label_mode="int",
image_size=image_size,
batch_size=32,
shuffle=True if mode == 'train' else False,
)
# Apply preprocessing
dataset = dataset.map(
lambda image, label: preprocess_image(image, label, scale))
# Prefetch for performance optimization
AUTOTUNE = tf.data.AUTOTUNE
dataset = dataset.prefetch(buffer_size=AUTOTUNE)
return dataset
# Load datasets
train_loader = load_dataset("dataset/cifar10/train", "train", IMAGE_SIZE)
test_loader = load_dataset("dataset/cifar10/test", "test", IMAGE_SIZE)
return train_loader, test_loader
def train(model, train_loader, criterion, optimizer, epochs, num_classes):
"""Train the neural network."""
print('##### Training the model')
for epoch in range(epochs):
# Initialize the running loss for the current epoch
running_loss = 0.0
total_loss = 0.0
# Iterate over mini-batches of training data
for i, (inputs, labels) in enumerate(train_loader):
with tf.GradientTape() as tape:
outputs = model(inputs, training=True)
# Convert labels to one-hot encoding
if labels.shape.rank > 1 and labels.shape[-1] == 1:
labels = tf.squeeze(labels, axis=-1)
labels = tf.cast(labels, dtype=tf.int32)
labels = tf.one_hot(labels, depth=num_classes)
loss = criterion(labels, outputs)
# Compute gradients and update model parameters
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(
zip(gradients, model.trainable_variables))
total_loss += loss.numpy()
running_loss += loss.numpy()
if i % 200 == 199: # Print every 200 mini-batches
print(
f"[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 200:.3f}"
)
running_loss = 0.0
print(
f"[{epoch + 1}] overall loss for epoch: "
f"{total_loss / len(train_loader):.3f}"
)
total_loss = 0.0
print('Training finished')
def evaluate(model, test_loader, criterion, num_classes):
"""Evaluate the neural network."""
print('##### Evaluating the model')
predicted_labels = []
true_labels = []
test_loss = 0.0
for inputs, labels in test_loader:
outputs = model(inputs, training=False)
true_labels.extend(labels.numpy())
predicted = tf.argmax(outputs, axis=-1).numpy()
if labels.shape.rank > 1 and labels.shape[-1] == 1:
labels = tf.squeeze(labels, axis=-1)
labels = tf.cast(labels, dtype=tf.int32)
labels = tf.one_hot(labels, depth=num_classes)
predicted_labels.extend(predicted)
test_loss += criterion(labels, outputs).numpy()
average_loss = test_loss / len(test_loader)
print(f"Test Loss: {average_loss:.3f}")
# Calculate the metrics
metrics = ['f1-score']
report = classification_report(true_labels, predicted_labels,
output_dict=True)
for metric in metrics:
metric_list = []
for class_label in report.keys():
if class_label not in ('macro avg', 'weighted avg', 'accuracy'):
print(f"{metric.capitalize()} for class {class_label}:",
report[class_label][metric])
metric_list.append(report[class_label][metric])
metric_value = sum(metric_list) / len(metric_list)
print(f"Average {metric.capitalize()}: {metric_value:.2f}")
print(f"Accuracy: {report['accuracy']}")
if __name__ == "__main__":
# Prepare datasets
train_loader, test_loader = prepare_datasets()
# Define the network, loss function, and optimizer
my_model = NeuralNetwork()
criterion = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001)
# Train the neural network
train(my_model, train_loader, criterion, optimizer, 10, 10)
# Evaluate the neural network
evaluate(my_model, test_loader, criterion, 10)
# Save the neural network
print('##### Saving the model')
my_model.save(f"my_model_{datetime.now().strftime('%Y%m%d_%H%M%S')}")
print("The model is saved successfully")
|