keras/examples/demo_functional.py

47 lines
1.0 KiB
Python
Raw Normal View History

2023-04-18 22:46:57 +00:00
import numpy as np
from keras_core import Model
from keras_core import layers
from keras_core import losses
from keras_core import metrics
from keras_core import optimizers
2023-05-18 22:07:14 +00:00
inputs = layers.Input((100,))
2023-05-28 21:58:33 +00:00
x = layers.Dense(128, activation="relu")(inputs)
2023-05-17 23:06:18 +00:00
residual = x
2023-05-28 21:58:33 +00:00
x = layers.Dense(128, activation="relu")(x)
2023-05-17 23:06:18 +00:00
x += residual
2023-05-14 03:17:42 +00:00
outputs = layers.Dense(16)(x)
model = Model(inputs, outputs)
2023-04-18 22:46:57 +00:00
2023-05-14 03:17:42 +00:00
model.summary()
2023-04-18 22:46:57 +00:00
2023-05-14 03:17:42 +00:00
x = np.random.random((50000, 100))
2023-04-18 22:46:57 +00:00
y = np.random.random((50000, 16))
batch_size = 32
2023-05-14 03:17:42 +00:00
epochs = 5
2023-04-18 22:46:57 +00:00
model.compile(
2023-05-17 23:06:18 +00:00
optimizer=optimizers.Adam(learning_rate=0.001),
2023-04-18 22:46:57 +00:00
loss=losses.MeanSquaredError(),
2023-05-28 21:58:33 +00:00
metrics=[
metrics.CategoricalAccuracy(name="acc"),
metrics.MeanSquaredError(name="mse"),
],
2023-04-18 22:46:57 +00:00
)
2023-05-18 22:07:14 +00:00
print("\nTrain model")
2023-04-21 22:01:17 +00:00
history = model.fit(
x, y, batch_size=batch_size, epochs=epochs, validation_split=0.2
)
2023-05-18 22:07:14 +00:00
print("\nHistory:")
2023-04-18 22:46:57 +00:00
print(history.history)
2023-05-18 22:07:14 +00:00
print("\nEvaluate model")
scores = model.evaluate(x, y, return_dict=True)
print(scores)
print("\nRun inference")
pred = model.predict(x)
print(f"Inferred output shape {pred.shape}")