Bookmark this: tool.io/neural-network/feedforward/source-code
Feedforward Neural Network Demonstrator Source Code
Browse the implementation files for Feedforward Neural Network Demonstrator.tool.ts typescript
import { parseFiniteNumberList } from '../../parse/numeric-dataset/tool';
const activations: Record<string, (value: number) => number> = {
linear: (value) => value,
relu: (value) => Math.max(0, value),
sigmoid: (value) => 1 / (1 + Math.exp(-value)),
tanh: Math.tanh
};
export const demonstrateFeedforwardNetwork = (
inputValuesInput: unknown,
weightsInput: unknown,
biasesInput: unknown,
activationInput: unknown
): string => {
const inputs = parseFiniteNumberList(inputValuesInput);
const biases = parseFiniteNumberList(biasesInput);
const activation =
typeof activationInput === 'string'
? activations[activationInput]
: undefined;
if (
!inputs ||
!biases ||
!activation ||
typeof weightsInput !== 'string'
)
return '';
let weights: unknown;
try {
weights = JSON.parse(weightsInput);
} catch {
return '';
}
if (
!Array.isArray(weights) ||
weights.length !== biases.length ||
weights.some(
(row) =>
!Array.isArray(row) ||
row.length !== inputs.length ||
row.some(
(value) =>
typeof value !== 'number' || !Number.isFinite(value)
)
)
)
return '';
const preActivation = (weights as number[][]).map(
(row, neuron) =>
row.reduce(
(sum, weight, index) => sum + weight * inputs[index],
biases[neuron]
)
);
const output = preActivation.map(activation);
return JSON.stringify(
{
activation: activationInput,
output: output.map((value) =>
Number(value.toPrecision(10))
),
preActivation: preActivation.map((value) =>
Number(value.toPrecision(10))
)
},
null,
2
);
};
export const Tool: TypeTool = {
name: 'Feedforward Neural Network Demonstrator',
slug: 'neural-network/feedforward',
intro:
'Run one dense neural-network layer with selectable activation entirely in the browser.',
tool: demonstrateFeedforwardNetwork,
i: [
{
example: '1, 2',
label: 'Input Vector',
placeholder: 'Numeric input features',
render: 'textarea',
type: 'text'
},
{
example: '[[0.5,1],[-1,0.25]]',
label: 'Weight Matrix',
placeholder: 'One JSON row per output neuron',
render: 'textarea',
type: 'text'
},
{
example: '0.1, -0.2',
label: 'Bias Vector',
placeholder: 'One bias per output neuron',
render: 'textarea',
type: 'text'
},
{
example: 'relu',
label: 'Activation',
options: [
{ text: 'ReLU', value: 'relu' },
{ text: 'Sigmoid', value: 'sigmoid' },
{ text: 'Tanh', value: 'tanh' },
{ text: 'Linear', value: 'linear' }
],
placeholder: 'Activation function',
type: 'select'
}
],
o: [
{
example: '{ "output": [2.6, 0] }',
label: 'Layer Output',
placeholder: 'Output will appear here...',
render: 'textarea',
type: 'text'
}
]
};
export default Tool;
Description
Browse the implementation files for Feedforward Neural Network Demonstrator.