<jupyter_start><jupyter_text>Lets now look into classification.Some of the examples are from [Deep Learning with Python, Second Edition](https://www.manning.com/books/deep-learning-with-python-second-edition?a_aid=keras&a_bid=76564dff).   Classifying movie reviews: A binary classification example  The IMDB dataset **Loading the IMDB dataset** More on the Dataset: https://ai.stanford.edu/~amaas/data/sentiment/<jupyter_code>from tensorflow.keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(
    num_words=10000)
train_data[0]
train_labels[0]
train_labels[1]
max([max(sequence) for sequence in train_data])<jupyter_output><empty_output><jupyter_text>**Decoding reviews back to text**<jupyter_code>word_index = imdb.get_word_index()
reverse_word_index = dict(
    [(value, key) for (key, value) in word_index.items()])
decoded_review = " ".join(
    [reverse_word_index.get(i - 3, "?") for i in train_data[4]])

decoded_review<jupyter_output><empty_output><jupyter_text>Preparing the data What is the problem with this data as it is? We have list of intigers. Each element as long as a given review.  IMDB Dataset: https://www.kaggle.com/datasets/ashirwadsangwan/imdb-dataset?msclkid=67c2fdb7c66911ec9c14c87c755eca0a **Encoding the integer sequences via multi-hot encoding**<jupyter_code>import numpy as np
def vectorize_sequences(sequences, dimension=10000):
    results = np.zeros((len(sequences), dimension))
    for i, sequence in enumerate(sequences):
        for j in sequence:
            results[i, j] = 1.
    return results
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)<jupyter_output><empty_output><jupyter_text>What are we loosing here?  What have we lost with that encoding?<jupyter_code>x_train[0]
y_train = np.asarray(train_labels).astype("float32")
y_test = np.asarray(test_labels).astype("float32")

y_train[0]<jupyter_output><empty_output><jupyter_text>Building your model **Model definition** **Thoughts and tips**  This data is made of binary inputs and one number, scalar outputs. This is a rare and friendly set up.  For this we use dense layers with relu activations. Sigmoid gets the score back to [0,1] for probability.  What about loss? Crossentropy is best for probability problems.  Rmsprop optimizer is a good start for every problem.<jupyter_code>from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(16, activation="relu"),
    layers.Dense(16, activation="relu"),
    layers.Dense(1, activation="sigmoid")
])<jupyter_output><empty_output><jupyter_text>**Compiling the model**<jupyter_code>model.compile(optimizer="rmsprop",
              loss="binary_crossentropy",
              metrics=["accuracy"])<jupyter_output><empty_output><jupyter_text>Try mean_squared_error!  Change the architecture of the network.  Do you have any questions regarding this... guessing match?  Validating your approach **Setting aside a validation set**<jupyter_code>x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]<jupyter_output><empty_output><jupyter_text>**Training your model**<jupyter_code>history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=20,
                    batch_size=512,
                    validation_data=(x_val, y_val))
history_dict = history.history
history_dict.keys()<jupyter_output><empty_output><jupyter_text>**Plotting the training and validation loss**<jupyter_code>import matplotlib.pyplot as plt
history_dict = history.history
loss_values = history_dict["loss"]
val_loss_values = history_dict["val_loss"]
epochs = range(1, len(loss_values) + 1)
plt.plot(epochs, loss_values, "bo", label="Training loss")
plt.plot(epochs, val_loss_values, "b", label="Validation loss")
plt.title("Training and validation loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>**Plotting the training and validation accuracy**<jupyter_code>plt.clf()
acc = history_dict["accuracy"]
val_acc = history_dict["val_accuracy"]
plt.plot(epochs, acc, "bo", label="Training acc")
plt.plot(epochs, val_acc, "b", label="Validation acc")
plt.title("Training and validation accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>**Retraining a model from scratch**<jupyter_code>model = keras.Sequential([
    layers.Dense(16, activation="relu"),
    layers.Dense(16, activation="relu"),
    layers.Dense(1, activation="sigmoid")
])
model.compile(optimizer="rmsprop",
              loss="binary_crossentropy",
              metrics=["accuracy"])
