PyTorch 1.8 : PyTorch の学習 : 基本 – Tensor

PyTorch 1.8 チュートリアル : PyTorch の学習 : 基本 – Tensor (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 03/12/2021 (1.8.0)

* 本ページは、PyTorch 1.8 Tutorials の以下のページを翻訳した上で適宜、補足説明したものです:

* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

 

無料セミナー実施中 クラスキャット主催 人工知能 & ビジネス Web セミナー

人工知能とビジネスをテーマにウェビナー (WEB セミナー) を定期的に開催しています。スケジュールは弊社 公式 Web サイト でご確認頂けます。
  • お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
  • Windows PC のブラウザからご参加が可能です。スマートデバイスもご利用可能です。
クラスキャットは人工知能・テレワークに関する各種サービスを提供しております :

人工知能研究開発支援 人工知能研修サービス テレワーク & オンライン授業を支援
PoC(概念実証)を失敗させないための支援 (本支援はセミナーに参加しアンケートに回答した方を対象としています。)

お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。

株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
E-Mail:sales-info@classcat.com  ;  WebSite: https://www.classcat.com/  ;  Facebook

 

PyTorch の学習 : 基本 – Tensor

Tensor は配列と行列に非常に類似した特別なデータ構造です。PyTorch では、モデルのパラメータに加えて、モデルの入力と出力をエンコードするために tensor を使用します。

Tensor は NumPy の ndarray に類似しています、tensor が GPU や他のハードウェア・アクセラレータ上で実行できることを別にして。実際に、tensor と NumPy 配列はしばしば同じ基礎的なメモリを共有できます、データをコピーする必要性を除去して (Bridge with NumPy 参照)。Tensor はまた自動微分のために最適化もされます (それについては後で Autograd セクションで更に見ます)。ndarray に馴染みがあれば、Tensor API で居心地が良いでしょう。そうでないなら、後についてきてください!

import torch
import numpy as np

 

Tensor を初期化する

Tensor は様々な方法で初期化できます。以下のサンプルを見てください :

 

データから直接

Tensor はデータから直接作成できます。データ型は自動的に推論されます。

data = [[1, 2],[3, 4]]
x_data = torch.tensor(data)

 

NumPy 配列から

Tensor は NumPy 配列から作成できます (そして vice versa – Bridge with NumPy 参照)。

np_array = np.array(data)
x_np = torch.from_numpy(np_array)

 

他の tensor から

新しい tensor は引数 tensor のプロパティ (shape, datatype) を保持します、明示的に override されない限りは。

x_ones = torch.ones_like(x_data) # retains the properties of x_data
print(f"Ones Tensor: \n {x_ones} \n")

x_rand = torch.rand_like(x_data, dtype=torch.float) # overrides the datatype of x_data
print(f"Random Tensor: \n {x_rand} \n")
Ones Tensor: 
 tensor([[1, 1],
        [1, 1]]) 

Random Tensor: 
 tensor([[0.8766, 0.4091],
        [0.6311, 0.4132]]) 

 

ランダムまたは定数値で

shape は tensor 次元のタプルです。下の関数では、それは出力 tensor の次元性を決定します。

shape = (2,3,)
rand_tensor = torch.rand(shape)
ones_tensor = torch.ones(shape)
zeros_tensor = torch.zeros(shape)

print(f"Random Tensor: \n {rand_tensor} \n")
print(f"Ones Tensor: \n {ones_tensor} \n")
print(f"Zeros Tensor: \n {zeros_tensor}")
Random Tensor: 
 tensor([[0.7784, 0.4058, 0.2150],
        [0.9332, 0.6106, 0.5435]]) 

Ones Tensor: 
 tensor([[1., 1., 1.],
        [1., 1., 1.]]) 

Zeros Tensor: 
 tensor([[0., 0., 0.],
        [0., 0., 0.]])

 

Tensor 属性

Tensor 属性はそれらの shape, datatype とそれらがその上でストアされているデバイスを記述します。

tensor = torch.rand(3,4)

print(f"Shape of tensor: {tensor.shape}")
print(f"Datatype of tensor: {tensor.dtype}")
print(f"Device tensor is stored on: {tensor.device}")
Shape of tensor: torch.Size([3, 4])
Datatype of tensor: torch.float32
Device tensor is stored on: cpu

 

Tensor 上の演算

算術、線形代数、行列操作 (転置、インデキシング、スライシング)、サンプリングそしてそれ以上を含む、100 以上の tensor 演算は ここ で包括的に説明されます。

これらの演算の各々は (典型的には CPU よりも高速なスピードで) GPU 上で実行できます。

デフォルトでは、tensor は CPU 上で作成されます。(GPU の利用可能性を確認した後) .to メソッドを使用して tensor を明示的に移動する必要があります。デバイスに渡り大規模な tensor をコピーすることは時間とメモリの観点から高価であり得ることを忘れないでください!

# We move our tensor to the GPU if available
if torch.cuda.is_available():
  tensor = tensor.to('cuda')

リストから演算の幾つかを試します。NumPy API に馴染みがあるならば、Tensor API を利用するのが容易なものであることを見出すでしょう。

 

標準的な numpy-like なインデキシングとスライシング

tensor = torch.ones(4, 4)
print('First row: ',tensor[0])
print('First column: ', tensor[:, 0])
print('Last column:', tensor[..., -1])
tensor[:,1] = 0
print(tensor)
First row:  tensor([1., 1., 1., 1.])
First column:  tensor([1., 1., 1., 1.])
Last column: tensor([1., 1., 1., 1.])
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]])

 

