Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.Bilinear function

PyTorch torch.nn.Bilinear function

PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual


torch.nn.Bilinear is the bilinear layer in PyTorch.

It applies a bilinear transformation to two inputs and is commonly used for feature fusion.

Function definition



torch.nn.Bilinear(in1_features, out_features, out_features, bias=True)

Formula



y = x1 * W * x2 + b


Usage examples

Example 1: Basic usage

Example

import

torch

import

torch.

nn

as

nn

Bilinear layer: two 100-dimensional inputs -> 50-dimensional output

bilinear

=

nn.

Bilinear

(

100

,

100

,

50

)

Two inputs

x1

=

torch.

randn

(

4

,

100

)

x2

=

torch.

randn

(

4

,

100

)

output

=

bilinear

(

x1

,

x2

)

print

(

"Input 1:"

,

x1.

shape

)

print

(

"Input 2:"

,

x2.

shape

)

print

(

"Output:"

,

output.

shape

)

Example 2: Feature fusion

Example

import

torch

import

torch.

nn

as

nn

Bilinear feature fusion (similar to 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

(

"Fused output:"

,

output.

shape

)

Example 3: Number of parameters

Example

import

torch

import

torch.

nn

as

nn

Bilinear layer parameters

bilinear

=

nn.

Bilinear

(

100

,

100

,

50

)

print

(

"Number of parameters:"

,

sum

(

p.

numel

(

)

for

p

in

bilinear.

parameters

(

)

)

)

print

(

"Weight shape:"

,

bilinear.

weight

.

shape

)

 

(50, 100, 100)


Use Cases

Note: Bilinear layers have a large number of parameters; use them with caution.


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual