PyTorch torch.nn.Bilinear 関数
torch.nn.BilinearPyTorch の双線形層です。
これは2つの入力に対して双線形変換を行い、特徴融合によく使用されます。
関数定義
torch.nn.Bilinear(in1_features, out_features, out_features, bias=True)
公式
y = x1 * W * x2 + b
使用例
例1: 基本的な使い方
実例
import torch
import torch.nn as nn
# 双線形層:2つの100次元入力 -> 50次元出力
bilinear = nn.Bilinear(100, 100, 50)
# 2つの入力
x1 = torch.randn(4, 100)
x2 = torch.randn(4, 100)
output = bilinear(x1, x2)
print("入力1:", x1.shape)
print("入力2:", x2.shape)
print("出力:", output.shape)
import torch.nn as nn
# 双線形層:2つの100次元入力 -> 50次元出力
bilinear = nn.Bilinear(100, 100, 50)
# 2つの入力
x1 = torch.randn(4, 100)
x2 = torch.randn(4, 100)
output = bilinear(x1, x2)
print("入力1:", x1.shape)
print("入力2:", x2.shape)
print("出力:", output.shape)
例2:特徴融合
実例
import torch
import torch.nn as nn
# 双線形特徴融合(Skip-gram と類似)
class FusionNet(nn.Module):
def __init__(self, dim=128):
super(FusionNet, self).__init__()
self.bilinear = nn.Bilinear(dim, dim, dim)
def forward(self, feat1, feat2):
return self.bilinear(feat1, feat2)
model = FusionNet()
f1 = torch.randn(4, 128)
f2 = torch.randn(4, 128)
output = model(f1, f2)
print("融合出力:", output.shape)
import torch.nn as nn
# 双線形特徴融合(Skip-gram と類似)
class FusionNet(nn.Module):
def __init__(self, dim=128):
super(FusionNet, self).__init__()
self.bilinear = nn.Bilinear(dim, dim, dim)
def forward(self, feat1, feat2):
return self.bilinear(feat1, feat2)
model = FusionNet()
f1 = torch.randn(4, 128)
f2 = torch.randn(4, 128)
output = model(f1, f2)
print("融合出力:", output.shape)
例3: パラメータ数
実例
import torch
import torch.nn as nn
# 双線形層のパラメータ
bilinear = nn.Bilinear(100, 100, 50)
print("パラメータ数:", sum(p.numel() for p in bilinear.parameters()))
print("重みの形状:", bilinear.weight.shape) # (50, 100, 100)
import torch.nn as nn
# 双線形層のパラメータ
bilinear = nn.Bilinear(100, 100, 50)
print("パラメータ数:", sum(p.numel() for p in bilinear.parameters()))
print("重みの形状:", bilinear.weight.shape) # (50, 100, 100)
使用シーン
- 特徴融合: マルチモーダル
- 注意機構
- インタラクションのモデリング
注意:双線形層はパラメータ数が大きいため、慎重に使用してください。
その他の拡張