CS计算机代考程序代写 information theory GPU Keras database python deep learning chain W04L1-1-MovieReviews

W04L1-1-MovieReviews

Classifying movie reviews: a binary classification example¶
This notebook is based on the code samples found in Chapter 3, Section 5 of Deep Learning with Python and hosted on https://github.com/fchollet/deep-learning-with-python-notebooks.

Note that the original text features far more content, in particular further explanations and figures.

In [1]:

import tensorflow as tf
tf.config.experimental.list_physical_devices()

Out[1]:

[PhysicalDevice(name=’/physical_device:CPU:0′, device_type=’CPU’),
PhysicalDevice(name=’/physical_device:XLA_CPU:0′, device_type=’XLA_CPU’),
PhysicalDevice(name=’/physical_device:GPU:0′, device_type=’GPU’),
PhysicalDevice(name=’/physical_device:XLA_GPU:0′, device_type=’XLA_GPU’)]

In [2]:

from tensorflow import keras
keras.__version__

Out[2]:

‘2.3.0-tf’

Two-class classification, or binary classification, may be the most widely applied kind of machine learning problem. In this example, we
will learn to classify movie reviews into “positive” reviews and “negative” reviews, just based on the text content of the reviews.

The IMDB dataset¶
We’ll be working with “IMDB dataset”, a set of 50,000 highly-polarized reviews from the Internet Movie Database. They are split into 25,000
reviews for training and 25,000 reviews for testing, each set consisting in 50% negative and 50% positive reviews.

The following code will load the dataset (when you run it for the first time, about 80MB of data will be downloaded to your machine):

Why do we have these two separate training and test sets? You should never test a machine learning model on the same data that you used to
train it! Just because a model performs well on its training data doesn’t mean that it will perform well on data it has never seen, and
what you actually care about is your model’s performance on new data (since you already know the labels of your training data — obviously
you don’t need your model to predict those). For instance, it is possible that your model could end up merely memorizing a mapping between
your training samples and their targets — which would be completely useless for the task of predicting targets for data never seen before.
We will go over this point in much more detail in the next chapter.

The IMDB dataset comes packaged with Keras. It has already been preprocessed: the reviews (sequences of words)
have been turned into sequences of integers, where each integer stands for a specific word in a dictionary.

In [3]:

from tensorflow.keras.datasets import imdb

(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

The argument num_words=10000 means that we will only keep the top 10,000 most frequently occurring words in the training data. Rare words
will be discarded. This allows us to work with vector data of manageable size.

The variables train_data and test_data are lists of reviews, each review being a list of word indices (encoding a sequence of words).

In [4]:

train_data[0][:10]

Out[4]:

[1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65]

train_labels and test_labels are lists of 0s and 1s, where 0 stands for “negative” and 1 stands for “positive”:

In [5]:

train_labels[0]

Out[5]:

1

Since we restricted ourselves to the top 10,000 most frequent words, no word index will exceed 10,000:

In [6]:

max([max(sequence) for sequence in train_data])

Out[6]:

9999

For kicks, here’s how you can quickly decode one of these reviews back to English words:

In [7]:

# word_index is a dictionary mapping words to an integer index
word_index = imdb.get_word_index()
# We reverse it, mapping integer indices to words
reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])
# We decode the review; note that our indices were offset by 3
# because 0, 1 and 2 are reserved indices for “padding”, “start of sequence”, and “unknown”.
decoded_review = ‘ ‘.join([reverse_word_index.get(i – 3, ‘?’) for i in train_data[0]])

In [8]:

decoded_review

Out[8]:

“? this film was just brilliant casting location scenery story direction everyone’s really suited the part they played and you could just imagine being there robert ? is an amazing actor and now the same being director ? father came from the same scottish island as myself so i loved the fact there was a real connection with this film the witty remarks throughout the film were great it was just brilliant so much that i bought the film as soon as it was released for ? and would recommend it to everyone to watch and the fly fishing was amazing really cried at the end it was so sad and you know what they say if you cry at a film it must have been good and this definitely was also ? to the two little boy’s that played the ? of norman and paul they were just brilliant children are often left out of the ? list i think because the stars that play them all grown up are such a big profile for the whole film but these children are amazing and should be praised for what they have done don’t you think the whole story was so lovely because it was true and was someone’s life after all that was shared with us all”

Preparing the data¶
Currently each document is represented as a sequence of integers (the word indices). We must convert it into a vector.

