Certainly! Below is a simple implementation of a perceptron in Oberon-07. This example demonstrates a perceptron with:
- A fixed number of inputs (e.g., 2 inputs)
- A training function using the perceptron learning rule
- A prediction function that outputs 0 or 1
Simple Perceptron in Oberon-07
MODULE SimplePerceptron;
IMPORT Out;
CONST
InputCount = 2; (* Number of inputs *)
TYPE
Vector = ARRAY InputCount OF REAL;
VAR
weights: Vector;
bias: REAL;
(* Initialize weights and bias to zero *)
PROCEDURE Init;
VAR i: INTEGER;
BEGIN
FOR i := 0 TO InputCount-1 DO
weights[i] := 0.0;
END;
bias := 0.0;
END Init;
(* Activation function: step function *)
PROCEDURE Activate(sum: REAL): INTEGER;
BEGIN
IF sum >= 0.0 THEN
RETURN 1
ELSE
RETURN 0
END;
END Activate;
(* Predict output for given input vector *)
PROCEDURE Predict(input: Vector): INTEGER;
VAR
i: INTEGER;
sum: REAL;
BEGIN
sum := bias;
FOR i := 0 TO InputCount-1 DO
sum := sum + weights[i] * input[i];
END;
RETURN Activate(sum);
END Predict;
(* Train perceptron with one training example *)
PROCEDURE Train(input: Vector; expected: INTEGER; learningRate: REAL);
VAR
prediction, error: INTEGER;
i: INTEGER;
BEGIN
prediction := Predict(input);
error := expected - prediction;
(* Update weights and bias *)
FOR i := 0 TO InputCount-1 DO
weights[i] := weights[i] + learningRate * REAL(error) * input[i];
END;
bias := bias + learningRate * REAL(error);
END Train;
(* Test the perceptron with a simple AND function *)
PROCEDURE Test;
VAR
inputs: ARRAY 4 OF Vector = [
[0.0, 0.0],
[0.0, 1.0],
[1.0, 0.0],
[1.0, 1.0]
];
outputs: ARRAY 4 OF INTEGER = [0, 0, 0, 1];
i, epoch: INTEGER;
learningRate: REAL;
BEGIN
learningRate := 0.1;
Init;
(* Train for 10 epochs *)
FOR epoch := 1 TO 10 DO
FOR i := 0 TO 3 DO
Train(inputs[i], outputs[i], learningRate);
END;
END;
(* Print results *)
Out.String("Perceptron results for AND function:" + Char(10));
FOR i := 0 TO 3 DO
Out.String("Input: ");
Out.Int(ROUND(inputs[i][0]), 1); Out.String(", ");
Out.Int(ROUND(inputs[i][1]), 1); Out.String(" -> Output: ");
Out.Int(Predict(inputs[i]), 1);
Out.Char(10);
END;
END Test;
BEGIN
Test;
END SimplePerceptron.
Explanation:
- weights and bias are initialized to zero.
- The Activate procedure implements a step function: returns 1 if sum ≥ 0, else 0.
- The Predict procedure calculates the weighted sum plus bias and applies the activation.
- The Train procedure updates weights and bias using the perceptron learning rule.
- The Test procedure trains the perceptron on the AND logic gate truth table and prints the results.
How to run:
- Compile this module with an Oberon-07 compiler.
- Run the module; it will output the perceptron's predictions for the AND function inputs.
If you want me to extend this with more features (e.g., dynamic input size, more epochs, or other activation functions), just ask!