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

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

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

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

0回答

1584閲覧

AttributeError: 'set' object has no attribute 'index'

tyuunibyou

総合スコア22

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2020/07/26 12:51

以下のコードを実行しようとしたのですが、タイトルのエラーが発生しました。
調べたところ、https://stackoverflow.com/questions/10788734/arrays-in-my-class-is-giving-me-an-error-attributeerror-set-object-has-no
を参照してエラー修正を試みたのですが解決できなかったため、教示いただけると幸いです。よろしくお願いいたします。

python

1import time 2def train_model(net,dataloader_dict,criterion,optimizer,num_epoch): 3 ##ネットワークがGPU使えるかの確認 4 ##evice~=torch.device("cuda:0" if torch.cuda is _availavle() else "cpu") 5 ##print("使用デバイス:",device) 6 ##net.to(device) 7 torch.backends.cudnn.banthmark=True 8 iteration=1 9 epoch_train_loss=0.0 10 epoch_val_loss=0.0 11 logs=[] 12 for epoch in range(num_epoch+1): 13 t_epoch_start=time.time() 14 t_iter_start=time.time() 15 print("--------------") 16 print("Epoch{}/{}".format(epoch+1,num_epochs)) 17 print("--------------") 18 for phase in ["train","val"]: 19 if phase=="traein": 20 net.train() 21 print("(train)") 22 else : 23 continue 24 for images ,targets in dataloader_dict[phase]: 25 ##image=image.to(device) 26 ##targets=[ann.to(device) for ann in targets] 27 optimizer.zero_grad() 28 with torch.set_grad_enabled(phase=="train"): 29 output=net(images) 30 loss_l,loss_c=criterion(outputs,targets) 31 loss=loss_l+loss_c 32 if phase=="train": 33 loss.backends() 34 nn.utils.clip_grad_value_( 35 net.named_parameters(),clip_value=2.0) 36 optimizer.step() 37 if (iteration%10==0): 38 t_iter_finish=time.time() 39 duration=t_iter_finish-t_iter_start 40 print("イテレーション{}|| Loss :{:.4f}||10iter:{:.4f}sec.".format(iteration,loss_item(),duration)) 41 t_iter_start=time.time() 42 epoch_train_loss+= loss_item() 43 iteration+=1 44 else: 45 epoch_val_loss+=loss.item() 46 t_epch_finish=time.time() 47 print("---------------") 48 print("epoch{}||Epoch_TRAIN_Loss:{:.4f}||Epoch_VAL_Loss:{:.4f}".format(epoch+1,epoch_train_loss,poch_val_loss)) 49 print("timer:{:.4f sec.".format(t_epoch_finisht_epoch_start)) 50 t_epoch_start=time.time() 51 log_epoch={"epoch":epoch+1,"train_loss":epoch_train_loss,"val_loss":epoch_val_loss} 52 log_append(log_epoch) 53 df=pd.DataFrame(logs) 54 df.to_csv("log_output.csv") 55 epoch_train_loss=0.0 56 epoch_val_loss=0.0 57 if ((epoch+1)%10==0): 58 torch.save(net.state_dict(),"weights/ssd300_"+str(epoch+1)+".ptr") 59 60ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー 61 62--------------------------------------------------------------------------- 63AttributeError Traceback (most recent call last) 64<ipython-input-211-e7f45b0bf37c> in <module>() 65 1 66 2 num_epochs=50 67----> 3 train_model(net,dataloader_dict,criterion,optimizer,num_epochs) 68 697 frames 70/content/drive/My Drive/Colab Notebooks/pytorch_advanced/2_objectdetection/utils/ssd_model.py in __call__(self, xml_path, width, height) 71 148 72 149 # アノテーションのクラス名のindexを取得して追加 73--> 150 label_idx = self.classes.index(name) 74 151 bndbox.append(label_idx) 75 152 76 77AttributeError: 'set' object has no attribute 'index' 78 79ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー 80エラー部分 81class Anno_xml2lst(object): 82 def __init__(self,classes): 83 self.classes=classes 84 def __call__(self,xml_path,width,height): 85 ret=[] 86 xml=ET.parse(xml_path).getroot() 87 for obj in xml.iter("object"): 88 difficult=int(obj.find("difficult").text) 89 if difficult==1: 90 continue 91 bndbox=[] 92 name=obj.find("name").text.lower().strip() 93 bbox=obj.find("bndbox") 94 pts=["xmin","ymin","xmax","ymax"] 95 for pt in (pts): 96 cur_pixel=int(bbox.find(pt).text)-1 97 if pt=="xmin" or pt=="xmax": 98 cur_pixel/=width 99 else: 100 cur_pixel/=height 101 bndbox.append(cur_pixel) 102 label_idx=self.classes.index(name) 103 bndbox.append(label_idx) 104 ret +=[bndbox] 105 return np.array(ret) 106 107

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

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

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

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

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

can110

2020/07/26 12:57

エラーの発生元のコードを提示ください。 また、使っているコードの出典(書籍、URL)も提示ください。
tyuunibyou

2020/07/26 12:59

エラー発生元は下記に記載しております。 また使ってる書籍は作りながら学ぶpytorchです。 エラー部分 class Anno_xml2lst(object): def __init__(self,classes): self.classes=classes def __call__(self,xml_path,width,height): ret=[] xml=ET.parse(xml_path).getroot() for obj in xml.iter("object"): difficult=int(obj.find("difficult").text) if difficult==1: continue bndbox=[] name=obj.find("name").text.lower().strip() bbox=obj.find("bndbox") pts=["xmin","ymin","xmax","ymax"] for pt in (pts): cur_pixel=int(bbox.find(pt).text)-1 if pt=="xmin" or pt=="xmax": cur_pixel/=width else: cur_pixel/=height bndbox.append(cur_pixel) label_idx=self.classes.index(name) bndbox.append(label_idx) ret +=[bndbox] return np.array(ret)
can110

2020/07/26 13:06

エラーメッセージで表示されている「train_model(net,dataloader_dict,criterion,optimizer,num_epochs)」 の行です。提示コードには見当たらないようです。 すなわち呼び出し元とエラー発生している「label_idx = self.classes.index(name)」とのつながりがわかるコードを提示くださいとの依頼です。
tyuunibyou

2020/07/26 13:11

いえ、なので上記記載通りですが、一応再度記載いたします。 エラー文は下記のとおりです。エラー箇所については上記のコメント部分になります /content/drive/My Drive/Colab Notebooks/pytorch_advanced/2_objectdetection/utils/ssd_model.py in __call__(self, xml_path, width, height) 148 149 # アノテーションのクラス名のindexを取得して追加 --> 150 label_idx = self.classes.index(name) 151 bndbox.append(label_idx) 152 AttributeError: 'set' object has no attribute 'index'
can110

2020/07/26 13:19

エラー文だけではなく、その発生元のコードを提示ください。一部分だけでは原因はわかりませんので。 そのコードには 「train_model(net,dataloader_dict,criterion,optimizer,num_epochs)」が含まれていると思います。 もっと直截にいえば、実行できて現象の再現するコードを提示ください、ということです。
tyuunibyou

2020/07/26 13:28

こちらでしょうか? ipython-input-220-497eb1e0f8f3> in train_model(net, dataloader_dict, criterion, optimizer, num_epochs) 22 else : 23 continue ---> 24 for images ,targets in dataloader_dict[phase]: 25 ##image=image.to(device) 26 ##targets=[ann.to(device) for ann in targets] /usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py in __next__(self) 343 344 def __next__(self): --> 345 data = self._next_data() 346 self._num_yielded += 1 347 if self._dataset_kind == _DatasetKind.Iterable and \ /usr/local/lib/python3.6/dist-packages/torch/utils/data/dataloader.py in _next_data(self) 383 def _next_data(self): 384 index = self._next_index() # may raise StopIteration --> 385 data = self._dataset_fetcher.fetch(index) # may raise StopIteration 386 if self._pin_memory: 387 data = _utils.pin_memory.pin_memory(data) /usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py in fetch(self, possibly_batched_index) 42 def fetch(self, possibly_batched_index): 43 if self.auto_collation: ---> 44 data = [self.dataset[idx] for idx in possibly_batched_index] 45 else: 46 data = self.dataset[possibly_batched_index] /usr/local/lib/python3.6/dist-packages/torch/utils/data/_utils/fetch.py in <listcomp>(.0) 42 def fetch(self, possibly_batched_index): 43 if self.auto_collation: ---> 44 data = [self.dataset[idx] for idx in possibly_batched_index] 45 else: 46 data = self.dataset[possibly_batched_index] /content/drive/My Drive/Colab Notebooks/pytorch_advanced/2_objectdetection/utils/ssd_model.py in __getitem__(self, index) 238 前処理をした画像のテンソル形式のデータとアノテーションを取得 239 ''' --> 240 im, gt, h, w = self.pull_item(index) 241 return im, gt 242 /content/drive/My Drive/Colab Notebooks/pytorch_advanced/2_objectdetection/utils/ssd_model.py in pull_item(self, index) 251 # 2. xml形式のアノテーション情報をリストに 252 anno_file_path = self.anno_list[index] --> 253 anno_list = self.transform_anno(anno_file_path, width, height) 254 255 # 3. 前処理を実施 /content/drive/My Drive/Colab Notebooks/pytorch_advanced/2_objectdetection/utils/ssd_model.py in __call__(self, xml_path, width, height) 148 149 # アノテーションのクラス名のindexを取得して追加 --> 150 label_idx = self.classes.index(name) 151 bndbox.append(label_idx) 152 AttributeError: 'set' object has no attribute 'index'
can110

