How to make a simple Machine Learning Website from scratch

Written by pradyumandixit | Published 2019/02/09
Tech Story Tags: machine-learning | artificial-intelligence | javascript | web-development | website

TLDRvia the TL;DR App

Learn to make a simple machine learning website which adapts text colour 🖌 according to changeable background contrast.

This might be a little bit turbulent for people who are very new to Machine Learning. If you’re new to Machine Learning, I’d suggest you to go through my this post here:

How to Understand Machine Learning with simple Code Examples

Are you enthusiastic about machine learning? Are you trying to implement a simple machine learning webpage from scratch?

Do you want to make something cool with HTML/CSS and JavaScript?

If yes, then you’re at the perfect place.

Here we will be making a simple webpage that changes the text colour according to the background color, using a simple machine learning library brain.js.

Let’s kick off our excitement with the result itself.

Here is the link to the webpage.

Go to the above link and try changing the RGB values of the slider, you’d notice the auto changing text colour with respect to the background contrast.

This is what we would be building here.

What? You didn’t open that link? You might miss something cool to see, but anyways here are the screenshots for you.

Green background, black text

Violet-ish background, white text

Didn’t quite get the feel from screenshots? Here is a GIF:

Colour-Learning GIF

Here is the full source code that you may want to see.

Let’s get into some code.

First off, we would make a simple html file, where we would structure our webpage. We would also be needing simple sliders for R, G, B values.

So the code for **index.html** would look something like this:

<!DOCTYPE html><head><meta charset="UTF-8"><script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/brain/0.6.3/brain.js"></script><link rel="stylesheet" type="text/css" href="style.css"><title>Colour Learning</title></head>

<body><div class="container" id="container"><div class="rgbValues">rgb(<input id="red" type="number" min="0" max="255" maxlength="3" onKeyPress="if(this.value.length == 3) return false" value=0 /><input id="green" type="number" min="0" max="255" maxlength="3" onKeyPress="if(this.value.length == 3) return false" value=0 /><input id="blue" type="number" min="0" max="255" maxlength="3" onKeyPress="if(this.value.length == 3) return false" value=0 />)</div><div class="colorPicker"><label for="redSlider">R</label><input type="range" min="0" max="255" step="1" id="redSlider" value="0"/><label>G</label><input type="range" min="0" max="255" step="1" id="greenSlider" value="0"><label>B</label><input type="range" min="0" max="255" step="1" id="blueSlider"value="0"></div></div>

<script type="text/javascript" src="app.js"></script>  

</body></html>

Here we’re also using the script **brain.js** which is a machine learning JavaScript library.

Now let’s design our webpage, that lets it change colour on movement of the slider. Yes, welcome CSS to your project.

The code for **style.css** would look something like this:

@import url('https://fonts.googleapis.com/css?family=Montserrat');

body {margin: 0;}

label {color: white;font-size: 20px;font-weight: bold;-webkit-transition: .3s;transition: color .3s}

.rgbValues input {background: transparent;border-color: white;border-style: solid;border-top: none;border-left: none;border-right: none;outline: none;font-family: 'Montserrat', sans-serif;width: 10%;font-size: 80%;color: white;text-align: center;-webkit-transition: .3s;transition: border-color .3stransition: color .3s}

.container {width: 100vw;height: 100vh;background-color: rgb(0,0,0);transition: background-color 500ms;}

.rgbValues {font-size: 5vw;font-family: 'Montserrat', sans-serif;color: white;text-align: center;position: absolute;top: 35%;left: 50%;transform: translate(-50%, -50%);width: 90%;-webkit-transition: .3s;transition: color .3s}

.colorPicker {position: absolute;top: 68%;left: 50%;transform: translate(-50%, -50%);text-align: center;font-family: 'Montserrat', sans-serif;}

.colorPicker input {-webkit-appearance: none; /* Override default CSS styles */appearance: none;display: block;border: none;width: 40vw;height: 4px;background: white;outline: none;-webkit-transition: .2s;transition: background .2s;margin: 25px;}

.colorPicker input::-webkit-slider-thumb {-webkit-appearance: none;appearance: none;width: 25px;height: 25px;border: 1px solid black;border-radius: 20px;background: white;cursor: pointer;}

/* For Firefox remove arrow menu input field*/input[type='number'] {-moz-appearance:textfield;}

/* Webkit browsers like Safari and Chrome remove arrow menu input field */input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button {-webkit-appearance: none;margin: 0;}

Yes, we’ve done it. Now go to your webpage and see how the slider changes the colours.

What? The text colour is not changing and neither is the background?

Well, don’t worry, it’s because we have not yet added the machine learning code that would train our neural network and make it understand which colour to change the text to.

I have tried to comment on the blocks of the code, so it would be more easier to understand.

Also we’re yet to add the code to change the background colour. So let’s first get done with that. The code will look something like this:

// Change background colourfunction changeBackgroundColor(r,g,b){container.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;}

So let’s get into some machine learning code with JavaScript.

// creations of object for neural networkfunction createNetworkObject(r,g,b){var networkObject = {r:null, g:null, b:null};networkObject.r = r/255;networkObject.g = g/255;networkObject.b = b/255;

return networkObject;  

}// Machine learning probability labelfunction networkLabel(result){

if(result.light > result.dark)  
	result = 'light';   
    else   
        result = 'dark';  
	  
return result;  

}

This above code creates objects for our neural network and also put the light or dark label that would be our labels, to change the text colour.

Now let’s get into training our neural network with data, and of course code. The code would look something like this:

// create new neural network objectconst network = new brain.NeuralNetwork();

