Repository navigation
Expand file tree
/
Copy pathpro.py
More file actions
132 lines (116 loc) · 3.93 KB
/
Copy pathpro.py
File metadata and controls
132 lines (116 loc) · 3.93 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
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
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, callbacks
from PIL import Image, ImageDraw
import os
import zipfile
import matplotlib.pyplot as plt
import random
# === Settings ===
IMAGE_SIZE = 64
CLASSES = ["circle", "square", "triangle"]
NUM_CLASSES = len(CLASSES)
SEED = 42
np.random.seed(SEED)
tf.random.set_seed(SEED)
random.seed(SEED)
# === GPU Info ===
gpus = tf.config.list_physical_devices('GPU')
if gpus:
print("🚀 GPU detected:", gpus[0].name)
else:
print("⚠️ No GPU detected. Using CPU.")
# === Synthetic Data Generator ===
def generate_image(shape, image_size=IMAGE_SIZE):
image = Image.new("L", (image_size, image_size), 0)
draw = ImageDraw.Draw(image)
if shape == "circle":
draw.ellipse((16, 16, 48, 48), fill=255)
elif shape == "square":
draw.rectangle((16, 16, 48, 48), fill=255)
elif shape == "triangle":
draw.polygon([(32, 16), (48, 48), (16, 48)], fill=255)
return np.array(image)
def generate_synthetic_dataset(n_samples=500):
X, Y = [], []
for _ in range(n_samples):
shape = random.choice(CLASSES)
img = generate_image(shape)
X.append(img / 255.0)
Y.append(CLASSES.index(shape))
X = np.expand_dims(np.array(X), -1)
Y = keras.utils.to_categorical(Y, NUM_CLASSES)
return X, Y
# === CNN Model ===
def build_model():
model = keras.Sequential([
layers.Input(shape=(IMAGE_SIZE, IMAGE_SIZE, 1)),
layers.Conv2D(32, (3,3), activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(64, (3,3), activation='relu'),
layers.MaxPooling2D(),
layers.Conv2D(128, (3,3), activation='relu'),
layers.Flatten(),
layers.Dense(128, activation='relu'),
layers.Dropout(0.3),
layers.Dense(NUM_CLASSES, activation='softmax')
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.summary()
return model
# === Plot training history ===
def plot_history(history):
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Train')
plt.plot(history.history['val_accuracy'], label='Val')
plt.title("Accuracy")
plt.legend()
plt.grid()
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Train')
plt.plot(history.history['val_loss'], label='Val')
plt.title("Loss")
plt.legend()
plt.grid()
plt.tight_layout()
plt.savefig("training_history.png")
plt.show()
# === Training and Export ===
def train_and_export():
print("🔄 Generating synthetic dataset...")
X_train, Y_train = generate_synthetic_dataset(1000)
print("🧠 Building model...")
model = build_model()
print("🚀 Starting training...")
early_stop = callbacks.EarlyStopping(patience=3, restore_best_weights=True)
history = model.fit(
X_train, Y_train,
epochs=20,
batch_size=32,
validation_split=0.1,
callbacks=[early_stop],
verbose=1
)
# Create folders
os.makedirs("exported", exist_ok=True)
# Save dataset
np.save("exported/X_train.npy", X_train)
np.save("exported/Y_train.npy", Y_train)
with zipfile.ZipFile("exported/synthetic_dataset.zip", "w") as zipf:
zipf.write("exported/X_train.npy", arcname="X_train.npy")
zipf.write("exported/Y_train.npy", arcname="Y_train.npy")
# Save model
model.save("exported/shape_classifier_model.keras")
print("📁 Model and dataset saved in 'exported/' folder")
# Final accuracy
val_acc = history.history['val_accuracy'][-1]
print(f"\n✅ Final Validation Accuracy: {val_acc:.4f}")
# Plot
plot_history(history)
# === Run main ===
if __name__ == "__main__":
train_and_export()