Code error can anyone explain me iam learning now pytorch

Manoj_Reddy: <p>TypeError                                 Traceback (most recent call last)<br>
 in <br>
1 model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,<br>
----&gt; 2                        num_epochs=30)</p>
<p> in train_model(model, criterion, optimizer, scheduler, num_epochs)<br>
21             # Iterate over data.<br>
22             for inputs, labels in dataloaders[phase]:<br>
—&gt; 23                 inputs = inputs.to(device)<br>
24                 labels = labels.to(device)<br>
25</p>
<p>TypeError: to() received an invalid combination of arguments - got (type), but expected one of:</p>
<ul>
<li>(torch.device device, torch.dtype dtype, bool non_blocking, bool copy, *, torch.memory_format memory_format)</li>
<li>(torch.dtype dtype, bool non_blocking, bool copy, *, torch.memory_format memory_format)</li>
<li>(Tensor tensor, bool non_blocking, bool copy, *, torch.memory_format memory_format)</li>
</ul>

ptrblck: <p>Try to <code>print</code> what <code>device</code> is set to as it seems to be a <code>type</code> while a <code>torch.device</code> or <code>str</code> is expected.</p>

Manoj_Reddy: <p>I have done it but again same I don’t understand why this comes every time for me</p>
<p>TypeError                                 Traceback (most recent call last)<br>
 in <br>
----&gt; 1 model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,num_epochs=50)</p>
<p> in train_model(model, criterion, optimizer, scheduler, num_epochs)<br>
21             # Iterate over data.<br>
22             for inputs, labels in dataloaders[phase]:<br>
—&gt; 23                 inputs = inputs.to(torch.device)<br>
24                 labels = labels.to(torch.device)<br>
25</p>
<p>TypeError: to() received an invalid combination of arguments - got (type), but expected one of:</p>
<ul>
<li>(torch.device device, torch.dtype dtype, bool non_blocking, bool copy, *, torch.memory_format memory_format)</li>
<li>(torch.dtype dtype, bool non_blocking, bool copy, *, torch.memory_format memory_format)</li>
<li>(Tensor tensor, bool non_blocking, bool copy, *, torch.memory_format memory_format)</li>
</ul>

Manoj_Reddy: <p>iam using the PyTorch computer vision transfer learning  code for 4000 data images to identify the photographer can anyone help me to get this done</p>

ptrblck: <p>In case you are stuck, please post a minimal and executable code snippet which would reproduce the issue.</p>

Manoj_Reddy: <p>from <strong>future</strong> import print_function, division</p>
<p>import torch</p>
<p>import torch.nn as nn</p>
<p>import torch.optim as optim</p>
<p>from torch.optim import lr_scheduler</p>
<p>import torch.backends.cudnn as cudnn</p>
<p>import numpy as np</p>
<p>import torchvision</p>
<p>from torchvision import datasets, models, transforms</p>
<p>import matplotlib.pyplot as plt</p>
<p>import time</p>
<p>import os</p>
<p>import copy</p>
<p>cudnn.benchmark = True</p>
<p>plt.ion()</p>
<p>data_transforms = {<br>
‘train’: transforms.Compose([<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>
]),<br>
‘test’: transforms.Compose([<br>
transforms.Resize(256),<br>
transforms.CenterCrop(224),<br>
transforms.ToTensor(),<br>
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])<br>
]),<br>
}</p>
<p>data_dir = ‘drive/MyDrive/data’<br>
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x),<br>
data_transforms[x])<br>
for x in [‘train’, ‘test’]}<br>
dataloaders = {x: torch.utils.data.DataLoader(image_datasets[x], batch_size=32,<br>
shuffle=True, num_workers=2)<br>
for x in [‘train’, ‘test’]}<br>
dataset_sizes = {x: len(image_datasets[x]) for x in [‘train’, ‘test’]}<br>
class_names = image_datasets[‘train’].classes</p>
<p>def imshow(inp, title=None):<br>
“”“Imshow for Tensor.”“”<br>
inp = inp.numpy().transpose((1, 2, 0))<br>
mean = np.array([0.485, 0.456, 0.406])<br>
std = np.array([0.229, 0.224, 0.225])<br>
inp = std * inp + mean<br>
inp = np.clip(inp, 0, 1)<br>
plt.imshow(inp)<br>
if title is not None:<br>
plt.title(title)<br>
plt.pause(0.001)  # pause a bit so that plots are updated</p>
<h1>
<a name="get-a-batch-of-training-data-1" class="anchor" href="#get-a-batch-of-training-data-1"></a>Get a batch of training data</h1>
<p>inputs, classes = next(iter(dataloaders[‘train’]))</p>
<h1>
<a name="make-a-grid-from-batch-2" class="anchor" href="#make-a-grid-from-batch-2"></a>Make a grid from batch</h1>
<p>out = torchvision.utils.make_grid(inputs)</p>
<p>imshow(out, title=[class_names[x] for x in classes])</p>
<p>def train_model(model, criterion, optimizer, scheduler, num_epochs=50):<br>
since = time.time()</p>
<pre><code>best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0

