Learn deep learning and neural networks including CNN, RNN, and transfer learning. Build powerful neural network models.
Learn deep learning and neural networks including CNN, RNN, and transfer learning. Build powerful neural network models.
Understand the fundamentals of neural networks and their components.
Content by: Nirav Khanpara
AI/ML Engineer
Neural Networks are computing systems inspired by biological neural networks. They consist of interconnected nodes (neurons) that process information and learn patterns from data.
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
# Generate sample data
np.random.seed(42)
X = np.random.randn(1000, 20)
y = (np.sum(X, axis=1) > 0).astype(int)
# Split the data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create the model
model = keras.Sequential([
keras.layers.Dense(64, activation='relu', input_shape=(20,)),
keras.layers.Dropout(0.2),
keras.layers.Dense(32, activation='relu'),
keras.layers.Dropout(0.2),
keras.layers.Dense(1, activation='sigmoid')
])
# Compile the model
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
# Train the model
history = model.fit(X_train, y_train,
epochs=50,
batch_size=32,
validation_split=0.2,
verbose=1)
# Evaluate the model
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"Test accuracy: {test_accuracy:.4f}")
# 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()
Test your understanding of this topic:
Learn Convolutional Neural Networks for processing image data.
Content by: Nirav Khanpara
AI/ML Engineer
Convolutional Neural Networks (CNNs) are specialized neural networks designed for processing grid-like data, such as images. They use convolutional layers to automatically learn spatial hierarchies of features.
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
# Generate sample image data
np.random.seed(42)
X = np.random.randn(1000, 28, 28, 1) # 1000 images, 28x28 pixels, 1 channel
y = np.random.randint(0, 10, 1000) # 10 classes
# Convert to one-hot encoding
y = tf.keras.utils.to_categorical(y, 10)
# Split the data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create CNN model
model = keras.Sequential([
keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Conv2D(64, (3, 3), activation='relu'),
keras.layers.MaxPooling2D((2, 2)),
keras.layers.Conv2D(64, (3, 3), activation='relu'),
keras.layers.Flatten(),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
history = model.fit(X_train, y_train,
epochs=10,
batch_size=32,
validation_split=0.2,
verbose=1)
# Evaluate the model
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"Test accuracy: {test_accuracy:.4f}")
Test your understanding of this topic:
Explore Recurrent Neural Networks for sequential data processing.
Content by: Nirav Khanpara
AI/ML Engineer
Recurrent Neural Networks (RNNs) are designed to work with sequential data. They have connections that form directed cycles, allowing them to maintain internal memory.
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
# Generate sample sequential data
np.random.seed(42)
X = np.random.randn(1000, 50, 10) # 1000 sequences, 50 time steps, 10 features
y = np.random.randint(0, 5, 1000) # 5 classes
# Convert to one-hot encoding
y = tf.keras.utils.to_categorical(y, 5)
# Split the data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create RNN model
model = keras.Sequential([
keras.layers.LSTM(64, return_sequences=True, input_shape=(50, 10)),
keras.layers.LSTM(32),
keras.layers.Dense(64, activation='relu'),
keras.layers.Dropout(0.2),
keras.layers.Dense(5, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
history = model.fit(X_train, y_train,
epochs=10,
batch_size=32,
validation_split=0.2,
verbose=1)
# Evaluate the model
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"Test accuracy: {test_accuracy:.4f}")
Test your understanding of this topic:
Learn how to use pre-trained models for efficient deep learning.
Content by: Nirav Khanpara
AI/ML Engineer
Transfer Learning involves using a pre-trained neural network model on a new task, leveraging learned features to improve performance and reduce training time.
import tensorflow as tf
from tensorflow import keras
import numpy as np
# Load a pre-trained model (e.g., MobileNetV2)
base_model = keras.applications.MobileNetV2(
input_shape=(224, 224, 3),
include_top=False,
weights='imagenet'
)
# Freeze the base model
base_model.trainable = False
# Generate sample image data
np.random.seed(42)
X = np.random.randn(100, 224, 224, 3) # 100 images, 224x224 pixels, 3 channels
y = np.random.randint(0, 5, 100) # 5 classes
y = tf.keras.utils.to_categorical(y, 5)
# Split the data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create the model
model = keras.Sequential([
base_model,
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dropout(0.2),
keras.layers.Dense(5, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# Train the model
history = model.fit(X_train, y_train,
epochs=5,
batch_size=32,
validation_split=0.2,
verbose=1)
# Evaluate the model
test_loss, test_accuracy = model.evaluate(X_test, y_test, verbose=0)
print(f"Test accuracy: {test_accuracy:.4f}")
Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 6