Published
Edited
May 22, 2022
6 stars
Insert cell
# Machine Learning
Insert cell
Insert cell
Insert cell
samplePoints = (num)=>{
let points=[]
for (let index = 0; index < num; ++index) {
points.push({
x:getRandomFloat(0,400),
y:getRandomFloat(0,400)
})
}
return points
}
Insert cell
Insert cell
team = function(point){
return (point.x > point.y) ? 1 : -1
}
Insert cell
guess = function(weights, point){
return (weights.x * point.x) > (weights.y * point.y) ? -1 : 1
}
Insert cell
Insert cell
Insert cell
trainingResults = []
Insert cell
learningRate = []
Insert cell
weightRatio = []
Insert cell
train = function(weights, iterations){
trainingResults.length=0
learningRate.length=0
weightRatio.length=0
let sample_points = samplePoints(iterations)
//alert(sample_points.length)
for(let i = 0; i<sample_points.length;i++){
let point = sample_points[i]
//console.log(point)
let attempt = guess(weights,point)
let real = team(point)
let error = real - attempt
trainingResults.push(error+2)
let learning_rate = ((1-i)*(1/sample_points.length)*0.1)+0.01
//let learning_rate=0.01
learningRate.push(learning_rate)
weights.x = weights.x + (error * learning_rate)
weights.y = weights.y + (error * learning_rate)
let ratio = weights.x / weights.y
weightRatio.push(ratio)
//weights.x = 1000
//weights.y = 1000 * ratio
}
return weights
}
Insert cell
trainedWeights = train(getRandomWeights(), 100000)
Insert cell
htl.html`${sparkline(trainingResults)}`
Insert cell
html`${sparkline(learningRate)}`
Insert cell
html`${sparkline(weightRatio)}`
Insert cell
svg`<svg viewBox="0 0 400 400" xmlns="http://www.w3.org/2000/svg">
${ samplePoints(1000).map((point)=>{
return svg`<circle cy="${point.y}" cx="${point.x}" r="3" fill="${guess(trainedWeights,point) <0 ? 'blue' : 'red'}"/>`
}) }
<line stroke="purple" x1="0" y1="0" x2="400" y2="400" />
</svg>`
Insert cell
d3 = require("d3@5")
Insert cell
Insert cell
guess(trainedWeights,{
x:getRandomFloat(0,400),
y:getRandomFloat(0,400)
})
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more