PyTorch torch.randn 関数
torch.randnは、PyTorch で標準正規分布(平均0、分散1のガウス分布)からランダムテンソルを作成するための関数です。
これは深層学習において、重みの初期化やランダム入力の生成などによく使用されます。
関数定義
torch.randn(*size, dtype=None, device=None, requires_grad=False)
パラメータ:
*size(int): テンソルの形状。dtype(torch.dtype, オプション): データ型。デフォルトはtorch.float32。device(torch.device, オプション): デバイス。requires_grad(bool, オプション): 勾配の計算が必要かどうか。
戻り値:
torch.Tensor: 乱数を含むテンソルを返します。
使用例
例1: ランダムテンソルの作成
実例
import torch
# 3x4 のランダムテンソルを作成
x = torch.randn(3, 4)
print(x)
# 3x4 のランダムテンソルを作成
x = torch.randn(3, 4)
print(x)
出力結果は次のとおりです:
tensor([[-0.2107, -0.6198, 0.2103, 0.4513],
[-0.0124, -1.1746, 0.1844, -0.6199],
[ 1.1729, -0.7669, 0.3034, -0.0808]])
例2: ニューラルネットワークの重み初期化
実例
import torch
import torch.nn as nn
# randn を使用してニューラルネットワークの重みを初期化
linear = nn.Linear(10, 5)
# ランダム値で重みを初期化
nn.init.randn_(linear.weight)
nn.init.zeros_(linear.bias)
print("重みの形状:", linear.weight.shape)
print("重みの平均:", linear.weight.mean().item())
print("重みの標準偏差:", linear.weight.std().item())
import torch.nn as nn
# randn を使用してニューラルネットワークの重みを初期化
linear = nn.Linear(10, 5)
# ランダム値で重みを初期化
nn.init.randn_(linear.weight)
nn.init.zeros_(linear.bias)
print("重みの形状:", linear.weight.shape)
print("重みの平均:", linear.weight.mean().item())
print("重みの標準偏差:", linear.weight.std().item())
その他の拡張
Pytorch torch リファレンスマニュアル