FunctionalCoLab1
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
passimport tensorflow as tf
from tensorflow.python.keras.utils.vis_utils import plot_model
import pydot
def build_model_with_sequential():
seq_model = tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation=tf.nn.relu),
tf.keras.layers.Dense(10, activation=tf.nn.softmax)])
return seq_model
def build_model_with_functional():
from tensorflow.keras.models import Model
input_layer = tf.keras.Input(shape=(28, 28))
flatten_layer = tf.keras.layers.Flatten()(input_layer)
first_dense = tf.keras.layers.Dense(128, activation=tf.nn.relu)(flatten_layer)
output_layer = tf.keras.layers.Dense(10, activation=tf.nn.softmax)(first_dense)
func_model = Model(inputs=input_layer, outputs=output_layer)
return func_model
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images = training_images / 255.0
test_images = test_images / 255.0
#model = build_model_with_functional()
model = build_model_with_sequential()
# Plot model graph
plot_model(model, show_shapes=True, show_layer_names=True, to_file='model.png')
model.compile(optimizer=tf.optimizers.Adam(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(training_images, training_labels, epochs=5)
model.evaluate(test_images, test_labels)