forked from svaksha/pythonidae
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtensorflow_training.py
More file actions
67 lines (57 loc) · 1.82 KB
/
Copy pathtensorflow_training.py
File metadata and controls
67 lines (57 loc) · 1.82 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
import tensorflow as tf
from tensorflow.keras.datasets import mnist
import numpy as np
# Load MNIST dataset
print("Loading MNIST dataset...")
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Normalize and reshape data
print("Preparing data...")
x_train = x_train.reshape(-1, 784) / 255.0
x_test = x_test.reshape(-1, 784) / 255.0
print(f"Training data shape: {x_train.shape}")
print(f"Test data shape: {x_test.shape}")
# Create model
print("\nBuilding model...")
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(784,)),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
# Compile model
print("Compiling model...")
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Display model architecture
print("\nModel Architecture:")
model.summary()
# Train model
print("\nTraining model...")
history = model.fit(
x_train, y_train,
epochs=10,
batch_size=32,
validation_split=0.2,
verbose=1
)
# Evaluate on test data
print("\nEvaluating on test data...")
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)
print(f"Test Loss: {test_loss:.4f}")
print(f"Test Accuracy: {test_accuracy:.4f}")
# Make predictions on sample images
print("\nMaking predictions on sample images...")
sample_predictions = model.predict(x_test[:5])
for i, pred in enumerate(sample_predictions):
predicted_class = np.argmax(pred)
actual_class = y_test[i]
confidence = pred[predicted_class]
print(f"Image {i}: Predicted={predicted_class}, Actual={actual_class}, Confidence={confidence:.4f}")
# Save the model
print("\nSaving model...")
model.save('mnist_model.h5')
print("Model saved as 'mnist_model.h5'")