dl-experiment-code 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ __version__ = "1.0.0"
@@ -0,0 +1,94 @@
1
+ import argparse
2
+ from pathlib import Path
3
+ import shutil
4
+
5
+ TEMPLATE_DIR = Path(__file__).parent / "templates"
6
+
7
+ EXPERIMENTS = {
8
+ "5": {
9
+ "local": ("exp5_local.py", "CNN image classification - local dataset"),
10
+ "online": ("exp5_online.py", "CNN image classification - Keras CIFAR-10"),
11
+ },
12
+ "6": {
13
+ "local": ("exp6_local.py", "CNN hyperparameter tuning - local dataset"),
14
+ "online": ("exp6_online.py", "CNN hyperparameter tuning - Keras CIFAR-10"),
15
+ },
16
+ "7": {
17
+ "local": ("exp7_local.py", "Autoencoder dimensionality reduction - local CSV"),
18
+ "online": ("exp7_online.py", "Autoencoder dimensionality reduction - Keras MNIST"),
19
+ },
20
+ "8": {
21
+ "local": ("exp8_local.py", "Educational object detection - local Pascal VOC XML"),
22
+ "online": ("exp8_online.py", "Educational object detection - Pascal VOC via TFDS"),
23
+ },
24
+ "9": {
25
+ "local": ("exp9_local.py", "LSTM sentiment analysis - local CSV"),
26
+ "online": ("exp9_online.py", "LSTM sentiment analysis - Keras IMDB"),
27
+ },
28
+ "10": {
29
+ "local": ("exp10_local.py", "LSTM hyperparameter tuning - local CSV"),
30
+ "online": ("exp10_online.py", "LSTM hyperparameter tuning - Keras IMDB"),
31
+ },
32
+ }
33
+
34
+ def read_template(filename):
35
+ return (TEMPLATE_DIR / filename).read_text(encoding="utf-8")
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(
39
+ prog="dlab-code",
40
+ description="Get ready-to-use Deep Learning experiment code.",
41
+ )
42
+ sub = parser.add_subparsers(dest="command", required=True)
43
+
44
+ get = sub.add_parser("get", help="Print or save experiment code")
45
+ get.add_argument("experiment", help="Experiment number: 5-10 or rnn-scratch")
46
+ get.add_argument(
47
+ "--dataset",
48
+ choices=["local", "online"],
49
+ default="online",
50
+ help="Dataset variant for experiments 5-10 (default: online)",
51
+ )
52
+ get.add_argument(
53
+ "--save",
54
+ metavar="FILE",
55
+ help="Save the generated code to a .py file instead of only printing it",
56
+ )
57
+
58
+ ls = sub.add_parser("list", help="List available experiments")
59
+
60
+ args = parser.parse_args()
61
+
62
+ if args.command == "list":
63
+ print("Available experiments:")
64
+ for number, variants in EXPERIMENTS.items():
65
+ print(f"\nExperiment {number}:")
66
+ for dataset, (_, description) in variants.items():
67
+ print(f" {dataset:7s} - {description}")
68
+ print("\nAdditional:")
69
+ print(" rnn-scratch - Vanilla RNN from scratch using NumPy")
70
+ return
71
+
72
+ exp = args.experiment.lower()
73
+
74
+ if exp in {"rnn-scratch", "rnn_scratch", "rnn"}:
75
+ code = read_template("rnn_scratch.py")
76
+ default_name = "rnn_from_scratch.py"
77
+ elif exp in EXPERIMENTS:
78
+ filename, _ = EXPERIMENTS[exp][args.dataset]
79
+ code = read_template(filename)
80
+ default_name = filename
81
+ else:
82
+ raise SystemExit(
83
+ "Unknown experiment. Use 'dlab-code list' to see available options."
84
+ )
85
+
86
+ if args.save:
87
+ output = Path(args.save)
88
+ output.write_text(code, encoding="utf-8")
89
+ print(f"Code saved to: {output.resolve()}")
90
+ else:
91
+ print(code)
92
+
93
+ if __name__ == "__main__":
94
+ main()
@@ -0,0 +1,120 @@
1
+ """
2
+ Experiment 10 - LSTM hyperparameter tuning using a LOCAL CSV.
3
+
4
+ CSV format:
5
+ text,label
6
+ """
7
+
8
+ import pandas as pd
9
+ import tensorflow as tf
10
+ from tensorflow import keras
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.preprocessing import LabelEncoder
13
+
14
+ CSV_PATH = "data/sentiment.csv"
15
+ TEXT_COLUMN = "text"
16
+ LABEL_COLUMN = "label"
17
+ MAX_WORDS = 10000
18
+ MAX_LENGTH = 150
19
+
20
+ df = pd.read_csv(CSV_PATH)[[TEXT_COLUMN, LABEL_COLUMN]].dropna()
21
+
22
+ texts = df[TEXT_COLUMN].astype(str).values
23
+ encoder = LabelEncoder()
24
+ labels = encoder.fit_transform(df[LABEL_COLUMN])
25
+
26
+ X_train, X_test, y_train, y_test = train_test_split(
27
+ texts,
28
+ labels,
29
+ test_size=0.2,
30
+ random_state=42,
31
+ stratify=labels,
32
+ )
33
+
34
+ vectorizer = keras.layers.TextVectorization(
35
+ max_tokens=MAX_WORDS,
36
+ output_sequence_length=MAX_LENGTH,
37
+ )
38
+ vectorizer.adapt(X_train)
39
+
40
+ def build_model(embedding_dim, lstm_units, dropout, learning_rate):
41
+ model = keras.Sequential([
42
+ keras.layers.Input(shape=(), dtype=tf.string),
43
+ vectorizer,
44
+ keras.layers.Embedding(
45
+ input_dim=MAX_WORDS,
46
+ output_dim=embedding_dim,
47
+ mask_zero=True,
48
+ ),
49
+ keras.layers.LSTM(lstm_units),
50
+ keras.layers.Dropout(dropout),
51
+ keras.layers.Dense(
52
+ len(encoder.classes_),
53
+ activation="softmax",
54
+ ),
55
+ ])
56
+
57
+ model.compile(
58
+ optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
59
+ loss="sparse_categorical_crossentropy",
60
+ metrics=["accuracy"],
61
+ )
62
+ return model
63
+
64
+ best_accuracy = -1
65
+ best_config = None
66
+
67
+ embedding_dims = [64, 128]
68
+ lstm_units_list = [32, 64]
69
+ dropouts = [0.3, 0.5]
70
+ learning_rates = [0.001, 0.0005]
71
+
72
+ for embedding_dim in embedding_dims:
73
+ for lstm_units in lstm_units_list:
74
+ for dropout in dropouts:
75
+ for learning_rate in learning_rates:
76
+ print(
77
+ f"\nembedding={embedding_dim}, "
78
+ f"LSTM={lstm_units}, dropout={dropout}, "
79
+ f"lr={learning_rate}"
80
+ )
81
+
82
+ model = build_model(
83
+ embedding_dim,
84
+ lstm_units,
85
+ dropout,
86
+ learning_rate,
87
+ )
88
+
89
+ model.fit(
90
+ X_train,
91
+ y_train,
92
+ validation_split=0.2,
93
+ epochs=5,
94
+ batch_size=32,
95
+ verbose=0,
96
+ )
97
+
98
+ _, accuracy = model.evaluate(
99
+ X_test,
100
+ y_test,
101
+ verbose=0,
102
+ )
103
+
104
+ print("Test accuracy:", round(accuracy, 4))
105
+
106
+ if accuracy > best_accuracy:
107
+ best_accuracy = accuracy
108
+ best_config = (
109
+ embedding_dim,
110
+ lstm_units,
111
+ dropout,
112
+ learning_rate,
113
+ )
114
+
115
+ print("\nBest LSTM configuration:")
116
+ print("Embedding dimension:", best_config[0])
117
+ print("LSTM units :", best_config[1])
118
+ print("Dropout :", best_config[2])
119
+ print("Learning rate :", best_config[3])
120
+ print("Test accuracy :", round(best_accuracy, 4))
@@ -0,0 +1,95 @@
1
+ """
2
+ Experiment 10 - LSTM hyperparameter tuning using the Keras IMDB dataset.
3
+ """
4
+
5
+ import numpy as np
6
+ import tensorflow as tf
7
+ from tensorflow import keras
8
+
9
+ MAX_WORDS = 10000
10
+ MAX_LENGTH = 150
11
+
12
+ (x_train, y_train), (x_test, y_test) = keras.datasets.imdb.load_data(
13
+ num_words=MAX_WORDS
14
+ )
15
+
16
+ x_train = keras.preprocessing.sequence.pad_sequences(
17
+ x_train, maxlen=MAX_LENGTH
18
+ )
19
+ x_test = keras.preprocessing.sequence.pad_sequences(
20
+ x_test, maxlen=MAX_LENGTH
21
+ )
22
+
23
+ def build_model(embedding_dim, lstm_units, dropout, learning_rate):
24
+ model = keras.Sequential([
25
+ keras.layers.Input(shape=(MAX_LENGTH,)),
26
+ keras.layers.Embedding(MAX_WORDS, embedding_dim),
27
+ keras.layers.LSTM(lstm_units),
28
+ keras.layers.Dropout(dropout),
29
+ keras.layers.Dense(1, activation="sigmoid"),
30
+ ])
31
+
32
+ model.compile(
33
+ optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
34
+ loss="binary_crossentropy",
35
+ metrics=["accuracy"],
36
+ )
37
+ return model
38
+
39
+ best_accuracy = -1
40
+ best_config = None
41
+
42
+ embedding_dims = [64, 128]
43
+ lstm_units_list = [32, 64]
44
+ dropouts = [0.3, 0.5]
45
+ learning_rates = [0.001, 0.0005]
46
+
47
+ for embedding_dim in embedding_dims:
48
+ for lstm_units in lstm_units_list:
49
+ for dropout in dropouts:
50
+ for learning_rate in learning_rates:
51
+ print(
52
+ f"\nembedding={embedding_dim}, "
53
+ f"LSTM={lstm_units}, dropout={dropout}, "
54
+ f"lr={learning_rate}"
55
+ )
56
+
57
+ model = build_model(
58
+ embedding_dim,
59
+ lstm_units,
60
+ dropout,
61
+ learning_rate,
62
+ )
63
+
64
+ model.fit(
65
+ x_train,
66
+ y_train,
67
+ validation_split=0.2,
68
+ epochs=5,
69
+ batch_size=32,
70
+ verbose=0,
71
+ )
72
+
73
+ _, accuracy = model.evaluate(
74
+ x_test,
75
+ y_test,
76
+ verbose=0,
77
+ )
78
+
79
+ print("Test accuracy:", round(accuracy, 4))
80
+
81
+ if accuracy > best_accuracy:
82
+ best_accuracy = accuracy
83
+ best_config = (
84
+ embedding_dim,
85
+ lstm_units,
86
+ dropout,
87
+ learning_rate,
88
+ )
89
+
90
+ print("\nBest LSTM configuration:")
91
+ print("Embedding dimension:", best_config[0])
92
+ print("LSTM units :", best_config[1])
93
+ print("Dropout :", best_config[2])
94
+ print("Learning rate :", best_config[3])
95
+ print("Test accuracy :", round(best_accuracy, 4))
@@ -0,0 +1,87 @@
1
+ """
2
+ Experiment 5 - CNN image classification using a LOCAL image directory.
3
+
4
+ Expected structure:
5
+ dataset/
6
+ class_a/
7
+ image1.jpg
8
+ image2.jpg
9
+ class_b/
10
+ image3.jpg
11
+ ...
12
+
13
+ Change DATASET_PATH if required.
14
+ """
15
+
16
+ import tensorflow as tf
17
+ from tensorflow import keras
18
+ import matplotlib.pyplot as plt
19
+
20
+ DATASET_PATH = "dataset"
21
+ IMAGE_SIZE = (128, 128)
22
+ BATCH_SIZE = 32
23
+ EPOCHS = 10
24
+
25
+ train_ds = keras.utils.image_dataset_from_directory(
26
+ DATASET_PATH,
27
+ image_size=IMAGE_SIZE,
28
+ batch_size=BATCH_SIZE,
29
+ validation_split=0.2,
30
+ subset="training",
31
+ seed=42,
32
+ )
33
+
34
+ val_ds = keras.utils.image_dataset_from_directory(
35
+ DATASET_PATH,
36
+ image_size=IMAGE_SIZE,
37
+ batch_size=BATCH_SIZE,
38
+ validation_split=0.2,
39
+ subset="validation",
40
+ seed=42,
41
+ )
42
+
43
+ class_names = train_ds.class_names
44
+ num_classes = len(class_names)
45
+
46
+ normalization = keras.layers.Rescaling(1.0 / 255)
47
+ train_ds = train_ds.map(lambda x, y: (normalization(x), y))
48
+ val_ds = val_ds.map(lambda x, y: (normalization(x), y))
49
+
50
+ model = keras.Sequential([
51
+ keras.layers.Input(shape=(*IMAGE_SIZE, 3)),
52
+ keras.layers.Conv2D(32, 3, activation="relu"),
53
+ keras.layers.MaxPooling2D(),
54
+ keras.layers.Conv2D(64, 3, activation="relu"),
55
+ keras.layers.MaxPooling2D(),
56
+ keras.layers.Conv2D(128, 3, activation="relu"),
57
+ keras.layers.MaxPooling2D(),
58
+ keras.layers.Flatten(),
59
+ keras.layers.Dense(128, activation="relu"),
60
+ keras.layers.Dropout(0.5),
61
+ keras.layers.Dense(num_classes, activation="softmax"),
62
+ ])
63
+
64
+ model.compile(
65
+ optimizer="adam",
66
+ loss="sparse_categorical_crossentropy",
67
+ metrics=["accuracy"],
68
+ )
69
+
70
+ model.summary()
71
+
72
+ history = model.fit(
73
+ train_ds,
74
+ validation_data=val_ds,
75
+ epochs=EPOCHS,
76
+ )
77
+
78
+ loss, accuracy = model.evaluate(val_ds)
79
+ print(f"\nValidation accuracy: {accuracy:.4f}")
80
+
81
+ plt.plot(history.history["accuracy"], label="Training")
82
+ plt.plot(history.history["val_accuracy"], label="Validation")
83
+ plt.xlabel("Epoch")
84
+ plt.ylabel("Accuracy")
85
+ plt.legend()
86
+ plt.title("CNN Image Classification - Local Dataset")
87
+ plt.show()
@@ -0,0 +1,60 @@
1
+ """
2
+ Experiment 5 - CNN image classification using the Keras CIFAR-10 dataset.
3
+ """
4
+
5
+ import tensorflow as tf
6
+ from tensorflow import keras
7
+ import matplotlib.pyplot as plt
8
+
9
+ (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
10
+
11
+ class_names = [
12
+ "airplane", "automobile", "bird", "cat", "deer",
13
+ "dog", "frog", "horse", "ship", "truck"
14
+ ]
15
+
16
+ x_train = x_train.astype("float32") / 255.0
17
+ x_test = x_test.astype("float32") / 255.0
18
+ y_train = y_train.flatten()
19
+ y_test = y_test.flatten()
20
+
21
+ model = keras.Sequential([
22
+ keras.layers.Input(shape=(32, 32, 3)),
23
+ keras.layers.Conv2D(32, 3, activation="relu"),
24
+ keras.layers.MaxPooling2D(),
25
+ keras.layers.Conv2D(64, 3, activation="relu"),
26
+ keras.layers.MaxPooling2D(),
27
+ keras.layers.Conv2D(128, 3, activation="relu"),
28
+ keras.layers.MaxPooling2D(),
29
+ keras.layers.Flatten(),
30
+ keras.layers.Dense(128, activation="relu"),
31
+ keras.layers.Dropout(0.5),
32
+ keras.layers.Dense(10, activation="softmax"),
33
+ ])
34
+
35
+ model.compile(
36
+ optimizer="adam",
37
+ loss="sparse_categorical_crossentropy",
38
+ metrics=["accuracy"],
39
+ )
40
+
41
+ model.summary()
42
+
43
+ history = model.fit(
44
+ x_train,
45
+ y_train,
46
+ validation_split=0.2,
47
+ epochs=10,
48
+ batch_size=64,
49
+ )
50
+
51
+ loss, accuracy = model.evaluate(x_test, y_test)
52
+ print(f"\nTest accuracy: {accuracy:.4f}")
53
+
54
+ plt.plot(history.history["accuracy"], label="Training")
55
+ plt.plot(history.history["val_accuracy"], label="Validation")
56
+ plt.xlabel("Epoch")
57
+ plt.ylabel("Accuracy")
58
+ plt.legend()
59
+ plt.title("CNN Image Classification - CIFAR-10")
60
+ plt.show()
@@ -0,0 +1,97 @@
1
+ """
2
+ Experiment 6 - CNN hyperparameter tuning using a LOCAL image directory.
3
+
4
+ Expected structure:
5
+ dataset/
6
+ class_a/
7
+ class_b/
8
+ ...
9
+
10
+ The script performs a small manual grid search over filters,
11
+ dropout, and learning rate.
12
+ """
13
+
14
+ import tensorflow as tf
15
+ from tensorflow import keras
16
+
17
+ DATASET_PATH = "dataset"
18
+ IMAGE_SIZE = (128, 128)
19
+ BATCH_SIZE = 32
20
+ EPOCHS = 5
21
+
22
+ train_ds = keras.utils.image_dataset_from_directory(
23
+ DATASET_PATH,
24
+ image_size=IMAGE_SIZE,
25
+ batch_size=BATCH_SIZE,
26
+ validation_split=0.2,
27
+ subset="training",
28
+ seed=42,
29
+ )
30
+
31
+ val_ds = keras.utils.image_dataset_from_directory(
32
+ DATASET_PATH,
33
+ image_size=IMAGE_SIZE,
34
+ batch_size=BATCH_SIZE,
35
+ validation_split=0.2,
36
+ subset="validation",
37
+ seed=42,
38
+ )
39
+
40
+ num_classes = len(train_ds.class_names)
41
+ normalization = keras.layers.Rescaling(1.0 / 255)
42
+
43
+ train_ds = train_ds.map(lambda x, y: (normalization(x), y))
44
+ val_ds = val_ds.map(lambda x, y: (normalization(x), y))
45
+
46
+ def build_model(filters, dropout):
47
+ return keras.Sequential([
48
+ keras.layers.Input(shape=(*IMAGE_SIZE, 3)),
49
+ keras.layers.Conv2D(filters, 3, activation="relu", padding="same"),
50
+ keras.layers.MaxPooling2D(),
51
+ keras.layers.Conv2D(filters * 2, 3, activation="relu", padding="same"),
52
+ keras.layers.MaxPooling2D(),
53
+ keras.layers.Conv2D(filters * 4, 3, activation="relu", padding="same"),
54
+ keras.layers.MaxPooling2D(),
55
+ keras.layers.Flatten(),
56
+ keras.layers.Dense(128, activation="relu"),
57
+ keras.layers.Dropout(dropout),
58
+ keras.layers.Dense(num_classes, activation="softmax"),
59
+ ])
60
+
61
+ best_accuracy = -1
62
+ best_config = None
63
+
64
+ for filters in [16, 32]:
65
+ for dropout in [0.3, 0.5]:
66
+ for learning_rate in [0.001, 0.0001]:
67
+ print(
68
+ f"\nTesting filters={filters}, dropout={dropout}, "
69
+ f"lr={learning_rate}"
70
+ )
71
+
72
+ model = build_model(filters, dropout)
73
+ model.compile(
74
+ optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
75
+ loss="sparse_categorical_crossentropy",
76
+ metrics=["accuracy"],
77
+ )
78
+
79
+ model.fit(
80
+ train_ds,
81
+ validation_data=val_ds,
82
+ epochs=EPOCHS,
83
+ verbose=0,
84
+ )
85
+
86
+ _, accuracy = model.evaluate(val_ds, verbose=0)
87
+ print("Validation accuracy:", round(accuracy, 4))
88
+
89
+ if accuracy > best_accuracy:
90
+ best_accuracy = accuracy
91
+ best_config = (filters, dropout, learning_rate)
92
+
93
+ print("\nBest CNN configuration:")
94
+ print("Filters :", best_config[0])
95
+ print("Dropout :", best_config[1])
96
+ print("Learning rate :", best_config[2])
97
+ print("Accuracy :", round(best_accuracy, 4))
@@ -0,0 +1,68 @@
1
+ """
2
+ Experiment 6 - CNN hyperparameter tuning using Keras CIFAR-10.
3
+ """
4
+
5
+ import tensorflow as tf
6
+ from tensorflow import keras
7
+
8
+ (x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
9
+
10
+ x_train = x_train.astype("float32") / 255.0
11
+ x_test = x_test.astype("float32") / 255.0
12
+ y_train = y_train.flatten()
13
+ y_test = y_test.flatten()
14
+
15
+ def build_model(filters, dropout):
16
+ return keras.Sequential([
17
+ keras.layers.Input(shape=(32, 32, 3)),
18
+ keras.layers.Conv2D(filters, 3, activation="relu", padding="same"),
19
+ keras.layers.MaxPooling2D(),
20
+ keras.layers.Conv2D(filters * 2, 3, activation="relu", padding="same"),
21
+ keras.layers.MaxPooling2D(),
22
+ keras.layers.Conv2D(filters * 4, 3, activation="relu", padding="same"),
23
+ keras.layers.MaxPooling2D(),
24
+ keras.layers.Flatten(),
25
+ keras.layers.Dense(128, activation="relu"),
26
+ keras.layers.Dropout(dropout),
27
+ keras.layers.Dense(10, activation="softmax"),
28
+ ])
29
+
30
+ best_accuracy = -1
31
+ best_config = None
32
+
33
+ for filters in [16, 32]:
34
+ for dropout in [0.3, 0.5]:
35
+ for learning_rate in [0.001, 0.0001]:
36
+ print(
37
+ f"\nTesting filters={filters}, dropout={dropout}, "
38
+ f"lr={learning_rate}"
39
+ )
40
+
41
+ model = build_model(filters, dropout)
42
+ model.compile(
43
+ optimizer=keras.optimizers.Adam(learning_rate=learning_rate),
44
+ loss="sparse_categorical_crossentropy",
45
+ metrics=["accuracy"],
46
+ )
47
+
48
+ model.fit(
49
+ x_train,
50
+ y_train,
51
+ validation_split=0.1,
52
+ epochs=5,
53
+ batch_size=64,
54
+ verbose=0,
55
+ )
56
+
57
+ _, accuracy = model.evaluate(x_test, y_test, verbose=0)
58
+ print("Test accuracy:", round(accuracy, 4))
59
+
60
+ if accuracy > best_accuracy:
61
+ best_accuracy = accuracy
62
+ best_config = (filters, dropout, learning_rate)
63
+
64
+ print("\nBest CNN configuration:")
65
+ print("Filters :", best_config[0])
66
+ print("Dropout :", best_config[1])
67
+ print("Learning rate :", best_config[2])
68
+ print("Test accuracy :", round(best_accuracy, 4))
@@ -0,0 +1,66 @@
1
+ """
2
+ Experiment 7 - Autoencoder dimensionality reduction on a LOCAL CSV dataset.
3
+
4
+ Expected CSV format:
5
+ feature1,feature2,feature3,...
6
+ numeric features only.
7
+
8
+ Change CSV_PATH as required.
9
+ """
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ import tensorflow as tf
14
+ from tensorflow import keras
15
+ import matplotlib.pyplot as plt
16
+ from sklearn.preprocessing import MinMaxScaler
17
+
18
+ CSV_PATH = "data/features.csv"
19
+ ENCODING_DIM = 2
20
+
21
+ df = pd.read_csv(CSV_PATH)
22
+ X = df.select_dtypes(include=[np.number]).dropna().values
23
+
24
+ scaler = MinMaxScaler()
25
+ X = scaler.fit_transform(X).astype("float32")
26
+
27
+ input_dim = X.shape[1]
28
+
29
+ encoder = keras.Sequential([
30
+ keras.layers.Input(shape=(input_dim,)),
31
+ keras.layers.Dense(128, activation="relu"),
32
+ keras.layers.Dense(32, activation="relu"),
33
+ keras.layers.Dense(ENCODING_DIM, activation="linear"),
34
+ ], name="encoder")
35
+
36
+ decoder = keras.Sequential([
37
+ keras.layers.Input(shape=(ENCODING_DIM,)),
38
+ keras.layers.Dense(32, activation="relu"),
39
+ keras.layers.Dense(128, activation="relu"),
40
+ keras.layers.Dense(input_dim, activation="sigmoid"),
41
+ ], name="decoder")
42
+
43
+ autoencoder = keras.Sequential([encoder, decoder])
44
+
45
+ autoencoder.compile(optimizer="adam", loss="mse")
46
+
47
+ autoencoder.fit(
48
+ X,
49
+ X,
50
+ epochs=20,
51
+ batch_size=32,
52
+ validation_split=0.2,
53
+ )
54
+
55
+ encoded = encoder.predict(X, verbose=0)
56
+ decoded = autoencoder.predict(X, verbose=0)
57
+
58
+ print("Original dimension:", input_dim)
59
+ print("Reduced dimension :", encoded.shape[1])
60
+
61
+ if ENCODING_DIM == 2:
62
+ plt.scatter(encoded[:, 0], encoded[:, 1], s=10)
63
+ plt.xlabel("Encoded feature 1")
64
+ plt.ylabel("Encoded feature 2")
65
+ plt.title("Autoencoder 2D Representation")
66
+ plt.show()