How to solv th error

Ayman_Abdelsattar_Me: <h1>
<a name="todo-display-an-image-along-with-the-top-5-classes-1" class="anchor" href="#todo-display-an-image-along-with-the-top-5-classes-1"></a>TODO: Display an image along with the top 5 classes</h1>
<p><span class="hashtag">#using</span> the restored one<br>
file_path = ‘flowers/test/11/image_03098.jpg’ <span class="hashtag">#an</span> example from test set</p>
<p>img = process_image (file_path)<br>
imshow (img)<br>
plt.show()<br>
probs, classes = predict (file_path, model, 5)</p>
<p><span class="hashtag">#print</span> (probs)<br>
<span class="hashtag">#print</span> (classes)</p>
<p><span class="hashtag">#preparing</span> class_names using mapping with cat_to_name</p>
<p>class_names = [cat_to_name [item] for item in classes]</p>
<p><span class="hashtag">#fig</span>, (ax2) = plt.subplots(figsize=(6,9), ncols=2)<br>
plt.figure(figsize = (6,10))<br>
plt.subplot(2,1,2)<br>
<span class="hashtag">#ax2</span>.barh(class_names, probs)<br>
<span class="hashtag">#ax2</span>.set_aspect(0.1)<br>
<span class="hashtag">#ax2</span>.set_yticks(classes)<br>
<span class="hashtag">#ax2</span>.set_title(‘Flower Class Probability’)<br>
<span class="hashtag">#ax2</span>.set_xlim(0, 1.1)</p>
<p>sns.barplot(x=probs, y=class_names, color= ‘red’);</p>
<p><span class="hashtag">#width</span> = 1/5<br>
<span class="hashtag">#plt</span>.subplot(2,1,2)<br>
<span class="hashtag">#plt</span>.bar (classes, probs, width, color = ‘blue’)<br>
plt.show()</p>
<p>error</p>
<hr>
<p>RuntimeError                              Traceback (most recent call last)<br>
 in ()<br>
7 imshow (img)<br>
8 plt.show()<br>
----&gt; 9 probs, classes = predict (file_path, model, 5)<br>
10<br>
11 <span class="hashtag">#print</span> (probs)</p>
<p> in predict(image_path, model, topk)<br>
18<br>
19     with torch.no_grad ():<br>
—&gt; 20         output = model.forward (img)<br>
21     output_prob = torch.exp (output) <span class="hashtag">#converting</span> into a probability<br>
22</p>
<p>/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/models/densenet.py in forward(self, x)<br>
218<br>
219     def forward(self, x):<br>
 → 220         features = self.features(x)<br>
221         out = F.relu(features, inplace=True)<br>
222         out = F.avg_pool2d(out, kernel_size=7, stride=1).view(features.size(0), -1)</p>
<p>/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in <strong>call</strong>(self, *input, **kwargs)<br>
489             result = self._slow_forward(*input, **kwargs)<br>
490         else:<br>
 → 491             result = self.forward(*input, **kwargs)<br>
492         for hook in self._forward_hooks.values():<br>
493             hook_result = hook(self, input, result)</p>
<p>/opt/conda/lib/python3.6/site-packages/torch/nn/modules/container.py in forward(self, input)<br>
89     def forward(self, input):<br>
90         for module in self._modules.values():<br>
—&gt; 91             input = module(input)<br>
92         return input<br>
93</p>
<p>/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in <strong>call</strong>(self, *input, **kwargs)<br>
489             result = self._slow_forward(*input, **kwargs)<br>
490         else:<br>
 → 491             result = self.forward(*input, **kwargs)<br>
492         for hook in self._forward_hooks.values():<br>
493             hook_result = hook(self, input, result)</p>
<p>/opt/conda/lib/python3.6/site-packages/torch/nn/modules/conv.py in forward(self, input)<br>
299     def forward(self, input):<br>
300         return F.conv2d(input, self.weight, self.bias, self.stride,<br>
 → 301                         self.padding, self.dilation, self.groups)<br>
302<br>
303</p>
<p>RuntimeError: Expected object of type torch.FloatTensor but found type torch.cuda.FloatTensor for argument <span class="hashtag">#2</span> ‘weight’</p>

raj-rishav: <p>The 2 objects are on different devices. I.e one is on <code>cpu</code> and other one on <code>cuda</code></p>

Ayman_Abdelsattar_Me: <p>thank you  i use the model load in the last code and problem solved but the other problem appear</p>
<h1>
<a name="todo-display-an-image-along-with-the-top-5-classes-1" class="anchor" href="#todo-display-an-image-along-with-the-top-5-classes-1"></a>TODO: Display an image along with the top 5 classes</h1>
<p><span class="hashtag">#using</span> the restored one</p>
<p>model= load_model(‘checkpoint.pth’)</p>
<p>file_path = ‘flowers/test/11/image_03098.jpg’</p>
<p>img = process_image (file_path)<br>
imshow (img)<br>
plt.show()<br>
probs, classes = predict (file_path, model, 5)</p>
<p><span class="hashtag">#print</span> (probs)<br>
<span class="hashtag">#print</span> (classes)</p>
<p><span class="hashtag">#preparing</span> class_names using mapping with cat_to_name</p>
<p>class_names = [cat_to_name [item] for item in classes]</p>
<p><span class="hashtag">#fig</span>, (ax2) = plt.subplots(figsize=(6,9), ncols=2)<br>
plt.figure(figsize = (6,10))<br>
plt.subplot(2,1,2)</p>
<p>sns.barplot(x=probs, y=class_names, color= ‘red’);</p>
<p>plt.show()</p>
<h2>
<a name="the-error-2" class="anchor" href="#the-error-2"></a>the error</h2>
<hr>
<p>AttributeError                            Traceback (most recent call last)<br>
 in ()<br>