for epoch in range(num_epochs):
    print(f'Epoch {epoch}/{num_epochs - 1}')
    print('-' * 10)

    # Each epoch has a training and validation phase
    for phase in ['train', 'test']:
        if phase == 'train':
            model.train()  # Set model to training mode
        else:
            model.eval()   # Set model to evaluate mode

        running_loss = 0.0
        running_corrects = 0

        # Iterate over data.
        for inputs, labels in dataloaders[phase]:
            inputs = inputs.to(torch.device)
            labels = labels.to(torch.device)

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward
            # track history if only in train
            with torch.set_grad_enabled(phase == 'train'):
                outputs = model(inputs)
                _, preds = torch.max(outputs, 1)
                loss = criterion(outputs, labels)

                # backward + optimize only if in training phase
                if phase == 'train':
                    loss.backward()
                    optimizer.step()

            # statistics
            running_loss += loss.item() * inputs.size(0)
            running_corrects += torch.sum(preds == labels.data)
        if phase == 'train':
            scheduler.step()

        epoch_loss = running_loss / dataset_sizes[phase]
        epoch_acc = running_corrects.double() / dataset_sizes[phase]

        print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')

        # deep copy the model
        if phase == 'test' and epoch_acc &gt; best_acc:
            best_acc = epoch_acc
            best_model_wts = copy.deepcopy(model.state_dict())

    print()

time_elapsed = time.time() - since
print(f'Training complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')
print(f'Best test Acc: {best_acc:4f}')

# load best model weights
model.load_state_dict(best_model_wts)
return model
</code></pre>
<p>def visualize_model(model, num_images=10):<br>
was_training = model.training<br>
model.eval()<br>
images_so_far = 0<br>
fig = plt.figure()</p>
<pre><code>with torch.no_grad():
    for i, (inputs, labels) in enumerate(dataloaders['test']):
        inputs = inputs.to(torch.device)
        labels = labels.to(torch.device)

        outputs = model(inputs)
        _, preds = torch.max(outputs, 1)

        for j in range(inputs.size()[0]):
            images_so_far += 1
            ax = plt.subplot(num_images//2, 2, images_so_far)
            ax.axis('off')
            ax.set_title(f'predicted: {class_names[preds[j]]}')
            imshow(inputs.cpu().data[j])

            if images_so_far == num_images:
                model.train(mode=was_training)
                return
    model.train(mode=was_training)
</code></pre>
<p>model_ft = models.resnet18(pretrained=True)</p>
<p>num_ftrs = model_ft.fc.in_features</p>
<h1>
<a name="here-the-size-of-each-output-sample-is-set-to-2-3" class="anchor" href="#here-the-size-of-each-output-sample-is-set-to-2-3"></a>Here the size of each output sample is set to 2.</h1>
<h1>
<a name="alternatively-it-can-be-generalized-to-nnlinearnum_ftrs-lenclass_names-4" class="anchor" href="#alternatively-it-can-be-generalized-to-nnlinearnum_ftrs-lenclass_names-4"></a>Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)).</h1>
<p>model_ft.fc = nn.Linear(num_ftrs, len(class_names),48)</p>
<p>criterion = nn.CrossEntropyLoss()</p>
<h1>
<a name="observe-that-all-parameters-are-being-optimized-5" class="anchor" href="#observe-that-all-parameters-are-being-optimized-5"></a>Observe that all parameters are being optimized</h1>
<p>optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)</p>
<h1>
<a name="decay-lr-by-a-factor-of-01-every-7-epochs-6" class="anchor" href="#decay-lr-by-a-factor-of-01-every-7-epochs-6"></a>Decay LR by a factor of 0.1 every 7 epochs</h1>
<p>exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)</p>
<p>model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler,num_epochs=50)</p>
<p>this is my almost code for training if can change anything and add please correct code I can try</p>
<p>thankyou</p>

ptrblck: <p>Your code is unfortunately neither executable nor properly formatted.<br>
However, based on the posted code, <code>inputs.to(torch.device)</code> is wrong since <code>torch.device</code> is just a type.<br>
Use <code>.to('cuda')</code> or <code>.to(torch.device('cuda')</code> instead.</p>

Manoj_Reddy: <p>hello<br>
iam using Pytorch computer vision transfer learning code for training my data set  of 4000 images according to the data set I have 48 classes my accuracy is getting in test is like 40% is there any suggestions for that I have divided data into 80-20 for train and validation</p>