Single Layer Perceptron in TensorFlow (original) (raw)

Last Updated : 6 Apr, 2026

A Single Layer Perceptron (SLP) is inspired by biological neurons and their ability to process information. It is based on the concept of an artificial neuron, which acts as the basic building block of neural networks and processes inputs to produce an output.

**Implementation

Let’s build a simple Single Layer Perceptron using TensorFlow to understand how a basic neural network works.

**Step1: Import required libraries

import tensorflow as tf from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler

`

**Step 2: Create and split dataset

Create a simple dataset with two features for binary classification and split it into training and testing sets.

Python `

X, y = make_classification( n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, random_state=42 )

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

`

**Step 3: Standardize the Dataset

Standardize the dataset so that features are on the same scale, which helps the model train faster and improves performance.

Python `

scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test)

`

**Step 4: Building a neural network

Build a single layer perceptron using a Sequential model with one Dense layer. The sigmoid activation is used to produce outputs between 0 and 1 for binary classification.

Python `

model = tf.keras.Sequential([ tf.keras.layers.Dense(1, activation='sigmoid', input_shape=(2,)) ])

`

Step 5: Compile the Model

Compile the model by selecting an optimizer, loss function and evaluation metric suitable for binary classification.

Python `

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

`

Step 6: Train the Model

Train the model on the training data using epochs and batch size, while keeping a validation split to monitor performance.

Python `

history = model.fit(X_train, y_train, epochs=50, batch_size=16, validation_split=0.1, verbose=0)

`

**Step 7: Model Evaluation

Evaluate the model on test data to check its performance on unseen samples.

Python `

loss, accuracy = model.evaluate(X_test, y_test, verbose=0) print(f"Test Accuracy: {accuracy:.2f}")

`

**Output:

Test Accuracy: 0.88

Download full code from here

Advantages

Limitations