Neural Networks in Python: MLP Classifiers

neuralplot

Neural networks are commonly used to solve classification problems, as we saw with the wine detection example in R.

If you read the last post on logistic regressions (which I recommend you do first as this example follows directly on from this), we examined a dataset of stocks with a view to determining whether a particular stock would pay a dividend or not. Here, we are going to attempt the same classification exercise (classifying a stock as a dividend payer or non-dividend payer), but using a neural network with the MLPClassifier library.

Here is the structure of our variables within the dataset:

Dependent Variable (Y)

  • Dividends (dummy variable) – if the company pays dividends currently it is given a ranking of 1. If the company does not pay dividends, it is given a ranking of 0.

Independent Variables (X)

  • Years: The number of years of consecutive dividend increases.
  • Earnings Estimates: If the stock beat earnings for the past four consecutive quarters, it is given a ranking of 1. Otherwise, it is given a ranking of 0.

Essentially, we wish to use the input variables years and earnings estimates to determine whether a stock will pay a dividend or not. This example will follow on from the script we used for the logistic regression example. Firstly, we are going to normalize the data in order to ensure that the MLPClassifier processes it accurately.

Data Normalization

In [7]:

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)
x_test = scaler.transform(x_test)

Model Training

Then, the relevant libraries are imported, including the MLPClassifier from the sklearn.neural_network.

In [8]:

import matplotlib.pyplot as plt
from sklearn.neural_network import MLPClassifier
import mglearn

We will then use the MLPClassifier on our x_train and y_train data to train the model. In this instance, two hidden nodes are specified, with a random_state = 0.


In [9]:

mlp = MLPClassifier(solver='lbfgs', random_state=0, hidden_layer_sizes=[2])
mlp.fit(x_train, y_train)

Neural Network Output

Accordingly, our MLP Classifier now has the following parameters.

Out [9]:

MLPClassifier(activation='relu', alpha=0.0001, batch_size='auto', beta_1=0.9,
       beta_2=0.999, early_stopping=False, epsilon=1e-08,
       hidden_layer_sizes=[2], learning_rate='constant',
       learning_rate_init=0.001, max_iter=200, momentum=0.9,
       nesterovs_momentum=True, power_t=0.5, random_state=0, shuffle=True,
       solver='lbfgs', tol=0.0001, validation_fraction=0.1, verbose=False,
       warm_start=False)

We then generate a series of predictions using mlp.predict.

In [10]:

pr = mlp.predict(x_test)

Out [10]:

array([1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0], dtype=int64)

Confusion Matrix and Classification Report

Then, a confusion matrix and classification report is generated to determine the level of accuracy of our classification, i.e. how accurate was the classifier in determining whether a stock would pay a dividend or not?

In [11]:

from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y_test,pr))

Out [11]:

[[9 1]
 [0 8]]

In [12]:

print(classification_report(y_test,pr))

Out [12]:

             precision    recall  f1-score   support

          0       1.00      0.90      0.95        10
          1       0.89      1.00      0.94         8

avg / total       0.95      0.94      0.94        18

We see that with a high precision score of 0.95, our classifier has shown a high degree of accuracy in classifying stocks as a dividend or non-dividend yielding stock.

Conclusion

In this example, we have seen how to use neural networks to classify a variable based on its inputs. For this particular instance, two hidden layers were used to capture additional variation not available from the input variables (or nodes). However, in a much larger dataset, it can often be the case that many more hidden nodes have to be employed in order to improve classification accuracy.

Hope you enjoyed this tutorial! The full code and dataset is available at my Github repository.

Leave a Reply

Your email address will not be published. Required fields are marked *