SlideShare a Scribd company logo
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

Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
Avinash Rai
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 

Recently uploaded (20)

2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx2024_Student Session 2_ Set Plan Preparation.pptx
2024_Student Session 2_ Set Plan Preparation.pptx
 
Salient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptxSalient features of Environment protection Act 1986.pptx
Salient features of Environment protection Act 1986.pptx
 
B.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdfB.ed spl. HI pdusu exam paper-2023-24.pdf
B.ed spl. HI pdusu exam paper-2023-24.pdf
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Industrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training ReportIndustrial Training Report- AKTU Industrial Training Report
Industrial Training Report- AKTU Industrial Training Report
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
50 ĐỀ LUYỆN THI IOE LỚP 9 - NĂM HỌC 2022-2023 (CÓ LINK HÌNH, FILE AUDIO VÀ ĐÁ...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Forest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDFForest and Wildlife Resources Class 10 Free Study Material PDF
Forest and Wildlife Resources Class 10 Free Study Material PDF
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
UNIT – IV_PCI Complaints: Complaints and evaluation of complaints, Handling o...
 
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdfDanh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
Danh sách HSG Bộ môn cấp trường - Cấp THPT.pdf
 
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptxJose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
Jose-Rizal-and-Philippine-Nationalism-National-Symbol-2.pptx
 
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
Mattingly "AI & Prompt Design: Limitations and Solutions with LLMs"
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.pptBasic_QTL_Marker-assisted_Selection_Sourabh.ppt
Basic_QTL_Marker-assisted_Selection_Sourabh.ppt
 
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptxMatatag-Curriculum and the 21st Century Skills Presentation.pptx
Matatag-Curriculum and the 21st Century Skills Presentation.pptx
 

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