SlideShare a Scribd company logo
1 of 4
Download to read offline
Hello, below is my code for an AlexNet assignment. If someone could look over, it to ensure it is
optimal or could be improved on. Thank You
import torch
import torch.nn as nn
import torchvision.datasets as datasets
import torch.optim as optim
import torchvision.transforms as transforms
from torchvision.models import AlexNet
# define data transforms
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# load the data
trainset = datasets.CIFAR100(root='./data', train=True, download=True,
transform=transform)
testset = datasets.CIFAR100(root='./data', train=False, download=True,
transform=transform)
#define the network architecture
class AlexNet(nn.Module):
def __init__(self):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 192, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(192, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 6 * 6, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, 1000),
)
def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.classifier(x)
return x
# set device to GPU if available, otherwise use CPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# initialize network, loss function, and optimizer
net = AlexNet(num_classes=1000)
net.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# train the network
num_epochs = 10
for epoch in range(num_epochs):
running_loss = 0.0
for i, data in enumerate(trainset, 0):
inputs, labels = data
if not isinstance(inputs, torch.Tensor):
inputs = torch.tensor(inputs)
if not isinstance(labels, torch.Tensor):
labels = torch.tensor(labels)
inputs, labels = inputs.to(device), labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 2000 == 1999:
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0

More Related Content

Similar to Hello- below is my code for an AlexNet assignment- If someone could lo.pdf

Hello below is my code for MPL image classification- When I try to run.pdf
Hello below is my code for MPL image classification- When I try to run.pdfHello below is my code for MPL image classification- When I try to run.pdf
Hello below is my code for MPL image classification- When I try to run.pdf
gaurav444u
 
Using R on Netezza
Using R on NetezzaUsing R on Netezza
Using R on Netezza
Ajay Ohri
 
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
actexerode
 

Similar to Hello- below is my code for an AlexNet assignment- If someone could lo.pdf (20)

GANS Project for Image idetification.pdf
GANS Project for Image idetification.pdfGANS Project for Image idetification.pdf
GANS Project for Image idetification.pdf
 
Load Data Fast!
Load Data Fast!Load Data Fast!
Load Data Fast!
 
Machine Learning with Tensorflow
Machine Learning with TensorflowMachine Learning with Tensorflow
Machine Learning with Tensorflow
 
.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming.Net 4.0 Threading and Parallel Programming
.Net 4.0 Threading and Parallel Programming
 
From Tensorflow Graph to Tensorflow Eager
From Tensorflow Graph to Tensorflow EagerFrom Tensorflow Graph to Tensorflow Eager
From Tensorflow Graph to Tensorflow Eager
 
AWS re:Invent 2018 - AIM401 - Deep Learning using Tensorflow
AWS re:Invent 2018 - AIM401 - Deep Learning using TensorflowAWS re:Invent 2018 - AIM401 - Deep Learning using Tensorflow
AWS re:Invent 2018 - AIM401 - Deep Learning using Tensorflow
 
Introduction to Deep Learning with Python
Introduction to Deep Learning with PythonIntroduction to Deep Learning with Python
Introduction to Deep Learning with Python
 
[REPEAT] Deep Learning Applications Using TensorFlow (AIM401-R) - AWS re:Inve...
[REPEAT] Deep Learning Applications Using TensorFlow (AIM401-R) - AWS re:Inve...[REPEAT] Deep Learning Applications Using TensorFlow (AIM401-R) - AWS re:Inve...
[REPEAT] Deep Learning Applications Using TensorFlow (AIM401-R) - AWS re:Inve...
 
Hello below is my code for MPL image classification- When I try to run.pdf
Hello below is my code for MPL image classification- When I try to run.pdfHello below is my code for MPL image classification- When I try to run.pdf
Hello below is my code for MPL image classification- When I try to run.pdf
 
Keras cheat sheet_python
Keras cheat sheet_pythonKeras cheat sheet_python
Keras cheat sheet_python
 
Viktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning ServiceViktor Tsykunov: Azure Machine Learning Service
Viktor Tsykunov: Azure Machine Learning Service
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
 
Assignment 6.1.pdf
Assignment 6.1.pdfAssignment 6.1.pdf
Assignment 6.1.pdf
 
TensorFlow example for AI Ukraine2016
TensorFlow example  for AI Ukraine2016TensorFlow example  for AI Ukraine2016
TensorFlow example for AI Ukraine2016
 
Using R on Netezza
Using R on NetezzaUsing R on Netezza
Using R on Netezza
 
Thunderstruck
ThunderstruckThunderstruck
Thunderstruck
 
MT_01_unittest_python.pdf
MT_01_unittest_python.pdfMT_01_unittest_python.pdf
MT_01_unittest_python.pdf
 
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
 

More from a2zmobiles

More from a2zmobiles (20)

7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf
7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf
7- Match the astronomer to his accomplishment a- Ptolemy i- Made very.pdf
 
7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf
7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf
7- In a multiple linear regression model y-X+-XN(0-2In)- the OLS estim (1).pdf
 
7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf
7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf
7- In addition to a pH imbalance- prolonged vomiting is also causing D.pdf
 
7- The temperature at which a certain substance boils is normally dist.pdf
7- The temperature at which a certain substance boils is normally dist.pdf7- The temperature at which a certain substance boils is normally dist.pdf
7- The temperature at which a certain substance boils is normally dist.pdf
 
