starwish’s diary

Pythonで高階関数

Kerasの勉強していたらfunctionalAPIということで次のような記述に出くわした。

from keras.layers import Input, Dense
from keras.models import Model

# This returns a tensor
inputs = Input(shape=(784,))

# a layer instance is callable on a tensor, and returns a tensor
x = Dense(64, activation='relu')(inputs)#こことか
x = Dense(64, activation='relu')(x)#こことか
predictions = Dense(10, activation='softmax')(x)

# This creates a model that includes
# the Input layer and three Dense layers
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop',
              loss='categorical_crossentropy',
              metrics=['accuracy'])
model.fit(data, labels)  # starts training

見慣れぬ記法だったので何かと思ったら高階関数とのこと

def func():
  return int
print(func()(1))

python高階関数というのは頭になかったので混乱したが言われてみればなるほど。しかしpythonって奥が深いというか、適当というか、柔軟性高いなあ。