2020/07/26 13:36

コードではなくエラーメッセージの全文のように見えますが、違いますでしょうか? エラーの原因は(質問者が書いた)ソースコードにあるはずですが、それが提示されないと原因を特定するのは非常に難しいです。 「実行できて現象の再現するコード」を提示されると回答得られやすくなります。
meg_

2020/07/26 13:41

質問のコードはご自身で書かれたものですか? もし参照元がある場合は提示してください。
tyuunibyou

2020/07/26 13:46

「実行できて現象の再現するコード」が分からないです。質問の一番最初に書いた関数で定義しているtrain_modelのコードとは別のコード部分でしょうか?
tyuunibyou

2020/07/26 13:47

コードはpytorchによる発展ディープラーニングを元にコードを書きました
can110

2020/07/26 14:07

質問文には関数と暮らすの定義しか書いてないですよね。関数は呼び出さないと実行されません。 実行されないと提示されたエラーも出ないと思うのですが、いかがでしょうか? つまり「train_model」の呼び出し部分のコードを提示くださいと依頼しています。
tyuunibyou

2020/07/26 14:11

失礼いたしました。呼び出しているコードはこちらになります num_epochs=50 train_model(net,dataloader_dict,criterion,optimizer,num_epochs) -------------- Epoch1/50 -------------- --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-287-e7f45b0bf37c> in <module>() 1 2 num_epochs=50 ----> 3 train_model(net,dataloader_dict,criterion,optimizer,num_epochs) 7 frames /content/drive/My Drive/Colab Notebooks/pytorch_advanced/2_objectdetection/utils/ssd_model.py in __call__(self, xml_path, width, height) 148 149 # アノテーションのクラス名のindexを取得して追加 --> 150 label_idx = self.classes.index(name) 151 bndbox.append(label_idx) 152 AttributeError: 'set' object has no attribute 'index'
meg_

2020/07/26 14:59

>コードはpytorchによる発展ディープラーニングを元にコードを書きました であれば、ご自身で追記・改変された部分があやしいかと思います。元のコードを知らないので的外れかもしれませんが。 >label_idx=self.classes.index(name) でのAttributeErrorであればインスタンスの初期化時のself.classes=classesで想定外のオブジェクトを渡しているのではないでしょうか?
meg_

2020/07/26 15:05

># アノテーションのクラス名のindexを取得して追加 から推測するとリストに対するindex()の操作をしたいのでしょうか? であればsetではなくlistオブジェクトを指定すれば良さそうです。
tyuunibyou

2020/08/11 15:59

すみません。こちらやはりわからないです。 set型は使用していませんがエラーが発生します。 setを仮に使用したらもっと早い段階でエラーが出ます。 <set型にしたとき> class Anno_xml2list(object): def __init__(self, classes): self.classes = set(classes)        ←変更点 def __call__(self,xml_path,width,height): ret=[] xml=ET.parse(xml_path).getroot() for obj in xml.iter("object"): difficult=int(obj.find("difficult").text) if difficult==1: continue bndbox=[] name = obj.find("name").text.lower().strip() bbox=obj.find("bndbox") pts=["xmin","ymin","xmax","ymax"] for pt in (pts): cur_pixel=int(bbox.find(pt).text)-1 if pt=="xmin" or pt=="xmax": cur_pixel/=width else: cur_pixel/=height bndbox.append(cur_pixel) label_idx=self.classes.index(name) bndbox.append(label_idx) ret +=[bndbox] return np.array(ret) で以下を実行すると voc_classes=["aeroplane","bycycle","bird","boat","bottle","bus","car","cat","chair","cow","diningtable","dog","horse","motorbike","person","pottedplant","sheep","sofa","train","tvmonitor"] transform_anno=Anno_xml2list(voc_classes) ind=1 image_file_path=val_img_list[ind] img=cv2.imread(image_file_path) height,width,channels=img.shape transform_anno(val_anno_list[ind],width,height) AttributeError: 'set' object has no attribute 'index'が発生します。 しかし、教材には self.classes = classes と記載されておりその後のtransform_annoも表示されます
tyuunibyou

2020/08/11 16:00

transform_anno(val_anno_list[ind],width,height))でエラーは出ないのにepochでエラーが出るのが分かりません
meg_

2020/08/12 02:00

Anno_xml2lstの初期化時に「self.classes=classes」の部分で何をself.classesに代入しているのか、質問のコードからは分かりません。 エラーメッセー「label_idx = self.classes.index(name)」の「AttributeError: 'set' object has no attribute 'index'」によると初期化時のclassesに問題があるのではないかと推測できます。 質問の情報からはこれ以上は分かりません。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問