Can you provide an example of a Simple neural network class in pure JavaScript with no…
- User
Can you provide an example of a Simple neural network class in pure JavaScript with no libraries.
- Assistant
class Neuron { constructor() { this.weights = []; }
randomWeight() { return Math.random() * 2 - 1; }
activate(input) { let sum = 0; for (let i = 0; i < input.length; i++) { sum += input[i] * this.weights[i]; } return 1 / (1 + Math.exp(-sum)); } }
class NeuralNetwork { constructor(inputSize, hiddenSize, outputSize) { this.inputSize = inputSize; this.hiddenSize = hiddenSize; this.outputSize = outputSize;
codethis.hiddenLayer = []; for (let i = 0; i < hiddenSize; i++) { let neuron = new Neuron(); neuron.weights = Array(inputSize).fill(0).map(() => neuron.randomWeight()); this.hiddenLayer.push(neuron); } this.outputLayer = []; for (let i = 0; i < outputSize; i++) { let neuron = new Neuron(); neuron.weights = Array(hiddenSize).fill(0).map(() => neuron.randomWeight()); this.outputLayer.push(neuron); }}
- User
class NeuralNetwork { constructor(inputSize, outputSize) { // Initialize weights and biases with random values this.weights = Array.from({ length: inputSize }, () => Math.random()); this.bias = Math.random(); this.outputSize = outputSize; }
// Sigmoid activation function sigmoid(x) { return 1 / (1 + Math.exp(-x)); }
// Feedforward calculation feedforward(inputs) { // Calculate weighted sum of inputs and weights, add bias, and apply sigmoid activation function const output = []; for (let i = 0; i < this.outputSize; i++) { let sum = 0; for (let j = 0; j < inputs.length; j++) { sum += inputs[j] * this.weights[j]; } sum += this.bias; output.push(this.sigmoid(sum)); } return output; }
// Train the network on a set of input/output pairs using gradient descent train(inputs, expectedOutputs, learningRate, epochs) { for (let epoch = 0; epoch < epochs; epoch++) { for (let i = 0; i < inputs.length; i++) { const output = this.feedforward(inputs[i]);
- Assistant
It looks like you've copied my previous reply. What would you like me to help you with?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)