Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Pytorch:ValueError:预期输入批次大小(32)与目标批次大小(64)匹配_Python 3.x_Conv Neural Network_Pytorch - Fatal编程技术网

Python 3.x Pytorch:ValueError:预期输入批次大小(32)与目标批次大小(64)匹配

Python 3.x Pytorch:ValueError:预期输入批次大小(32)与目标批次大小(64)匹配,python-3.x,conv-neural-network,pytorch,Python 3.x,Conv Neural Network,Pytorch,尝试在MNIST数据集上运行CNN示例,批大小=64,通道=1,n_h=28,n_w=28,n_iters=1000。程序运行前500次迭代,然后给出上述误差。 论坛上已经讨论了相同的主题,例如: 而且,它们都不能帮助我识别以下代码中的错误: class CNN_MNIST(nn.Module): def __init__(self): super(CNN_MNIST,self).__init__() # convolution layer 1 self.cnn1 =

尝试在MNIST数据集上运行CNN示例,批大小=64,通道=1,n_h=28,n_w=28,n_iters=1000。程序运行前500次迭代,然后给出上述误差。 论坛上已经讨论了相同的主题,例如: 而且,它们都不能帮助我识别以下代码中的错误:

class CNN_MNIST(nn.Module):
def __init__(self):
    super(CNN_MNIST,self).__init__()

    # convolution layer 1
    self.cnn1 = nn.Conv2d(in_channels=1, out_channels= 32, kernel_size=5,
                          stride=1,padding=2)

    # ReLU activation 
    self.relu1 = nn.ReLU()

    # maxpool 1
    self.maxpool1 = nn.MaxPool2d(kernel_size=2,stride=2)

    # convolution 2
    self.cnn2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5,
                          stride=1,padding=2)

    # ReLU activation 
    self.relu2 = nn.ReLU()

    # maxpool 2
    self.maxpool2 = nn.MaxPool2d(kernel_size=2,stride=2)

    # fully connected 1
    self.fc1 = nn.Linear(7*7*64,1000)
    # fully connected 2
    self.fc2 = nn.Linear(1000,10)

def forward(self,x):

    # convolution 1
    out = self.cnn1(x)
    # activation function
    out = self.relu1(out)
    # maxpool 1
    out = self.maxpool1(out)

    # convolution 2
    out = self.cnn2(out)
    # activation function
    out = self.relu2(out)
    # maxpool 2
    out = self.maxpool2(out)

    # flatten the output
    out = out.view(out.size(0),-1)

    # fully connected layers
    out = self.fc1(out)
    out = self.fc2(out)

    return out
# model trainning
count = 0
loss_list = []
iteration_list = []
accuracy_list = []

for epoch in range(int(n_epochs)):
    for i, (image,labels) in enumerate(train_loader):

    train = Variable(image)
    labels = Variable(labels)

    # clear gradient
    optimizer.zero_grad()

    # forward propagation
    output = cnn_model(train)

    # calculate softmax and cross entropy loss
    loss = error(output,label)

    # calculate gradients
    loss.backward()

    # update the optimizer
    optimizer.step()

    count += 1

    if count % 50 ==0:
        # calculate the accuracy
        correct = 0
        total = 0

        # iterate through the test data
        for image, labels in test_loader:

            test = Variable(image)

            # forward propagation
            output = cnn_model(test)

            # get prediction
            predict = torch.max(output.data,1)[1]

            # total number of labels
            total += len(labels)

            # correct prediction
            correct += (predict==labels).sum()

        # accuracy
        accuracy = 100*correct/float(total)

        # store loss, number of iteration, and accuracy
        loss_list.append(loss.data)
        iteration_list.append(count)
        accuracy_list.append(accuracy)

        # print loss and accurcay as the algorithm progresses
        if count % 500 ==0:
            print('Iteration :{}    Loss :{}    Accuracy :

{}'.format(count,loss.item(),accuracy))
错误如下:

    ---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-19-9e93a242961b> in <module>
     18 
     19         # calculate softmax and cross entropy loss
---> 20         loss = error(output,label)
     21 
     22         # calculate gradients

~\Anaconda3\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs)
    545             result = self._slow_forward(*input, **kwargs)
    546         else:
--> 547             result = self.forward(*input, **kwargs)
    548         for hook in self._forward_hooks.values():
    549             hook_result = hook(self, input, result)

~\Anaconda3\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)
    914     def forward(self, input, target):
    915         return F.cross_entropy(input, target, weight=self.weight,
--> 916                                ignore_index=self.ignore_index, reduction=self.reduction)
    917 
    918 

~\Anaconda3\lib\site-packages\torch\nn\functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
   1993     if size_average is not None or reduce is not None:
   1994         reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 1995     return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
   1996 
   1997 

~\Anaconda3\lib\site-packages\torch\nn\functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
   1820     if input.size(0) != target.size(0):
   1821         raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
-> 1822                          .format(input.size(0), target.size(0)))
   1823     if dim == 2:
   1824         ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)

ValueError: Expected input batch_size (32) to match target batch_size (64).
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在里面
18
19#计算softmax和交叉熵损失
--->20损失=错误(输出、标签)
21
22#计算坡度
~\Anaconda3\lib\site packages\torch\nn\modules\module.py在调用中(self,*input,**kwargs)
545结果=self.\u slow\u forward(*输入,**kwargs)
546其他:
-->547结果=自我转发(*输入,**kwargs)
548用于钩住自身。\u向前\u钩住.values():
549钩子结果=钩子(自身、输入、结果)
~\Anaconda3\lib\site packages\torch\nn\modules\loss.py前进(自身、输入、目标)
914 def前进(自身、输入、目标):
915返回F.交叉熵(输入,目标,重量=自身重量,
-->916忽略索引=自我。忽略索引,减少=自我。减少)
917
918
交叉熵中的~\Anaconda3\lib\site packages\torch\nn\functional.py(输入、目标、权重、大小平均值、忽略索引、减少、减少)
1993如果尺寸_平均值不是无或减少值不是无:
1994 reduce=\u reduce.legacy\u get\u字符串(大小\u平均值,reduce)
->1995返回nll_损失(log_softmax(输入,1),目标,重量,无,忽略指数,无,减少)
1996
1997
nll\U损耗中的~\Anaconda3\lib\site packages\torch\nn\functional.py(输入、目标、重量、平均尺寸、忽略索引、减少、减少)
1820如果输入。大小(0)!=目标。大小(0):
1821 raise VALUERROR('预期的输入批次大小({})与目标批次大小({})匹配。'
->1822.格式(input.size(0)、target.size(0)))
1823如果尺寸=2:
1824 ret=torch.\u C.\u nn.nll\u损失(输入、目标、重量、减少量。获取枚举(减少量),忽略索引)
ValueError:预期输入批次大小(32)与目标批次大小(64)匹配。

您为您的损失提供了错误的目标:

loss=错误(输出、标签)
当你的加载器给你

枚举(列车装载机)中的i(图像、标签)的
:
列车=变量(图)
标签=变量(标签)
因此,您从加载程序中获得了一个变量名
labels
(带
s
),但您将
label
(无
s
)添加到您的损失中

批量大小是您最不担心的