質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
PyTorch

PyTorchは、オープンソースのPython向けの機械学習ライブラリ。Facebookの人工知能研究グループが開発を主導しています。強力なGPUサポートを備えたテンソル計算、テープベースの自動微分による柔軟なニューラルネットワークの記述が可能です。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Q&A

解決済

1回答

253閲覧

pytorchのdataloaderクラスを辞書型で整理したい

sasa__tomo

総合スコア1

PyTorch

PyTorchは、オープンソースのPython向けの機械学習ライブラリ。Facebookの人工知能研究グループが開発を主導しています。強力なGPUサポートを備えたテンソル計算、テープベースの自動微分による柔軟なニューラルネットワークの記述が可能です。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

0グッド

0クリップ

投稿2023/05/23 07:22

編集2023/05/23 10:20

実現したいこと

pytorchでDataloaderを格納した辞書型配列を作成したい(for文を使って)

前提

pytorchでLSTMモデルの訓練をしているとき、気になったことがあったので質問させていただきます。

4つのcsvデータを読み込みそれぞれのデータセット用のデータローダを格納した辞書型配列を使い、モデルの訓練を行うとエラーが起きます。

python

1#Dataloaderを格納した辞書型作成 2 3train_loader_dict={} 4 5for i,video in enumerate(np.unique(df_label['video'].values)): 6 df = pd.read_csv("./outlier_detection_xy/data/"+video+"/position_data_labeled.csv") 7 #label=="normal"だけを抽出 8 df=df[df['label']=='normal'] 9 10 #以下のyがLSTMモデルへの入力 11 #x=df['frame'].values 12 13 y=df['RIGHT_ANKLE_x'].values-df['LEFT_ANKLE_x'].values 14 15 train_dataset=Dataset(y) 16 17 train_loader=DataLoader(train_dataset,batch_size=4, shuffle=False, drop_last=True) 18 train_loader_dict[video]=train_loader 19 20 print(train_loader_dict)

python

1#Datasetクラス 2 3class Dataset(torch.utils.data.Dataset): 4 """ 5 params 6 y : (numpy)異常値を省いた時系列データ 7 data_length : (int) 各データの時系列長 8 9 returns 10 train_data : トレーニングデータ(t=1,2,...,y.size-1の値) 11 train_label : トレーニングデータのラベル(t=sizeの値) 12 """ 13 def __init__(self, y,data_length=6): 14 self.y=y 15 self.data_length=data_length 16 17 def __getitem__(self, index): 18 19 train_data=y[index:index+self.data_length].reshape(1,-1).T 20 train_label=y[index+self.data_length] 21 return train_data, train_label 22 23 def __len__(self): 24 return len(self.y)-self.data_length

発生している問題・エラーメッセージ

145の数値から辞書型train_loader_dictから取り出したtrain_loaderがfor文で最後に格納したtrain_loaderに置き換わっているのかなと思います。

/usr/local/lib/python3.10/dist-packages/torch/nn/modules/loss.py:536: UserWarning: Using a target size (torch.Size([4])) that is different to the input size (torch.Size([4, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size. return F.mse_loss(input, target, reduction=self.reduction) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-142-1949d1956cbb> in <cell line: 1>() 7 print(video_name) 8 ----> 9 for train_data, train_label in train_loader: 10 11 n=n+1 4 frames <ipython-input-116-dba67668cc3b> in __getitem__(self, index) 16 17 train_data=y[index:index+self.data_length].reshape(1,-1).T ---> 18 train_label=y[index+self.data_length] 19 return train_data, train_label 20 IndexError: index 145 is out of bounds for axis 0 with size 145

該当のソースコード

python

1#モデル訓練時エラーが起きるコード(for文で辞書作成) 2for epoch in range(epochs_num): 3 # training 4 running_loss = 0.0 5 training_accuracy = 0.0 6 n=0 7 for video_name,train_loader in train_loader_dict.items(): 8 print(video_name) 9 10 for train_data, train_label in train_loader: 11 12 n=n+1 13 print(n) 14 #print(train_data) 15 optimizer.zero_grad() 16 output = model(train_data) 17 18 loss = criterion(output, train_label) 19 loss.backward() 20 optimizer.step() 21 22 running_loss += loss.item() 23 training_accuracy += np.sum(np.abs((output.data - train_label.data).numpy()) < 0.1) #outputとlabelの誤差が0.1以内なら正しいとみなす。 24 25 training_accuracy /= training_size 26 print('%d loss: %.3f, training_accuracy: %.5f' % (epoch + 1, running_loss, training_accuracy))

実践したこと

dataloader一つを使った場合うまくいった。

python

1#データローダ作成 2df = pd.read_csv("./outlier_detection_xy/data/"+"IMG_0893_7080_7260"+"/position_data_labeled.csv") 3 4df=df[df['label']=='normal'] 5 6y=df['RIGHT_ANKLE_x'].values-df['LEFT_ANKLE_x'].values 7 8train_loader=DataLoader(Dataset(y),batch_size=4, shuffle=False, drop_last=True) 9 10 11#モデル訓練 12from pandas.core.groupby.groupby import OutputFrameOrSeries 13for epoch in range(epochs_num): 14 # training 15 running_loss = 0.0 16 training_accuracy = 0.0 17 18 for train_data, train_label in train_loader: 19 20   optimizer.zero_grad() 21 output = model(train_data) 22 23 loss = criterion(output, train_label.reshape(-1,1)) 24 loss.backward() 25 optimizer.step() 26 27 running_loss += loss.item() 28 29 30 print('%d loss: %.3f, training_accuracy: %.5f' % (epoch + 1, running_loss, training_accuracy)) 31

補足情報(FW/ツールのバージョンなど)

python3.9 google colaboratry使用

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jbpb0

2023/05/23 08:06

「#うまくいったコード(べた書き)」の > df1=df[df['label']=='normal'] df2=df[df['label']=='normal'] df3=df[df['label']=='normal'] df4=df[df['label']=='normal'] の「df」って、何でしょうか?
sasa__tomo

2023/05/23 08:11

質問ありがとうございます。 すいません。記述ミスでした。 今うまくいったコードを修正して実行したところ、同じエラーが起きてしまったので、また別のところに間違いがあるみたいです。 ご指摘本当にありがとうございます。
sasa__tomo

2023/05/23 08:11

正しくはdfの後に数字が続きます。
jbpb0

2023/05/23 08:20

> 正しくはdfの後に数字が続きます。 > 今うまくいったコードを修正して実行したところ、同じエラーが起きてしまった 書き方によらず同じエラーが起きて、そのエラーを直したいのなら、そのように質問を書き直してください
sasa__tomo

2023/05/23 10:21

遅くなってすいません。修正いたしました。
guest

回答1

0

自己解決

Datasetクラスの__getitem__内のyがself.yとなっていないのが原因でした。
回答してくださった方ありがとうございました。

投稿2023/05/23 10:55

sasa__tomo

総合スコア1

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問