10 imshow (img)<br>
11 plt.show()<br>
—&gt; 12 probs, classes = predict (file_path, model, 5)<br>
13<br>
14 <span class="hashtag">#print</span> (probs)</p>
<p> in predict(image_path, model, topk)<br>
18<br>
19     with torch.no_grad ():<br>
—&gt; 20         output = model.forward (img)<br>
21     output_prob = torch.exp (output) <span class="hashtag">#converting</span> into a probability<br>
22</p>
<p>AttributeError: ‘NoneType’ object has no attribute ‘forward’</p>

raj-rishav: <p>the <code>model</code> you trying to use, is <code>None</code><br>
You might want to check your <code>load_model</code> function. Or can you provide the code you using to fetch the model?</p>

Ayman_Abdelsattar_Me: <h1>
<a name="imports-here-1" class="anchor" href="#imports-here-1"></a>Imports here</h1>
<p>%matplotlib inline<br>
%config InlineBackend.figure_format = ‘retina’</p>
<p>import matplotlib.pyplot as plt<br>
import torch<br>
import numpy as np<br>
from torch import nn<br>
from torch import optim<br>
from torchvision import datasets, models, transforms<br>
import torch.nn.functional as F<br>
import torch.utils.data<br>
import pandas as pd<br>
<span class="hashtag">#import</span> helper<br>
from collections import OrderedDict<br>
from PIL import Image<br>
import seaborn as sns</p>
<h1>
<a name="todo-define-your-transforms-for-the-training-validation-and-testing-sets-2" class="anchor" href="#todo-define-your-transforms-for-the-training-validation-and-testing-sets-2"></a>TODO: Define your transforms for the training, validation, and testing sets</h1>
<p>train_data_transforms = transforms.Compose ([transforms.RandomRotation (30),<br>
transforms.RandomResizedCrop (224),<br>
transforms.RandomHorizontalFlip (),<br>
transforms.ToTensor (),<br>
transforms.Normalize ([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])<br>
])</p>
<p>valid_data_transforms = transforms.Compose ([transforms.Resize (255),<br>
transforms.CenterCrop (224),<br>
transforms.ToTensor (),<br>
transforms.Normalize ([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])<br>
])</p>
<p>test_data_transforms = transforms.Compose ([transforms.Resize (255),<br>
transforms.CenterCrop (224),<br>
transforms.ToTensor (),<br>
transforms.Normalize ([0.485, 0.456, 0.406],[0.229, 0.224, 0.225])<br>
])</p>
<h1>
<a name="todo-load-the-datasets-with-imagefolder-3" class="anchor" href="#todo-load-the-datasets-with-imagefolder-3"></a>TODO: Load the datasets with ImageFolder</h1>
<p>train_image_datasets = datasets.ImageFolder (train_dir, transform = train_data_transforms)<br>
valid_image_datasets = datasets.ImageFolder (valid_dir, transform = valid_data_transforms)<br>
test_image_datasets = datasets.ImageFolder (test_dir, transform = test_data_transforms)</p>
<h1>
<a name="todo-using-the-image-datasets-and-the-trainforms-define-the-dataloaders-4" class="anchor" href="#todo-using-the-image-datasets-and-the-trainforms-define-the-dataloaders-4"></a>TODO: Using the image datasets and the trainforms, define the dataloaders</h1>
<p>train_loader = torch.utils.data.DataLoader(train_image_datasets, batch_size = 64, shuffle = True)<br>
valid_loader = torch.utils.data.DataLoader(valid_image_datasets, batch_size = 64, shuffle = True)<br>
test_loader = torch.utils.data.DataLoader(test_image_datasets, batch_size = 64, shuffle = True)</p>
<hr>
<p><span class="hashtag">#Label</span> mapping<br>
<span class="hashtag">#This</span> will give you a dictionary mapping the integer encoded categories to the actual names of the flowers</p>
<p>import json</p>
<p>with open(‘cat_to_name.json’, ‘r’) as f:<br>
cat_to_name = json.load(f)<br>
cat_to_name</p>
<h1>
<a name="updating-classifer-in-the-network-5" class="anchor" href="#updating-classifer-in-the-network-5"></a>updating classifer in the network</h1>
<p>for param in model.parameters():<br>
param.requires_grad = False</p>
<p>classifier = nn.Sequential  (OrderedDict ([<br>
(‘fc1’, nn.Linear (9216, 4096)),<br>
(‘relu1’, nn.ReLU ()),<br>
(‘dropout1’, nn.Dropout (p = 0.4)),<br>
(‘fc2’, nn.Linear (4096, 2048)),<br>
(‘relu2’, nn.ReLU ()),<br>
(‘dropout2’, nn.Dropout (p = 0.4)),<br>
(‘fc3’, nn.Linear (2048, 102)),<br>
(‘output’, nn.LogSoftmax (dim =1))<br>
]))<br>
model.classifier = classifier<br>
model</p>
<h2>
<a name="initializing-criterion-and-optimizer-criterion-nnnllloss-optimizer-optimadam-modelclassifierparameters-lr-0001-6" class="anchor" href="#initializing-criterion-and-optimizer-criterion-nnnllloss-optimizer-optimadam-modelclassifierparameters-lr-0001-6"></a>--------------------<span class="hashtag">#initializing</span> criterion and optimizer<br>
criterion = nn.NLLLoss ()<br>
optimizer = optim.Adam (model.classifier.parameters (), lr = 0.001)</h2>
<h1>
<a name="defining-validation-for-the-model-7" class="anchor" href="#defining-validation-for-the-model-7"></a>Defining validation  for the model</h1>
<p>def validation(model, valid_loader, criterion):<br>
model.to (‘cuda’)</p>
<pre><code>valid_loss = 0
accuracy = 0
for inputs, labels in valid_loader:
    
    inputs, labels = inputs.to('cuda'), labels.to('cuda')
    output = model.forward(inputs)
    valid_loss += criterion(output, labels).item()

    ps = torch.exp(output)
    equality = (labels.data == ps.max(dim=1)[1])
    accuracy += equality.type(torch.FloatTensor).mean()

