<jupyter_start><jupyter_text>Part 1: import and observe data Import the data<jupyter_code>from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)<jupyter_output><__array_function__ internals>:5: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\keras\datasets\imdb.py:159: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray.
  x_train, y_train = np.array(xs[:idx]), np.array(labels[:idx])
C:\ProgramData\Anaconda3\envs\tf\lib\site-packages\tensorflow\python\keras\datasets\imdb.py:160: VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprec[...]<jupyter_text>Take a look at the dataData is stored as nested tuples; values are integers that correspond to individual words;a dictionary is provided to find the corresponding relationship;0 stands for negative review,1 stands for positive review;<jupyter_code>b = [len(a) for a in train_data]
print(max(b), min(b), len(b))
print(train_data[:2])
print(len(train_labels))
print(train_labels[:5])<jupyter_output>25000
[1 0 0 1 0]<jupyter_text>Check the corresponding English words.<jupyter_code>word_index = imdb.get_word_index()
print(list(word_index.items())[:10])
reverse_word_index = {val: key for (key, val) in word_index.items()}
print([reverse_word_index[i] for i in train_data[0]])<jupyter_output>[('fawn', 34701), ('tsukino', 52006), ('nunnery', 52007), ('sonja', 16816), ('vani', 63951), ('woods', 1408), ('spiders', 16115), ('hanging', 2345), ('woody', 2289), ('trawling', 52008)]
['the', 'as', 'you', 'with', 'out', 'themselves', 'powerful', 'lets', 'loves', 'their', 'becomes', 'reaching', 'had', 'journalist', 'of', 'lot', 'from', 'anyone', 'to', 'have', 'after', 'out', 'atmosphere', 'never', 'more', 'room', 'and', 'it', 'so', 'heart', 'shows', 'to', 'years', 'of', 'every', 'never', 'going', 'and', 'help', 'moments', 'or', 'of', 'every', 'chest', 'visual', 'movie', 'except', 'her', 'was', 'several', 'of', 'enough', 'more', 'with', 'is', 'now', 'current', 'film', 'as', 'you', 'of', 'mine', 'potentially', 'unfortunately', 'of', 'you', 'than', 'him', 'that', 'with', 'out', 'themselves', 'her', 'get', 'for', 'was', 'camp', 'of', 'you', 'movie', 'sometimes', 'movie', 'that', 'with', 'scary', 'but', 'and', 'to', 'story', 'wonderful', 'that', 'in', 'seeing', 'in', 'character', 'to', 'o[...]<jupyter_text>Part 2: Prepare the dataconvert input to tensor;one-hot encode<jupyter_code>import numpy as np
def vectorize_sequence(sequences, dimension=10000):
    result = np.zeros((len(sequences), dimension))
    for i in range(len(sequences)):
        for w in sequences[i]:
            result[(i, w)] = 1
    return result

x_train = vectorize_sequence(train_data)
x_test = vectorize_sequence(test_data)
x_train[:2]
x_test[:2]
y_train = np.array(train_labels).astype('float32')
y_test = np.array(test_labels).astype('float32')<jupyter_output><empty_output><jupyter_text>Part 3: Build and train the neural network* Two intermediate dense layers with 16 hidden units each* A third layer will output the scalar prediction regarding the sentiment of the current review* intermediate layers will use "relu" activation function* final layer uses sigmoid function<jupyter_code>from keras import models
from keras import layers

# build the model
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

# compile the model
model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])
# validating the approach
# set aside a validation set

x_val = x_train[:10000]
y_val = y_train[:10000]

partial_x_train = x_train[10000:]
partial_y_train = y_train[10000:]
# train the validation model
history = model.fit(partial_x_train,
                    partial_y_train,
                    epochs=4,
                    batch_size=512,
                    validation_data=(x_val, y_val))
# get training history
history_dict = history.history
history_dict.keys()<jupyter_output><empty_output><jupyter_text>Plot 1: training and validation loss<jupyter_code># plot the training and validation loss

import matplotlib.pyplot as plt
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']

epochs = range(1, 5)

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>Plot 2: training and validation accuracy<jupyter_code># plot the training and validation accuracy

plt.clf()   # clears the figure
acc_values = history_dict['accuracy']
val_acc_values = history_dict['val_accuracy']

plt.plot(epochs, acc_values, 'bo', label="Training acc")
plt.plot(epochs, val_acc_values, '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>Evaluate the trained model - while validating<jupyter_code>results = model.evaluate(x_test, y_test)
print(results)<jupyter_output>782/782 [==============================] - 2s 2ms/step - loss: 0.3193 - accuracy: 0.8693: 0s - loss: 0
[0.3193119466304779, 0.8692799806594849]<jupyter_text>Train the model on the entire training set<jupyter_code># build the model
model2 = models.Sequential()
model2.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model2.add(layers.Dense(16, activation='relu'))
model2.add(layers.Dense(1, activation='sigmoid'))

# compile the model
model2.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])



history2 = model2.fit(x_train,
                    y_train,
                    epochs=4,
                    batch_size=512)

results = model2.evaluate(x_test, y_test)
print(results)<jupyter_output>Epoch 1/4
49/49 [==============================] - 0s 8ms/step - loss: 0.4396 - accuracy: 0.8204
Epoch 2/4
49/49 [==============================] - 0s 8ms/step - loss: 0.2523 - accuracy: 0.9103
Epoch 3/4
49/49 [==============================] - 0s 8ms/step - loss: 0.1941 - accuracy: 0.9308
Epoch 4/4
49/49 [==============================] - 0s 7ms/step - loss: 0.1636 - accuracy: 0.9410
782/782 [==============================] - 1s 849us/step - loss: 0.2963 - accuracy: 0.8823
[0.29633039236068726, 0.882319986820221]<jupyter_text>Generate Predictions<jupyter_code>print(model.predict(x_test))<jupyter_output>[[3.2472014e-03]
 [1.0000000e+00]
 [9.8970866e-01]
 ...
 [3.5217404e-04]
 [2.4462044e-03]
 [7.8724790e-01]]
{'fraction_non_alphanumeric': 0.1723808222920366, 'fraction_numerical': 0.05395437781723808, 'mean_word_length': 5.602344454463481, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 36, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '105588', 'license': 'MIT', 'n_tokens_mistral': 2779, 'n_tokens_neox': 2457, 'n_words': 624, 'path': 'Project 01 Movie Reviews Classifier.ipynb', 'repo_name': 'Linchin/Deep-Learning-with-Python', 'size': '7321'}