

PyTorch Lightningをつかってネットワークの学習をしようとししているのですが、

[code]

    # 学習の実行
    trainer.fit(net, train_loader, val_loader)
    
[/code]

を実行しようとしたところ、下記エラーがでます。  
何が原因なのでしょうか？

コードファイルの添付いいたします

[code]

    INFO:pytorch_lightning.callbacks.model_summary:
      | Name | Type   | Params
    --------------------------------
    0 | fc1  | Linear | 20    
    1 | fc2  | Linear | 15    
    --------------------------------
    35        Trainable params
    0         Non-trainable params
    35        Total params
    0.000     Total estimated model params size (MB)
    Sanity Checking:
    0/? [00:00<?, ?it/s]
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-34-559331086c50> in <module>
          1 # 学習の実行
    ----> 2 trainer.fit(net, train_loader, val_loader)
    
    14 frames
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/trainer/trainer.py in fit(self, model, train_dataloaders, val_dataloaders, datamodule, ckpt_path)
        601             raise TypeError(f"`Trainer.fit()` requires a `LightningModule`, got: {model.__class__.__qualname__}")
        602         self.strategy._lightning_module = model
    --> 603         call._call_and_handle_interrupt(
        604             self, self._fit_impl, model, train_dataloaders, val_dataloaders, datamodule, ckpt_path
        605         )
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/trainer/call.py in _call_and_handle_interrupt(trainer, trainer_fn, *args, **kwargs)
         36             return trainer.strategy.launcher.launch(trainer_fn, *args, trainer=trainer, **kwargs)
         37         else:
    ---> 38             return trainer_fn(*args, **kwargs)
         39 
         40     except _TunerExitException:
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/trainer/trainer.py in _fit_impl(self, model, train_dataloaders, val_dataloaders, datamodule, ckpt_path)
        643             model_connected=self.lightning_module is not None,
        644         )
    --> 645         self._run(model, ckpt_path=self.ckpt_path)
        646 
        647         assert self.state.stopped
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/trainer/trainer.py in _run(self, model, ckpt_path)
       1096         self._checkpoint_connector.resume_end()
       1097 
    -> 1098         results = self._run_stage()
       1099 
       1100         log.detail(f"{self.__class__.__name__}: trainer tearing down")
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/trainer/trainer.py in _run_stage(self)
       1175         if self.predicting:
       1176             return self._run_predict()
    -> 1177         self._run_train()
       1178 
       1179     def _pre_training_routine(self) -> None:
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/trainer/trainer.py in _run_train(self)
       1188 
       1189         with isolate_rng():
    -> 1190             self._run_sanity_check()
       1191 
       1192         # enable train mode
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/trainer/trainer.py in _run_sanity_check(self)
       1260             # run eval step
       1261             with torch.no_grad():
    -> 1262                 val_loop.run()
       1263 
       1264             self._call_callback_hooks("on_sanity_check_end")
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/loops/loop.py in run(self, *args, **kwargs)
        197             try:
        198                 self.on_advance_start(*args, **kwargs)
    --> 199                 self.advance(*args, **kwargs)
        200                 self.on_advance_end()
        201                 self._restarting = False
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/loops/dataloader/evaluation_loop.py in advance(self, *args, **kwargs)
        150         if self.num_dataloaders > 1:
        151             kwargs["dataloader_idx"] = dataloader_idx
    --> 152         dl_outputs = self.epoch_loop.run(self._data_fetcher, dl_max_batches, kwargs)
        153 
        154         # store batch level output per dataloader
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/loops/loop.py in run(self, *args, **kwargs)
        197             try:
        198                 self.on_advance_start(*args, **kwargs)
    --> 199                 self.advance(*args, **kwargs)
        200                 self.on_advance_end()
        201                 self._restarting = False
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/loops/epoch/evaluation_epoch_loop.py in advance(self, data_fetcher, dl_max_batches, kwargs)
        135 
        136         # lightning module methods
    --> 137         output = self._evaluation_step(**kwargs)
        138         output = self._evaluation_step_end(output)
        139 
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/loops/epoch/evaluation_epoch_loop.py in _evaluation_step(self, **kwargs)
        232         """
        233         hook_name = "test_step" if self.trainer.testing else "validation_step"
    --> 234         output = self.trainer._call_strategy_hook(hook_name, *kwargs.values())
        235 
        236         return output
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/trainer/trainer.py in _call_strategy_hook(self, hook_name, *args, **kwargs)
       1478 
       1479         with self.profiler.profile(f"[Strategy]{self.strategy.__class__.__name__}.{hook_name}"):
    -> 1480             output = fn(*args, **kwargs)
       1481 
       1482         # restore current_fx when nested context
    
    /usr/local/lib/python3.8/dist-packages/pytorch_lightning/strategies/strategy.py in validation_step(self, *args, **kwargs)
        388         with self.precision_plugin.val_step_context():
        389             assert isinstance(self.model, ValidationStep)
    --> 390             return self.model.validation_step(*args, **kwargs)
        391 
        392     def test_step(self, *args: Any, **kwargs: Any) -> Optional[STEP_OUTPUT]:
    
    <ipython-input-13-80fd211086af> in validation_step(self, batch, batch_idx)
         28         loss = F.cross_entropy(y, t)
         29         self.log('val_loss', loss, on_step=False, on_epoch=True)
    ---> 30         self.log('val_acc', accuracy(y.softmax(dim=-1), t), on_step=False, on_epoch=True)
         31         return loss
         32 
    
    TypeError: accuracy() missing 1 required positional argument: 'task'
    
[/code]


CC BY-SA 4.0
2022-12-30T06:34:33.927
93108
2023-01-15T15:58:03.833
2022-12-30T06:41:53.683
3060
56291
question
python pytorch
PyTorch Lightningでの学習の実行でエラーがでます


エラー出力の最後に

[code]

    TypeError: accuracy() missing 1 required positional argument: 'task'
    
[/code]

とあるので，[TorchMetrics--ACCURACY--Functional
Interface](https://torchmetrics.readthedocs.io/en/stable/classification/accuracy.html#functional-
interface) を参考に `task='multiclass', num_classes=3` を3カ所の `accuracy()`
に設定して実行したところエラーは発生しなくなりました。なお，Google Colab (Python 3.8.16, torch 1.13.0+cu116,
pytorch-lightning 1.8.6, torchmetrics 0.11.0)
での確認に用いた（提示されたノートブックから集めた）コードは下記になります。

[code]

    from sklearn.datasets import load_iris
    import torch
    from torch import nn
    import torch.nn.functional as F
    import pytorch_lightning as pl
    from pytorch_lightning.loggers import CSVLogger
    from torchmetrics.functional import accuracy
    
    
    class Net(pl.LightningModule):
        def __init__(self):
            super().__init__()
            self.fc1 = nn.Linear(4, 4)
            self.fc2 = nn.Linear(4, 3)
    
        def forward(self, x):
            h = self.fc1(x)
            h = F.relu(h)
            h = self.fc2(h)
            return h
    
        def training_step(self, batch, batch_idx):
            x, t = batch
            y = self(x)
            loss = F.cross_entropy(y, t)
            self.log('train_loss', loss, on_step=True, on_epoch=True, prog_bar=True)
            self.log('train_acc', accuracy(y.softmax(dim=-1), t,
                                           task='multiclass', num_classes=3),
                     on_step=True, on_epoch=True, prog_bar=True)
            return loss
    
        def validation_step(self, batch, batch_idx):
            x, t = batch
            y = self(x)
            loss = F.cross_entropy(y, t)
            self.log('val_loss', loss, on_step=False, on_epoch=True)
            self.log('val_acc', accuracy(y.softmax(dim=-1), t,
                                         task='multiclass', num_classes=3),
                     on_step=False, on_epoch=True)
            return loss
    
        def test_step(self, batch, batch_idx):
            x, t = batch
            y = self(x)
            loss = F.cross_entropy(y, t)
            self.log('test_loss', loss, on_step=False, on_epoch=True)
            self.log('test_acc', accuracy(y.softmax(dim=-1), t,
                                          task='multiclass', num_classes=3),
                     on_step=False, on_epoch=True)
            return loss
    
        def configure_optimizers(self):
            optimizer = torch.optim.SGD(self.parameters(), lr=0.01)
            return optimizer
    
    
    torch.manual_seed(0)
    pl.seed_everything(0)
    
    iris = load_iris()
    data = iris['data']
    target = iris['target']
    data = torch.tensor(data, dtype=torch.float32)
    target = torch.tensor(target, dtype=torch.int64)
    dataset = torch.utils.data.TensorDataset(data, target)
    
    n_train = int(len(dataset) * 0.6)
    n_val = int(len(dataset) * 0.2)
    n_test = len(dataset) - n_train - n_val
    train, val, test = torch.utils.data.random_split(dataset, [n_train, n_val, n_test])
    
    batch_size = 10
    train_loader = torch.utils.data.DataLoader(train, batch_size,
                                               shuffle=True, drop_last=True)
    val_loader = torch.utils.data.DataLoader(val, batch_size)
    test_loader = torch.utils.data.DataLoader(test, batch_size)
    
    net = Net()
    
    logger = CSVLogger(save_dir='logs', name='my_exp')
    trainer = pl.Trainer(max_epochs=30, deterministic=True, logger=logger)
    
    trainer.fit(net, train_loader, val_loader)
    
[/code]


CC BY-SA 4.0
2023-01-15T15:58:03.833
93364
2023-01-15T15:58:03.833
54588
93108
answer