Day 10 · From features to predictions
MLP regression vs classification
One network idea, different predictions. Understand the output layer, follow seven readable formulas and compare Python examples with computed learning visuals.
Explore the checked guide
Choose the outputConnect quantities, categories and labels to the right head.
Follow the mathematicsRead forward passes, probabilities and reporting metrics.
Check the examplesCompare exact historical code with separate modern runs.
In this lesson
The quick answer
Predict a quantity, a class or several labels
An MLP can solve regression or classification problems. The target determines how you represent its outputs, choose its loss and evaluate its predictions. Hidden layers transform features in both cases.
Build on Day 9’s single perceptron by connecting neurons into hidden layers. Start with the checked guide for current API details, then read the complete historical lesson below.
Read the checked guide first
The hidden network can be similar; the target changes the output
Regression predicts a quantity; classification predicts a category or a set of labels. Both can use fully connected hidden layers. The important differences are the target representation, output activation, loss and evaluation metric. Choose those together, rather than assuming that adding more layers changes a regression task into a classification task.
Compatibility and example correction: the original regression snippet uses an RMSE argument removed from modern scikit-learn. The original “multiclass” snippet also reuses arrays previously filtered to two Iris classes, so it actually remains binary when run in that context. Every original passage and code block is retained below; the added examples here correct those issues explicitly.
1. Separate hidden activations from the output head
Let a⁽⁰⁾ = x be the input feature vector. A hidden layer multiplies the previous activations by a weight matrix, adds a bias vector and applies a nonlinear function g. The dimensions must match: a matrix maps the previous layer’s width to the next layer’s width.
In the scikit-learn examples, activation="relu" chooses the hidden-layer activation. It does not request a ReLU output for every task. The fitted estimator’s out_activation_ identifies its output activation. A purely linear stack with no nonlinear hidden activations is still a linear mapping, even if several layers are written down.
2. Match the output to what a label means
For the default squared-error regression setup, an identity output returns unrestricted real values. It can produce negative predictions even if every training target is positive. This differs from a nonnegative-target model: supported MLPRegressor(loss="poisson") uses an exponential output link and requires nonnegative targets. It is therefore inaccurate to claim that every regression MLP always has the same output activation.
For binary classification, one logit z can produce the positive-class probability through the sigmoid function. The two class probabilities are then 1 − p and p. Their array order must be read from the fitted classes_, rather than guessed from a column number.
Multilabel classification has a separate binary label for each possible tag. Several labels can apply at once, so outputs such as [0.8, 0.7, 0.1] are allowed and do not need to sum to one. Multiclass classification instead chooses one of K mutually exclusive classes. Softmax converts its K logits into probabilities summing to one.
For illustrative logits [1, 2, 0], softmax gives approximately [0.244728, 0.665241, 0.090031]. Rounding can slightly change a displayed sum. Probability outputs are not automatically calibrated: a confidence of 0.8 is not, by itself, evidence of 80% correctness on comparable future examples.
3. Keep training loss and reporting metrics distinct
For one continuous output, RMSE is the square root of the average squared prediction error. It has the target’s units, so RMSE values from housing prices and a different benchmark target cannot be compared as if they measured the same outcome.
Binary cross-entropy uses a binary target t and its predicted positive-class probability p. Multiclass cross-entropy uses a one-hot target vector, where exactly one component is 1. These losses evaluate probabilities, while accuracy evaluates the final selected labels.
Here logs are natural logarithms. The default regressor optimizes a squared-error-based training objective, with its configured regularization; the classifier uses log loss. Report RMSE, accuracy, log loss or other suitable metrics on separate data. A favorable training loss does not establish generalization, and accuracy alone can conceal class imbalance or poorly calibrated probabilities.
4. Repair the RMSE call without hiding the historical code
The preserved call mean_squared_error(y_valid, y_pred, squared=False) raises TypeError in the checked scikit-learn 1.8.0 environment. The modern API is root_mean_squared_error(y_valid, y_pred). This compatibility probe was executed directly. It does not establish that the whole original housing training ran.
The California housing dataset was not cached here. Its presence was checked with downloads disabled, and no network download was performed. Consequently, the original housing preparation and regression fit are not claimed tested. The separately labelled built-in diabetes example below provides an executed no-download regression demonstration instead.
5. Restore all classes before claiming a multiclass result
The original binary example removes Iris class 2 before splitting the data. Running the next snippet against those same arrays still gives two classes, even though the heading calls it multiclass. Both original classification snippets were executed in that dependent context: each produced a logistic output with one model output and classes [0, 1].
Each achieved 1.0 accuracy on its 25-row validation split, but the final snippet also reached its 200-iteration limit with a convergence warning. Perfect validation accuracy does not cancel that warning or make the task three-class. The corrected example reloads the complete Iris dataset and uses stratified splits, retaining classes [0, 1, 2] and a three-output softmax head.
6. Fit preprocessing on training data only
Reserve validation and test rows before fitting the scaler. Fit the pipeline on training rows, then apply its learned transformations to validation and test data. Our regression example also scales the target through TransformedTargetRegressor, fitted only on training targets, and converts predictions back to original target units.
Be precise about built-in early stopping. With a stochastic solver, early_stopping=True reserves an internal fraction of the data passed to the MLP; it does not automatically use a separately named X_valid. An outer pipeline’s scaler has already fitted that outer training set, including the MLP’s later internal holdout. For a strictly isolated preprocessing-validation boundary, make an explicit split and fit preprocessing on its training part. The executed examples use L-BFGS and explicit external splits, without built-in early stopping.
7. Read activation advice as a choice to evaluate
The preserved activation catalogue discusses broader neural-network designs. Standard scikit-learn MLP hidden activations are identity, logistic, tanh and ReLU. ELU, Swish, Mish, Leaky ReLU and PReLU are not additional activation options in these estimators, and their constructors do not provide a dropout parameter. Other frameworks support different choices.
These classes offer L2 regularization through alpha; supported stochastic solvers can also use early stopping. Neither a particular activation nor a “typical” hidden-layer count guarantees faster training or better accuracy. Deep learning remains part of machine learning; an MLP can be shallow or deep, and data size alone does not define the boundary.
8. Inspect a recorded regression and a proper three-class run
The following independent examples were executed with scikit-learn 1.8.0. Diabetes uses 264 training, 89 validation and 89 test rows; Iris uses stratified 90/30/30 splits. Both fit fixed, small models, with no test-driven hyperparameter search. The diabetes test RMSE is 68.915538 target units; the Iris model correctly predicts 28 of 30 test rows, giving accuracy 0.933333 and log loss 0.135598. These results describe those splits and models, not a universal performance promise.
import numpy as np
from sklearn.datasets import load_diabetes, load_iris
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.compose import TransformedTargetRegressor
from sklearn.neural_network import MLPRegressor, MLPClassifier
from sklearn.metrics import root_mean_squared_error, accuracy_score
def split_rows(y, stratified=False):
ids = np.arange(len(y))
train_full, test = train_test_split(
ids, test_size=0.2, random_state=42,
stratify=y if stratified else None)
train, valid = train_test_split(
train_full, test_size=0.25, random_state=42,
stratify=y[train_full] if stratified else None)
return train, valid, test
# Separate no-download regression benchmark, NOT California housing.
X, y = load_diabetes(return_X_y=True)
train, valid, test = split_rows(y)
reg = TransformedTargetRegressor(
regressor=make_pipeline(StandardScaler(), MLPRegressor(
hidden_layer_sizes=(16,), activation="relu", solver="lbfgs",
alpha=1.0, max_iter=1000, random_state=42)),
transformer=StandardScaler())
reg.fit(X[train], y[train])
print("Validation RMSE:", root_mean_squared_error(
y[valid], reg.predict(X[valid])))
print("Test RMSE:", root_mean_squared_error(
y[test], reg.predict(X[test])))
# Restore all THREE Iris classes: do not reuse the binary-filtered arrays.
X, y = load_iris(return_X_y=True)
train, valid, test = split_rows(y, stratified=True)
clf = make_pipeline(StandardScaler(), MLPClassifier(
hidden_layer_sizes=(16,), activation="relu", solver="lbfgs",
alpha=0.1, max_iter=1000, random_state=42))
clf.fit(X[train], y[train])
print("Validation accuracy:", accuracy_score(
y[valid], clf.predict(X[valid])))
print("Test accuracy:", accuracy_score(y[test], clf.predict(X[test])))
probabilities = clf.predict_proba(X[test])
assert clf[-1].classes_.tolist() == [0, 1, 2]
assert np.allclose(probabilities.sum(axis=1), 1)
The new charts use recorded held-out predictions. Their forward passes were independently reconstructed from the learned weights and matched the estimator outputs. Probability rows were checked to sum to one, RMSE matched its explicit mathematical definition, and scaler means matched training rows only. Validation and test sets were disjoint from training.
9. Use the corrected primary references
Some preserved bibliographic labels and links are mismatched. Understanding the difficulty of training deep feedforward neural networks, by Glorot and Bengio, is an AISTATS 2010 paper. Deep learning, by LeCun, Bengio and Hinton, is a 2015 Nature review. These corrected references are separate from the unchanged original list.
Primary sources: scikit-learn’s MLPRegressor, MLPClassifier, root_mean_squared_error and data-leakage guidance describe the relevant APIs and evaluation practices. Read the original Glorot–Bengio 2010 paper and LeCun–Bengio–Hinton 2015 review at their publishers.
See what the outputs mean
From task definitions to recorded predictions
The first visual illustrates task-specific heads. The next two show actual held-out predictions from the separate built-in benchmarks described above. These precise diagrams and plots are computed with Python.



The complete original lesson
Every original explanation, code block, table and reference
All original wording remains, including repeated explanations, four Python code blocks, the architecture table and the full reference list. Separate notes explain API compatibility, class filtering and bibliographic corrections without removing the historical material.
Long formulas, the table and code scroll within their own regions. Focus a region with the keyboard and use the arrow keys to read across. Open a learning visual to inspect its full-size labels.
Regression with Multi-Layer Perceptrons (MLPs)
Introduction
Neural networks, particularly Multi-Layer Perceptrons (MLPs), are essential tools in machine learning for solving both regression and classification problems. This guide will provide a detailed explanation of MLPs, covering their structure, activation functions, and implementation using Scikit-Learn.
Regression vs. Classification: Key Differences
Regression
Objective: Predict continuous values.
Output: Single or multiple continuous values.
Example: Predicting house prices, stock prices, or temperature.
Classification
Objective: Predict discrete class labels.
Output: Class probabilities or specific class labels.
Example: Classifying emails as spam or not spam, recognizing handwritten digits, or identifying types of animals in images.
Regression with MLPs
MLPs can be utilized for regression tasks, predicting continuous outcomes. Let’s walk through the implementation using the California housing dataset.
Activation Functions in Regression MLPs
In regression tasks, MLPs typically use non-linear activation functions like ReLU in the hidden layers to capture complex patterns in the data. The output layer may use a linear activation function to predict continuous values.
Fetching and Preparing the Data
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
# Load the California housing dataset
housing = fetch_california_housing()
# Split the data into training, validation, and test sets
X_train_full, X_test, y_train_full, y_test = train_test_split(housing.data, housing.target, random_state=42)
X_train, X_valid, y_train, y_valid = train_test_split(X_train_full, y_train_full, random_state=42)
Building and Training the MLP Model
from sklearn.neural_network import MLPRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
# Define the MLP model
mlp_reg = MLPRegressor(hidden_layer_sizes=[50, 50, 50], activation='relu', solver='adam', random_state=42)
# Create a pipeline with standard scaling and the MLP model
pipeline = make_pipeline(StandardScaler(), mlp_reg)
# Train the model
pipeline.fit(X_train, y_train)
# Predict on the validation set
y_pred = pipeline.predict(X_valid)
# Calculate the Root Mean Squared Error (RMSE)
rmse = mean_squared_error(y_valid, y_pred, squared=False)
print(f'Validation RMSE: {rmse:.3f}')
Explanation of the Code
MLPRegressor: This class is used to create a multi-layer perceptron regressor. The
hidden_layer_sizesparameter specifies the number of neurons in each hidden layer. Theactivation='relu'parameter ensures that ReLU is used as the activation function in hidden layers.StandardScaler: This preprocessing step standardizes the features by removing the mean and scaling to unit variance, which is crucial for the efficient training of neural networks.
make_pipeline: This function chains together the preprocessing step and the MLP model for streamlined training.
mean_squared_error: This function computes the mean squared error between the predicted and actual values. Setting
squared=Falsereturns the root mean squared error (RMSE), providing an intuitive measure of prediction error.
Why Use These Techniques?
Standard Scaling: Neural networks perform better when the input features are scaled to have zero mean and unit variance.
Hidden Layers with ReLU: The ReLU activation function introduces non-linearity, enabling the network to learn complex relationships in the data.
Pipeline: Combining preprocessing and model training in a pipeline ensures that the transformations applied to the training data are also applied to the test data, maintaining consistency.
Classification with Multi-Layer Perceptrons (MLPs)
Introduction
Neural networks, particularly Multi-Layer Perceptrons (MLPs), are also widely used for classification tasks. This guide will provide a detailed explanation of how to use MLPs for classification, covering their structure, activation functions, and implementation using Scikit-Learn.
Classification Tasks
Binary Classification
For binary classification, a single output neuron with the sigmoid activation function is used to predict probabilities between 0 and 1. This is suitable for tasks where there are only two possible classes.
Example: Binary Classification with the Iris Dataset
from sklearn.neural_network import MLPClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
# Load the Iris dataset
iris = load_iris()
X, y = iris.data, iris.target
# For simplicity, we'll convert it into a binary classification problem
# by selecting only two classes
X = X[y != 2]
y = y[y != 2]
# Split the data into training and validation sets
X_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state=42)
# Define the MLP model for classification
mlp_clf = MLPClassifier(hidden_layer_sizes=[50, 50, 50], activation='relu', solver='adam', random_state=42)
# Create a pipeline with standard scaling and the MLP model
pipeline = make_pipeline(StandardScaler(), mlp_clf)
# Train the model
pipeline.fit(X_train, y_train)
# Predict on the validation set
y_pred = pipeline.predict(X_valid)
# Calculate the accuracy
accuracy = accuracy_score(y_valid, y_pred)
print(f'Validation Accuracy: {accuracy:.3f}')
Explanation of the Code
MLPClassifier: This class is used to create a multi-layer perceptron classifier. The
hidden_layer_sizesparameter specifies the number of neurons in each hidden layer. Theactivation='relu'parameter ensures that ReLU is used as the activation function in hidden layers.Sigmoid Activation: In binary classification, the sigmoid function outputs probabilities between 0 and 1, which are used to predict the class labels.
StandardScaler and Pipeline: Similar to the regression task, standard scaling and the pipeline are used to ensure consistent preprocessing and model training.
accuracy_score: This function computes the accuracy of the model, which is the proportion of correct predictions out of the total predictions made.
Multilabel Binary Classification
For multilabel binary classification, you would use multiple output neurons with sigmoid activation functions, each neuron outputting a probability for a different label.
Multiclass Classification
For multiclass classification, the output layer uses the softmax activation function to produce a probability distribution over multiple classes:
# Define the MLP model for multiclass classification
mlp_clf = MLPClassifier(hidden_layer_sizes=[50], activation='relu', solver='adam', random_state=42)
# Create a pipeline with standard scaling and the MLP model
pipeline = make_pipeline(StandardScaler(), mlp_clf)
# Train the model
pipeline.fit(X_train, y_train)
# Predict on the validation set
y_pred = pipeline.predict(X_valid)
# Calculate the accuracy
accuracy = pipeline.score(X_valid, y_valid)
print(f'Validation Accuracy: {accuracy:.3f}')
Explanation of the Code
Softmax Activation: The softmax function is used in the output layer of a neural network for multiclass classification problems. It converts raw class scores into probabilities that sum to 1, making it possible to interpret the outputs as probabilities of each class.
MLPClassifier: For multiclass classification, the MLPClassifier is configured similarly to binary classification, but with an output layer that uses the softmax activation function.
StandardScaler and Pipeline: Again, standard scaling and pipelines ensure consistent preprocessing and model training.
accuracy_score: The accuracy score for multiclass classification measures the proportion of correct predictions out of the total predictions made.
Why Use These Techniques?
Activation Functions: The choice of activation function in the output layer (sigmoid for binary classification, softmax for multiclass classification) ensures that the outputs are interpretable as probabilities.
Standard Scaling: Ensuring the input features are standardized helps improve the performance and convergence of the neural network.
Pipelines: Using pipelines for preprocessing and model training ensures that the same transformations applied to the training data are also applied to the test data, maintaining consistency.
Multi-Layer Perceptrons (MLPs) in Machine Learning and Deep Learning
by ingoampt, July 24, 2024
Choosing the Right Activation Functions
Selecting the appropriate activation functions is crucial for optimizing the performance of MLPs. Different activation functions can greatly influence the model’s ability to learn and generalize from the data. Here are some commonly used activation functions along with their characteristics and best use cases:
ReLU (Rectified Linear Unit):
Characteristics: Non-linear, allows for faster and more effective training.
Best For: Hidden layers in both regression and classification tasks due to its simplicity and efficiency.
Variants: Leaky ReLU, Parametric ReLU, Randomized ReLU, which address the “dying ReLU” problem by allowing small gradients when the unit is not active.
Sigmoid:
Characteristics: Outputs values between 0 and 1, useful for binary classification.
Best For: Output layer in binary classification problems.
Challenges: Can suffer from vanishing gradient problems.
Tanh (Hyperbolic Tangent):
Characteristics: Outputs values between -1 and 1, zero-centered, which can make optimization easier.
Best For: Hidden layers, especially in earlier neural network architectures.
Challenges: Similar to sigmoid, can suffer from vanishing gradient problems.
Softmax:
Characteristics: Converts outputs to a probability distribution, where the sum of all probabilities is 1.
Best For: Output layer in multiclass classification problems.
ELU (Exponential Linear Unit):
Characteristics: Helps the network converge faster and produce more accurate results by allowing negative values.
Best For: Deep neural networks where faster convergence and higher accuracy are desired.
Swish:
Characteristics: Smooth, non-monotonic function that can improve model performance and training speed.
Best For: Deep neural networks, often used in reinforcement learning and various deep learning tasks.
Leaky ReLU and PReLU:
Characteristics: Variants of ReLU that allow a small, non-zero gradient when the unit is not active.
Best For: Hidden layers to prevent the “dying ReLU” problem.
Mish:
Characteristics: Self-regularizing non-monotonic activation function that can improve generalization.
Best For: Hidden layers in deep networks, providing smooth, non-monotonic outputs.
Multi-Layer Perceptrons (MLPs) in Machine Learning and Deep Learning
by ingoampt, July 24, 2024
Practical Implementation Tips
Data Preprocessing: Standardizing features using StandardScaler is crucial for efficient training.
Model Architecture: Carefully design the architecture based on task complexity, balancing depth and width of hidden layers.
Evaluation Metrics: Use appropriate metrics such as RMSE for regression, and accuracy, precision, recall, and F1-score for classification.
Regularization Techniques: Implement dropout, L2 regularization, or early stopping to prevent overfitting.
Deep Learning vs. Machine Learning
MLPs are utilized in both machine learning and deep learning. Here’s how they differ:
Deep Learning: Leverages large-scale data and high computational power with architectures like CNNs and RNNs, suitable for complex tasks like image and speech recognition.
Machine Learning: Often involves more feature engineering and typically handles smaller datasets, used for tasks like predictive analytics and basic classification/regression.
When deploying MLPs, it’s crucial to preprocess data correctly and choose appropriate activation functions to match the task requirements. For regression, MLPs predict continuous outputs and require careful handling of activation functions to ensure accurate predictions. For classification, MLPs can manage both binary and multiclass outputs, leveraging sigmoid and softmax functions to produce meaningful probability distributions.
By following best practices in data preprocessing, model architecture design, and performance evaluation, MLPs can be a robust solution for a wide range of machine learning problems.
FootNotes : The Table Below is the Tipycall Classification MLPs architecture
| Hyperparameter | Binary Classification | Multilabel Binary Classification | Multiclass Classification |
|---|---|---|---|
| # hidden layers | Typically 1 to 5 layers, depending on the task | Typically 1 to 5 layers, depending on the task | Typically 1 to 5 layers, depending on the task |
| # output neurons | 1 | 1 per binary label | 1 per class |
| Output layer activation | Sigmoid | Sigmoid | Softmax |
| Loss function | Cross-entropy | Cross-entropy | Cross-entropy |
| Additional Info | Common in spam detection or disease diagnosis | Used in tag prediction for images | Appropriate for digit or facial recognition |
The table we reference categorizes key hyperparameters for different classification tasks: binary classification, multilabel binary classification, and multiclass classification. Each type of classification has specific requirements for the number of hidden layers, output neurons, activation functions, and loss functions, which are detailed and explained to ensure effective network design.
Common and Output Layer Activation Functions
ReLU (Rectified Linear Unit): Widely used in hidden layers, ReLU introduces non-linearity by outputting the input directly if it is positive; otherwise, it outputs zero. This helps in avoiding the vanishing gradient problem, allowing networks to learn faster and more effectively. (Glorot et al., 2011)
Tanh (Hyperbolic Tangent): Outputs values between -1 and 1, centering the data which can make learning easier and faster. However, like the Sigmoid function, it can suffer from the vanishing gradient problem. (LeCun et al., 1998)
Sigmoid: While less common in hidden layers due to potential gradient issues, it outputs values between 0 and 1, making it useful in binary classification contexts. (Schmidhuber, 2015)
Output Layer Activation Functions
Sigmoid: Used in binary classification because it maps any real-valued number into a value between 0 and 1, making it perfect for predicting probabilities. Each output neuron represents the probability of a particular class. (Deng et al., 2014)
Softmax: Applied in multiclass classification, Softmax converts raw scores (logits) into probabilities that sum to one, making it ideal for scenarios where each instance can belong to one class out of many. (Goodfellow et al., 2016)
Linear: Employed in regression tasks, the linear activation function allows the output to take any value, fitting the continuous nature of regression outputs. (Haykin, 2009)
Applying Activation Functions for Specific Tasks
Binary Classification
Activation Function: Sigmoid
Reason: The sigmoid function confines output between 0 and 1, representing the probability of an input belonging to the positive class. This is crucial for tasks like spam detection or medical diagnosis where the result is binary. (Deng et al., 2014)
Multilabel Binary Classification
Activation Function: Sigmoid
Reason: Each label is treated as an independent binary classification task. Using sigmoid allows each output neuron to independently predict the presence of each label, making it suitable for tasks like image tagging where multiple labels can apply. (Goodfellow et al., 2016)
Multiclass Classification
Activation Function: Softmax
Reason: Softmax is used to generate a probability distribution over multiple classes, ensuring the sum of all probabilities equals one. This makes it ideal for tasks like digit recognition, where each input must be classified into one of several distinct categories. (LeCun et al., 1998)
Conclusion
In this post, we explored the differences between regression and classification using Multi-Layer Perceptrons (MLPs). Although MLPs share a common architecture, the way they are configured for regression versus classification tasks differs significantly.
Regression tasks involve predicting continuous values. In these cases:
The output layer often uses a linear activation function.
Loss functions such as Mean Squared Error (MSE) are commonly used.
The model’s performance is evaluated using metrics that measure continuous differences, like RMSE or MAE.
Classification tasks involve assigning discrete labels or categories. For these:
The output layer typically uses a softmax (for multi-class) or sigmoid (for binary) activation function.
Cross-entropy loss functions are used to measure how well the model’s probability distribution matches the true labels.
Metrics such as accuracy, precision, recall, and F1-score help evaluate model effectiveness.
By understanding these differences, you can tailor your MLP design and training approach to suit the specific needs of your problem—whether you’re predicting continuous outcomes or classifying inputs into categories.
Ultimately, the choice between regression and classification affects not only the model’s configuration but also how you interpret and measure success. With these insights, you can confidently approach real-world machine learning tasks, selecting appropriate strategies and techniques for building more effective MLP models.
Resources and Further Reading
LeCun, Y., Bengio, Y., & Hinton, G. (1998). Deep learning. Nature.
Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press.
Schmidhuber, J. (2015). Deep learning in neural networks: An overview. Neural Networks.
Haykin, S. (2009). Neural Networks and Learning Machines. Prentice Hall.
Common questions
Make the task and the output agree
What is the difference between regression and classification with an MLP?
Regression predicts a numerical quantity, while classification predicts categories or labels. Their hidden layers can be similar, but the target representation, output activation, training loss and evaluation metric must fit the task.
Which output activation should an MLP use?
A default squared-error regressor uses an identity output. Binary classification can use one sigmoid output, multilabel classification uses independent sigmoid outputs, and mutually exclusive multiclass classification uses softmax. Supported Poisson regression uses an exponential link, so the loss and target assumptions matter.
Does the activation parameter change the output layer in scikit-learn?
The activation parameter of MLPRegressor and MLPClassifier selects the hidden-layer activation. The estimator chooses its output activation from the task and supported loss. Inspect out_activation_ after fitting instead of assuming that activation="relu" requests a ReLU output.
Why does the original RMSE code fail in modern scikit-learn?
The original mean_squared_error call includes squared=False, which raises TypeError in the checked scikit-learn 1.8.0 environment. Use root_mean_squared_error for RMSE. The full original housing fit was not executed because its dataset was not cached; a separate built-in benchmark was executed and clearly labelled.
Why is the original multiclass example still binary?
The preceding code removes Iris class 2 and reuses the filtered arrays. Running the later snippet against those arrays still trains on two classes. The added example reloads the complete Iris dataset, retains all three classes and verifies three softmax probabilities per row.
How can I evaluate an MLP without leaking validation or test data?
Split the rows before fitting preprocessing. Fit scalers and the model on training data, use validation data for model decisions, and keep test data separate for the final assessment. A pipeline helps apply learned transformations consistently. Report suitable held-out metrics and do not treat training accuracy or a probability output as proof of generalization or calibration.
Continue the series
Next: choose activation functions
You have connected task definitions to output heads. Continue with the functions that give a neural network its nonlinear behaviour.
Editorial note: the original California housing training was not rerun because the dataset was not cached. The dependent original classification snippets, RMSE compatibility probe and separate modern benchmark examples were executed. New plots use their recorded predictions; technical checks and source preservation are documented in the project record. This is an educational example, not a guarantee of model performance.