We will use a variant of one-hot encoding where each element of the vector represents whether the word is in the document (1) or not (0).

For example, the sequence [3, 5] is converted into a 10,000-dimensional vector that would be all-zeros except for indices 3 and 5, which would be ones. Due to the requirements of keras, we must use float numbers (not integers).

In [9]:

import numpy as np

def vectorize_sequences(sequences, dimension=10000):
# Create an all-zero matrix of shape (len(sequences), dimension)
results = np.zeros((len(sequences), dimension))
for i, sequence in enumerate(sequences):
results[i, sequence] = 1. # set specific indices of results[i] to 1s
return results

# Our vectorized training data
x_train = vectorize_sequences(train_data)
# Our vectorized test data
x_test = vectorize_sequences(test_data)

Note the following from the above code:

enumerate(list) is a simple way to iterate over all elements of a list and find the position of each element. For example:

In [10]:

for i, x in enumerate([‘a’, ‘b’, ‘c’]):
print(i, x)

0 a
1 b
2 c

We can set multiple elements of a numpy array to 1 by using a list of indices. The following code illustrates this:

In [11]:

import numpy as np
a = np.zeros(10)
a

Out[11]:

array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

In [12]:

a[[2,5,6]] = 1
a

Out[12]:

array([0., 0., 1., 0., 0., 1., 1., 0., 0., 0.])

Here’s what our samples look like now:

In [13]:

x_train[0]

Out[13]:

array([0., 1., 1., …, 0., 0., 0.])

We should also vectorize our labels, which is straightforward:

In [14]:

# Our vectorized labels
y_train = np.asarray(train_labels).astype(‘float32’)
y_test = np.asarray(test_labels).astype(‘float32′)

In [15]:

y_train[:5]

Out[15]:

array([1., 0., 0., 1., 0.], dtype=float32)

Now our data is ready to be fed into a neural network.

Building our network¶
Our input data is simply vectors, and our labels are scalars (1s and 0s): this is the easiest setup you will ever encounter. A type of
network that performs well on such a problem would be a simple stack of fully-connected (Dense) layers with relu activations: Dense(16,
activation=’relu’)

The argument being passed to each Dense layer (16) is the number of “hidden units” of the layer. What’s a hidden unit? It’s a dimension
in the representation space of the layer.

Each Dense layer with a relu activation implements the following chain of tensor operations:

output = relu(dot(W, input) + b)

Having 16 hidden units means that the weight matrix W will have shape (input_dimension, 16), i.e. the dot product with W will project the
input data onto a 16-dimensional representation space (and then we would add the bias vector b and apply the relu operation). You can
intuitively understand the dimensionality of your representation space as “how much freedom you are allowing the network to have when
learning internal representations”. Having more hidden units (a higher-dimensional representation space) allows your network to learn more
complex representations, but it makes your network more computationally expensive and may lead to learning unwanted patterns (patterns that
will improve performance on the training data but not on the test data).

There are two key architecture decisions to be made about such stack of dense layers:

How many layers to use.
How many “hidden units” to chose for each layer.

For this problem, we will make the following architecture choice:
two intermediate layers with 16 hidden units each,
and a third layer which will output the scalar prediction regarding the sentiment of the current review.
The intermediate layers will use relu as their “activation function”,
and the final layer will use a sigmoid activation so as to output a probability
(a score between 0 and 1, indicating how likely the sample is to have the target “1”, i.e. how likely the review is to be positive).
A relu (rectified linear unit) is a function meant to zero-out negative values,
while a sigmoid “squashes” arbitrary values into the [0, 1] interval, thus outputting something that can be interpreted as a probability.

Here’s what our network looks like:

Before designing the model we need to configure Tensorflow with the following code. This is some piece of “magic” that you need to insert so that Tensorflow works well with some GPU configurations.

In [16]:

physical_devices = tf.config.list_physical_devices(‘GPU’)
tf.config.experimental.set_memory_growth(physical_devices[0], enable=True)

Finally, here’s the Keras implementation:

In [17]:

from tensorflow.keras import models
from tensorflow.keras import layers

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’))

The above code specifies a sequence of three dense layers.

The first two layers have 16 hidden units, the last layer has 1 hidden unit.
We need to specify the shape of the input to the first layer. In our case, the input is a vector with 10,000 elements. Keras can then determine the shape of the input to the subsequent layers, because it knows that the output of the first layer is 16 cells, so this is the input to the second layer.
the output of the second layer is 16 cells, so this is the output to the third layer.

