บทนำ
tf.keras.layers.Dense คือ Fully Connected Layer พื้นฐานของ Neural Network สร้างได้จาก Custom Layer ด้วยการ Override build, call
การติดตั้ง
pip install tensorflow
ตัวอย่างโค้ด (Custom Dense Layer)
from tensorflow import keras
from tensorflow.keras import layers
import tensorflow as tf
class CustomDense(layers.Layer):
def __init__(self, units=32):
super(CustomDense, self).__init__()
self.units = units
def build(self, input_shape):
self.w = self.add_weight(
shape=(input_shape[-1], self.units),
initializer="random_normal",
trainable=True
)
self.b = self.add_weight(
shape=(self.units,),
initializer="random_normal",
trainable=True
)
def call(self, inputs):
return tf.matmul(inputs, self.w) + self.b
inputs = keras.Input((4,))
outputs = CustomDense(10)(inputs)
print("Keras model is being generated")
model = keras.Model(inputs, outputs)ผลลัพธ์
Keras model is being generated
คำอธิบาย
build(): สร้าง Weights (Kernel, Bias) ตาม Input Shapecall(): Forward Pass (Linear Transformation)Built-in Dense Layer มี Activation, Regularization, Constraints เพิ่มเติม