tensor を結合する (= join)

与えられた次元に沿って tensor のシークエンスを連結するために torch.cat を使用できます。torch.stack もまた見てください、torch.cat とは微妙に異なるもう一つの tensor 結合 op です。

t1 = torch.cat([tensor, tensor, tensor], dim=1)
print(t1)
tensor([[1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.],
        [1., 0., 1., 1., 1., 0., 1., 1., 1., 0., 1., 1.]])

 

算術演算

# This computes the matrix multiplication between two tensors. y1, y2, y3 will have the same value
y1 = tensor @ tensor.T
y2 = tensor.matmul(tensor.T)

y3 = torch.rand_like(tensor)
torch.matmul(tensor, tensor.T, out=y3)


# This computes the element-wise product. z1, z2, z3 will have the same value
z1 = tensor * tensor
z2 = tensor.mul(tensor)

z3 = torch.rand_like(tensor)
torch.mul(tensor, tensor, out=z3)

 

単一要素 tensor

例えば tensor の総ての値を一つの値に合計することにより、1-要素 tenor を持つ場合、item() を使用してそれを Python 数値に変換することができます :

agg = tensor.sum()
agg_item = agg.item()
print(agg_item, type(agg_item))
12.0 <class 'float'>

 

In-place 演算

結果を operand (演算対象) にストアする演算は in-place と呼ばれます。例えば: x.copy_(y), x.t_() は x を変更します。

print(tensor, "\n")
tensor.add_(5)
print(tensor)
tensor([[1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.],
        [1., 0., 1., 1.]]) 

tensor([[6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.],
        [6., 5., 6., 6.]])

Note

in-place 演算はある程度メモリを節約しますが、履歴を直ちに失うために導関数を計算するときに問題になり得ます。そのため、それらの利用は推奨されません。

 

NumPy とのブリッジ

CPU 上の Tensor と NumPy 配列は基礎的なメモリ位置を供給できて、そして一つの変更は他方を変更します。

 

Tensor to NumPy 配列

t = torch.ones(5)
print(f"t: {t}")
n = t.numpy()
print(f"n: {n}")
t: tensor([1., 1., 1., 1., 1.])
n: [1. 1. 1. 1. 1.]

tensor の変更は NumPy 配列に反映されます。

t.add_(1)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.])
n: [2. 2. 2. 2. 2.]

 

NumPy 配列 to Tensor

n = np.ones(5)
t = torch.from_numpy(n)

NumPy 配列の変更は tensor に反映されます。

np.add(n, 1, out=n)
print(f"t: {t}")
print(f"n: {n}")
t: tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
n: [2. 2. 2. 2. 2.]
 

以上