dgith commited on
Commit
92214ba
·
verified ·
1 Parent(s): 6748826

Create train_model.py

Browse files
Files changed (1) hide show
  1. train_model.py +59 -0
train_model.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # train_model.py - Download, train, and export MNIST model
2
+
3
+ import tensorflow as tf
4
+ import numpy as np
5
+ import os
6
+
7
+ print("Loading MNIST dataset...")
8
+
9
+ # Load and preprocess data
10
+ (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
11
+
12
+ # Normalize pixel values to [0, 1]
13
+ x_train = x_train.astype('float32') / 255.0
14
+ x_test = x_test.astype('float32') / 255.0
15
+
16
+ # Optional: Use subset for faster training during development
17
+ # x_train, y_train = x_train[:20000], y_train[:20000]
18
+ # x_test, y_test = x_test[:5000], y_test[:5000]
19
+
20
+ print(f"Training on {len(x_train)} samples")
21
+ print(f"Testing on {len(x_test)} samples")
22
+
23
+ # Build model
24
+ model = tf.keras.Sequential([
25
+ tf.keras.layers.Flatten(input_shape=(28, 28)),
26
+ tf.keras.layers.Dense(128, activation='relu'),
27
+ tf.keras.layers.Dropout(0.2),
28
+ tf.keras.layers.Dense(64, activation='relu'),
29
+ tf.keras.layers.Dropout(0.1),
30
+ tf.keras.layers.Dense(10, activation='softmax')
31
+ ])
32
+
33
+ # Compile
34
+ model.compile(
35
+ optimizer='adam',
36
+ loss='sparse_categorical_crossentropy',
37
+ metrics=['accuracy']
38
+ )
39
+
40
+ # Train
41
+ print("Training model...")
42
+ model.fit(
43
+ x_train, y_train,
44
+ epochs=5,
45
+ batch_size=32,
46
+ validation_data=(x_test, y_test),
47
+ verbose=1
48
+ )
49
+
50
+ # Evaluate
51
+ test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)
52
+ print(f"\n✅ Model trained! Test Accuracy: {test_accuracy:.4f}")
53
+
54
+ # Create models directory
55
+ os.makedirs("model", exist_ok=True)
56
+
57
+ # Save model in Keras format (.h5)
58
+ model.save("model/mnist_model.h5")
59
+ print("💾 Model saved to model/mnist_model.h5")