Visualkeras: Spam Classification Conv1D Dense Example#

An example showing Spam the visualkeras function used by a tf.keras.Model model.

 9 # Authors: The scikit-plots developers
10 # SPDX-License-Identifier: BSD-3-Clause

Installing dependencies https://sphinx-gallery.github.io/stable/configuration.html#using-multiple-code-blocks-to-create-a-single-figure

%%bash
# (e.g. %%bash or %%writefile) will be turned into a runnable code block.
# pip install -q tensorflow
# apt-get -qq install curl

pip install protobuf==5.29.4

26 import tensorflow as tf
27
28 # Clear any session to reset the state of TensorFlow/Keras
29 tf.keras.backend.clear_session()
32 model = tf.keras.models.Sequential()
33 model.add(tf.keras.layers.InputLayer(input_shape=(100,)))
34
35 # To convert 2D of input data into a 3D input
36 # Reshape to a compatible shape for Conv1D as [batch_size, time_steps, input_dimension]
37 # The Conv1D layer expects a 3D input: (batch_size, steps, channels).
38 # The Reshape layer now reshapes the input to (n_timesteps,n_features) like (100, 1),
39 # which matches the expected input of Conv1D.
40 model.add(
41     tf.keras.layers.Reshape((100, 1))
42 )  # Shape: (batch_size, 100, 1), input_shape=(100,)
43
44 # Add Conv1D and other layers
45 model.add(tf.keras.layers.Conv1D(32, 1, strides=1, activation="relu"))
46 model.add(tf.keras.layers.Dropout(0.5))
47 model.add(tf.keras.layers.MaxPooling1D(pool_size=2))
48
49 # Flatten and add Dense layers
50 model.add(tf.keras.layers.Flatten())
51 model.add(tf.keras.layers.Dense(64, activation="relu"))
52 model.add(tf.keras.layers.Dense(32, activation="relu"))
53 model.add(tf.keras.layers.Dense(1, activation="sigmoid"))
54
55 # Compile the model
56 model.compile(optimizer="rmsprop", loss="binary_crossentropy", metrics=["accuracy"])
57 model.summary()
/home/circleci/.pyenv/versions/3.11.13/lib/python3.11/site-packages/keras/src/layers/core/input_layer.py:27: UserWarning:

Argument `input_shape` is deprecated. Use `shape` instead.

Model: "sequential"
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓
┃ Layer (type)                    ┃ Output Shape           ┃       Param # ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩
│ reshape (Reshape)               │ (None, 100, 1)         │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ conv1d (Conv1D)                 │ (None, 100, 32)        │            64 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dropout (Dropout)               │ (None, 100, 32)        │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ max_pooling1d (MaxPooling1D)    │ (None, 50, 32)         │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ flatten (Flatten)               │ (None, 1600)           │             0 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense (Dense)                   │ (None, 64)             │       102,464 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense_1 (Dense)                 │ (None, 32)             │         2,080 │
├─────────────────────────────────┼────────────────────────┼───────────────┤
│ dense_2 (Dense)                 │ (None, 1)              │            33 │
└─────────────────────────────────┴────────────────────────┴───────────────┘
 Total params: 104,641 (408.75 KB)
 Trainable params: 104,641 (408.75 KB)
 Non-trainable params: 0 (0.00 B)
60 import matplotlib.pyplot as plt
61 from scikitplot import visualkeras
64 img_spam = visualkeras.layered_view(
65     model,
66     min_z=1,
67     min_xy=1,
68     max_z=4096,
69     max_xy=4096,
70     scale_z=6,
71     scale_xy=0.2,
72     font={"font_size": 14},
73     text_callable="default",
74     one_dim_orientation="x",
75     # to_file="./spam_conv_x.png",
76     save_fig=True,
77     save_fig_filename="spam_conv_x.png",
78     show_fig=True,
79 )
80 img_spam
plot conv dense
<matplotlib.image.AxesImage object at 0x7ff03b1f3590>
83 img_spam = visualkeras.layered_view(
84     model,
85     min_z=1,
86     min_xy=1,
87     max_z=4096,
88     max_xy=4096,
89     scale_z=6,
90     scale_xy=0.2,
91     font={"font_size": 14},
92     text_callable="default",
93     one_dim_orientation="y",
94     # to_file="./spam_conv_y.png",
95     save_fig=True,
96     save_fig_filename="spam_conv_y.png",
97 )
98 img_spam
plot conv dense
<matplotlib.image.AxesImage object at 0x7ff0380bbad0>
101 img_spam = visualkeras.layered_view(
102     model,
103     min_z=1,
104     min_xy=1,
105     max_z=4096,
106     max_xy=4096,
107     scale_z=0.2,
108     scale_xy=1,
109     font={"font_size": 9},
110     text_callable="default",
111     one_dim_orientation="z",
112     # to_file="./spam_conv_z.png",
113     save_fig=True,
114     save_fig_filename="spam_conv_z.png",
115     overwrite=False,
116     add_timestamp=True,
117     verbose=True,
118 )
119 img_spam
plot conv dense
[INFO] Saving path to: /home/circleci/repo/galleries/examples/visualkeras_ANN/result_images/spam_conv_z_20250629_134219Z.png

<matplotlib.image.AxesImage object at 0x7ff02815a110>

Tags: model-type: classification model-workflow: model building plot-type: visualkeras domain: neural network level: intermediate purpose: showcase

Total running time of the script: (0 minutes 3.156 seconds)

Related examples

visualkeras: Spam Dense example

visualkeras: Spam Dense example

visualkeras: autoencoder example

visualkeras: autoencoder example

visualkeras: transformers example

visualkeras: transformers example

visualkeras: custom VGG example

visualkeras: custom VGG example

Gallery generated by Sphinx-Gallery