xxxxxxxxxx
57
// Declare global variables
let neuralNetwork;
let trainingData = [];
let totalPoints = 1000;
let circlePoints = 0;
function setup() {
// Create a canvas
createCanvas(400, 400);
// Create the neural network
neuralNetwork = ml5.neuralNetwork();
// Generate training data
for (let i = 0; i < totalPoints; i++) {
let x = random(-1, 1);
let y = random(-1, 1);
let label = x * x + y * y < 1 ? 1 : 0; // Check if the point is inside the circle
trainingData.push({ input: [x, y], output: [label] });
}
// Train the neural network
neuralNetwork.addData(trainingData);
neuralNetwork.normalizeData();
neuralNetwork.train({ epochs: 32 }, finishedTraining);
}
function finishedTraining() {
// Use the trained neural network to estimate pi
for (let i = 0; i < totalPoints; i++) {
let x = random(-1, 1);
let y = random(-1, 1);
let input = [x, y];
neuralNetwork.predict(input, (err, result) => {
if (result[0].value > 0.5) {
circlePoints++;
}
});
}
// Calculate the estimated value of pi
let piEstimate = 4 * (circlePoints / totalPoints);
// Display the estimated value of pi
textSize(32);
textAlign(CENTER, CENTER);
text("Estimated Pi: " + piEstimate, width / 2, height / 2);
}
function draw() {
// Display a loading message while training
background(220);
textSize(32);
textAlign(CENTER, CENTER);
text("Training the neural network...", width / 2, height / 2);
}