Tensor Flow
1. TensorFlow program that demonstrates building, training, and using a simple neural network to classify handwritten digits using the famous MNIST dataset.
# Simple TensorFlow 2.x Demo: MNIST Handwritten Digit Classification
# Works with TensorFlow 2.10+ (including TensorFlow 2.17 in 2025)
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
print(f"TensorFlow version: {tf.__version__}")
print(f"GPU Available: {len(tf.config.list_physical_devices('GPU')) > 0}")
# 1. Load and preprocess the MNIST dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Normalize pixel values to 0-1
x_train = x_train / 255.0
x_test = x_test / 255.0
# Reshape to add channel dimension (28, 28, 1)
x_train = x_train.reshape(-1, 28, 28, 1)
x_test = x_test.reshape(-1, 28, 28, 1)
print(f"Training data shape: {x_train.shape}")
print(f"Test data shape: {x_test.shape}")
# 2. Build a Convolutional Neural Network (CNN)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28,28,1)),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax') # 10 digits
])
# Compile the model
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# Print model architecture
model.summary()
# 3. Train the model
print("\nTraining the model...")
history = model.fit(
x_train, y_train,
epochs=10,
validation_data=(x_test, y_test),
batch_size=128,
verbose=1
)
# 4. Evaluate the model
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)
print(f"\nTest accuracy: {test_accuracy:.4f} ({test_accuracy*100:.2f}%)")
# 5. Make predictions on a few test images
predictions = model.predict(x_test[:5])
predicted_labels = np.argmax(predictions, axis=1)
# 6. Visualize results
plt.figure(figsize=(12, 6))
for i in range(5):
plt.subplot(1, 5, i+1)
plt.imshow(x_test[i].reshape(28, 28), cmap='gray')
plt.title(f"Pred: {predicted_labels[i]}\nTrue: {y_test[i]}")
plt.axis('off')
plt.suptitle('Sample Predictions')
plt.show()
# 7. Plot training history
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history.history['accuracy'], label='Training Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Model Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.subplot(1, 2, 2)
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Model Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.tight_layout()
plt.show()
# 8. Save the trained model (optional)
model.save('mnist_cnn_model.keras')
print("\nModel saved as 'mnist_cnn_model.keras'")
# Bonus: Load and use the saved model
# loaded_model = tf.keras.models.load_model('mnist_cnn_model.keras')
# new_predictions = loaded_model.predict(x_test[:5])
2. Here's a simple TensorFlow program that demonstrates basic concepts with a linear regression example:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Generate sample data: y = 2x + 1 + some noise
x_data = np.linspace(0, 10, 50)
y_data = 2 * x_data + 1 + np.random.normal(0, 1, 50)
# Create a simple linear model
model = tf.keras.Sequential([
tf.keras.layers.Dense(units=1, input_shape=[1])
])
# Compile the model
model.compile(
optimizer='adam',
loss='mean_squared_error'
)
print("Training the model...")
# Train the model
history = model.fit(x_data, y_data, epochs=100, verbose=0)
# Make predictions
predictions = model.predict(x_data)
# Print the learned weights
weights = model.layers[0].get_weights()
print(f"\nLearned weight (slope): {weights[0][0][0]:.2f}")
print(f"Learned bias (intercept): {weights[1][0]:.2f}")
# Plot the results
plt.figure(figsize=(10, 6))
plt.scatter(x_data, y_data, label='Original Data', alpha=0.7)
plt.plot(x_data, predictions, color='red', label='Model Prediction')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Simple Linear Regression with TensorFlow')
plt.legend()
plt.show()
Comments