| 1 | import tensorflow as tf |
| 2 | from time import perf_counter |
| 3 | |
| 4 | |
| 5 | def config(): |
| 6 | num_threads = 16 |
| 7 | tf.config.threading.set_inter_op_parallelism_threads(num_threads) |
| 8 | tf.config.threading.set_intra_op_parallelism_threads(num_threads) |
| 9 | |
| 10 | |
| 11 | def run_benchmark(): |
| 12 | mnist = tf.keras.datasets.mnist |
| 13 | |
| 14 | (x_train, y_train), (x_test, y_test) = mnist.load_data() |
| 15 | x_train, x_test = x_train / 255.0, x_test / 255.0 |
| 16 | |
| 17 | model = tf.keras.models.Sequential( |
| 18 | [ |
| 19 | tf.keras.layers.Flatten(input_shape=(28, 28)), |
| 20 | tf.keras.layers.Dense(128, activation="relu"), |
| 21 | tf.keras.layers.Dropout(0.2), |
| 22 | tf.keras.layers.Dense(10), |
| 23 | ] |
| 24 | ) |
| 25 | |
| 26 | predictions = model(x_train[:1]).numpy() |
| 27 | print("predictions", predictions) |
| 28 | |
| 29 | loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) |
| 30 | model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"]) |
| 31 | t0 = perf_counter() |
| 32 | model.fit(x_train, y_train, epochs=5) |
| 33 | model.evaluate(x_test, y_test, verbose=2) |
| 34 | dt = perf_counter() - t0 |
| 35 | print(f"Total time: {dt}") |
| 36 | |
| 37 | |
| 38 | run_benchmark() |