前提
PyTorchの勉強をしています。
超基本的な回帰として、sin関数の回帰を考えていました。
実現したいこと
- 教師データ(X, y)からsin関数を学習する。
発生している問題・エラーメッセージ
RuntimeError Traceback (most recent call last) Cell In [97], line 1 ----> 1 training_loop( 2 n_epochs=5000, 3 optimizer=optimizer, 4 model=net, 5 loss_fn=nn.MSELoss, 6 X_train=X_train, 7 X_test=X_test, 8 t_train=t_train, 9 t_test=t_test 10 ) Cell In [95], line 9, in training_loop(n_epochs, optimizer, model, loss_fn, X_train, X_test, t_train, t_test) 7 print(t_train) 8 print(y_train.shape, t_train.shape) ---> 9 loss_train = loss_fn(y_train, t_train) 11 y_test = model(X_test) 12 loss_test = loss_fn(y_test, t_test) File /usr/local/lib/python3.8/dist-packages/torch/nn/modules/loss.py:533, in MSELoss.__init__(self, size_average, reduce, reduction) 532 def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None: --> 533 super(MSELoss, self).__init__(size_average, reduce, reduction) File /usr/local/lib/python3.8/dist-packages/torch/nn/modules/loss.py:23, in _Loss.__init__(self, size_average, reduce, reduction) 21 super(_Loss, self).__init__() 22 if size_average is not None or reduce is not None: ---> 23 self.reduction: str = _Reduction.legacy_get_string(size_average, reduce) 24 else: 25 self.reduction = reduction File /usr/local/lib/python3.8/dist-packages/torch/nn/_reduction.py:35, in legacy_get_string(size_average, reduce, emit_warning) 32 if reduce is None: 33 reduce = True ---> 35 if size_average and reduce: 36 ret = 'mean' 37 elif reduce: RuntimeError: Boolean value of Tensor with more than one value is ambiguous
該当のソースコード
Python
1import torch 2import torch.nn as nn 3import numpy as np 4%matplotlib inline 5import matplotlib.pyplot as plt 6 7def get_data(N, tr): 8 X = np.random.rand(N) 9 y = np.sin(2 * np.pi * X) 10 tr = int(N * tr) 11 X_train = torch.tensor(X[:tr], dtype=torch.float32).unsqueeze(1) 12 X_test = torch.tensor(X[tr:], dtype=torch.float32).unsqueeze(1) 13 t_train = torch.tensor(y[:tr], dtype=torch.float32).unsqueeze(1) 14 t_test = torch.tensor(y[tr:], dtype=torch.float32).unsqueeze(1) 15 return X_train, X_test, t_train, t_test 16 17X_train, X_test, t_train, t_test = get_data(100, 0.8) 18 19class Net(nn.Module): 20 def __init__(self): 21 super().__init__() 22 self.fc1 = nn.Linear(1, 5) 23 self.relu = nn.ReLU() 24 self.fc2 = nn.Linear(5, 1) 25 26 def forward(self, x): 27 x = self.fc1(x) 28 x = self.relu(x) 29 x = self.fc2(x) 30 return x 31 32net = Net() 33optimizer = torch.optim.SGD(net.parameters(), lr=1e-2) 34 35def training_loop(n_epochs, optimizer, model, loss_fn, X_train, X_test, t_train, t_test): 36 for epoch in range(1, n_epochs + 1): 37 y_train = model(X_train) 38 # print('y_train') 39 # print(y_train) 40 # print('t_train') 41 # print(t_train) 42 # print(y_train.shape, t_train.shape) 43 loss_train = loss_fn(y_train, t_train) 44 45 y_test = model(X_test) 46 loss_test = loss_fn(y_test, t_test) 47 48 optimizer.zero_grad() 49 loss_train.backward() 50 optimizer.step() 51 52 if epoch == 1 or epoch % 1000 == 0: 53 print(f"Epoch {epoch}, Training loss {loss_train.item():.4f}," 54 f" Validation loss {loss_test.item():.4f}") 55 56training_loop( 57 n_epochs=5000, 58 optimizer=optimizer, 59 model=net, 60 loss_fn=nn.MSELoss, 61 X_train=X_train, 62 X_test=X_test, 63 t_train=t_train, 64 t_test=t_test 65)
試したこと
こういうのは通るのかな?と思って以下のコードを動かしてみたのですが動きました。
Python
1lfn = nn.MSELoss() 2x = torch.tensor([ 3 [-0.5455], 4 [-0.4873], 5 [-0.4621], 6 [-0.3595]], dtype=torch.float32) 7t = torch.tensor([ 8 [-8.0954e-01], 9 [-7.6121e-01], 10 [-2.8437e-01], 11 [ 2.7563e-02] 12]) 13lfn(x, t)
より必要な情報等あれば教えてください。
よろしくお願い申し上げます。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/11/20 10:26
2022/11/20 13:30