Note how we specify the activation function to each layer. It is important that the activation function of the last layer is a sigmoid activation. This makes it possible for the system to output a probability. The sigmoid activation function is normally used for binary classification like in this example.

To make our network ready for training, we need to pick three more things, as part of the “compilation” step:

A loss function: this is how the network will be able to measure how good a job it is doing on its training data, and thus how it will be
able to steer itself in the right direction. We will use binary crossentropy, which is a common loss function for binary classification. It isn’t the only viable choice: you could use, for instance, mean_squared_error. But crossentropy is usually the best choice when you are dealing with models that output probabilities. Crossentropy is a quantity from the field of Information Theory, that measures the “distance” between probability distributions, or in our case, between the ground-truth distribution and our predictions.
An optimizer: this is the mechanism through which the network will update itself based on the data it sees and its loss function. We will use rmsprop, which is a simple optimiser. There are other optimisers that you can try, you can find them in the documentation of keras: https://keras.io/api/optimizers/
Metrics to monitor during training and testing. Here we will only care about accuracy (the fraction of the images that were correctly
classified).

Here’s the step where we configure our model with the rmsprop optimizer and the binary_crossentropy loss function. Note that we will
also monitor accuracy during training.

In [18]:

model.compile(optimizer=’rmsprop’,
loss=’binary_crossentropy’,
metrics=[‘accuracy’])

We are passing our optimizer, loss function and metrics as strings, which is possible because rmsprop, binary_crossentropy and
accuracy are packaged as part of Keras.

Sometimes you may want to configure the parameters of your optimizer, or pass a custom loss
function or metric function. This former can be done by passing an optimizer class instance as the optimizer argument:

In [19]:

from tensorflow.keras import optimizers

model.compile(optimizer=optimizers.RMSprop(lr=0.001),
loss=’binary_crossentropy’,
metrics=[‘accuracy’])

The latter can be done by passing function objects as the loss or metrics arguments:

In [20]:

from tensorflow.keras import losses
from tensorflow.keras import metrics

model.compile(optimizer=optimizers.RMSprop(lr=0.001),
loss=losses.binary_crossentropy,
metrics=[metrics.binary_accuracy])

We can now check that the model is what we expect by inspecting the summary produced by Tensorflow Keras:

In [21]:

model.summary()

Model: “sequential”
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense (Dense) (None, 16) 160016
_________________________________________________________________
dense_1 (Dense) (None, 16) 272
_________________________________________________________________
dense_2 (Dense) (None, 1) 17
=================================================================
Total params: 160,305
Trainable params: 160,305
Non-trainable params: 0
_________________________________________________________________

There are 160,305 parameters. Can you work out why? (hint: note that all nodes of each layer are connected to the nodes of the next layer, and there is an additional hidden node in each layer that represents the bias)

Validating our approach¶
In order to monitor during training the accuracy of the model on data that it has never seen before, we will create a “validation set” by
setting apart 10,000 samples from the original training data:

In [22]:

x_val = x_train[:10000]
partial_x_train = x_train[10000:]

y_val = y_train[:10000]
partial_y_train = y_train[10000:]

We will now train our model for 20 epochs (20 iterations over all samples in the x_train and y_train tensors), in mini-batches of 512
samples. At this same time we will monitor loss and accuracy on the 10,000 samples that we set apart. This is done by passing the
validation data as the validation_data argument:

In [23]:

history = model.fit(partial_x_train,
partial_y_train,
epochs=20,
batch_size=512,
validation_data=(x_val, y_val))

