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

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

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

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

Q&A

1回答

1019閲覧

テンソル変換された画像が出力されない

k.lolo

総合スコア4

PyTorch

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

0グッド

0クリップ

投稿2022/10/21 08:32

編集2022/11/03 14:09

前提

pytorch実践入門という本の7章の画像分類モデルの構築を行っております。
鳥の画像をテンソル変換して出力したいのですが出力されません。どうしてでしょうか?よろしくお願いいたします。

やってほしいこと


なぜ画像が出力されずエラーとなるのかを教えていただきたいです。また、対処法として画像が出力されるためにはどんなコードを書けば良いのか教えていただきたいです。

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


AttributeError Traceback (most recent call last)
<ipython-input-405-50be3884ac1f> in <module>
1 img, _ = cifar2[0]
2
----> 3 plt.imshow(img.permute(1, 2, 0))
4 plt.show()

/opt/anaconda3/lib/python3.8/site-packages/PIL/Image.py in getattr(self, name)
539 )
540 return self._category
--> 541 raise AttributeError(name)
542
543 @property

AttributeError: permute

該当のソースコード

%matplotlib inline from matplotlib import pyplot as plt import numpy as np import torch torch.set_printoptions(edgeitems=2) torch.manual_seed(123) import torch import torchvision cifar10_data = torchvision.datasets. CIFAR10( root='./cifar-10', train=True, download=True, transform=torchvision.transforms.ToTensor()) cifar10 = torchvision.datasets.CIFAR10(root='./cifar-10', train=True, download=True) # <1> cifar10_val = torchvision.datasets.CIFAR10(root='./cifar-10', train=False, download=True) # <2> type(cifar10).__mro__ len(cifar10) class_names = ['airplane','automobile','bird','cat','deer', 'dog','frog','horse','ship','truck'] fig = plt.figure(figsize=(8,3)) num_classes = 10 for i in range(num_classes): ax = fig.add_subplot(2, 5, 1 + i, xticks=[], yticks=[]) ax.set_title(class_names[i]) img = next(img for img, label in cifar10 if label == i) plt.imshow(img) plt.show() img, label = cifar10[99] img, label, class_names[label] plt.imshow(img) plt.show() from torchvision import transforms dir(transforms) to_tensor = transforms.ToTensor() img_t = to_tensor(img) img_t.shape tensor_cifar10 = torchvision.datasets.CIFAR10(root='./cifar-10', train=True, download=False, transform=transforms.ToTensor()) img_t, _ = tensor_cifar10[99] type(img_t) img_t.shape, img_t.dtype img_t.min(), img_t.max() plt.imshow(img_t.permute(1, 2, 0)) plt.show() imgs = torch.stack([img_t for img_t, _ in tensor_cifar10], dim=3) imgs.shape imgs.view(3, -1).mean(dim=1) imgs.view(3, -1).std(dim=1) transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)) transformed_cifar10 = torchvision.datasets.CIFAR10(root='./cifar-10', train=True, download=False, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465),(0.2470, 0.2435, 0.2616))])) img_t, _ = transformed_cifar10[99] plt.imshow(img_t.permute(1, 2, 0)) plt.show() label_map = {0: 0, 2: 1} class_names = ['airplane', 'bird'] cifar2 = [(img, label_map[label]) for img, label in cifar10 if label in [0, 2]] cifar2_val = [(img, label_map[label]) for img, label in cifar10_val if label in [0, 2]] import torch.nn as nn n_out = 2 model = nn.Sequential( nn.Linear( 3072, # <1> 512, # <2> ), nn.Tanh(), nn.Linear( 512, # <2> n_out, # <3> ) ) def softmax(x): return torch.exp(x) / torch.exp(x).sum() softmax(x).sum() x = torch.tensor([1.0, 2.0, 3.0]) softmax(x) softmax = nn.Softmax(dim=1) x = torch.tensor([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]) softmax(x) model = nn.Sequential( nn.Linear(3072, 512), nn.Tanh(), nn.Linear(512, 2), nn.Softmax(dim=1)) img, _ = cifar2[0] plt.imshow(img.permute(1, 2, 0)) plt.show()

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

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

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

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

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

jbpb0

2022/10/21 10:26 編集

> AttributeError: permute エラーが出てる行のすぐ上に下記を追加して実行したら分かりますが、「img」は「torch.Tensor」ではありません print(type(img)) > 鳥の画像をテンソル変換して出力したい 「テンソル変換」するなら plt.imshow(img.permute(1, 2, 0)) ↓ 修正 plt.imshow(torchvision.transforms.functional.to_tensor(img).permute(1, 2, 0))
k.lolo

2022/10/21 10:37

この後新たな次元(バッチ)を増やしてモデルを実行しようとしているのですが次のコードを打つとまたまたエラーが出てしまいます。なぜでしょうか? img_batch = img.view(-1).unsqueeze(0)
jbpb0

2022/10/21 16:02 編集

私が上のコメントに書いたコードは、表示用に一時的にtorch.Tensorのデータを作ってるだけで、「img」そのものをtorch.Tensorに変換してるわけではありません > 対処法として画像が出力されるためにはどんなコードを書けば良いのか と書かれてるので、画像が表示できるだけでいい、と思いましたので 表示させる以外にもtorch.Tensorに変換したのが要るなら、下記のようにして、「img_ts」を使ってみてください plt.imshow(img.permute(1, 2, 0)) ↓ 修正 img_ts = torchvision.transforms.functional.to_tensor(img) plt.imshow(img_ts.permute(1, 2, 0))
guest

回答1

0

AttributeError: permute

エラーが出てる行のすぐ上に下記を追加して実行したら分かりますが、「img」は「torch.Tensor」ではありません

python

1print(type(img))

 

鳥の画像をテンソル変換して出力したい

対処法として画像が出力されるためにはどんなコードを書けば良いのか

「テンソル変換」して「表示」されればいいのなら

python

1plt.imshow(img.permute(1, 2, 0))

↓ 修正

python

1plt.imshow(torchvision.transforms.functional.to_tensor(img).permute(1, 2, 0))

投稿2022/11/03 05:09

jbpb0

総合スコア7651

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

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

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

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問