NT1_keras下搭建一个3层模型并且修改。

In [1]:
import keraskeras.__version__
C:\ProgramData\Anaconda3\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.  from ._conv import register_converters as _register_convertersUsing TensorFlow backend.
Out[1]:
'2.1.5'

Classifying movie reviews: a binary classification example

This notebook contains the code samples found in Chapter 3, Section 5 of Deep Learning with Python. Note that the original text features far more content, in particular further explanations and figures: in this notebook, you will only find source code and related comments.


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.

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.

Just like the MNIST dataset, 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.

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

In [2]:
from keras.datasets import imdb(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
A local file was found, but it seems to be incomplete or outdated because the auto file hash does not match the original value of 599dadb1135973df5b59232a0e9a887c so we will re-download the data.Downloading data from https://s3.amazonaws.com/text-datasets/imdb.npz17465344/17464789 [==============================] - 12s 1us/step

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). train_labels and test_labels are lists of 0s and 1s, where 0 stands for "negative" and 1 stands for "positive":

In [3]:
train_data[0]
Out[3]:
[1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 2, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 2, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38, 76, 15, 13, 1247, 4, 22, 17, 515, 17, 12, 16, 626, 18, 2, 5, 62, 386, 12, 8, 316, 8, 106, 5, 4, 2223, 5244, 16, 480, 66, 3785, 33, 4, 130, 12, 16, 38, 619, 5, 25, 124, 51, 36, 135, 48, 25, 1415, 33, 6, 22, 12, 215, 28, 77, 52, 5, 14, 407, 16, 82, 2, 8, 4, 107, 117, 5952, 15, 256, 4, 2, 7, 3766, 5, 723, 36, 71, 43, 530, 476, 26, 400, 317, 46, 7, 4, 2, 1029, 13, 104, 88, 4, 381, 15, 297, 98, 32, 2071, 56, 26, 141, 6, 194, 7486, 18, 4, 226, 22, 21, 134, 476, 26, 480, 5, 144, 30, 5535, 18, 51, 36, 28, 224, 92, 25, 104, 4, 226, 65, 16, 38, 1334, 88, 12, 16, 283, 5, 16, 4472, 113, 103, 32, 15, 16, 5345, 19, 178, 32]
In [4]:
train_labels[0]
Out[4]:
1

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

In [5]:
max([max(sequence) for sequence in train_data])
Out[5]:
9999

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

In [6]:
# word_index is a dictionary mapping words to an integer indexword_index = imdb.get_word_index()# We reverse it, mapping integer indices to wordsreverse_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]])
Downloading data from https://s3.amazonaws.com/text-datasets/imdb_word_index.json1646592/1641221 [==============================] - 6s 3us/step
In [7]:
decoded_review
Out[7]:
"? 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

We cannot feed lists of integers into a neural network. We have to turn our lists into tensors. There are two ways we could do that:

  • We could pad our lists so that they all have the same length, and turn them into an integer tensor of shape (samples, word_indices), then use as first layer in our network a layer capable of handling such integer tensors (the Embedding layer, which we will cover in detail later in the book).
  • We could one-hot-encode our lists to turn them into vectors of 0s and 1s. Concretely, this would mean for instance turning the sequence [3, 5] into a 10,000-dimensional vector that would be all-zeros except for indices 3 and 5, which would be ones. Then we could use as first layer in our network a Dense layer, capable of handling floating point vector data.

We will go with the latter solution. Let's vectorize our data, which we will do manually for maximum clarity:

In [8]:
import numpy as npdef 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 datax_train = vectorize_sequences(train_data)# Our vectorized test datax_test = vectorize_sequences(test_data)

Here's what our samples look like now:

In [9]:
x_train[0]
Out[9]:
array([0., 1., 1., ..., 0., 0., 0.])

We should also vectorize our labels, which is straightforward:

In [10]:
# Our vectorized labelsy_train = np.asarray(train_labels).astype('float32')y_test = np.asarray(test_labels).astype('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. You may remember from the previous chapter that each such 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.