Epoch 1/20
30/30 [==============================] – 1s 37ms/step – loss: 0.5211 – binary_accuracy: 0.7875 – val_loss: 0.4037 – val_binary_accuracy: 0.8658
Epoch 2/20
30/30 [==============================] – 1s 30ms/step – loss: 0.3159 – binary_accuracy: 0.9015 – val_loss: 0.3105 – val_binary_accuracy: 0.8859
Epoch 3/20
30/30 [==============================] – 1s 26ms/step – loss: 0.2310 – binary_accuracy: 0.9259 – val_loss: 0.2852 – val_binary_accuracy: 0.8870
Epoch 4/20
30/30 [==============================] – 1s 26ms/step – loss: 0.1826 – binary_accuracy: 0.9427 – val_loss: 0.2771 – val_binary_accuracy: 0.8865
Epoch 5/20
30/30 [==============================] – 1s 29ms/step – loss: 0.1491 – binary_accuracy: 0.9514 – val_loss: 0.2777 – val_binary_accuracy: 0.8889
Epoch 6/20
30/30 [==============================] – 1s 23ms/step – loss: 0.1220 – binary_accuracy: 0.9629 – val_loss: 0.2906 – val_binary_accuracy: 0.8864
Epoch 7/20
30/30 [==============================] – 1s 24ms/step – loss: 0.1052 – binary_accuracy: 0.9661 – val_loss: 0.3168 – val_binary_accuracy: 0.8809
Epoch 8/20
30/30 [==============================] – 1s 24ms/step – loss: 0.0847 – binary_accuracy: 0.9762 – val_loss: 0.3217 – val_binary_accuracy: 0.8823
Epoch 9/20
30/30 [==============================] – 1s 25ms/step – loss: 0.0742 – binary_accuracy: 0.9794 – val_loss: 0.3517 – val_binary_accuracy: 0.8765
Epoch 10/20
30/30 [==============================] – 1s 24ms/step – loss: 0.0616 – binary_accuracy: 0.9836 – val_loss: 0.3654 – val_binary_accuracy: 0.8794
Epoch 11/20
30/30 [==============================] – 1s 25ms/step – loss: 0.0522 – binary_accuracy: 0.9874 – val_loss: 0.4046 – val_binary_accuracy: 0.8702
Epoch 12/20
30/30 [==============================] – 1s 24ms/step – loss: 0.0410 – binary_accuracy: 0.9907 – val_loss: 0.4211 – val_binary_accuracy: 0.8745
Epoch 13/20
30/30 [==============================] – 1s 26ms/step – loss: 0.0355 – binary_accuracy: 0.9918 – val_loss: 0.4630 – val_binary_accuracy: 0.8738
Epoch 14/20
30/30 [==============================] – 1s 31ms/step – loss: 0.0281 – binary_accuracy: 0.9950 – val_loss: 0.4887 – val_binary_accuracy: 0.8688
Epoch 15/20
30/30 [==============================] – 1s 23ms/step – loss: 0.0252 – binary_accuracy: 0.9954 – val_loss: 0.5282 – val_binary_accuracy: 0.8669
Epoch 16/20
30/30 [==============================] – 1s 23ms/step – loss: 0.0216 – binary_accuracy: 0.9958 – val_loss: 0.5461 – val_binary_accuracy: 0.8674
Epoch 17/20
30/30 [==============================] – 1s 23ms/step – loss: 0.0145 – binary_accuracy: 0.9979 – val_loss: 0.5777 – val_binary_accuracy: 0.8660
Epoch 18/20
30/30 [==============================] – 1s 23ms/step – loss: 0.0128 – binary_accuracy: 0.9987 – val_loss: 0.6077 – val_binary_accuracy: 0.8653
Epoch 19/20
30/30 [==============================] – 1s 23ms/step – loss: 0.0116 – binary_accuracy: 0.9981 – val_loss: 0.6413 – val_binary_accuracy: 0.8657
Epoch 20/20
30/30 [==============================] – 1s 22ms/step – loss: 0.0063 – binary_accuracy: 0.9997 – val_loss: 0.6830 – val_binary_accuracy: 0.8657

On CPU, this will take less than two seconds per epoch — training is over in 20 seconds. At the end of every epoch, there is a slight pause
as the model computes its loss and accuracy on the 10,000 samples of the validation data.

4 quantities are being displayed during training:

the “loss” of the network over the training data, and the accuracy of the network over
the training data.
the “loss” and accuracy of the network over the validation data.

Note that the call to model.fit() returns a History object. This object has a member history, which is a dictionary containing data
about everything that happened during training. Let’s take a look at it:

In [24]:

history_dict = history.history
history_dict.keys()

Out[24]:

dict_keys([‘loss’, ‘binary_accuracy’, ‘val_loss’, ‘val_binary_accuracy’])

It contains 4 entries: one per metric that was being monitored, during training and during validation.

Let’s use Matplotlib to plot the
training and validation loss side by side, as well as the training and validation accuracy:

In [25]:

%matplotlib inline
import matplotlib.pyplot as plt

acc = history.history[‘binary_accuracy’]
val_acc = history.history[‘val_binary_accuracy’]
loss = history.history[‘loss’]
val_loss = history.history[‘val_loss’]

