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
1 week ago 01:01:39 1
TIME SLIP STORIES (SN 18 EP 38) TRUE UNEXPLAINABLE EXPERIENCES WITH MISSING TIME & TIME SLIPS
3 weeks ago 00:05:07 1
OMNIMAR - Feels Like Velvet (Official Video) | darkTunes Music Group
3 weeks ago 00:01:29 1
Zebra Birth and First Steps in the Wild: A Miraculous Moment | WILDLIFE
3 weeks ago 00:02:16 1
The End of The Sun - Official Release Date Trailer | A Slavic Mythology Adventure Game
4 weeks ago 00:07:24 5
Umar Keyn - Lie (DNDM Remix)
4 weeks ago 00:11:29 253
DOOM: The Dark Ages | Developer_Direct 2025 (4K) | Coming May 15, 2025
1 month ago 00:18:02 2
Occult Hollywood // Cinema as Ritual Magic
1 month ago 00:32:17 2
The Dark World of Megachurches
1 month ago 00:02:59 1
Si Ai - Marshmello x UKAY Remix | Love Story Video Edit
1 month ago 00:01:37 1
THE MECHANIC 3 - First Trailer | Jason Statham, Gal Gadot, Liam Neeson
1 month ago 00:01:22 1
Hitman (2025) - First Trailer | Jason Statham
1 month ago 00:02:43 1
Addison Rae - Aquamarine (Official Video)
1 month ago 00:09:37 1
DNA Risks in Vaccines?! Investigative Report on ALARMING Discoveries
1 month ago 00:01:50 1
Kitten Absolutely Loves Snow Leopard cub ♥️
1 month ago 00:02:00 1
Farm Folks - Official Gameplay Reveal Trailer
1 month ago 00:30:12 1
The Most Famous Russian Analog Horror Series | MAGNITOSHAKHTINSKAIA OBLAST
1 month ago 00:01:51 33
A Nightmare on Elm Street (2025) Reboot - TEASER TRAILER (4K) Robert Englund, Freddy Krueger
1 month ago 00:10:45 2
Fr. Lazarus El Anthony - Monk’s Life S03 E03- CYC
1 month ago 00:09:52 2
Fr. Lazarus El Anthony - Monk’s Life S03 E04- CYC
1 month ago 00:14:12 2
Fr. Lazarus El Anthony - The 14 Holy Steps of Jesus Christ - Monk’s Life S03 E05- CYC
1 month ago 00:03:13 2
🌙 The Beautiful Pole Vaulter Embla Matilde Njerve 🌟
1 month ago 00:04:54 1
EnviFX Review : Is This the Best Trading Platform for 2025?