7- The length of time necessary to complete a specific task is exponen.pdf
7- The length of time necessary to complete a specific task is exponen.pdf7- The length of time necessary to complete a specific task is exponen.pdf
7- The length of time necessary to complete a specific task is exponen.pdf
 
7- The following data have been collected for a British healthcare IT.pdf
7- The following data have been collected for a British healthcare IT.pdf7- The following data have been collected for a British healthcare IT.pdf
7- The following data have been collected for a British healthcare IT.pdf
 
7- Many news organizations conduct polls asking adults in the United S.pdf
7- Many news organizations conduct polls asking adults in the United S.pdf7- Many news organizations conduct polls asking adults in the United S.pdf
7- Many news organizations conduct polls asking adults in the United S.pdf
 
7- Calculate - DV for the following foed label (For carbohydrate and F.pdf
7- Calculate - DV for the following foed label (For carbohydrate and F.pdf7- Calculate - DV for the following foed label (For carbohydrate and F.pdf
7- Calculate - DV for the following foed label (For carbohydrate and F.pdf
 
7- With the help of suitable examples- Explain how the application of.pdf
7- With the help of suitable examples- Explain how the application of.pdf7- With the help of suitable examples- Explain how the application of.pdf
7- With the help of suitable examples- Explain how the application of.pdf
 
7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf
7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf
7- A taxpayer's wife died in 2021 and he has not remarried- He has two.pdf
 
7- In his book- Alfred Wegener presented many lines of evidence that E.pdf
7- In his book- Alfred Wegener presented many lines of evidence that E.pdf7- In his book- Alfred Wegener presented many lines of evidence that E.pdf
7- In his book- Alfred Wegener presented many lines of evidence that E.pdf
 
7- In humans- the allele for normal blood clotting- H- is dominant to.pdf
7- In humans- the allele for normal blood clotting- H- is dominant to.pdf7- In humans- the allele for normal blood clotting- H- is dominant to.pdf
7- In humans- the allele for normal blood clotting- H- is dominant to.pdf
 
7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf
7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf
7- Examine the map of the Murky Mists Mountain- - D- INote tne strike.pdf
 
7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf
7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf
7- 7- Caleulating Returns and Variability (LO1) Usine the followine re.pdf
 
7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf
7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf
7- A perpetuity-immediate pays 1500 per year- Alice receives the first.pdf
 
7- A cohort study employs a- Subjects known at the start to have the d.pdf
7- A cohort study employs a- Subjects known at the start to have the d.pdf7- A cohort study employs a- Subjects known at the start to have the d.pdf
7- A cohort study employs a- Subjects known at the start to have the d.pdf
 
7- When I present the German Tank Problem- the most popular proposals.pdf
7- When I present the German Tank Problem- the most popular proposals.pdf7- When I present the German Tank Problem- the most popular proposals.pdf
7- When I present the German Tank Problem- the most popular proposals.pdf
 
7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf
7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf
7- (Microsoft Visual Basic) Display a triangle Hints- The following co.pdf
 
HELPPP Which of the following are differences in the recommendations.pdf
HELPPP   Which of the following are differences in the recommendations.pdfHELPPP   Which of the following are differences in the recommendations.pdf
HELPPP Which of the following are differences in the recommendations.pdf
 
Hemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdf
Hemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdfHemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdf
Hemophilia is due to a recessive allele (h) linked to the X chromosome (1).pdf
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 

Hello- below is my code for an AlexNet assignment- If someone could lo.pdf

  • 1. Hello, below is my code for an AlexNet assignment. If someone could look over, it to ensure it is optimal or could be improved on. Thank You import torch import torch.nn as nn import torchvision.datasets as datasets import torch.optim as optim import torchvision.transforms as transforms from torchvision.models import AlexNet # define data transforms transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # load the data trainset = datasets.CIFAR100(root='./data', train=True, download=True, transform=transform) testset = datasets.CIFAR100(root='./data', train=False, download=True, transform=transform) #define the network architecture class AlexNet(nn.Module): def __init__(self): super(AlexNet, self).__init__() self.features = nn.Sequential( nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2),
  • 2. nn.Conv2d(64, 192, kernel_size=5, padding=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(192, 384, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(384, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.Conv2d(256, 256, kernel_size=3, padding=1), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), ) self.avgpool = nn.AdaptiveAvgPool2d((6, 6)) self.classifier = nn.Sequential( nn.Dropout(), nn.Linear(256 * 6 * 6, 4096), nn.ReLU(inplace=True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(inplace=True), nn.Linear(4096, 1000), ) def forward(self, x): x = self.features(x)
  • 3. x = self.avgpool(x) x = torch.flatten(x, 1) x = self.classifier(x) return x # set device to GPU if available, otherwise use CPU device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # initialize network, loss function, and optimizer net = AlexNet(num_classes=1000) net.to(device) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # train the network num_epochs = 10 for epoch in range(num_epochs): running_loss = 0.0 for i, data in enumerate(trainset, 0): inputs, labels = data if not isinstance(inputs, torch.Tensor): inputs = torch.tensor(inputs) if not isinstance(labels, torch.Tensor): labels = torch.tensor(labels) inputs, labels = inputs.to(device), labels.to(device) # zero the parameter gradients
  • 4. optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if i % 2000 == 1999: print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0