In the next chapter, you will learn formal principles to guide you in making these choices. For the time being, you will have to trust us with 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:

3-layer network

And here's the Keras implementation, very similar to the MNIST example you saw previously:

In [11]:
from keras import modelsfrom keras import layersmodel = 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'))

Lastly, we need to pick a loss function and an optimizer. Since we are facing a binary classification problem and the output of our network is a probability (we end our network with a single-unit layer with a sigmoid activation), is it best to use the binary_crossentropy loss. 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.

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 [12]:
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 [13]:
from keras import optimizersmodel.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 [14]:
from keras import lossesfrom keras import metricsmodel.compile(optimizer=optimizers.RMSprop(lr=0.001),              loss=losses.binary_crossentropy,              metrics=[metrics.binary_accuracy])

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 [15]:
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 [16]:
history = model.fit(partial_x_train,                    partial_y_train,                    epochs=20,                    batch_size=512,                    validation_data=(x_val, y_val))
Train on 15000 samples, validate on 10000 samplesEpoch 1/2015000/15000 [==============================] - 2s 153us/step - loss: 0.5084 - binary_accuracy: 0.7813 - val_loss: 0.3797 - val_binary_accuracy: 0.8684Epoch 2/2015000/15000 [==============================] - 2s 150us/step - loss: 0.3004 - binary_accuracy: 0.9047 - val_loss: 0.3004 - val_binary_accuracy: 0.8897Epoch 3/2015000/15000 [==============================] - 2s 156us/step - loss: 0.2179 - binary_accuracy: 0.9285 - val_loss: 0.3085 - val_binary_accuracy: 0.8711Epoch 4/2015000/15000 [==============================] - 2s 138us/step - loss: 0.1750 - binary_accuracy: 0.9437 - val_loss: 0.2840 - val_binary_accuracy: 0.8832Epoch 5/2015000/15000 [==============================] - 2s 144us/step - loss: 0.1427 - binary_accuracy: 0.9543 - val_loss: 0.2841 - val_binary_accuracy: 0.8872Epoch 6/2015000/15000 [==============================] - 2s 138us/step - loss: 0.1150 - binary_accuracy: 0.9650 - val_loss: 0.3166 - val_binary_accuracy: 0.8772Epoch 7/2015000/15000 [==============================] - 2s 139us/step - loss: 0.0980 - binary_accuracy: 0.9705 - val_loss: 0.3127 - val_binary_accuracy: 0.8846Epoch 8/2015000/15000 [==============================] - 2s 132us/step - loss: 0.0807 - binary_accuracy: 0.9763 - val_loss: 0.3859 - val_binary_accuracy: 0.8649Epoch 9/2015000/15000 [==============================] - 2s 141us/step - loss: 0.0661 - binary_accuracy: 0.9821 - val_loss: 0.3635 - val_binary_accuracy: 0.8782Epoch 10/2015000/15000 [==============================] - 2s 136us/step - loss: 0.0561 - binary_accuracy: 0.9853 - val_loss: 0.3843 - val_binary_accuracy: 0.8792Epoch 11/2015000/15000 [==============================] - 2s 138us/step - loss: 0.0439 - binary_accuracy: 0.9893 - val_loss: 0.4153 - val_binary_accuracy: 0.8779Epoch 12/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0381 - binary_accuracy: 0.9921 - val_loss: 0.4525 - val_binary_accuracy: 0.8689Epoch 13/2015000/15000 [==============================] - 2s 130us/step - loss: 0.0300 - binary_accuracy: 0.9928 - val_loss: 0.4698 - val_binary_accuracy: 0.8729Epoch 14/2015000/15000 [==============================] - 2s 130us/step - loss: 0.0247 - binary_accuracy: 0.9945 - val_loss: 0.5023 - val_binary_accuracy: 0.8725Epoch 15/2015000/15000 [==============================] - 2s 135us/step - loss: 0.0175 - binary_accuracy: 0.9980 - val_loss: 0.5339 - val_binary_accuracy: 0.8694Epoch 16/2015000/15000 [==============================] - 2s 144us/step - loss: 0.0150 - binary_accuracy: 0.9984 - val_loss: 0.5721 - val_binary_accuracy: 0.8697Epoch 17/2015000/15000 [==============================] - 2s 153us/step - loss: 0.0147 - binary_accuracy: 0.9971 - val_loss: 0.6024 - val_binary_accuracy: 0.8702Epoch 18/2015000/15000 [==============================] - 2s 150us/step - loss: 0.0083 - binary_accuracy: 0.9993 - val_loss: 0.6801 - val_binary_accuracy: 0.8633Epoch 19/2015000/15000 [==============================] - 2s 145us/step - loss: 0.0064 - binary_accuracy: 0.9997 - val_loss: 0.7548 - val_binary_accuracy: 0.8536Epoch 20/2015000/15000 [==============================] - 2s 139us/step - loss: 0.0076 - binary_accuracy: 0.9986 - val_loss: 0.6997 - val_binary_accuracy: 0.8652

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.

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 [17]:
history_dict = history.historyhistory_dict.keys()
Out[17]:
dict_keys(['val_loss', 'val_binary_accuracy', 'loss', '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 [22]:
import matplotlib.pyplot as pltacc = 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 [24]:
plt.clf()   # clear figureacc_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. In general, there is a range of techniques you can leverage to mitigate overfitting, which we will cover in the next chapter.

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

In [25]:
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)results = model.evaluate(x_test, y_test)
Epoch 1/425000/25000 [==============================] - 3s 111us/step - loss: 0.4749 - acc: 0.8217Epoch 2/425000/25000 [==============================] - 2s 89us/step - loss: 0.2658 - acc: 0.9097Epoch 3/425000/25000 [==============================] - 2s 96us/step - loss: 0.1982 - acc: 0.9299Epoch 4/425000/25000 [==============================] - 2s 88us/step - loss: 0.1679 - acc: 0.940225000/25000 [==============================] - 2s 94us/step
In [26]:
results
Out[26]:
[0.3244061092185974, 0.87296]

只需要在第4个epoch就已经最好,所以这里又跑了4个epochOur fairly naive approach achieves an accuracy of 88%. 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 [27]:
model.predict(x_test)
Out[27]:
array([[0.13954607],       [0.999701  ],       [0.28927267],       ...,       [0.07174454],       [0.04302894],       [0.47943923]], dtype=float32)

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.
In [31]:
# Try to use layers with more hidden units or less hidden units: 32 units, 64 units...
In [38]:
model = models.Sequential()model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))model.add(layers.Dense(16, activation='relu'))model.add(layers.Dense(16, activation='relu'))model.add(layers.Dense(1, activation='sigmoid'))model.compile(optimizer='rmsprop',              loss='binary_crossentropy',              metrics=['accuracy'])history = model.fit(partial_x_train,                    partial_y_train,                    epochs=20,                    batch_size=512,                    validation_data=(x_val, y_val))history_dict = history.historyhistory_dict.keys()acc = history.history['acc']val_acc = history.history['val_acc']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()
Train on 15000 samples, validate on 10000 samplesEpoch 1/2015000/15000 [==============================] - 2s 149us/step - loss: 0.5338 - acc: 0.7786 - val_loss: 0.3996 - val_acc: 0.8690Epoch 2/2015000/15000 [==============================] - 2s 125us/step - loss: 0.3112 - acc: 0.9001 - val_loss: 0.2969 - val_acc: 0.8900Epoch 3/2015000/15000 [==============================] - 2s 125us/step - loss: 0.2161 - acc: 0.9265 - val_loss: 0.2719 - val_acc: 0.8937Epoch 4/2015000/15000 [==============================] - 2s 124us/step - loss: 0.1678 - acc: 0.9418 - val_loss: 0.2940 - val_acc: 0.8813Epoch 5/2015000/15000 [==============================] - 2s 125us/step - loss: 0.1376 - acc: 0.9529 - val_loss: 0.2851 - val_acc: 0.8887Epoch 6/2015000/15000 [==============================] - 2s 125us/step - loss: 0.1063 - acc: 0.9667 - val_loss: 0.3280 - val_acc: 0.8786Epoch 7/2015000/15000 [==============================] - 2s 125us/step - loss: 0.0921 - acc: 0.9693 - val_loss: 0.3336 - val_acc: 0.8819Epoch 8/2015000/15000 [==============================] - 2s 124us/step - loss: 0.0703 - acc: 0.9803 - val_loss: 0.3545 - val_acc: 0.8803Epoch 9/2015000/15000 [==============================] - 2s 127us/step - loss: 0.0592 - acc: 0.9831 - val_loss: 0.3850 - val_acc: 0.8765Epoch 10/2015000/15000 [==============================] - 2s 129us/step - loss: 0.0490 - acc: 0.9858 - val_loss: 0.4398 - val_acc: 0.8682Epoch 11/2015000/15000 [==============================] - 2s 133us/step - loss: 0.0415 - acc: 0.9881 - val_loss: 0.4495 - val_acc: 0.8765Epoch 12/2015000/15000 [==============================] - 2s 125us/step - loss: 0.0330 - acc: 0.9909 - val_loss: 0.4765 - val_acc: 0.8730Epoch 13/2015000/15000 [==============================] - 2s 132us/step - loss: 0.0209 - acc: 0.9961 - val_loss: 0.5083 - val_acc: 0.8718Epoch 14/2015000/15000 [==============================] - 2s 126us/step - loss: 0.0222 - acc: 0.9949 - val_loss: 0.5407 - val_acc: 0.8723Epoch 15/2015000/15000 [==============================] - 2s 139us/step - loss: 0.0159 - acc: 0.9965 - val_loss: 0.5733 - val_acc: 0.8712Epoch 16/2015000/15000 [==============================] - 2s 140us/step - loss: 0.0113 - acc: 0.9981 - val_loss: 0.7271 - val_acc: 0.8501Epoch 17/2015000/15000 [==============================] - 2s 127us/step - loss: 0.0065 - acc: 0.9995 - val_loss: 0.6463 - val_acc: 0.8691Epoch 18/2015000/15000 [==============================] - 2s 127us/step - loss: 0.0157 - acc: 0.9951 - val_loss: 0.6848 - val_acc: 0.8676Epoch 19/2015000/15000 [==============================] - 2s 126us/step - loss: 0.0031 - acc: 0.9998 - val_loss: 0.7128 - val_acc: 0.8661Epoch 20/2015000/15000 [==============================] - 2s 125us/step - loss: 0.0109 - acc: 0.9972 - val_loss: 0.7495 - val_acc: 0.8666
In [39]:
plt.clf()   # clear figureacc_values = history_dict['acc']val_acc_values = history_dict['val_acc']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()
Out[39]:
<matplotlib.legend.Legend at 0x1a948cd1080>

