Introduction to TensorFlow — Build Your First ML Model
DodaTech
1 min read
In this tutorial, you'll learn about Introduction to TensorFlow. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
What You'll Learn
Install TensorFlow, build a neural network with Keras, train it on the MNIST dataset, and evaluate its accuracy.
Why It Matters
TensorFlow is the most widely used ML framework in production. It powers Google Search, YouTube recommendations, and countless industrial ML systems.
Real-World Use
Image classification, text analysis, recommendation systems, and time series forecasting.
Installation
Pip install TensorFlow
Step 1: Load the Data
import TensorFlow as tf
# Load MNIST handwritten digits dataset
(x_train, y_train), (x_test, y_test) = tf.Keras.datasets.mnist.load_data()
# Normalize pixel values to 0-1
x_train, x_test = x_train / 255.0, x_test / 255.0
print(f"Training samples: {len(x_train)}")
print(f"Test samples: {len(x_test)}")
print(f"Image shape: {x_train[0].shape}")
Expected output:
Training samples: 60000
Test samples: 10000
Image shape: (28, 28)
Step 2: Build the Model
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
Step 3: Train
history = model.fit(
x_train, y_train,
epochs=5,
validation_data=(x_test, y_test)
)
Expected output (simplified):
Epoch 1/5 loss: 0.2933 accuracy: 0.9156 val_loss: 0.1324 val_accuracy: 0.9614
Epoch 2/5 loss: 0.1313 accuracy: 0.9614 val_loss: 0.0971 val_accuracy: 0.9706
...
Epoch 5/5 loss: 0.0687 accuracy: 0.9789 val_loss: 0.0746 val_accuracy: 0.9770
Step 4: Evaluate
test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print(f"\nTest accuracy: {test_acc:.4f}")
Expected output:
Test accuracy: 0.9770
97.7% accuracy on digits it's never seen before.
Step 5: Make a Prediction
import numpy as np
predictions = model.predict(x_test[:1])
predicted_digit = np.argmax(predictions[0])
print(f"Predicted digit: {predicted_digit}")
← Previous
What is RAG? Retrieval Augmented Generation Explained
Next →
PyTorch Basics — Build Your First Neural Network
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro