Dive into Deep Learning Lec7: Regularization in PyTorch from Scratch (Custom Loss Function Autograd)
This video discusses the implementation of a custom loss function in PyTorch and using to compute the gradient of the loss function with respect to the model parameters. This approach has many applications, including regularizing deep learning models and neural networks using l1 and l2 norms. This video discusses the basics of regularization, such as adding penalty terms and regularization parameters that control the tradeoff between model fitting and complexity. We present a simple example using synthetic data to generate training and test data points. We then define a neural network model, initialize its weights, and define various loss functions. We also discuss how to implement Stochastic Gradient Descent (SGD). Here is the code summary:
import numpy as np
import torch
from torch import nn
from import data
import as plt
# Implementation from Scratch
def init_params():
“““Parameter initialization“““
w = (0, 1, size=(num_inputs, 1), requires_grad=True)
b = (1, requires_grad=True)
return [w, b]
def l2_penalty(w):
“““Defining the penalty term “““
return ((2)) / 2
def l1_penalty(w):
“““Defining the penalty term “““
return ((w))
def forward(X, w, b):
“““Linear regression model“““
return (X, w) b
def squared_loss(y_hat, y):
“““Squared loss“““
return (y_hat - ()) ** 2 / 2
def sgd(params, lr, batch_size):
“““Minibatch stochastic gradient descent“““
with ():
for param in params:
param -= lr * / batch_size
()
def evaluate_loss(net, data_iter, loss):
“““Evaluate the loss of a model on the given dataset“““
l = 0
for X, y in data_iter:
out = net(X)
y = ()
w, b = init_params()
num_epochs, lr, alpha, beta = 200, .001, 5, 1
net = lambda X: forward(X, w, b)
train_loss = (num_epochs)
test_loss = (num_epochs)
for epoch in range(num_epochs):
for X, y in train_iter:
l = squared_loss(net(X), y) alpha * l2_penalty(w) beta * l1_penalty(w)
().backward()
sgd([w, b], lr, batch_size)
with ():
train_loss[epoch] = evaluate_loss(net, train_iter, squared_loss)
test_loss[epoch] = evaluate_loss(net, test_iter, squared_loss)
({’’: 14})
((num_epochs), train_loss, label=’train’)
((num_epochs), test_loss, label=’test’)
()
(’log’)
l = loss(out, y).sum()
return l
#python #regularization #machinelearning
1 view
7
0
2 days ago 00:00:16 0
When the zebra decides to take revenge on the lion, who can stop him? #shorts #shortvideo #wildlife
5 days ago 00:00:00 4
TEYU S&A Chiller Live Stream in May
5 days ago 00:18:08 1
Vanessa Trump’s Stunning Transformation Since She Left Don Jr. Is Causing A Stir
7 days ago 00:29:27 0
I built a FANTASY MUSHROOM CAVE in Minecraft Create Mod
1 week ago 00:10:06 31
BRUTAL Head Kicks & Lightning KOs That’ll Leave You Speechless! | Women’s MMA Carnage!
2 weeks ago 01:11:24 9
Amazing Cake Decorating Ideas at Another Level | Satisfying Creations
2 weeks ago 00:00:14 0
Why Defending Ibrahim Traore Is KEY to Your Future
2 weeks ago 00:06:00 0
Nelly porn but very hot!Sexy girls in bikinis.
2 weeks ago 00:00:50 0
What Makes Dreamy Curtains So Special? Find Out Their Unique Advantages! 🤔
2 weeks ago 00:04:41 1
Jutta Leerdam | Netherlands Speed Skater & Fitness Icon | Bio & Info
4 weeks ago 00:11:41 0
Diving Into The Realist World Of Stanislav Plutenko Through His Surreal Artwork
4 weeks ago 00:36:34 1
We SHIFTED Timelines in 1999: Y2K & CIA’s Secret Time Manipulation Program Exposed!
1 month ago 00:03:15 2
DJ Strawbeeree - Nothing Compares on the Dancefloor (Short Edit) #edm #dancemusic #dance
1 month ago 00:03:37 0
Silence Is Sexy: Focal Bathys Hi-Fi Noise-Cancelling Headphones That Flex Harder Than Your Ex - YouTube
1 month ago 00:01:43 2
Treasures Beneath the Sea: The Girls on a Mission! 💎#AIAdventure #AICreatedStory #GirlsExploreWithAI
1 month ago 01:40:32 1
Secrets of the Vatican: From John Paul II to the Death of Pope Francis
1 month ago 01:22:00 0
The Montauk Project: Stranger Things Exposed
2 months ago 00:08:47 2
Fatima Diame | Long Jump | NRG Sport | Athlete 6
2 months ago 02:04:43 10
🎭 PIANO🎻 VIOLIN X METAL + BASS - Mist Theme Music (Cinematic Instrumental)
2 months ago 00:20:15 2
Karoline Leavitt’s Lifestyle 2025★ House Tour, Husband, Children, Cars, Net Worth....
2 months ago 00:57:36 9
President Vučić: “They Want To Overthrow Me“
2 months ago 00:04:08 1
Why Timothee Chalamet’s Acting Is Different (Video Essay)