epochs = range(1, len(acc) + 1)

# “bo” is for “blue dot”
plt.plot(epochs, loss, ‘bo’, label=’Training loss’)
# b is for “solid blue line”
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()

In [26]:

plt.clf() # clear figure
acc_values = history_dict[‘binary_accuracy’]
val_acc_values = history_dict[‘val_binary_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(‘Loss’)
plt.legend()

plt.show()

The dots are the training loss and accuracy, while the solid lines are the validation loss and accuracy. Note that your own results may vary
slightly due to a different random initialization of your network.

As you can see, the training loss decreases with every epoch and the training accuracy increases with every epoch. That’s what you would
expect when running gradient descent optimization — the quantity you are trying to minimize should get lower with every iteration. But that
isn’t the case for the validation loss and accuracy: they seem to peak at the fourth epoch. This is an example of what we were warning
against earlier: a model that performs better on the training data isn’t necessarily a model that will do better on data it has never seen
before. In precise terms, what you are seeing is “overfitting”: after the second epoch, we are over-optimizing on the training data, and we
ended up learning representations that are specific to the training data and do not generalize to data outside of the training set.

In this case, to prevent overfitting, we could simply stop training after three epochs.

Let’s train a new network from scratch for four epochs, then evaluate it on our test data:

In [30]:

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’))

model.compile(optimizer=’rmsprop’,
loss=’binary_crossentropy’,
metrics=[‘accuracy’])

model.fit(x_train, y_train, epochs=4, batch_size=512)
test_loss, test_accuracy = model.evaluate(x_test, y_test)

Epoch 1/4
49/49 [==============================] – 0s 9ms/step – loss: 0.4256 – accuracy: 0.8243
Epoch 2/4
49/49 [==============================] – 0s 8ms/step – loss: 0.2483 – accuracy: 0.9126
Epoch 3/4
49/49 [==============================] – 0s 9ms/step – loss: 0.1919 – accuracy: 0.9322
Epoch 4/4
49/49 [==============================] – 0s 8ms/step – loss: 0.1655 – accuracy: 0.9403
782/782 [==============================] – 2s 2ms/step – loss: 0.3411 – accuracy: 0.8663

In [31]:

print(‘test_accuracy:’, test_accuracy)

test_accuracy: 0.8662800192832947

Our fairly naive approach achieves an accuracy of 87%. With state-of-the-art approaches, one should be able to get close to 95%.

Using a trained network to generate predictions on new data¶
After having trained a network, you will want to use it in a practical setting. You can generate the likelihood of reviews being positive
by using the predict method:

In [34]:

model.predict(x_test)

Out[34]:

array([[0.13390556],
[0.99959666],
[0.3760867 ],
…,
[0.06444773],
[0.03531824],
[0.327287 ]], dtype=float32)

The output is saying,for every sample, what is the probability that the review is positive.

As you can see, the network is very confident for some samples (0.99 or more, or 0.01 or less) but less confident for others (0.6, 0.4).

Further experiments¶
We were using 2 hidden layers. Try to use 1 or 3 hidden layers and see how it affects validation and test accuracy.
Try to use layers with more hidden units or less hidden units: 32 units, 64 units…
Try to use the mse loss function instead of binary_crossentropy.
Try to use the tanh activation (an activation that was popular in the early days of neural networks) instead of relu.

These experiments will help convince you that the architecture choices we have made are all fairly reasonable, although they can still be
improved!

Conclusions¶
Here’s what you should take away from this example:

There’s usually quite a bit of preprocessing you need to do on your raw data in order to be able to feed it — as tensors — into a neural
network. In the case of sequences of words, they can be encoded as binary vectors — but there are other encoding options too.
Stacks of Dense layers with relu activations can solve a wide range of problems (including sentiment classification), and you will
likely use them frequently.
In a binary classification problem (two output classes), your network should end with a Dense layer with 1 unit and a sigmoid activation,
i.e. the output of your network should be a scalar between 0 and 1, encoding a probability.

With such a scalar sigmoid output, on a binary classification problem, the loss function you should use is binary_crossentropy.
The rmsprop optimizer is generally a good enough choice of optimizer, whatever your problem. That’s one less thing for you to worry
about.
As they get better on their training data, neural networks eventually start overfitting and end up obtaining increasingly worse results on data
never-seen-before. Make sure to always monitor performance on data that is outside of the training set.

In [ ]: