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
3 weeks ago 00:04:20 1
The REAL Reason Olivia Dunne Is The Face Of Gymnastics..
4 weeks ago 00:37:44 1
Social Media/Phone Addiction With Stanford’s Dr. Anna Lembke | RealPod FULL Episode
4 weeks ago 00:03:43 1
What makes exercise addictive? | Anna Lembke and Peter Attia
4 weeks ago 00:02:29 1
Transform Your Video Creation Process with VideoGen AI!
4 weeks ago 00:03:57 107
Earthquake NOW In USA! California SHAKEN TODAY! Los angeles Earthquake March 9 2025
1 month ago 00:02:03 1
Boost Affiliate Earnings Fast with Commission Gorilla V3!
1 month ago 00:06:00 1
Delicate beauties under the southern the heat of the night. Remix.
1 month ago 00:14:37 1
🔴 As US Cozies Up To Russia’s Economy, Putin’s Call With China Just Changed Everything
1 month ago 00:10:04 1
EDM Club Mix Electric Dream [Future Pulse Remix] |Booster Upbeat Bass 2025|
2 months ago 00:23:30 1
Terrifying Truths Learned on Carnivore
2 months ago 11:29:01 1
Relaxing Music 🌸 Eliminate Negative Energy & Heal Your Heart ~ Perfect for Relaxation ♥️
2 months ago 00:36:51 1
💥 Breaking! Protestant Church ⛪ in England 🇬🇧 on Path to Holy Orthodoxy ☦️
2 months ago 00:09:02 1
exposing the hvh catfish queen
2 months ago 01:01:39 1
TIME SLIP STORIES (SN 18 EP 38) TRUE UNEXPLAINABLE EXPERIENCES WITH MISSING TIME & TIME SLIPS
2 months ago 00:05:07 1
OMNIMAR - Feels Like Velvet (Official Video) | darkTunes Music Group
2 months ago 00:01:29 1
Zebra Birth and First Steps in the Wild: A Miraculous Moment | WILDLIFE
2 months ago 00:02:16 1
The End of The Sun - Official Release Date Trailer | A Slavic Mythology Adventure Game
2 months ago 00:07:24 5
Umar Keyn - Lie (DNDM Remix)
2 months ago 00:11:29 402
DOOM: The Dark Ages | Developer_Direct 2025 (4K) | Coming May 15, 2025
3 months ago 00:18:02 2
Occult Hollywood // Cinema as Ritual Magic
3 months ago 00:32:17 2
The Dark World of Megachurches
3 months ago 00:02:59 1
Si Ai - Marshmello x UKAY Remix | Love Story Video Edit
3 months ago 00:01:37 1
THE MECHANIC 3 - First Trailer | Jason Statham, Gal Gadot, Liam Neeson