

機械学習のコードを実装しており，LogisticRegression(nn.Module)をモデルにしています．  
損失lossの計算時に配列のサイズのミスマッチに関するエラーがでます．xはshape=[1,64],yはshape=[1,6]です．  
エラーに該当するfor文内はxはshape=[64],yはshape=[6]です．どなたか，このエラーの直し方をご教示下さい．よろしくお願い致します．  
'''エラー文'''

[code]

    Traceback (most recent call last):
    File "C:/Users/name/Desktop/myo-python-1.0.4/bindsnet-master/bindsnet/nextrsnn.py", line 101, in <module>
    loss = criterion(output.squeeze(-1),  y.long())
    File "C:\Python36\lib\site-packages\torch\nn\modules\module.py", line 722, in _call_impl
    result = self.forward(*input, **kwargs)
    File "C:\Python36\lib\site-packages\torch\nn\modules\loss.py", line 948, in forward
    ignore_index=self.ignore_index, reduction=self.reduction)
    File "C:\Python36\lib\site-packages\torch\nn\functional.py", line 2422, in cross_entropy
    return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
    File "C:\Python36\lib\site-packages\torch\nn\functional.py", line 2216, in nll_loss
    .format(input.size(0), target.size(0)))
     ValueError: Expected input batch_size (1) to match target batch_size (6).
    
[/code]

'''コードとエラー箇所'''