// training datanetwork.train([{ input: { r: 0.62, g: 0.72, b: 0.88 }, output: { light: 1 } },{ input: { r: 0.1, g: 0.84, b: 0.72 }, output: { light: 1 } },{ input: { r: 0.33, g: 0.24, b: 0.29 }, output: { dark: 1 } },{ input: { r: 0.74, g: 0.78, b: 0.86 }, output: { light: 1 } },{ input: { r: 0.31, g: 0.35, b: 0.41 }, output: { dark: 1 } },{ input: {r: 1, g: 0.42, b: 0.52}, output: { dark: 1 } },{ input: {r: 0, g: 0, b: 1}, output: { dark: 1 } },{ input: {r: 0.8, g: 0.44, b: 1}, output: { dark: 1 } },{ input: {r: 0, g: 0.44, b: 1}, output: { dark: 1 } },{ input: {r: 0.3 , g: 0.6, b: 1}, output: { dark: 1 } },{ input: {r: 0.1, g: 0.6, b: 0}, output: { dark: 1 } }]);

// grab inputs in .rgbValues divvar input = document.querySelectorAll(".rgbValues input");// grab inputs in .colorPicker divvar sliderInput = document.querySelectorAll('.colorPicker input');

// rgb sliderfor(var i = 0; i < sliderInput.length; i++){sliderInput[i].addEventListener("input", function(){var redSlider = document.getElementById("redSlider").value;var greenSlider = document.getElementById("greenSlider").value;var blueSlider = document.getElementById("blueSlider").value;

	document.getElementById("red").value = redSlider;  
	document.getElementById("green").value = greenSlider;  
	document.getElementById("blue").value = blueSlider;  

	changeBackgroundColor(redSlider,greenSlider,blueSlider);  

	var networkObject = createNetworkObject(redSlider,greenSlider,blueSlider);  
	var MLresult = network.run(networkObject);  

	MLresult = networkLabel(MLresult);  
	console.log(MLresult);  

	changeElementsColor(MLresult, input, sliderInput);  
});  

}

// rgb value input (the non slider one)for(var i = 0; i < input.length; i++){input[i].addEventListener("keyup", function(e){// right arrow key to next tabif(e.keyCode == 39){$(this).next('input, select').focus();}// left arrow key to previous tabif(e.keyCode == 37){$(this).prev('input, select').focus();}// max value input 255if(e.target.value > 255){e.target.value = 255;}

	var container = document.getElementById("container");  
	var red = document.getElementById("red").value;  
	var green = document.getElementById("green").value;  
	var blue = document.getElementById("blue").value;   

	// change slider values to correspong to rgb value input(s)  
	document.getElementById('redSlider').value = red;  
	document.getElementById('greenSlider').value = green;  
	document.getElementById('blueSlider').value = blue;  

	changeBackgroundColor(red, green, blue);  

	// machine learning   
	var networkObject = createNetworkObject(red,green,blue);  
	var MLresult = network.run(networkObject);  

	MLresult = networkLabel(MLresult);  
	console.log(MLresult);  

	changeElementsColor(MLresult, input, sliderInput);  
});  

// when input changes from up down arrows keys to change value  
input\[i\].addEventListener("change", function(){  
	var container = document.getElementById("container");  
	var red = document.getElementById("red").value;  
	var green = document.getElementById("green").value;  
	var blue = document.getElementById("blue").value;  
  
	changeBackgroundColor(red, green, blue);  

	// machine learning   
	var networkObject = createNetworkObject(red,green,blue);  
	var MLresult = network.run(networkObject);  

	MLresult = networkLabel(MLresult);  
	console.log(MLresult);  
	  
	var MLresult = network.run(networkObject);  

	// black text for 'light' colours  
	changeElementsColor(MLresult, input, sliderInput);  
});  

}

Please refer to the comments I have provided, it would help you understand this big but straight forward piece of code, better.

And now we should add the code that would work the wonders in our machine learning code. This piece of code helps to change the text colour according to need and the training.

// change colors on page relative to backgroundfunction changeElementsColor(result, input, sliderInput){if (result == 'light'){for(var i = 0; i < input.length; i++){input[i].parentElement.style.color = "black";input[i].style.color = "black";input[i].style.borderColor = "black";}for(var i = 0; i < sliderInput.length; i++){sliderInput[i].style.backgroundColor = 'black';}// grab label elementvar label = document.getElementsByTagName('LABEL');for(var i = 0; i < label.length; i++){label[i].style.color = 'black';}}else if (result == 'dark'){for(var i = 0; i < input.length; i++){input[i].parentElement.style.color = "white";input[i].style.color = "white";input[i].style.borderColor = "white";}for(var i = 0; i < sliderInput.length; i++){sliderInput[i].style.backgroundColor = 'white';}

		var label = document.getElementsByTagName('LABEL');  
		for(var i = 0; i < label.length; i++){  
			label\[i\].style.color = 'white';  
		}  
	}  

}

And yes, that’s it.

Take a look at your webpage and auto changing text colour according to the contrast, using machine learning.

If you’ve some difficulties in the code above, please take a look at the source code here.

You’ve successfully built yourself a machine learning website using simple JavaScript, HTML and CSS.

What are you waiting for?

Go and Show Off!!

In case we’re meeting for the first time here, I am Pradyuman Dixit and I mostly write about Machine learning, Android Development and sometimes about Web Development.

You can read my other Machine Learning posts here:

How to Understand Machine Learning with simple Code Examples

How to make a Machine Learning Android Game as a beginner


Published by HackerNoon on 2019/02/09