Python Data Science Jobs & Interviews
20.5K subscribers
191 photos
4 videos
25 files
332 links
Your go-to hub for Python and Data Science—featuring questions, answers, quizzes, and interview tips to sharpen your skills and boost your career in the data-driven world.

Admin: @Hussein_Sheikho
Download Telegram
#NeuralNetworks #MachineLearning #Python #DeepLearning #ArtificialIntelligence #Programming #TensorFlow #PyTorch #NeuralNetworkExample

Question: How can you implement a simple feedforward neural network in Python using TensorFlow to classify handwritten digits from the MNIST dataset, and what are the key steps involved in training and evaluating such a model?

---

Answer:

To implement a simple feedforward neural network for classifying handwritten digits from the MNIST dataset using TensorFlow, follow these steps:

### 1. Import Required Libraries
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
import numpy as np

### 2. Load and Preprocess the Data
# Load MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Normalize pixel values to range [0, 1]
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0

# Flatten images to 1D arrays (28x28 -> 784)
x_train = x_train.reshape(-1, 784)
x_test = x_test.reshape(-1, 784)

# Convert labels to one-hot encoding
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)

### 3. Build the Neural Network Model
model = models.Sequential([
layers.Dense(128, activation='relu', input_shape=(784,)),
layers.Dropout(0.3),
layers.Dense(64, activation='relu'),
layers.Dropout(0.3),
layers.Dense(10, activation='softmax')
])

### 4. Compile the Model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])

### 5. Train the Model
history = model.fit(x_train, y_train, 
epochs=10,
batch_size=128,
validation_split=0.2,
verbose=1)

### 6. Evaluate the Model
test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)
print(f"Test Accuracy: {test_accuracy:.4f}")

### 7. Make Predictions
predictions = model.predict(x_test[:5])  # Predict first 5 samples
predicted_classes = np.argmax(predictions, axis=1)
print("Predicted classes:", predicted_classes)

---

### Key Steps Explained:
- Data Preprocessing: Normalizing pixel values and flattening images.
- Model Architecture: Using dense layers with ReLU activation and dropout for regularization.
- Compilation: Choosing an optimizer (Adam), loss function (categorical crossentropy), and metrics.
- Training: Fitting the model on training data with validation split.
- Evaluation: Testing performance on unseen data.
- Prediction: Generating outputs for new inputs.

This example demonstrates a basic feedforward neural network suitable for beginners in deep learning.

By: @DataScienceQ ✈️
Please open Telegram to view this post
VIEW IN TELEGRAM
1