[code]

    import torch
    import torch.nn as nn
    import numpy as np
    from bindsnet.network import Network
    from bindsnet.network.nodes import Input, LIFNodes
    from bindsnet.network.topology import Connection
    from bindsnet.network.monitors import Monitor
    
    # モデルの定義
    class LogisticRegression(nn.Module):
         def __init__(self, input_size, num_classes):
            super(LogisticRegression, self).__init__()
            self.linear = nn.Linear(input_size, num_classes)
            self.dropout = nn.Dropout(0.5)
    
         def forward(self, x,):
            x = x.view(-1, 64)
            return self.linear(x)
     # ネットワーク作成
     input_size = 64
     num_classes = 6
     time = 64     
     network = Network(dt=1.0)
     _BATCH_SIZE = 300
     # ニューロンのレイヤー 5層作成
     inpt = Input(n=64, sum_input=True)
     middle = LIFNodes(n=40, trace=True, sum_input=True)
     center = LIFNodes(n=40, trace=True, sum_input=True)
     final = LIFNodes(n=40, trace=True, sum_input=True)
     out = LIFNodes(n=6, sum_input=True)
    
     # レイヤー同士の接続
     inpt_middle = Connection(source=inpt, target=middle, wmin=0, wmax=1e-1)
     middle_center = Connection(source=middle, target=center, wmin=0, wmax=1e-1)
     center_final = Connection(source=center, target=final, wmin=0, wmax=1e-1)
     final_out = Connection(source=final, target=out, wmin=0, wmax=1e-1)
    
     # 全てのレイヤー5層をネットワークに接続
     network.add_layer(inpt, name='A')
     network.add_layer(middle, name='B')
     network.add_layer(center, name='C')
     network.add_layer(final,  name='D')
     network.add_layer(out, name='E')
    
     forward_connection = Connection(source=inpt, target=middle, w=0.05 + 0.1*torch.randn(inpt.n, middle.n))
     network.add_connection(connection=forward_connection, source="A", target="B")
     forward_connection = Connection(source=middle, target=center, w=0.05 + 0.1*torch.randn(middle.n, center.n))
     network.add_connection(connection=forward_connection, source="B", target="C")
     forward_connection = Connection(source=center, target=final, w=0.05 + 0.1*torch.randn(center.n, final.n))
     network.add_connection(connection=forward_connection, source="C", target="D")
     forward_connection = Connection(source=final, target=out, w=0.05 + 0.1*torch.randn(final.n, out.n))
     network.add_connection(connection=forward_connection, source="D", target="E")
     recurrent_connection = Connection(source=out, target=out, w=0.025*(torch.eye(out.n)-1),)
     network.add_connection(connection=recurrent_connection, source="E", target="E")
    
     # 入力と出力層Monitorを作成(電圧とスパイクを記録)
     inpt_monitor = Monitor(obj=inpt, state_vars=("s", "v"), time=500,)
     middle_monitor = Monitor(obj=inpt, state_vars=("s", "v"), time=500,)
     center_monitor = Monitor(obj=inpt, state_vars=("s", "v"), time=500,)
     final_monitor = Monitor(obj=inpt, state_vars=("s", "v"), time=500,)
     out_monitor = Monitor(obj=inpt, state_vars=("s", "v"), time=500,)
    
     # Monitorをネットワークに接続
     network.add_monitor(monitor=inpt_monitor, name="A")
     network.add_monitor(monitor=middle_monitor, name="B")
     network.add_monitor(monitor=center_monitor, name="C")
     network.add_monitor(monitor=final_monitor, name="D")
     network.add_monitor(monitor=out_monitor, name="E")
    
     for l in network.layers:
         m = Monitor(network.layers[l], state_vars=['s'], time=time)
         network.add_monitor(m, name=l)
    
      # トレーニングデータをロード 　x = shape[1,64] y = [1,6]
      npzfile = np.load("C:/Users/name/Desktop/myo-python-1.0.4/myo-armband-nn-master/data/train_set.npz")
      x = npzfile['x']
      y = npzfile['y']
      # tensor型に変換
      x = torch.from_numpy(x).float()
      y = torch.from_numpy(y).float()
    
      training_pairs = []
      for i, (x, y) in enumerate(zip(x.view(-1, 64), y)):
          inputs = {'A': x.repeat(time, 1), 'E_b': torch.ones(time, 1)}
          network.run(inputs=inputs, time=time)
          training_pairs.append([network.monitors['E'].get('s').sum(-1), y])
          network.reset_state_variables()
    
         if (i + 1) % 50 == 0: print('Train progress: (%d / 500)' % (i + 1))
         if (i + 1) == 500: print(); break
    
         model = LogisticRegression(input_size, num_classes); criterion = nn.CrossEntropyLoss()   
         optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
        # スパイクとラベルのトレーニング
        for epoch in range(6):
              for i, (s, y) in enumerate(training_pairs):
                  optimizer.zero_grad(); output = model(s.float()).view(-1,6)
                  loss = criterion(output.squeeze(-1),  y.long()) ☚ここです
                  loss.backward(); optimizer.step()
    
        test_pairs = []
        for i, (x, y) in enumerate(zip(x.view(-1, 64), y)):
            inputs = {'A': x.repeat(time, 1), 'E_b': torch.ones(time, 1)}
            network.run(inputs=inputs, time=time)
            test_pairs.append([network.monitors['E'].get('s').sum(-1), y])
            network.reset_state_variables()
    
        if (i + 1) % 50 == 0: print('Test progress: (%d / 500)' % (i + 1))
        if (i + 1) == 500: print(); break
    
        correct, total = 0, 0
        for s, y in test_pairs:
            output = model(s); _, predicted = torch.max(output.data.unsueeze(0), 1)
            total += 1; correct += int(predicted == y.long())
    
        print('Accuracy of logistic regression on 500 test examples: %2f %%\n ' % (100 * correct / total))
         torch.save({
            'epoch': epoch,
            'model_state_dict': model.state_dict(),
            'optimizer_state_dict': optimizer.state_dict(),
            'loss': loss,
            }, "C:/Users/name/Desktop/myo-python-1.0.4/bindsnet-master/bindsnet/pytorchsession")
    
[/code]


CC BY-SA 4.0
2020-12-07T06:35:24.697
72473
2022-02-18T07:02:20.223
41671
question
python pytorch
Expected input batch_size (1) to match target batch_size (6).のエラーを直したいです．


エラー出力に `ValueError: Expected input batch_size (1) to match target batch_size
(6).` とあるように、input, target のバッチサイズが異なるようです。

ドキュメントにあるように、バッチサイズを表す0次元目のサイズは同じである必要があります。  
[torch.nn.CrossEntropyLoss - PyTorch
doc](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html?highlight=crossentropy#torch.nn.CrossEntropyLoss)

* * *

よりよい回答を得るために、こちらも参考にしてみてください。

  * [良い質問をするには？ - stackoverflow](https://ja.stackoverflow.com/help/how-to-ask)
  * [再現可能な短いサンプルコードの書き方 - stackoverflow](https://ja.stackoverflow.com/help/minimal-reproducible-example)


CC BY-SA 4.0
2021-01-23T21:39:06.680
73534
2021-01-23T21:45:21.117
2021-01-23T21:45:21.117
41038
41038
72473
answer