2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Functorの使い方

2
Posted at

juliaでFunctorについて

Functorは、structを通常の関数のように扱いたい時に使われる。
下の例だと、fucntion a::structとすることで、あたかもstrunctを関数として扱うことができる。
例えば、ニューラルネットワークのAffine変換を考える。

module My

struct Affine
    W
    b
    Affine(W, b) = new(W, b) #これはなくても動く。
end

# Functorはstruct(Affine)を関数のように扱う。xは引数。
function (a::Affine)(x)
    a.W * x + a.b
end
end

using .My
Affine = My.Affine
keisan(W, b, x) = W * x + b

W = rand(2,3)
b = rand(2)
x = rand(3)
a = Affine(W, b);
@assert a(x)  keisan(W, b, x)

juliaのFuctorは、pythonでいうと__call__に相当する。

class Goma:
    def __init__(self, name):
        self.name = name # "ごま"

    def __call__(self, human): # "Azarashi"
        print(f"Hello {human}, I am {self.name}")

g = Goma("ごま")
g("Azarashi")

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?