Case 1. Convolution in pure PHP
Implementation in pure PHP
We implement the convolution operation by hand – without any libraries or ready-made ML algorithms – and see how a filter highlights features of an image. The image is a 5 × 5 matrix of brightness values (0 – black, 255 – white), the filter (kernel) is a 3 × 3 matrix of weights. The kernel slides over the image with stride 1 and no padding; at every position the pixels are multiplied by the weights and summed, giving one value of the feature map. The kernel is not flipped (cross-correlation), as in most CNN implementations.
Example of code:
<?php
/**
* Apply a convolution-style filter to a 2D matrix.
*
* This implementation uses cross-correlation:
* the kernel is not flipped.
*
* @param array<array<int|float>> $input
* @param array<array<int|float>> $kernel
* @return array<array<int|float>>
*/
function convolve(array $input, array $kernel): array
{
if (!array_is_list($input) || !array_is_list($kernel)) {
throw new InvalidArgumentException(
'Input matrix and kernel must use sequential numeric indexes.'
);
}
$inputHeight = count($input);
$inputWidth = count($input[0] ?? []);
$kernelHeight = count($kernel);
$kernelWidth = count($kernel[0] ?? []);
if ($inputHeight === 0 || $inputWidth === 0) {
throw new InvalidArgumentException('Input matrix must not be empty.');
}
if ($kernelHeight === 0 || $kernelWidth === 0) {
throw new InvalidArgumentException('Kernel must not be empty.');
}
foreach ($input as $row) {
if (!array_is_list($row) || count($row) !== $inputWidth) {
throw new InvalidArgumentException('Input matrix must be rectangular.');
}
}
foreach ($kernel as $row) {
if (!array_is_list($row) || count($row) !== $kernelWidth) {
throw new InvalidArgumentException('Kernel must be rectangular.');
}
}
if ($kernelHeight > $inputHeight || $kernelWidth > $inputWidth) {
throw new InvalidArgumentException('Kernel must fit inside the input matrix.');
}
$outputHeight = $inputHeight - $kernelHeight + 1;
$outputWidth = $inputWidth - $kernelWidth + 1;
$output = [];
for ($y = 0; $y < $outputHeight; $y++) {
$outputRow = [];
for ($x = 0; $x < $outputWidth; $x++) {
$sum = 0;
for ($ky = 0; $ky < $kernelHeight; $ky++) {
for ($kx = 0; $kx < $kernelWidth; $kx++) {
$pixel = $input[$y + $ky][$x + $kx];
$weight = $kernel[$ky][$kx];
$sum += $pixel * $weight;
}
}
$outputRow[] = $sum;
}
$output[] = $outputRow;
}
return $output;
}
/**
* Print a matrix in a readable format.
*/
function printMatrix(array $matrix): void
{
foreach ($matrix as $row) {
echo implode("\t",
array_map(static fn (int|float $value): string => (string) $value, $row)
) . "\n";
}
}