A single neuron neural network in Python (original) (raw)

Last Updated : 30 Sep, 2025

A single neuron neural network is the simplest form of an artificial neural network, consisting of just one processing unit that takes multiple inputs, applies weights, passes the result through an activation function and produces an output.

r

Single Neuron Neural Network

Implementation

We will build a single neuron neural network in Python using NumPy.

Step 1: Import Libraries and perform Reproducibility

import numpy as np np.random.seed(1)

`

Step 2: Class and Weight Initialization

class NeuralNetwork: def init(self): self.weight_matrix = 2 * np.random.random((3, 1)) - 1

`

Step 3: Activation Function and Derivative

`

Step 4: Forward Propagation

def forward_propagation(self, inputs): inputs = np.atleast_2d(inputs) return self.tanh(np.dot(inputs, self.weight_matrix))

`

Step 5: Training the Neuron

def train(self, train_inputs, train_outputs, num_train_iterations, learning_rate=0.1, verbose=False): m = train_inputs.shape[0] for iteration in range(num_train_iterations): output = self.forward_propagation(train_inputs) error = train_outputs - output delta = error * self.tanh_derivative(output) adjustment = np.dot(train_inputs.T, delta) / m self.weight_matrix += learning_rate * adjustment

    if verbose and (iteration % max(1, num_train_iterations // 10) == 0):
        loss = np.mean(error ** 2)
        print(f"Iter {iteration:6d}  loss={loss:.6f}")

`

Step 6: Driver Code

We will run our system,

Python `

if name == "main": nn = NeuralNetwork() print("Initial weights:\n", nn.weight_matrix)

X = np.array([[0, 0, 1],
              [1, 1, 1],
              [1, 0, 1],
              [0, 1, 1]])
y = np.array([[0, 1, 1, 0]]).T

nn.train(X, y, num_train_iterations=10000, learning_rate=0.1, verbose=True)

print("\nTrained weights:\n", nn.weight_matrix)

print("\nTest [1, 0, 0] ->", nn.forward_propagation(np.array([1, 0, 0])))

`

**Output:

Screenshot-2025-09-18-172257

Result

Applications

Advantages

Limitations