model.fit(x_train, y_train, epochs=4, batch_size=512)
results = model.evaluate(x_test, y_test)
results<jupyter_output><empty_output><jupyter_text>Using a trained model to generate predictions on new data<jupyter_code>model.predict(x_test)<jupyter_output><empty_output><jupyter_text>Classifying newswires: A multiclass classification example  The Reuters dataset **Loading the Reuters dataset** More on the Dataset, cool explained example: https://martin-thoma.com/nlp-reuters/<jupyter_code>from tensorflow.keras.datasets import reuters
(train_data, train_labels), (test_data, test_labels) = reuters.load_data(
    num_words=10000)
len(train_data)
len(test_data)
train_data[10]<jupyter_output><empty_output><jupyter_text>**Decoding newswires back to text**<jupyter_code>word_index = reuters.get_word_index()
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
decoded_newswire = " ".join([reverse_word_index.get(i - 3, "?") for i in
    train_data[0]])

decoded_newswire
train_labels[10]<jupyter_output><empty_output><jupyter_text>Preparing the data **Encoding the input data**<jupyter_code>x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)<jupyter_output><empty_output><jupyter_text>**Encoding the labels** So any idea what to do with the labels?<jupyter_code>def to_one_hot(labels, dimension=46):
    results = np.zeros((len(labels), dimension))
    for i, label in enumerate(labels):
        results[i, label] = 1.
    return results
y_train = to_one_hot(train_labels)
y_test = to_one_hot(test_labels)
from tensorflow.keras.utils import to_categorical
y_train = to_categorical(train_labels)
y_test = to_categorical(test_labels)

y_train[0]<jupyter_output><empty_output><jupyter_text>Building your model **Model definition** Now we have way more classes to work with, and way more info that needs to diffrenciate between the data points.  We need more neurons.<jupyter_code>model = keras.Sequential([
    layers.Dense(64, activation="relu"),
    layers.Dense(64, activation="relu"),
    layers.Dense(46, activation="softmax")
])<jupyter_output><empty_output><jupyter_text>**Compiling the model**<jupyter_code>model.compile(optimizer="rmsprop",
              loss="categorical_crossentropy",
              metrics=["accuracy"])<jupyter_output><empty_output><jupyter_text>Validating your approach **Setting aside a validation set**<jupyter_code>x_val = x_train[:1000]
partial_x_train = x_train[1000:]
y_val = y_train[:1000]
partial_y_train = y_train[1000:]<jupyter_output><empty_output><jupyter_text>**Training the model**<jupyter_code>history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=20,
                    batch_size=512,
                    validation_data=(x_val, y_val))<jupyter_output>Epoch 1/20
16/16 [==============================] - 2s 48ms/step - loss: 2.7815 - accuracy: 0.4308 - val_loss: 1.8570 - val_accuracy: 0.6280
Epoch 2/20
16/16 [==============================] - 0s 29ms/step - loss: 1.4956 - accuracy: 0.7020 - val_loss: 1.3316 - val_accuracy: 0.7210
Epoch 3/20
16/16 [==============================] - 1s 32ms/step - loss: 1.0693 - accuracy: 0.7741 - val_loss: 1.1291 - val_accuracy: 0.7630
Epoch 4/20
16/16 [==============================] - 1s 35ms/step - loss: 0.8338 - accuracy: 0.8291 - val_loss: 1.0247 - val_accuracy: 0.7810
Epoch 5/20
16/16 [==============================] - 1s 33ms/step - loss: 0.6609 - accuracy: 0.8646 - val_loss: 0.9658 - val_accuracy: 0.7950
Epoch 6/20
16/16 [==============================] - 1s 33ms/step - loss: 0.5256 - accuracy: 0.8949 - val_loss: 0.9092 - val_accuracy: 0.8230
Epoch 7/20
16/16 [==============================] - 1s 34ms/step - loss: 0.4226 - accuracy: 0.9119 - val_loss: 0.8971 - val_accuracy: 0.8190
Epoch 8/20
16[...]<jupyter_text>**Plotting the training and validation loss**<jupyter_code>loss = history.history["loss"]
val_loss = history.history["val_loss"]
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, "bo", label="Training loss")
plt.plot(epochs, val_loss, "b", label="Validation loss")
plt.title("Training and validation loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>**Plotting the training and validation accuracy**<jupyter_code>plt.clf()
acc = history.history["accuracy"]
val_acc = history.history["val_accuracy"]
plt.plot(epochs, acc, "bo", label="Training accuracy")
plt.plot(epochs, val_acc, "b", label="Validation accuracy")
plt.title("Training and validation accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>**Retraining a model from scratch**<jupyter_code>model = keras.Sequential([
  layers.Dense(64, activation="relu"),
  layers.Dense(64, activation="relu"),
  layers.Dense(46, activation="softmax")
])
model.compile(optimizer="rmsprop",
              loss="categorical_crossentropy",
              metrics=["accuracy"])
