You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I am a cnn model with fashionMNIST but its is not predicting accurately every image ?, Also i wanted to connect this cnn to opencv and detect objects from real world ?
#410
import torch
from torch import nn
import torchvision
from torchvision import datasets
from torchvision import transforms
from torchvision.transforms import ToTensor
from pandas.core.internals.base import T
from IPython.lib.display import fsdecode
from torchvision import datasets
import matplotlib.pyplot as plt
model.eval()
with torch.inference_mode():
for sample in data:
sample = torch.unsqueeze(sample,dim=0).to(device)
pred_logits = model(sample)
pred_prob = torch.softmax(pred_logits.squeeze(),dim=0)
pred_probs.append(pred_prob.cpu())
return torch.stack(pred_probs)
import random
random.seed(42)
test_samples=[]
test_labels=[]
for sample, label in random.sample(list(test_set),k=9):
test_samples.append(sample)
test_labels.append(label)
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Here is the code:-
import torch
from torch import nn
import torchvision
from torchvision import datasets
from torchvision import transforms
from torchvision.transforms import ToTensor
from pandas.core.internals.base import T
from IPython.lib.display import fsdecode
from torchvision import datasets
import matplotlib.pyplot as plt
train_set = datasets.FashionMNIST(
root='data',
train=True,
download=True,
transform = torchvision.transforms.ToTensor(),
target_transform=None
)
test_set = datasets.FashionMNIST(
root='data',
train=False,
download=True,
transform=torchvision.transforms.ToTensor(),
target_transform=None
)
from torch.utils.data import DataLoader
train_dataloader = DataLoader(
dataset=train_set,
batch_size=32,
shuffle=True
)
test_datalaoder = DataLoader(
dataset = test_set,
batch_size=32,
shuffle=False
)
class_list = train_set.classes
class_list
class conv_nn1(nn.Module):
def init(self,input,hidden,output):
super().init()
self.Conv_block1 = nn.Sequential(
nn.Conv2d(
in_channels=input,
out_channels=hidden,
kernel_size=3,
stride=1,
padding=1
def forward(self,x:torch.Tensor):
x = self.Conv_block1(x)
x = self.Conv_block2(x)
x = self.classifier(x)
return x
model_vision_new = conv_nn1(input = 1,
output = len(class_list),
hidden=10)
model_vision_new
losfn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(params=model_vision_new.parameters(),
lr=0.01)
def accuracy_fn(y_true,y_pred):
correct = torch.eq(y_true,y_pred).sum().item()
acc = correct/len(y_pred)*100
return acc
from ctypes import string_at
from timeit import default_timer as timer
def train_timer(start:float,
end:float,
device:torch.device=None):
total_time= end-start
print(f"Total Time {total_time}")
return total_time
device = 'cuda' if torch.cuda.is_available else 'cpu'
device
from tqdm.auto import tqdm
torch.manual_seed(42)
start = timer()
epochs=3
for epoch in tqdm(range(epochs)):
print(f"Epoch {epoch}")
train_step(model=model_vision_new.to(device),
data_loader=train_dataloader,
losfn=losfn,
optimizer=optimizer,
accuracy_fn=accuracy_fn,
device=device
test_step(model=model_vision_new.to(device),
data_loader=test_datalaoder,
losfn=losfn,
accuracy_fn=accuracy_fn,
device=device)
endz= timer()
train_timer(start=start,
end=endz,
device = str(next(model_vision_new.parameters())))
params = model_vision_new.parameters()
num_param = sum(i.numel() for i in params)
num_param
def make_predictions(model:torch.nn.Module,
data:list,
device:torch.device=device):
pred_probs =[]
model.eval()
with torch.inference_mode():
for sample in data:
sample = torch.unsqueeze(sample,dim=0).to(device)
pred_logits = model(sample)
pred_prob = torch.softmax(pred_logits.squeeze(),dim=0)
pred_probs.append(pred_prob.cpu())
return torch.stack(pred_probs)
import random
random.seed(42)
test_samples=[]
test_labels=[]
for sample, label in random.sample(list(test_set),k=9):
test_samples.append(sample)
test_labels.append(label)
pred_probs = make_predictions(
model=model_vision_new,
data=test_samples
)
test_samples[0].shape
plt.imshow(test_samples[0].squeeze(),cmap='gray')
plt.title(class_list[test_labels[0]])
pred_probs = make_predictions(model=model_vision_new,
data=test_samples)
pred_probs
pred_classes = pred_probs.argmax(dim=0)
pred_classes
test_labels
plt.figsize=(9,9)
nrows=3
ncols=3
for i, sample in enumerate(test_samples):
plt.subplot(nrows,ncols,i+1)
plt.imshow(sample.squeeze(),cmap='gray')
pred_label = class_list[pred_classes[i]]
truth_label = class_list[test_labels[i]]
title_text = f"Pred {pred_label} | Truth : {truth_label}"
if pred_label == truth_label:
plt.title(title_text,fontsize=10,c='g')
else:
plt.title(title_text,fontsize=10,c='r')
plt.axis(False)
Beta Was this translation helpful? Give feedback.
All reactions