keras/examples/demo_functional.py

60 lines
1.4 KiB
Python
Raw Normal View History

2023-04-18 22:46:57 +00:00
import numpy as np
2023-08-24 03:38:59 +00:00
from keras import Model
from keras import layers
from keras import losses
from keras import metrics
from keras import optimizers
import keras as keras
2023-07-26 19:43:40 +00:00
keras.config.disable_traceback_filtering()
2023-04-18 22:46:57 +00:00
2023-05-18 22:07:14 +00:00
inputs = layers.Input((100,))
2023-07-28 16:54:33 +00:00
x = layers.Dense(512, activation="relu")(inputs)
2023-05-17 23:06:18 +00:00
residual = x
2023-07-28 16:54:33 +00:00
x = layers.Dense(512, activation="relu")(x)
x = layers.Dense(512, activation="relu")(x)
x += residual
2023-07-28 16:54:33 +00:00
x = layers.Dense(512, activation="relu")(x)
residual = x
2023-07-28 16:54:33 +00:00
x = layers.Dense(512, activation="relu")(x)
x = layers.Dense(512, activation="relu")(x)
2023-07-27 22:22:52 +00:00
x += residual
residual = x
2023-07-28 16:54:33 +00:00
x = layers.Dense(512, activation="relu")(x)
x = layers.Dense(512, 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
2023-08-24 03:38:59 +00:00
print("\nTrain model")
history = model.fit(
x, y, batch_size=batch_size, epochs=epochs, validation_split=0.2
)
print("\nHistory:")
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}")