从结果上来看,添加或者减少隐藏层没有带来明显变化

In [40]:
#Try to use the `mse` loss function instead of `binary_crossentropy`.
In [46]:
model = models.Sequential()model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))model.add(layers.Dense(16, activation='relu'))model.add(layers.Dense(16, activation='relu'))model.add(layers.Dense(1, activation='sigmoid'))model.compile(optimizer='rmsprop',              loss='mse',              metrics=['accuracy'])history = model.fit(partial_x_train,                    partial_y_train,                    epochs=20,                    batch_size=512,                    validation_data=(x_val, y_val))history_dict = history.historyhistory_dict.keys()acc = history.history['acc']val_acc = history.history['val_acc']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()
Train on 15000 samples, validate on 10000 samplesEpoch 1/2015000/15000 [==============================] - 2s 151us/step - loss: 0.1932 - acc: 0.7371 - val_loss: 0.1328 - val_acc: 0.8684Epoch 2/2015000/15000 [==============================] - 2s 127us/step - loss: 0.0994 - acc: 0.8982 - val_loss: 0.0967 - val_acc: 0.8816Epoch 3/2015000/15000 [==============================] - 2s 128us/step - loss: 0.0670 - acc: 0.9257 - val_loss: 0.0886 - val_acc: 0.8844Epoch 4/2015000/15000 [==============================] - 2s 128us/step - loss: 0.0493 - acc: 0.9458 - val_loss: 0.0840 - val_acc: 0.8858Epoch 5/2015000/15000 [==============================] - 2s 127us/step - loss: 0.0378 - acc: 0.9596 - val_loss: 0.0855 - val_acc: 0.8844Epoch 6/2015000/15000 [==============================] - 2s 127us/step - loss: 0.0316 - acc: 0.9661 - val_loss: 0.0879 - val_acc: 0.8812Epoch 7/2015000/15000 [==============================] - 2s 128us/step - loss: 0.0263 - acc: 0.9728 - val_loss: 0.0889 - val_acc: 0.8811Epoch 8/2015000/15000 [==============================] - 2s 128us/step - loss: 0.0201 - acc: 0.9811 - val_loss: 0.1158 - val_acc: 0.8522Epoch 9/2015000/15000 [==============================] - 2s 130us/step - loss: 0.0176 - acc: 0.9825 - val_loss: 0.0921 - val_acc: 0.8793Epoch 10/2015000/15000 [==============================] - 2s 129us/step - loss: 0.0133 - acc: 0.9872 - val_loss: 0.0943 - val_acc: 0.8778Epoch 11/2015000/15000 [==============================] - 2s 129us/step - loss: 0.0118 - acc: 0.9885 - val_loss: 0.0965 - val_acc: 0.8767Epoch 12/2015000/15000 [==============================] - 2s 129us/step - loss: 0.0095 - acc: 0.9907 - val_loss: 0.0977 - val_acc: 0.8760Epoch 13/2015000/15000 [==============================] - 2s 128us/step - loss: 0.0090 - acc: 0.9905 - val_loss: 0.1027 - val_acc: 0.8714Epoch 14/2015000/15000 [==============================] - 2s 128us/step - loss: 0.0049 - acc: 0.9960 - val_loss: 0.1011 - val_acc: 0.8717Epoch 15/2015000/15000 [==============================] - 2s 129us/step - loss: 0.0067 - acc: 0.9927 - val_loss: 0.1030 - val_acc: 0.8711Epoch 16/2015000/15000 [==============================] - 2s 129us/step - loss: 0.0034 - acc: 0.9970 - val_loss: 0.1045 - val_acc: 0.8705Epoch 17/2015000/15000 [==============================] - 2s 135us/step - loss: 0.0062 - acc: 0.9933 - val_loss: 0.1064 - val_acc: 0.8696Epoch 18/2015000/15000 [==============================] - 2s 133us/step - loss: 0.0026 - acc: 0.9976 - val_loss: 0.1076 - val_acc: 0.8687Epoch 19/2015000/15000 [==============================] - 2s 129us/step - loss: 0.0057 - acc: 0.9935 - val_loss: 0.1091 - val_acc: 0.8679Epoch 20/2015000/15000 [==============================] - 2s 128us/step - loss: 0.0022 - acc: 0.9978 - val_loss: 0.1104 - val_acc: 0.8671
In [47]:
plt.clf()   # clear figureacc_values = history_dict['acc']val_acc_values = history_dict['val_acc']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()
Out[47]:
<matplotlib.legend.Legend at 0x1a948f9fdd8>