return valid_loss, accuracy
</code></pre>
<hr>
<p><span class="hashtag">#training</span> a model</p>
<p><span class="hashtag">#change</span> to cuda if enabled<br>
model.to (‘cuda’)<br>
epochs = 12<br>
print_every = 40<br>
steps = 0</p>
<p>for e in range (epochs):<br>
running_loss = 0<br>
for ii, (inputs, labels) in enumerate (train_loader):<br>
steps += 1</p>
<pre><code>    inputs, labels = inputs.to('cuda'), labels.to('cuda')

    optimizer.zero_grad () #where optimizer is working on classifier paramters only

    # Forward and backward passes
    outputs = model.forward (inputs) #calculating output
    loss = criterion (outputs, labels) #calculating loss
    loss.backward () 
    optimizer.step () #performs single optimization step 

    running_loss += loss.item () # loss.item () returns scalar value of Loss function

    if steps % print_every == 0:
        model.eval () #switching to evaluation mode so that dropout is turned off
        
        # Turn off gradients for validation, saves memory and computations
        with torch.no_grad():
            valid_loss, accuracy = validation(model, valid_loader, criterion)
        
        print("Epoch: {}/{}.. ".format(e+1, epochs),
              "Training Loss: {:.3f}.. ".format(running_loss/print_every),
              "Valid Loss: {:.3f}.. ".format(valid_loss/len(valid_loader)),
              "Valid Accuracy: {:.3f}%".format(accuracy/len(valid_loader)*100))
        
        running_loss = 0
        
        # Make sure training is back on
        model.train()
        
        ------------------------------------------
</code></pre>
<p>def check_accuracy_on_test(test_loader):<br>
right = 0<br>
total = 0<br>
<span class="hashtag">#training</span> a model<br>
<span class="hashtag">#change</span> to cuda if enabled</p>
<pre><code>model.to('cuda:0')
</code></pre>
<p><span class="hashtag">#switching</span> to evaluation mode so that dropout is turned off</p>
<h1>
<a name="turn-off-gradients-for-validation-saves-memory-and-computations-8" class="anchor" href="#turn-off-gradients-for-validation-saves-memory-and-computations-8"></a>Turn off gradients for validation, saves memory and computations</h1>
<pre><code>with torch.no_grad():
    for data in test_loader:
        images, labels = data
        images, labels = images.to('cuda'), labels.to('cuda')
        outputs = model(images)
        _, predicted = torch.max(outputs.data, 1)
        total += labels.size(0)
        right += (predicted == labels).sum().item()

print('kindly be informed that the accuracy of the network on the test images: %d %%' % (100 * right / total))
</code></pre>
<h2>
<a name="check_accuracy_on_testtest_loader-9" class="anchor" href="#check_accuracy_on_testtest_loader-9"></a>check_accuracy_on_test(test_loader)</h2>
<p>model.to (‘cpu’) <span class="hashtag">#no</span> need to use cuda for saving/loading model.</p>
<h1>
<a name="todo-save-the-checkpoint-10" class="anchor" href="#todo-save-the-checkpoint-10"></a>TODO: Save the checkpoint</h1>
<p>model.class_to_idx = train_image_datasets.class_to_idx <span class="hashtag">#saving</span> mapping between predicted class and class name,<br>
<span class="hashtag">#second</span> variable is a class name in numeric</p>
<p><span class="hashtag">#creating</span> dictionary<br>
checkpoint = {‘classifier’: model.classifier,<br>
‘state_dict’: model.state_dict (),<br>
‘mapping’:    model.class_to_idx<br>
}</p>
<h2>
<a name="torchsave-checkpoint-project_checkpointpth-you-should-also-store-other-hyper-parameters-like-the-number-of-epochs-the-learning_rate-arch-param-along-with-the-checkpoint-this-parameters-are-required-in-case-you-need-to-continue-training-your-model-11" class="anchor" href="#torchsave-checkpoint-project_checkpointpth-you-should-also-store-other-hyper-parameters-like-the-number-of-epochs-the-learning_rate-arch-param-along-with-the-checkpoint-this-parameters-are-required-in-case-you-need-to-continue-training-your-model-11"></a>torch.save (checkpoint, ‘project_checkpoint.pth’)<br>
<span class="hashtag">#you</span> should also store other hyper-parameters like the number of epochs, the learning_rate, arch param<br>
<span class="hashtag">#along</span> with the checkpoint. This parameters are required in case you need to continue training your model</h2>
<h1>
<a name="todo-write-a-function-that-loads-a-checkpoint-and-rebuilds-the-model-12" class="anchor" href="#todo-write-a-function-that-loads-a-checkpoint-and-rebuilds-the-model-12"></a>TODO: Write a function that loads a checkpoint and rebuilds the model</h1>
<p>def loading_model (file_path):<br>
checkpoint = torch.load (file_path) <span class="hashtag">#loading</span> checkpoint from a file<br>
model = models.alexnet (pretrained = True) <span class="hashtag">#function</span> works solely for Alexnet<br>
<span class="hashtag">#you</span> can use the arch from the checkpoint and choose the model architecture in a more generic way:<br>
<span class="hashtag">#model</span> = getattr(models, checkpoint[‘arch’]</p>
<pre><code>model.classifier = checkpoint ['classifier']
model.load_state_dict (checkpoint ['state_dict'])
model.class_to_idx = checkpoint ['mapping']

for param in model.parameters(): 
    param.requires_grad = False #turning off tuning of the model

return model
</code></pre>
<h2>
<a name="print-model-13" class="anchor" href="#print-model-13"></a>print (model)</h2>
<p>def process_image(image):<br>
‘’’ Scales, crops, and normalizes a PIL image for a PyTorch model,<br>
returns an Numpy array<br>
‘’’<br>
<span class="hashtag">#size</span> = 256, 256<br>
img = Image.open (image) <span class="hashtag">#loading</span> image<br>
Image_width, Image_height = img.size <span class="hashtag">#original</span> size<br>
<span class="hashtag">#proportion</span> = Image_width/ float (Image_height) <span class="hashtag">#to</span> keep aspect ratio</p>
<pre><code>if Image_width &gt; Image_height: 
    Image_height = 256
    img.thumbnail ((50000, Image_height), Image.ANTIALIAS)
else: 
    Image_width = 256
    img.thumbnail ((Image_width,50000), Image.ANTIALIAS)
    

Image_width, Image_height = img.size 
#new size of img
#resize 224x224 in the center
img_reduce = 224
img_left = (Image_width - img_reduce)/2 
img_top = (Image_height - img_reduce)/2
img_right = img_left + 224 
img_bottom = img_top + 224
img = img.crop ((img_left, img_top, img_right, img_bottom))

#preparing numpy array
np_image = np.array (img)/255 
np_image -= np.array ([0.485, 0.456, 0.406]) 
np_image /= np.array ([0.229, 0.224, 0.225])

np_image= np_image.transpose ((2,0,1))

return np_image

img_1 = (data_dir  +'/test' + '/1/' + 'image_06743.jpg')
img_1 = process_image(img_1)
print(img_1.shape)
(np.array([0.229, 0.224, 0.225])).shape
img_1 = img_1.transpose ((1,2,0))
img_1
</code></pre>
<hr>
<p>def imshow(image, ax=None, title=None):<br>
“”“Imshow for Tensor.”“”<br>
if ax is None:<br>
fig, ax = plt.subplots()</p>
<pre><code># PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
image = np.array(image)
image = image.transpose((1, 2, 0))

# Undo preprocessing
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = std * image + mean

# Image needs to be clipped between 0 and 1 or it looks like noise when displayed
image = np.clip(image, 0, 1)
 
ax.imshow(image)

return ax
</code></pre>
<h2>
<a name="image_path-flowerstrain13image_05744jpg-img-process_imageimage_path-imgshape-imshowimg-14" class="anchor" href="#image_path-flowerstrain13image_05744jpg-img-process_imageimage_path-imgshape-imshowimg-14"></a>image_path = ‘flowers/train/13/image_05744.jpg’<br>
img = process_image(image_path)<br>
<span class="hashtag">#img</span>.shape<br>
imshow(img)</h2>
<p><span class="hashtag">#mapping</span> = train_image_datasets.class_to_idx</p>
<p><span class="hashtag">#indeces</span> = np.array ([1, 10, 100, 101, 102])<br>
<span class="hashtag">#classes</span> = pd.DataFrame ([mapping [item] for item in indeces]) <span class="hashtag">#replacing</span> indeces with classes<br>
<span class="hashtag">#classes</span> = np.array (classes) <span class="hashtag">#converting</span> to Numpy array<br>
def predict(image_path, model, topk  = 5):<br>
‘’’ Predict the class (or classes) of an image using a trained deep learning model.</p>
<pre><code>'''

print (type(model))
# TODO: Implement the code to predict the class from an image file
image = process_image (image_path) #loading image and processing it using above defined function

#we cannot pass image to model.forward 'as is' as it is expecting tensor, not numpy array
#converting to tensor
img = torch.from_numpy (image).type(torch.FloatTensor)

img = img.unsqueeze (dim = 0) #used to make size of torch as expected. as forward method is working with batches,
#doing that we will have batch size = 1 
    
with torch.no_grad ():
    output = model.forward (img)
output_prob = torch.exp (output) #converting into a probability

probs, indeces = output_prob.topk (topk=5)
probs = probs.numpy () #converting both to numpy array
indeces = indeces.numpy () 

probs = probs.tolist () [0] #converting both to list
indeces = indeces.tolist () [0]


mapping = {val: key for key, val in
model.class_to_idx.items()
            }

classes = [mapping [item] for item in indeces]
#classes = pd.DataFrame ([mapping [item] for item in indeces]) #replacing indeces with classes
classes = np.array (classes) #converting to Numpy array 

return probs, classes
</code></pre>
<hr>
<h1>
<a name="todo-display-an-image-along-with-the-top-5-classes-15" class="anchor" href="#todo-display-an-image-along-with-the-top-5-classes-15"></a>TODO: Display an image along with the top 5 classes</h1>
<p><span class="hashtag">#using</span> the restored one</p>
<p>model=loading_model(‘project_checkpoint.pth’)</p>
<p>file_path = ‘flowers/test/11/image_03130.jpg’</p>
<p>img = process_image (file_path)<br>
imshow (img)<br>
plt.show()<br>
probs, classes = predict(file_path, model, 5)<br>
<span class="hashtag">#probs</span> = probs.numpy ()<br>
<span class="hashtag">#indeces</span> = indeces.numpy ()</p>
<h2>
<a name="print-probs-print-classes-16" class="anchor" href="#print-probs-print-classes-16"></a><span class="hashtag">#print</span> (probs)<br>
<span class="hashtag">#print</span> (classes)</h2>
<h2>
<a name="class-torchvisionmodelsalexnetalexnet-17" class="anchor" href="#class-torchvisionmodelsalexnetalexnet-17"></a>class ‘torchvision.models.alexnet.AlexNet’&gt;</h2>
<p>TypeError                                 Traceback (most recent call last)<br>
 in ()<br>
10 imshow (img)<br>
11 plt.show()<br>
—&gt; 12 probs, classes = predict(file_path, model, 5)<br>
13 <span class="hashtag">#probs</span> = probs.numpy ()<br>
14 <span class="hashtag">#indeces</span> = indeces.numpy ()</p>
<p> in predict(image_path, model, topk)<br>
24     output_prob = torch.exp (output) <span class="hashtag">#converting</span> into a probability<br>
25<br>
—&gt; 26     probs, indeces = output_prob.topk (topk=5)<br>
27     probs = probs.numpy () <span class="hashtag">#converting</span> both to numpy array<br>
28     indeces = indeces.numpy ()</p>
<h2>
<a name="typeerror-topk-missing-1-required-positional-arguments-k-18" class="anchor" href="#typeerror-topk-missing-1-required-positional-arguments-k-18"></a>TypeError: topk() missing 1 required positional arguments: “k”</h2>
<p><span class="hashtag">#preparing</span> class_names using mapping with cat_to_name</p>
<p>class_names = [cat_to_name [item] for item in classes]</p>
<p><span class="hashtag">#fig</span>, (ax2) = plt.subplots(figsize=(6,9), ncols=2)<br>
plt.figure(figsize = (6,10))<br>
plt.subplot(2,1,2)</p>
<p>sns.barplot(x=probs, y=class_names, color= ‘red’);</p>
<p>plt.show()</p>

raj-rishav: <aside class="quote no-group" data-username="Ayman_Abdelsattar_Me" data-post="5" data-topic="174566">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ayman_abdelsattar_me/48/58166_2.png" class="avatar"> Ayman_Abdelsattar_Me:</div>
<blockquote>
<p>—&gt; 26 probs, indeces = output_prob.topk (topk=5)</p>
</blockquote>
</aside>
<p>change <code>output_prob.topk(topk=5)</code> to <code>output_prob.topk(k=5)</code><br>
as <code>k</code> is the argument name</p>

Ayman_Abdelsattar_Me: <p>Many thanks this solve the issue but iave anothe error as the following</p>
<h1>
<a name="todo-display-an-image-along-with-the-top-5-classes-1" class="anchor" href="#todo-display-an-image-along-with-the-top-5-classes-1"></a>TODO: Display an image along with the top 5 classes</h1>
<p><span class="hashtag">#using</span> the restored one</p>
<p>model=loading_model(‘project_checkpoint.pth’)</p>
<p>file_path = ‘flowers/test/11/image_03130.jpg’</p>
<p>img = process_image (file_path<br>
)<br>
imshow (img)</p>
<p>plt.show()<br>
probs, classes = predict(file_path, model, 5)<br>
<span class="hashtag">#probs</span> = probs.numpy ()<br>
<span class="hashtag">#indeces</span> = indeces.numpy ()</p>
<p><span class="hashtag">#print</span> (probs)<br>
<span class="hashtag">#print</span> (classes)<br>
<span class="hashtag">#preparing</span> class_names using mapping with cat_to_name</p>
<p>class_names = [cat_to_name [item] for item in classes]</p>
<p><span class="hashtag">#fig</span>, (ax2) = plt.subplots(figsize=(6,9), ncols=2)<br>
plt.figure(figsize = (6,10))<br>
plt.subplot(2,1,2)</p>
<p>sns.barplot(x=probs, y=class_names, color= ‘red’);</p>
<p>plt.show()</p>
<hr>
<p>error</p>
<hr>
<p>TypeError                                 Traceback (most recent call last)<br>
 in ()<br>
20 <span class="hashtag">#preparing</span> class_names using mapping with cat_to_name<br>
21<br>
—&gt; 22 class_names = [cat_to_name [item] for item in classes]<br>
23<br>
24 <span class="hashtag">#fig</span>, (ax2) = plt.subplots(figsize=(6,9), ncols=2)</p>
<p> in (.0)<br>
20 <span class="hashtag">#preparing</span> class_names using mapping with cat_to_name<br>
21<br>
—&gt; 22 class_names = [cat_to_name [item] for item in classes]<br>
23<br>
24 <span class="hashtag">#fig</span>, (ax2) = plt.subplots(figsize=(6,9), ncols=2)</p>
<p>TypeError: unhashable type: ‘numpy.ndarray’</p>

raj-rishav: <p>Basically its saying that you trying to do some illegal operation on datatype i.e <code>numpy.ndarray</code> . Can you provide the output of <code>classes</code> and <code>cat_to_name</code>?</p>

Ayman_Abdelsattar_Me: <h1>
<a name="todo-display-an-image-along-with-the-top-5-classes-1" class="anchor" href="#todo-display-an-image-along-with-the-top-5-classes-1"></a>TODO: Display an image along with the top 5 classes</h1>
<p><span class="hashtag">#using</span> the restored one</p>
<p>model=loading_model(‘project_checkpoint.pth’)</p>
<p>file_path = ‘flowers/test/11/image_03130.jpg’</p>
<p>img = process_image (file_path)<br>
imshow (img)</p>
<p>plt.show()<br>
probs, classes = predict(file_path, model, 5)</p>
<p>print (classes)<br>
print(cat_to_name)</p>
<p><span class="hashtag">#probs</span> = probs.numpy ()<br>
<span class="hashtag">#indeces</span> = indeces.numpy ()</p>
<p><span class="hashtag">#print</span> (probs)<br>
<span class="hashtag">#print</span> (classes)<br>
<span class="hashtag">#preparing</span> class_names using mapping with cat_to_name</p>
<p>class_names = [cat_to_name [item] for item in classes]</p>
<p>output</p>
<h2>
<a name="h-72-18-94-83-96-21-fire-lily-3-canterbury-bells-45-bolero-deep-blue-1-pink-primrose-34-mexican-aster-27-prince-of-wales-feathers-7-moon-orchid-16-globe-flower-25-grape-hyacinth-26-corn-poppy-79-toad-lily-39-siam-tulip-24-red-ginger-67-spring-crocus-35-alpine-sea-holly-32-garden-phlox-10-globe-thistle-6-tiger-lily-93-ball-moss-33-love-in-the-mist-9-monkshood-102-blackberry-lily-14-spear-thistle-19-balloon-flower-100-blanket-flower-13-king-protea-49-oxeye-daisy-15-yellow-iris-61-cautleya-spicata-31-carnation-64-silverbush-68-bearded-iris-63-black-eyed-susan-69-windflower-62-japanese-anemone-20-giant-white-arum-lily-38-great-masterwort-4-sweet-pea-86-tree-mallow-101-trumpet-creeper-42-daffodil-22-pincushion-flower-2-hard-leaved-pocket-orchid-54-sunflower-66-osteospermum-70-tree-poppy-85-desert-rose-99-bromelia-87-magnolia-5-english-marigold-92-bee-balm-28-stemless-gentian-97-mallow-57-gaura-40-lenten-rose-47-marigold-59-orange-dahlia-48-buttercup-55-pelargonium-36-ruby-lipped-cattleya-91-hippeastrum-29-artichoke-71-gazania-90-canna-lily-18-peruvian-lily-98-mexican-petunia-8-bird-of-paradise-30-sweet-william-17-purple-coneflower-52-wild-pansy-84-columbine-12-colts-foot-11-snapdragon-96-camellia-23-fritillary-50-common-dandelion-44-poinsettia-53-primula-72-azalea-65-californian-poppy-80-anthurium-76-morning-glory-37-cape-flower-56-bishop-of-llandaff-60-pink-yellow-dahlia-82-clematis-58-geranium-75-thorn-apple-41-barbeton-daisy-95-bougainvillea-43-sword-lily-83-hibiscus-78-lotus-lotus-88-cyclamen-94-foxglove-81-frangipani-74-rose-89-watercress-73-water-lily-46-wallflower-77-passion-flower-51-petunia-2" class="anchor" href="#h-72-18-94-83-96-21-fire-lily-3-canterbury-bells-45-bolero-deep-blue-1-pink-primrose-34-mexican-aster-27-prince-of-wales-feathers-7-moon-orchid-16-globe-flower-25-grape-hyacinth-26-corn-poppy-79-toad-lily-39-siam-tulip-24-red-ginger-67-spring-crocus-35-alpine-sea-holly-32-garden-phlox-10-globe-thistle-6-tiger-lily-93-ball-moss-33-love-in-the-mist-9-monkshood-102-blackberry-lily-14-spear-thistle-19-balloon-flower-100-blanket-flower-13-king-protea-49-oxeye-daisy-15-yellow-iris-61-cautleya-spicata-31-carnation-64-silverbush-68-bearded-iris-63-black-eyed-susan-69-windflower-62-japanese-anemone-20-giant-white-arum-lily-38-great-masterwort-4-sweet-pea-86-tree-mallow-101-trumpet-creeper-42-daffodil-22-pincushion-flower-2-hard-leaved-pocket-orchid-54-sunflower-66-osteospermum-70-tree-poppy-85-desert-rose-99-bromelia-87-magnolia-5-english-marigold-92-bee-balm-28-stemless-gentian-97-mallow-57-gaura-40-lenten-rose-47-marigold-59-orange-dahlia-48-buttercup-55-pelargonium-36-ruby-lipped-cattleya-91-hippeastrum-29-artichoke-71-gazania-90-canna-lily-18-peruvian-lily-98-mexican-petunia-8-bird-of-paradise-30-sweet-william-17-purple-coneflower-52-wild-pansy-84-columbine-12-colts-foot-11-snapdragon-96-camellia-23-fritillary-50-common-dandelion-44-poinsettia-53-primula-72-azalea-65-californian-poppy-80-anthurium-76-morning-glory-37-cape-flower-56-bishop-of-llandaff-60-pink-yellow-dahlia-82-clematis-58-geranium-75-thorn-apple-41-barbeton-daisy-95-bougainvillea-43-sword-lily-83-hibiscus-78-lotus-lotus-88-cyclamen-94-foxglove-81-frangipani-74-rose-89-watercress-73-water-lily-46-wallflower-77-passion-flower-51-petunia-2"></a>[[‘72’]<br>
[‘18’]<br>
[‘94’]<br>
[‘83’]<br>
[‘96’]]<br>
{‘21’: ‘fire lily’, ‘3’: ‘canterbury bells’, ‘45’: ‘bolero deep blue’, ‘1’: ‘pink primrose’, ‘34’: ‘mexican aster’, ‘27’: ‘prince of wales feathers’, ‘7’: ‘moon orchid’, ‘16’: ‘globe-flower’, ‘25’: ‘grape hyacinth’, ‘26’: ‘corn poppy’, ‘79’: ‘toad lily’, ‘39’: ‘siam tulip’, ‘24’: ‘red ginger’, ‘67’: ‘spring crocus’, ‘35’: ‘alpine sea holly’, ‘32’: ‘garden phlox’, ‘10’: ‘globe thistle’, ‘6’: ‘tiger lily’, ‘93’: ‘ball moss’, ‘33’: ‘love in the mist’, ‘9’: ‘monkshood’, ‘102’: ‘blackberry lily’, ‘14’: ‘spear thistle’, ‘19’: ‘balloon flower’, ‘100’: ‘blanket flower’, ‘13’: ‘king protea’, ‘49’: ‘oxeye daisy’, ‘15’: ‘yellow iris’, ‘61’: ‘cautleya spicata’, ‘31’: ‘carnation’, ‘64’: ‘silverbush’, ‘68’: ‘bearded iris’, ‘63’: ‘black-eyed susan’, ‘69’: ‘windflower’, ‘62’: ‘japanese anemone’, ‘20’: ‘giant white arum lily’, ‘38’: ‘great masterwort’, ‘4’: ‘sweet pea’, ‘86’: ‘tree mallow’, ‘101’: ‘trumpet creeper’, ‘42’: ‘daffodil’, ‘22’: ‘pincushion flower’, ‘2’: ‘hard-leaved pocket orchid’, ‘54’: ‘sunflower’, ‘66’: ‘osteospermum’, ‘70’: ‘tree poppy’, ‘85’: ‘desert-rose’, ‘99’: ‘bromelia’, ‘87’: ‘magnolia’, ‘5’: ‘english marigold’, ‘92’: ‘bee balm’, ‘28’: ‘stemless gentian’, ‘97’: ‘mallow’, ‘57’: ‘gaura’, ‘40’: ‘lenten rose’, ‘47’: ‘marigold’, ‘59’: ‘orange dahlia’, ‘48’: ‘buttercup’, ‘55’: ‘pelargonium’, ‘36’: ‘ruby-lipped cattleya’, ‘91’: ‘hippeastrum’, ‘29’: ‘artichoke’, ‘71’: ‘gazania’, ‘90’: ‘canna lily’, ‘18’: ‘peruvian lily’, ‘98’: ‘mexican petunia’, ‘8’: ‘bird of paradise’, ‘30’: ‘sweet william’, ‘17’: ‘purple coneflower’, ‘52’: ‘wild pansy’, ‘84’: ‘columbine’, ‘12’: “colt’s foot”, ‘11’: ‘snapdragon’, ‘96’: ‘camellia’, ‘23’: ‘fritillary’, ‘50’: ‘common dandelion’, ‘44’: ‘poinsettia’, ‘53’: ‘primula’, ‘72’: ‘azalea’, ‘65’: ‘californian poppy’, ‘80’: ‘anthurium’, ‘76’: ‘morning glory’, ‘37’: ‘cape flower’, ‘56’: ‘bishop of llandaff’, ‘60’: ‘pink-yellow dahlia’, ‘82’: ‘clematis’, ‘58’: ‘geranium’, ‘75’: ‘thorn apple’, ‘41’: ‘barbeton daisy’, ‘95’: ‘bougainvillea’, ‘43’: ‘sword lily’, ‘83’: ‘hibiscus’, ‘78’: ‘lotus lotus’, ‘88’: ‘cyclamen’, ‘94’: ‘foxglove’, ‘81’: ‘frangipani’, ‘74’: ‘rose’, ‘89’: ‘watercress’, ‘73’: ‘water lily’, ‘46’: ‘wallflower’, ‘77’: ‘passion flower’, ‘51’: ‘petunia’}</h2>
<p>TypeError                                 Traceback (most recent call last)<br>
 in ()<br>
23 <span class="hashtag">#preparing</span> class_names using mapping with cat_to_name<br>
24<br>
—&gt; 25 class_names = [cat_to_name [item] for item in classes]<br>
26</p>
<p> in (.0)<br>
23 <span class="hashtag">#preparing</span> class_names using mapping with cat_to_name<br>
24<br>
—&gt; 25 class_names = [cat_to_name [item] for item in classes]<br>
26</p>
<p>TypeError: unhashable type: ‘numpy.ndarray’</p>

raj-rishav: <p>As you can see there, <code>classes</code> has 2 dimensions. So to make it work you will have to use:<br>
<code>class_names = [cat_to_name [item[0]] for item in classes]</code> . This will help you get the <code>class_names</code> .Can you tell me though if there’s any reason you have all those <code>int</code> as <code>str</code> ?</p>

Ayman_Abdelsattar_Me: <p>thank you very much may alot of code made me not foucse<br>
thank you</p>

Ayman_Abdelsattar_Me: <p>for train.py file have error  could you help please</p>
<p>def load_model (arch, hidden_layers):<br>
if arch == ‘alexnet’: # checkpoint saving will be defined<br>
model = models.alexnet (pretrained = True)<br>
for param in model.parameters():<br>
param.requires_grad = False<br>
if hidden_layers: <span class="hashtag">#in</span> case hidden_layers were given<br>
classifier = nn.Sequential  (OrderedDict ([<br>
(‘fc1’, nn.Linear (9216, 4096)),<br>
(‘relu1’, nn.ReLU ()),<br>
(‘dropout1’, nn.Dropout (p = 0.4)),<br>
(‘fc2’, nn.Linear (4096,hidden_layers)),<br>
(‘relu2’, nn.ReLU ()),<br>
(‘dropout2’, nn.Dropout (p = 0.4)),<br>
(‘fc3’, nn.Linear (hidden_layers, 102)),<br>
(‘output’, nn.LogSoftmax (dim =1))<br>
]))<br>
else: <span class="hashtag">#if</span> hidden_layers not given<br>
classifier = nn.Sequential  (OrderedDict ([<br>
(‘fc1’, nn.Linear (9216, 4096)),<br>
(‘relu1’, nn.ReLU ()),<br>
(‘dropout1’, nn.Dropout (p = 0.4)),<br>
(‘fc2’, nn.Linear (4096, 2048)),<br>
(‘relu2’, nn.ReLU ()),<br>
(‘dropout2’, nn.Dropout (p = 0.4)),<br>
(‘fc3’, nn.Linear (2048, 102)),<br>
(‘output’, nn.LogSoftmax (dim =1))<br>
]))<br>
model.classifier = classifier<br>
return model, arch</p>
<hr>
<p>Traceback (most recent call last):<br>
File “train.py”, line 143, in <br>
model, arch = load_model (args.arch, args.hidden_layers)<br>
File “train.py”, line 121, in load_model<br>
model.classifier = classifier<br>
UnboundLocalError: local variable ‘classifier’ referenced before assignment</p>