How to use MLP Classifier and Regressor in Python?
MACHINE LEARNING RECIPES DATA CLEANING PYTHON DATA MUNGING PANDAS CHEATSHEET     ALL TAGS

How to use MLP Classifier and Regressor in Python?

How to use MLP Classifier and Regressor in Python?

This recipe helps you use MLP Classifier and Regressor in Python

0

Recipe Objective

We have worked on various models and used them to predict the output. Here is one such model that is MLP which is an important model of Artificial Neural Network and can be used as Regressor and Classifier.

So this is the recipe on how we can use MLP Classifier and Regressor in Python.

Step 1 - Import the library

from sklearn import datasets from sklearn import metrics from sklearn.neural_network import MLPClassifier from sklearn.neural_network import MLPRegressor from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import seaborn as sns plt.style.use('ggplot')

We have imported all the modules that would be needed like metrics, datasets, MLPClassifier, MLPRegressor etc. We will see the use of each modules step by step further.

Step 2 - Setting up the Data for Classifier

We have imported inbuilt wine dataset from the module datasets and stored the data in X and the target in y. We have also used train_test_split to split the dataset into two parts such that 30% of data is in test and rest in train. dataset = datasets.load_wine() X = dataset.data; y = dataset.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)

Step 3 - Using MLP Classifier and calculating the scores

We have made an object for thr model and fitted the train data. Then we have used the test data to test the model by predicting the output from the model for test data. model = MLPClassifier() model.fit(X_train, y_train) print(model) expected_y = y_test predicted_y = model.predict(X_test)

Now We are calcutaing other scores for the model using classification_report and confusion matrix by passing expected and predicted values of target of test set. print(metrics.classification_report(expected_y, predicted_y)) print(metrics.confusion_matrix(expected_y, predicted_y))

Step 4 - Setting up the Data for Regressor

We have imported inbuilt boston dataset from the module datasets and stored the data in X and the target in y. We have also used train_test_split to split the dataset into two parts such that 30% of data is in test and rest in train. dataset = datasets..load_boston() X = dataset.data; y = dataset.target X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30)

Step 5 - Using MLP Regressor and calculating the scores

We have made an object for thr model and fitted the train data. Then we have used the test data to test the model by predicting the output from the model for test data. model = MLPRegressor() model.fit(X_train, y_train) print(model) expected_y = y_test predicted_y = model.predict(X_test)

Now We are calcutaing other scores for the model using r_2 score and mean_squared_log_error by passing expected and predicted values of target of test set. print(metrics.r2_score(expected_y, predicted_y)) print(metrics.mean_squared_log_error(expected_y, predicted_y))

Step 6 - Ploting the model

We are ploting the regressor model: plt.figure(figsize=(10,10)) sns.regplot(expected_y, predicted_y, fit_reg=True, scatter_kws={"s": 100}) So the final output comes as:

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=(100,), learning_rate='constant',
       learning_rate_init=0.001, max_iter=200, momentum=0.9,
       n_iter_no_change=10, nesterovs_momentum=True, power_t=0.5,
       random_state=None, shuffle=True, solver='adam', tol=0.0001,
       validation_fraction=0.1, verbose=False, warm_start=False)

              precision    recall  f1-score   support

           0       0.83      0.83      0.83        12
           1       0.80      1.00      0.89        16
           2       1.00      0.76      0.87        17

   micro avg       0.87      0.87      0.87        45
   macro avg       0.88      0.87      0.86        45
weighted avg       0.88      0.87      0.87        45


[[10  2  0]
 [ 0 16  0]
 [ 2  2 13]]

MLPRegressor(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=(100,), learning_rate='constant',
       learning_rate_init=0.001, max_iter=200, momentum=0.9,
       n_iter_no_change=10, nesterovs_momentum=True, power_t=0.5,
       random_state=None, shuffle=True, solver='adam', tol=0.0001,
       validation_fraction=0.1, verbose=False, warm_start=False)

0.5857867538727082

0.06206481879580382

Relevant Projects

Deep Learning with Keras in R to Predict Customer Churn
In this deep learning project, we will predict customer churn using Artificial Neural Networks and learn how to model an ANN in R with the keras deep learning package.

Credit Card Fraud Detection as a Classification Problem
In this data science project, we will predict the credit card fraud in the transactional dataset using some of the predictive models.

German Credit Dataset Analysis to Classify Loan Applications
In this data science project, you will work with German credit dataset using classification techniques like Decision Tree, Neural Networks etc to classify loan applications using R.

PySpark Tutorial - Learn to use Apache Spark with Python
PySpark Project-Get a handle on using Python with Spark through this hands-on data processing spark python tutorial.

Ecommerce product reviews - Pairwise ranking and sentiment analysis
This project analyzes a dataset containing ecommerce product reviews. The goal is to use machine learning models to perform sentiment analysis on product reviews and rank them based on relevance. Reviews play a key role in product recommendation systems.

Perform Time series modelling using Facebook Prophet
In this project, we are going to talk about Time Series Forecasting to predict the electricity requirement for a particular house using Prophet.

Ensemble Machine Learning Project - All State Insurance Claims Severity Prediction
In this ensemble machine learning project, we will predict what kind of claims an insurance company will get. This is implemented in python using ensemble machine learning algorithms.

Time Series Forecasting with LSTM Neural Network Python
Deep Learning Project- Learn to apply deep learning paradigm to forecast univariate time series data.

Predict Employee Computer Access Needs in Python
Data Science Project in Python- Given his or her job role, predict employee access needs using amazon employee database.

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.