执行这个修改,从结果上来看,有所提高

看上去,mse非常的不适合这个问题

In [45]:
# Try to use the `tanh` activation (an activation that was popular in the early days of neural networks) instead of `relu`.
In [48]:
model = models.Sequential()model.add(layers.Dense(16, activation='tanh', input_shape=(10000,)))model.add(layers.Dense(16, activation='tanh'))model.add(layers.Dense(16, activation='tanh'))model.add(layers.Dense(1, activation='sigmoid'))model.compile(optimizer='rmsprop',              loss='mse',              metrics=['accuracy'])history = model.fit(partial_x_train,                    partial_y_train,                    epochs=20,                    batch_size=512,                    validation_data=(x_val, y_val))history_dict = history.historyhistory_dict.keys()acc = history.history['acc']val_acc = history.history['val_acc']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()
Train on 15000 samples, validate on 10000 samplesEpoch 1/2015000/15000 [==============================] - 2s 158us/step - loss: 0.1523 - acc: 0.7944 - val_loss: 0.1029 - val_acc: 0.8706Epoch 2/2015000/15000 [==============================] - 2s 138us/step - loss: 0.0740 - acc: 0.9085 - val_loss: 0.0850 - val_acc: 0.8854Epoch 3/2015000/15000 [==============================] - 2s 130us/step - loss: 0.0497 - acc: 0.9386 - val_loss: 0.0845 - val_acc: 0.8863Epoch 4/2015000/15000 [==============================] - 2s 136us/step - loss: 0.0346 - acc: 0.9585 - val_loss: 0.0927 - val_acc: 0.8770Epoch 5/2015000/15000 [==============================] - 2s 142us/step - loss: 0.0303 - acc: 0.9631 - val_loss: 0.0939 - val_acc: 0.8812Epoch 6/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0241 - acc: 0.9723 - val_loss: 0.0979 - val_acc: 0.8797Epoch 7/2015000/15000 [==============================] - 2s 130us/step - loss: 0.0219 - acc: 0.9739 - val_loss: 0.1009 - val_acc: 0.8770Epoch 8/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0192 - acc: 0.9785 - val_loss: 0.1046 - val_acc: 0.8760Epoch 9/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0160 - acc: 0.9821 - val_loss: 0.1077 - val_acc: 0.8729Epoch 10/2015000/15000 [==============================] - 2s 130us/step - loss: 0.0132 - acc: 0.9852 - val_loss: 0.1071 - val_acc: 0.8755Epoch 11/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0133 - acc: 0.9851 - val_loss: 0.1097 - val_acc: 0.8739Epoch 12/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0146 - acc: 0.9837 - val_loss: 0.1120 - val_acc: 0.8717Epoch 13/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0071 - acc: 0.9929 - val_loss: 0.1407 - val_acc: 0.8436Epoch 14/2015000/15000 [==============================] - 2s 132us/step - loss: 0.0078 - acc: 0.9917 - val_loss: 0.1145 - val_acc: 0.8720Epoch 15/2015000/15000 [==============================] - 2s 136us/step - loss: 0.0128 - acc: 0.9855 - val_loss: 0.1164 - val_acc: 0.8700Epoch 16/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0057 - acc: 0.9943 - val_loss: 0.1190 - val_acc: 0.8673Epoch 17/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0124 - acc: 0.9861 - val_loss: 0.1196 - val_acc: 0.8670Epoch 18/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0052 - acc: 0.9948 - val_loss: 0.1207 - val_acc: 0.8665Epoch 19/2015000/15000 [==============================] - 2s 131us/step - loss: 0.0111 - acc: 0.9870 - val_loss: 0.1210 - val_acc: 0.8661Epoch 20/2015000/15000 [==============================] - 2s 135us/step - loss: 0.0050 - acc: 0.9950 - val_loss: 0.1225 - val_acc: 0.8651
In [49]:
plt.clf()   # clear figureacc_values = history_dict['acc']val_acc_values = history_dict['val_acc']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()
Out[49]:
<matplotlib.legend.Legend at 0x1a948c45ef0>

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.




附件列表

     

    posted @ 2018-06-01 20:02 jsxyhelu 阅读(...) 评论(...) 编辑 收藏