model.fit(x_train,
          y_train,
          epochs=9,
          batch_size=512)
results = model.evaluate(x_test, y_test)
results
import copy
test_labels_copy = copy.copy(test_labels)
np.random.shuffle(test_labels_copy)
hits_array = np.array(test_labels) == np.array(test_labels_copy)
hits_array.mean()<jupyter_output><empty_output><jupyter_text>Generating predictions on new data<jupyter_code>predictions = model.predict(x_test)
predictions[0].shape
np.sum(predictions[0])
np.argmax(predictions[0])<jupyter_output><empty_output><jupyter_text>The importance of having sufficiently large intermediate layers **A model with an information bottleneck**<jupyter_code>model = keras.Sequential([
    layers.Dense(64, activation="relu"),
    layers.Dense(4, activation="relu"),
    layers.Dense(46, activation="softmax")
])
model.compile(optimizer="rmsprop",
              loss="categorical_crossentropy",
              metrics=["accuracy"])
model.fit(partial_x_train,
          partial_y_train,
          epochs=20,
          batch_size=128,
          validation_data=(x_val, y_val))<jupyter_output>Epoch 1/20
63/63 [==============================] - 2s 20ms/step - loss: 2.7647 - accuracy: 0.4342 - val_loss: 2.0372 - val_accuracy: 0.5670
Epoch 2/20
63/63 [==============================] - 1s 14ms/step - loss: 1.7203 - accuracy: 0.5960 - val_loss: 1.6272 - val_accuracy: 0.6150
Epoch 3/20
63/63 [==============================] - 1s 15ms/step - loss: 1.4170 - accuracy: 0.6486 - val_loss: 1.4995 - val_accuracy: 0.6440
Epoch 4/20
63/63 [==============================] - 1s 16ms/step - loss: 1.2546 - accuracy: 0.6688 - val_loss: 1.4457 - val_accuracy: 0.6460
Epoch 5/20
63/63 [==============================] - 1s 17ms/step - loss: 1.1503 - accuracy: 0.7097 - val_loss: 1.4674 - val_accuracy: 0.6600
Epoch 6/20
63/63 [==============================] - 1s 16ms/step - loss: 1.0784 - accuracy: 0.7300 - val_loss: 1.4540 - val_accuracy: 0.6690
Epoch 7/20
63/63 [==============================] - 1s 16ms/step - loss: 1.0175 - accuracy: 0.7398 - val_loss: 1.4807 - val_accuracy: 0.6690
Epoch 8/20
63[...]
{'fraction_non_alphanumeric': 0.15956996529247439, 'fraction_numerical': 0.049521713366629985, 'mean_word_length': 5.392857142857143, 'pattern_counts': {'":': 0, '<': 99, '<?xml version=': 0, '>': 99, 'https://': 4, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '25', 'dir': 'jupyter-structured-clean-dedup', 'id': '276277', 'license': 'MIT', 'n_tokens_mistral': 4510, 'n_tokens_neox': 4041, 'n_words': 848, 'path': 'Classes/Class-04.28/code/classification.ipynb', 'repo_name': 'pamelon/DeepLearning-ALK', 'size': '11813'}