HTML Images


Images can improve the design and the appearance of a web page.


Example

<img src="pic_trulli.jpg" alt="Italian Trulli">

Example

<img src="img_girl.jpg" alt="Girl in a jacket">

Example

<img src="img_chania.jpg" alt="Flowers in Chania">

HTML Images Syntax

The HTML <img> tag is used to embed an image in a web page.

Images are not technically inserted into a web page; images are linked to web pages. The <img> tag creates a holding space for the referenced image.

The <img> tag is empty, it contains attributes only, and does not have a closing tag.

The <img> tag has two required attributes:

  • src - Specifies the path to the image
  • alt - Specifies an alternate text for the image

Syntax

<img src="url" alt="alternatetext">

The src Attribute

The required src attribute specifies the path (URL) to the image.

Note: When a web page loads, it is the browser, at that moment, that gets the image from a web server and inserts it into the page. Therefore, make sure that the image actually stays in the same spot in relation to the web page, otherwise your visitors will get a broken link icon. The broken link icon and the alt text are shown if the browser cannot find the image.

Example

<img src="img_chania.jpg" alt="Flowers in Chania">


The alt Attribute

The required alt attribute provides an alternate text for an image, if the user for some reason cannot view it (because of slow connection, an error in the src attribute, or if the user uses a screen reader).

The value of the alt attribute should describe the image:

Example

<img src="img_chania.jpg" alt="Flowers in Chania">

If a browser cannot find an image, it will display the value of the alt attribute:

Example

<img src="wrongname.gif" alt="Flowers in Chania">

Tip: A screen reader is a software program that reads the HTML code, and allows the user to "listen" to the content. Screen readers are useful for people who are visually impaired or learning disabled.


Image Size - Width and Height

You can use the style attribute to specify the width and height of an image.

Example

<img src="img_girl.jpg" alt="Girl in a jacket" style="width:500px;height:600px;">

Alternatively, you can use the width and height attributes:

Example

<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600">

The width and height attributes always define the width and height of the image in pixels.

Note: Always specify the width and height of an image. If width and height are not specified, the web page might flicker while the image loads.


Width and Height, or Style?

The width, height, and style attributes are all valid in HTML.

However, we suggest using the style attribute. It prevents styles sheets from changing the size of images:

Example

<!DOCTYPE html>
<html>
<head>
<style>
img {
  width: 100%;
}
</style>
</head>
<body>

<img src="html5.gif" alt="HTML5 Icon" width="128" height="128">

<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">

</body>
</html>

Images in Another Folder

If you have your images in a sub-folder, you must include the folder name in the src attribute:

Example

<img src="/images/html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">

Images on Another Server/Website

Some web sites point to an image on another server.

To point to an image on another server, you must specify an absolute (full) URL in the src attribute:

Example

<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com">

Notes on external images: External images might be under copyright. If you do not get permission to use it, you may be in violation of copyright laws. In addition, you cannot control external images; they can suddenly be removed or changed.


Animated Images

HTML allows animated GIFs:

Example

<img src="programming.gif" alt="Computer Man" style="width:48px;height:48px;">

Image as a Link

To use an image as a link, put the <img> tag inside the <a> tag:

Example

<a href="default.asp">
  <img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;">
</a>

Image Floating

Use the CSS float property to let the image float to the right or to the left of a text:

Example

<p><img src="smiley.gif" alt="Smiley face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.</p>

<p><img src="smiley.gif" alt="Smiley face" style="float:left;width:42px;height:42px;">
The image will float to the left of the text.</p>

Tip: To learn more about CSS Float, read our .


Common Image Formats

Here are the most common image file types, which are supported in all browsers (Chrome, Edge, Firefox, Safari, Opera):

Abbreviation File Format File Extension
APNG Animated Portable Network Graphics .apng
GIF Graphics Interchange Format .gif
ICO Microsoft Icon .ico, .cur
JPEG Joint Photographic Expert Group image .jpg, .jpeg, .jfif, .pjpeg, .pjp
PNG Portable Network Graphics .png
SVG Scalable Vector Graphics .svg

Chapter Summary

  • Use the HTML <img> element to define an image
  • Use the HTML src attribute to define the URL of the image
  • Use the HTML alt attribute to define an alternate text for an image, if it cannot be displayed
  • Use the HTML width and height attributes or the CSS width and height properties to define the size of the image
  • Use the CSS float property to let the image float to the left or to the right

Note: Loading large images takes time, and can slow down your web page. Use images carefully.


HTML Exercises

Test Yourself With Exercises

Exercise:

Use the HTML image attributes to set the size of the image to 250 pixels wide and 400 pixels tall.

<img src="scream.png" ="250" ="400">


HTML Image Tags

Tag Description
Defines an image
Defines an image map
Defines a clickable area inside an image map
Defines a container for multiple image resources

For a complete list of all available HTML tags, visit our .


 

Machine Learning is a subfield of Artificial intelligence

"Learning machines to imitate human intelligence"

 
 

Machine Learning (ML)

Traditional programming uses known algorithms to produce results from data:

Data + Algorithms = Results

 

Machine learning creates new algorithms from data and results:

 

Data + Results = Algorithms

Neural Networks (NN)

Neural Networks is:

  • A programming technique
  • A method used in machine learning
  • A software that learns from mistakes

Neural Networks are based on how the human brain works:
Neurons are sending messages to each other. While the neurons are trying to solve a problem (over and over again), it is strengthening the connections that lead to success and diminishing the connections that lead to failure.

 


Perceptrons

The Perceptron defines the first step into Neural Networks.

It represents a single neuron with only one input layer, and no hidden layers.

 


Neural Networks

 

Neural Networks are Multi-Layer Perceptrons.

 

In its simplest form, a neural network is made up from:

  • An input layer (yellow)
  • A hidden layer (blue)
  • An output layer (red)

In the Neural Network Model, input data (yellow) are processed against a hidden layer (blue) before producing the final output (red).

The First Layer:
The yellow perceptrons are making simple decisions based on the input. Each single decision is sent to the perceptrons in the next layer.

The Second Layer:
The blue perceptrons are making decisions by weighing the results from the first layer. This layer make more complex decisions at a more abstract level than the first layer.



Deep Neural Networks

Deep Neural Networks is:

  • A programming technique
  • A method used in machine learning
  • A software that learns from mistakes

Deep Neural Networks are made up of several hidden layers of neural networks that perform complex operations on massive amounts of data.

Each successive layer uses the preceding layer as input.

For instance, optical reading uses low layers to identify edges, and higher layers to identify letters.

 

In the Deep Neural Network Model, input data (yellow) are processed against a hidden layer (blue) and modified against more hidden layers (green) to produce the final output (red).

The First Layer:
The yellow perceptrons are making simple decisions based on the input. Each single decision is sent to the perceptrons in the next layer.

The Second Layer:
The blue perceptrons are making decisions by weighing the results from the first layer. This layer make more complex decisions at a more abstract level than the first layer.

The Third Layer:
Even more complex decisions are made by the green perceptrons.


Deep Learning (DL)

Deep Learning is a subset of Machine Learning.

Deep Learning is responsible for the AI boom of the last years.

Deep learning is an advanced type of ML that handles complex tasks like image recognition.

Machine Learning Deep Learning
A subset of AI A subset of Machine Learning
Uses smaller data sets Uses larger datasets
Trained by humans Learns on its own
Creates simple algorithms Creates complex algorithms

 

 
ML Intro
 

Artificial Intelligence
Is a Contrast to
Human Intelligence

 

What is Artificial Intelligence?

Artificial Intelligence suggest that machines can mimic humans in:

  • Talking
  • Thinking
  • Learning
  • Planning
  • Understanding

Artificial Intelligence is also called Machine Intelligence and Computer Intelligence.


Arthur Samuel 1959:

"Machine Learning is a subfield of computer science that gives computers the ability to learn without being programmed"

Arthur Samuel, IBM Journal of Research and Development, Vol. 3, 1959.


Wikipedia 2022:

Artificial intelligence is intelligence demonstrated by machines. Unlike natural intelligence displayed by humans and animals, which involves consciousness and emotionality.


Investopedia 2022:

Artificial intelligence refers to the simulation of human intelligence in machines that are programmed to think like humans and mimic their actions.


IBM 2022:

Artificial intelligence leverages computers and machines to mimic the problem-solving and decision-making capabilities of the human mind.


Britannica 2022:

Artificial intelligence is the ability of a digital computer or computer-controlled robot to perform tasks commonly associated with intelligent beings, .... such as the ability to reason, discover meaning, generalize, or learn from past experience.


Artificial Intelligence (AI)

Artificial Intelligence is a scientific discipline embracing several Data Science fields ranging from narrow AI to strong AI, including machine learning, deep learning, big data and data mining.

Artificial Intelligence Narrow AI Machine Learning Neural Networks Big Data Deep Learning Strong AI
 

Narrow AI

Narrow Artificial Intelligence is limited to narrow (specific) areas like most of the AI we have around us today:

  • Email spam Filters
  • Text to Speech
  • Speech Recognition
  • Self Driving Cars
  • E-Payment
  • Google Maps
  • Text Autocorrect
  • Automated Translation
  • Chatbots
  • Social Media
  • Face Detection
  • Visual Perception
  • Search Algorithms
  • Robots
  • Automated Investment
  • NLP - Natural Language Processing
  • Flying Drones
  • IBM's Dr. Watson
  • Apple's Siri
  • Microsoft's Cortana
  • Amazon's Alexa
  • Netflix's Recommendations

Narrow AI is also called Weak AI.

Weak AI: Built to simulate human intelligence.

Strong AI: Built to copy human intelligence.



Strong AI

Strong Artificial Intelligence is the type of AI that mimics human intelligence.

Strong AI indicates the ability to think, plan, learn, and communicate.

Strong AI is the theoretical next level of AI: True Intelligence.

Strong AI moves towards machines with self-awareness, consciousness, and objective thoughts.

  One need not decide if a machine can "think".
One need only decide if a machine can act as intelligently as a human.

Alan Turing

 

 

 

ML and AI
 

Traditionally, Machine Learning applications are using R or Python.

But JavaScript has a great future as an Machine Learning language:

  • JavaScript is well known. All developers can use it.
  • Security is built in. JavaScript cannot access your files.
  • JavaScript is faster than Python.
  • JavaScript can use hardware acceleration.
  • JavaScript runs in the browser

JavaScript is Good for Machine Learning

Machine Learning can be math-heavy. The nature of neural networks is highly technical, and the jargon that goes along with it tends to scare people away.

This is where JavaScript comes to help, with easy to understand software to simplifying the process of creating and training neural networks.

With new Machine Learning libraries, JavaScript developers can add Machine Learning and Artificial Intelligence to web applications.


WebGL API

WebGL is a JavaScript API for rendering 2d and 3D graphics in any browser.

WebGL can run on both integrated and standalone graphic cards in any PC.

WebGL brings 3D graphics to the web browser. Major browser vendors Apple (Safari), Google (Chrome), Microsoft (Edge), and Mozilla (Firefox) are members of the WebGL Working Group.

 


JavaScript Machine Learning Libraries

Machine Learning in the Browser means:

  • Machine Learning in JavaScript
  • Machine Learning for the Web
  • Machine Learning for Everyone
  • Machine Learning on more Platforms

Advantages:

  • Easy to use. Nothing to install.
  • Powerful graphics. Browsers support WebGL.
  • Better privacy. Data can stay on the client.
  • More platforms. JavaScript runs on mobile devices.

Math.js

Math.js is an extensive math library for JavaScript and Node.js.

Math.js is powerful and easy to use. It comes with a large set of built-in functions, a flexible expression parser, and solutions to work with many data types like numbers, big numbers, complex numbers, fractions, units, arrays, and matrices.


Brain.js

Brain.js is a JavaScript library that makes it easy to understand Neural Networks because it hides the complexity of the mathematics.

Brain.js is simple to use. You do not need to know neural networks in details to work with Brain.js.

Brain.js provides multiple neural network implementations as different neural nets can be trained to do different things well.

 


ml5.js

ml5.js is trying to make machine learning more accessible to a wider audience.

The ml5 team is working to wrap machine learning functionality in friendlier ways.

The example below uses only three lines of code to classify an image:

<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
<script src="https://unpkg.com/ml5@latest/dist/ml5.min.js"></script>
<body>
<h1>Image Classification</h1>
<h2>With MobileNet and ml5.js</h2>
<div id="result">Scanning ...</div>
<img id="image" src="pic1.jpg" width="100%">

<script>
// Initialize Image Classifier with MobileNet.
const classifier =  ml5.imageClassifier('MobileNet');
classifier.classify(document.getElementById("image"), gotResult);

// Function to run when results arrive
function gotResult(error, results) {
  const element = document.getElementById("result");
  if (error) {
    element.innerHTML = error;
  } else {
    let num = results[0].confidence * 100;
    element.innerHTML = results[0].label + "<br>Confidence: " + num.toFixed(2) + "%";
  }
}
</script>
</body>
</html>

Image Classification

With MobileNet and ml5.js

robin, American robin, Turdus migratorius
Confidence: 95.52%

 

Try substitute "pic1.jpg" with "pic2.jpg" and "pic3.jpg".


TensorFlow

is a web application written in d3.js.

With TensorFlow Playground you can learn about Neural Networks (NN) without math.

In your own Web Browser you can create a Neural Network and see the result.

TensorFlow.js was previously called Tf.js and Deeplearn.js.


Plotting in the Browser

Here is a list of some JavaScript libraries to use for both Machine Learning graphs and other HTML charts:

 


Plotting Equations

<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<body>
<h1>Using Plotly.js</h1>
<p>Enter Equation:</p>
<p><input id="equation" type="text" value="x * 2 + 17"></p>
<p>
<button onclick='plot("scatter")'>Scatter</button>
<button onclick='plot("lines")'>Draw Line</button>
</p>
<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
function plot(type) {
const exp = document.getElementById("equation").value;
const xValues = [];
const yValues = [];
let mode = "lines";
if (type == "scatter") {mode = "markers"}

// Generate values
for (let x = 0; x <= 10; x += 1) {
  xValues.push(x);
  yValues.push(eval(exp));
}

// Display using Plotly
const data = [{x:xValues, y:yValues, mode:mode, type:"scatter"}];
const layout = {title: "y = " + exp};
Plotly.newPlot("myPlot", data, layout);
}
</script>

</body>
</html>

 


Plotting Values

<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>
<h1>Using Plotly.js</h1>

<p>X values:<br>
<input id="xvalues" style="width:95%" type="text"
value="50,60,70,80,90,100,110,120,130,140,150"></p>

<p>Y values:<br>
<input id="yvalues" style="width:95%" type="text"
value="7,8,8,9,9,9,10,11,14,14,15"></p>

<button onclick='plot("scatter")'>Scatter</button>
<button onclick='plot("lines")'>Draw Lines</button>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
function plot(type) {
const xArray = document.getElementById("xvalues").value.split(',');
const yArray = document.getElementById("yvalues").value.split(',');
let mode = "lines";
if (type == "scatter") {mode = "markers"}
  Plotly.newPlot("myPlot", [{x:xArray, y:yArray, mode:mode, type:"scatter"}]);
}
</script>

</body>
</html>

 



Machine Learning Languages

Programming languages involved in Machine Learning and Artificial Intelligence are:

  • LISP
  • R
  • Python
  • C++
  • Java
  • JavaScript
  • SQL

LISP

LISP is the second oldest programming language in the world (1958), one year younger than Fortran (1957).

The term Artificial Intelligence was made up by John McCarthy who invented LISP.

LISP was founded on the theory of Recursive Functions (self modifying functions), and this is very suitable for Machine Learning programs where "self-learning" is an important part of the program.

 


 

The R Language

R is a programming language for Graphics and Statistical computing.

R is supported by the .

R comes with a wide set of statistical and graphical techniques for:

  • Linear Modeling
  • Nonlinear Modeling
  • Statistical Tests
  • Time-series Analysis
  • Classification
  • Clustering

Python

Python is a general-purpose coding language. It can be used for all types of programming and software development.

Python is typically used for server development, like building web apps for web servers.

Python is also typically used in Data Science.

An advantage for using Python is that it comes with some very suitable libraries:

  • NumPy (Library for working with Arrays)
  • SciPy (Library for Statistical Science)
  • Matplotlib (Graph Plotting Library)
  • NLTK (Natural Language Toolkit)
  • TensorFlow (Machine Learning)

 

 

Languages


C++

C++ holds the title: "The worlds fastest programming language".

Because of the speed, C++ is a preferred language when programming Computer Games.

It provides faster execution and has less response time which is applied in search engines and development of computer games.

Google uses C++ in Artificial Intelligence and Machine Learning programs for SEO (Search Engine Optimization).

SHARK is a super-fast C++ library with support for supervised learning algorithms, linear regression, neural networks, and clustering.

MLPACK is also a super-fast machine learning library for C++.


Java

Java is another general-purpose coding language that can be used for all types of software development.

For Machine Learning, Java is mostly used to create algorithms, and neural networks.


SQL

SQL (Structured Query Language) is the most popular language for managing data.

Knowledge of SQL databases, tables and queries helps data scientists when dealing with data.

SQL is very convenient for storing, manipulating, and retrieving data in databases.

 

 
Machine Learning in JavaScript
 

Image Classification Example


Artificial Music Intelligence

Can an algorithm compose better music than a human?

David Cope is a former professor of music at the University of Santa Cruz (California).

For over 30 years, David Cope has been developing Emmy or EMI (Experimental Musical Intelligence), an algorithm to compose music in the style of famous composers.


Bach, Larson, or EMI?

In a test performed by professor Douglas Hofstadter of the University of Oregon, a pianist performed three musical pieces in the style of Bach:

  • One written by Bach
  • One written by Steve Larson
  • One written by EMI

Dr. Larson was hurt when the audience concluded that his piece was written by EMI.

He felt better when the listeners decided that the piece composed by EMI was a genuine Bach.

Source

Vivaldi


Project Baseline

is an initiative to make it easy for everyone to contribute to the map of human health and to participate in clinical research.

In Project Baseline, researchers, clinicians, engineers, designers, advocates, and volunteers, can collaborate building the next generation of healthcare tools and services.

 

Baseline


Data Scientists

Data Scientists can be experts in multiple disciplines:

  • Applied mathematics
  • Computational statistics
  • Computer Science
  • Machine learning
  • Deep learning

Data Scientists also have significant big data experience:

  • Business Intelligence
  • Data Base Design
  • Data Warehouse Design
  • Data Mining
  • SQL Queries
  • SQL Reporting

 

Artificial Intelligence is a scientific discipline embracing several Data Science fields ranging from narrow AI to strong AI, including machine learning, deep learning, big data and data mining.


Artificial Health Intelligence

The Corona Pandemic pushed the need for optimizing Medical Healthcare.

 

Machine learning is a new technology that can provide better drug discovery, shorter development time, and lower drug costs.

Machine Learning enables healthcare to use "big data" for making better medical or clinical decisions.


FDA Statement

Statement from FDA Commissioner Scott Gottlieb, M.D. on steps toward a new, tailored review framework for artificial intelligence-based medical devices:

"Artificial intelligence and machine learning have the potential to fundamentally transform the delivery of health care. As technology and science advance, we can expect to see earlier disease detection, more accurate diagnosis, more targeted therapies and significant improvements in personalized medicine".

 



 
ML Examples

 

 

Linear Graphs

 
 

Machine Learning often uses line graphs to show relationships.

A line graph displays the values of a linear function: y = ax + b

Important keywords:

  • Linear (Straight)
  • Slope (Angle)
  • Intercept (Start value)

Linear

Linear means straight. A linear graph is a straight line.

The graph consists of two axes: x-axis (horizontal) and y-axis (vertical).

 

 

Example

Example

const xValues = [];
const yValues = [];

// Generate values
for (let x = 0; x <= 10; x += 1) {
  xValues.push(x);
  yValues.push(x);
}

// Define Data
const data = [{
  x: xValues,
  y: yValues,
  mode: "lines"
}];

// Define Layout
const layout = {title: "y = x"};

// Display using Plotly
Plotly.newPlot("myPlot", data, layout);
 

 


 


Slope

The slope is the angle of the graph.

The slope is the a value in a linear graph:

y = ax

In this example, slope = 1.2:

 

 

Example

Example

let slope = 1.2;
const xValues = [];
const yValues = [];

// Generate values
for (let x = 0; x <= 10; x += 1) {
  xValues.push(x);
  yValues.push(x * slope);
}

// Define Data
const data = [{
  x: xValues,
  y: yValues,
  mode: "lines"
}];
// Define Layout
const layout = {title: "Slope=" + slope};

// Display using Plotly
Plotly.newPlot("myPlot", data, layout);
 

 


Intercept

The Intercept is the start value of the graph.

The intercept is the b value in a linear graph:

y = ax + b

In this example, slope = 1.2 and intercept = 2:

 

Example

 

<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

<body>
<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
let slope = 1.2;
let intercept = 7;
const xValues = [];
const yValues = [];

// Generate values
for (let x = 0; x <= 10; x += 1) {
  xValues.push(x);
  yValues.push(x * slope + intercept);
}

// Define Data
const data = [{
  x: xValues,
  y: yValues,
  mode: "lines"
}];

// Define Layout
let layout = {title: "Slope=" + slope + " Intercept=" + intercept};

// Display using Plotly
Plotly.newPlot("myPlot", data, layout);
</script>

</body>
</html>

 

 

 

 

ML Linear Graphs

Scatter Plots

 
  • Data Collections
  • Scatter Plots
  • Graphs

 

Data Collection

 

Collecting data is the most important part of any Machine Intelligence projects.

The most common data to collect are numbers and measurements.

Often data are stored in arrays representing the relationship between values.

This table contains house prices versus size:

Price 7 8 8 9 9 9 10 11 14 14 15
Size 50 60 70 80 90 100 110 120 130 140 150

Scatter Plots

A Scatter Plot has points scattered over an area representing the relationship between two values.

Example

<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
const xArray = [50,60,70,80,90,100,110,120,130,140,150];
const yArray = [7,8,8,9,9,9,10,11,14,14,15];

// Define Data
const data = [{
  x:xArray,
  y:yArray,
  mode:"markers"
}];

// Define Layout
const layout = {
  xaxis: {range: [40, 160], title: "Square Meters"},
  yaxis: {range: [5, 16], title: "Price in Millions"},  
  title: "House Prices vs. Size"
};

// Display using Plotly
Plotly.newPlot("myPlot", data, layout);
</script>

</body>
</html>



Graphs

A Graph can also be used to show the same values:

Price 7 8 8 9 9 9 10 11 14 14 15
Size 50 60 70 80 90 100 110 120 130 140 150
 

Source Code

<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
const xArray = [50,60,70,80,90,100,110,120,130,140,150];
const yArray = [7,8,8,9,9,9,10,11,14,14,15];

// Define Data
const data = [{
  x: xArray,
  y: yArray,
  mode:"lines"
}];

// Define Layout
const layout = {
  xaxis: {range: [40, 160], title: "Square Meters"},
  yaxis: {range: [5, 16], title: "Price in Millions"},  
  title: "House Prices vs. Size"
};

// Display using Plotly
Plotly.newPlot("myPlot", data, layout);
</script>

</body>
</html>

 


When to Use Scatter Plots

Scatter plots are great for:

  • Seeing the "Big Picture"
  • Compare different values
  • Discovering potential trends
  • Discovering patterns in data
  • Discovering relationships between data
  • Discovering Clusters and Correlations

 

 
ML Scatter Plots
 

A Perceptron is an Artificial Neuron

It is the simplest possible Neural Network

Neural Networks are the building blocks of Machine Learning.

Frank Rosenblatt

Frank Rosenblatt (1928 – 1971) was an American psychologist notable in the field of Artificial Intelligence.

In 1957 he started something really big. He "invented" a Perceptron program, on an IBM 704 computer at Cornell Aeronautical Laboratory.

Scientists had discovered that brain cells (Neurons) receive input from our senses by electrical signals.

The Neurons, then again, use electrical signals to store information, and to make decisions based on previous input.

Frank had the idea that Perceptrons could simulate brain principles, with the ability to learn and make decisions.


The Perceptron

The original Perceptron was designed to take a number of binary inputs, and produce one binary output (0 or 1).

The idea was to use different weights to represent the importance of each input, and that the sum of the values should be greater than a threshold value before making a decision like yes or no (true or false) (0 or 1).

 



Perceptron Example

Imagine a perceptron (in your brain).

The perceptron tries to decide if you should go to a concert.

Is the artist good? Is the weather good?

What weights should these facts have?

Criteria Input Weight
Artists is Good x1 = 0 or 1 w1 = 0.7
Weather is Good x2 = 0 or 1 w2 = 0.6
Friend will Come x3 = 0 or 1 w3 = 0.5
Food is Served x4 = 0 or 1 w4 = 0.3
Alcohol is Served x5 = 0 or 1 w5 = 0.4

Perceptron


The Perceptron Algorithm

Frank Rosenblatt suggested this algorithm:

  1. Set a threshold value
  2. Multiply all inputs with its weights
  3. Sum all the results
  4. Activate the output

1. Set a threshold value:

  • Threshold = 1.5

2. Multiply all inputs with its weights:

  • x1 * w1 = 1 * 0.7 = 0.7
  • x2 * w2 = 0 * 0.6 = 0
  • x3 * w3 = 1 * 0.5 = 0.5
  • x4 * w4 = 0 * 0.3 = 0
  • x5 * w5 = 1 * 0.4 = 0.4

3. Sum all the results:

  • 0.7 + 0 + 0.5 + 0 + 0.4 = 1.6 (The Weighted Sum)

4. Activate the Output:

  • Return true if the sum > 1.5 ("Yes I will go to the Concert")

 

Note

If the weather weight is 0.6 for you, it might be different for someone else. A higher weight means that the weather is more important to them.

If the threshold value is 1.5 for you, it might be different for someone else. A lower threshold means they are more wanting to go to any concert.

 

Example

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Perceptron</h1>

<p>Will I go to the consert?</p>
<div id="demo"></div>

<script>
const threshold = 1.5;
const inputs = [1, 0, 1, 0, 1];
const weights = [0.7, 0.6, 0.5, 0.3, 0.4];

let sum = 0;
for (let i = 0; i < inputs.length; i++) {
  sum += inputs[i] * weights[i];
}

document.getElementById("demo").innerHTML = (sum > threshold);  
</script>

</body>
</html>

 


Perceptron Terminology

  • Perceptron Inputs (nodes)
  • Node values (1, 0, 1, 0, 1)
  • Node Weights (0.7, 0.6, 0.5, 0.3, 0.4)
  • Activation Function (sum > treshold)

Nodes (Perceptron Inputs)

Perceptron inputs are called nodes.

The nodes have both a value and a weight.


Node Values (Input Values)

Each input node has a binary value of 1 or 0.

This can be interpreted as true or false / yes or no.

In the example above, the node values are: 1, 0, 1, 0, 1


Node Weights

Weights shows the strength of each node.

In the example above, the node weights are: 0.7, 0.6, 0.5, 0.3, 0.4


The Activation Function

The activation function maps the the weighted sum into a binary value of 1 or 0.

This can be interpreted as true or false / yes or no.

In the example above, the activation function is simple: (sum > 1.5)

Note

It is obvious that a decision is NOT made by one neuron alone.

Many other neurons must provide input:

  • Is the artist good
  • Is the weather good
  • ...

Multi-Layer Perceptrons can be used for very sophisticated decision making.


Neural Networks

The Perceptron defines the first step into Neural Networks:

Neural Networks

 
ML Perceptrons
 

Neural Networks are used in applications like Facial Recognition.

These applications use Pattern Recognition.

This type of Classification can be done with a Perceptron.

Perceptrons can be used to classify data into two parts.

Perceptrons are also known as a Linear Binary Classifiers.

Pattern Classification

Imagine a strait line (a linear graph) in a space with scattered x y points.

How can you classify the points over and under the linA perceptron can be trained to recognize the points over the line, without knowing the formula for the line.

Perceptron



How to Program a Perceptron

To program a perceptron, we can use a simple JavaScript program that will:

  1. Create a simple plotter
  2. Create 500 random x y points
  3. Display the x y points
  4. Create a line function: f(x)
  5. Display the line
  6. Compute the desired answers
  7. Display the desired answers

Create a Simple Plotter

Creating a simple plotter object is described in the .

Example

 

const plotter = new XYPlotter("myCanvas");
plotter.transformXY();

const xMax = plotter.xMax;
const yMax = plotter.yMax;
const xMin = plotter.xMin;
const yMin = plotter.yMin;

Create Random X Y Points

Create as many xy points as wanted.

Let the x values be random (between 0 and maximum).

Let the y values be random (between 0 and maximum).

Display the points in the plotter:

Example

 

<!DOCTYPE html>
<html>
<script src="myplotlib.js"></script>

<body>
<canvas id="myCanvas" width="400px" height="400px" style="width:100%;max-width:400px;border:1px solid black"></canvas>

<script>
// Create a Plotter
const plotter = new XYPlotter("myCanvas");
plotter.transformXY();
const xMax = plotter.xMax;
const yMax = plotter.yMax;
const xMin = plotter.xMin;
const yMin = plotter.yMin;

// Create Random XY Points
const numPoints = 500;
const xPoints = [];
const yPoints = [];
for (let i = 0; i < numPoints; i++) {
  xPoints[i] = Math.random() * xMax;
  yPoints[i] = Math.random() * yMax;
}

//Plot the Points
plotter.plotPoints(numPoints, xPoints, yPoints, "blue");

</script>
</body>
</html>

 


Create a Line Function

Display the line in the plotter:

<!DOCTYPE html>
<html>
<script src="myplotlib.js"></script>

<body>
<canvas id="myCanvas" width="400px" height="400px" style="width:100%;max-width:400px;border:1px solid black"></canvas>

<script>
// Create a Plotter
const plotter = new XYPlotter("myCanvas");
plotter.transformXY();
const xMax = plotter.xMax;
const yMax = plotter.yMax;
const xMin = plotter.xMin;
const yMin = plotter.yMin;

// Create Random XY Points
const numPoints = 500;
const xPoints = [];
const yPoints = [];
for (let i = 0; i < numPoints; i++) {
  xPoints[i] = Math.random() * xMax;
  yPoints[i] = Math.random() * yMax;
}

// Line Function
function f(x) {
  return x * 1.2 + 50;
}

//Plot the Points and the Line
plotter.plotPoints(numPoints, xPoints, yPoints, "blue");
plotter.plotLine(xMin, f(xMin), xMax, f(xMax), "black");

</script>
</body>
</html>


Compute Correct Answers

Compute the correct answers based on the line function:

y = x * 1.2 + 50.

The desired answer is 1 if y is over the line and 0 if y is under the line.

Store the desired answers in an array (desired[]).

Example

let desired = [];
for (let i = 0; i < numPoints; i++) {
  desired[i] = 0;
  if (yPoints[i] > f(xPoints[i])) {desired[i] = 1;}
}

Display the Correct Answers

 

For each point, if desired[i] = 1 display a black point, else display a blue point.

Example

<!DOCTYPE html>
<html>
<script src="myplotlib.js"></script>

<body>
<canvas id="myCanvas" width="400px" height="400px" style="width:100%;max-width:400px;border:1px solid black"></canvas>

<script>
// Create a Plotter
const plotter = new XYPlotter("myCanvas");
plotter.transformXY();
const xMax = plotter.xMax;
const yMax = plotter.yMax;
const xMin = plotter.xMin;
const yMin = plotter.yMin;

// Create Random XY Points
const numPoints = 500;
const xPoints = [];
const yPoints = [];
for (let i = 0; i < numPoints; i++) {
  xPoints[i] = Math.random() * xMax;
  yPoints[i] = Math.random() * yMax;
}

// Line Function
function f(x) {
  return x * 1.2 + 50;
}

//Plot the Line
plotter.plotLine(xMin, f(xMin), xMax, f(xMax), "black");

// Compute Desired Answers
const desired = [];
for (let i = 0; i < numPoints; i++) {
  desired[i] = 0;
  if (yPoints[i] > f(xPoints[i])) {desired[i] = 1}
}

// Diplay Desired Result
for (let i = 0; i < numPoints; i++) {
  let color = "blue";
  if (desired[i]) color = "black";
  plotter.plotPoint(xPoints[i], yPoints[i], color);
}
</script>
</body>
</html>


How to Train a Perceptron

In the next chapter, you will learn how to use the correct answers to:

Train a perceptron to predict the output values of unknown input values.

 

 
ML Recognition
 
  • Create a Perceptron Object
  • Create a Training Function
  • Train the perceptron against correct answers

Training Task

Imagine a straight line in a space with scattered x y points.

Train a perceptron to classify the points over and under the line.

Create a Perceptron Object

Create a Perceptron object. Name it anything (like Perceptron).

Let the perceptron accept two parameters:

  1. The number of inputs (no)
  2. The learning rate (learningRate).

Set the default learning rate to 0.00001.

Then create random weights between -1 and 1 for each input.

 

Example

// Perceptron Object
function Perceptron(no, learningRate = 0.00001) {

// Set Initial Values
this.learnc = learningRate;
this.bias = 1;

// Compute Random Weights
this.weights = [];
for (let i = 0; i <= no; i++) {
  this.weights[i] = Math.random() * 2 - 1;
}

// End Perceptron Object
}
 
 

The Random Weights

The Perceptron will start with a random weight for each input.

The Learning Rate

For each mistake, while training the Perceptron, the weights will be adjusted with a small fraction.

This small fraction is the "Perceptron's learning rate".

In the Perceptron object we call it learnc.

The Bias

Sometimes, if both inputs are zero, the perceptron might produce an incorrect output.

To avoid this, we give the perceptron an extra input with the value of 1.

This is called a bias.



Add an Activate Function

Remember the perceptron algorithm:

  • Multiply each input with the perceptron's weights
  • Sum the results
  • Compute the outcome

Example

this.activate = function(inputs) {
  let sum = 0;
  for (let i = 0; i < inputs.length; i++) {
    sum += inputs[i] * this.weights[i];
  }
  if (sum > 0) {return 1} else {return 0}
}

The activation function will output:

  • 1 if the sum is greater than 0
  • 0 if the sum is less than 0

Create a Training Function

The training function guesses the outcome based on the activate function.

Every time the guess is wrong, the perceptron should adjust the weights.

After many guesses and adjustments, the weights will be correct.

Example

<!DOCTYPE html>
<html>
<script src="myplotlib.js"></script>

<body>
<canvas id="myCanvas" width="400px" height="400px" style="width:100%;max-width:400px;border:1px solid black"></canvas>

<script>
// Initiate Values
const numPoints = 500;
const learningRate = 0.00001;

// Create a Plotter
const plotter = new XYPlotter("myCanvas");
plotter.transformXY();
const xMax = plotter.xMax;
const yMax = plotter.yMax;
const xMin = plotter.xMin;
const yMin = plotter.yMin;

// Create Random XY Points
const xPoints = [];
const yPoints = [];
for (let i = 0; i < numPoints; i++) {
  xPoints[i] = Math.random() * xMax;
  yPoints[i] = Math.random() * yMax;
}

// Line Function
function f(x) {
  return x * 1.2 + 50;
}

//Plot the Line
plotter.plotLine(xMin, f(xMin), xMax, f(xMax), "black");

// Compute Desired Answers
const desired = [];
for (let i = 0; i < numPoints; i++) {
  desired[i] = 0;
  if (yPoints[i] > f(xPoints[i])) {desired[i] = 1}
}

// Create a Perceptron
const ptron = new Perceptron(2, learningRate);

// Train the Perceptron
for (let j = 0; j <= 10000; j++) {
  for (let i = 0; i < numPoints; i++) {
    ptron.train([xPoints[i], yPoints[i]], desired[i]);
  }
}

// Display the Result
for (let i = 0; i < numPoints; i++) {
  const x = xPoints[i];
  const y = yPoints[i];
  let guess = ptron.activate([x, y, ptron.bias]);
  let color = "black";
  if (guess == 0) color = "blue";
  plotter.plotPoint(x, y, color);
}

// Perceptron Object ---------------------
function Perceptron(no, learningRate = 0.00001) {

// Set Initial Values
this.learnc = learningRate;
this.bias = 1;

// Compute Random Weights
this.weights = [];
for (let i = 0; i <= no; i++) {
  this.weights[i] = Math.random() * 2 - 1;
}

// Activate Function
this.activate = function(inputs) {
  let sum = 0;
  for (let i = 0; i < inputs.length; i++) {
    sum += inputs[i] * this.weights[i];
  } 
  if (sum > 0) {return 1} else {return 0}
}

// Train Function
this.train = function(inputs, desired) {
  inputs.push(this.bias);
  let guess = this.activate(inputs);
  let error = desired - guess;
  if (error != 0) {
    for (let i = 0; i < inputs.length; i++) {
      this.weights[i] += this.learnc * error * inputs[i];         
    }
  }
}

// End Perceptron Object
}
</script>
</body>
</html>


Backpropagation

After each guess, the perceptron calculates how wrong the guess was.

If the guess is wrong, the perceptron adjusts the bias and the weights so that the guess will be a little bit more correct the next time.

This type of learning is called backpropagation.

After trying (a few thousand times) your perceptron will become quite good at guessing.


Create Your Own Library

Library Code

// Perceptron Object
function Perceptron(no, learningRate = 0.00001) {

// Set Initial Values
this.learnc = learningRate;
this.bias = 1;

// Compute Random Weights
this.weights = [];
for (let i = 0; i <= no; i++) {
  this.weights[i] = Math.random() * 2 - 1;
}

// Activate Function
this.activate = function(inputs) {
  let sum = 0;
  for (let i = 0; i < inputs.length; i++) {
    sum += inputs[i] * this.weights[i];
  }
  if (sum > 0) {return 1} else {return 0}
}

// Train Function
this.train = function(inputs, desired) {
  inputs.push(this.bias);
  let guess = this.activate(inputs);
  let error = desired - guess;
  if (error != 0) {
    for (let i = 0; i < inputs.length; i++) {
      this.weights[i] += this.learnc * error * inputs[i];
    }
  }
}

// End Perceptron Object
}

Now you can include the library in HTML:

<script src="myperceptron.js"></script>
 

Use Your Library

Example

<!DOCTYPE html>
<html>
<script src="myperceptron.js"></script>
<script src="myplotlib.js"></script>
<body>
<canvas id="myCanvas" width="400px" height="400px" style="width:100%;max-width:400px;border:1px solid black"></canvas>

<script>
// Initiate Values
const numPoints = 500;
const learningRate = 0.00001;

// Create a Plotter
const plotter = new XYPlotter("myCanvas");
plotter.transformXY();
const xMax = plotter.xMax;
const yMax = plotter.yMax;
const xMin = plotter.xMin;
const yMin = plotter.yMin;

// Create Random XY Points
const xPoints = [];
const yPoints = [];
for (let i = 0; i < numPoints; i++) {
  xPoints[i] = Math.random() * xMax;
  yPoints[i] = Math.random() * yMax;
}

// Line Function
function f(x) {
  return x * 1.2 + 50;
}

//Plot the Line
plotter.plotLine(xMin, f(xMin), xMax, f(xMax), "black");

// Compute Desired Answers
const desired = [];
for (let i = 0; i < numPoints; i++) {
  desired[i] = 0;
  if (yPoints[i] > f(xPoints[i])) {desired[i] = 1}
}

// Create a Perceptron
const ptron = new Perceptron(2, learningRate);

// Train the Perceptron
for (let j = 0; j <= 10000; j++) {
  for (let i = 0; i < numPoints; i++) {
    ptron.train([xPoints[i], yPoints[i]], desired[i]);
  }
}

// Display the Result
for (let i = 0; i < numPoints; i++) {
  const x = xPoints[i];
  const y = yPoints[i];
  let guess = ptron.activate([x, y, ptron.bias]);
  let color = "black";
  if (guess == 0) color = "blue";
  plotter.plotPoint(x, y, color);
}
</script>
</body>
</html>

 

 
ML Training
 
  • A Perceptron must be Tested and Evaluated
  • A Perceptron must be tested against Real Values.

Test Your Library

Generate new unknown points and check if your Perceptron can guess the right answers:

Example

<!DOCTYPE html>
<html>
<script src="myperceptron.js"></script>
<script src="myplotlib.js"></script>
<body>
<canvas id="myCanvas" width="400px" height="400px" style="width:100%;max-width:400px;border:1px solid black"></canvas>
<script>
// Initiate Values
const numPoints = 500;
const learningRate = 0.00001;

// Create a Plotter
const plotter = new XYPlotter("myCanvas");
plotter.transformXY();
const xMax = plotter.xMax;
const yMax = plotter.yMax;
const xMin = plotter.xMin;
const yMin = plotter.yMin;

// Create Random XY Points
const xPoints = [];
const yPoints = [];
for (let i = 0; i < numPoints; i++) {
  xPoints[i] = Math.random() * xMax;
  yPoints[i] = Math.random() * yMax;
}

// Line Function
function f(x) {
  return x * 1.2 + 50;
}

//Plot the Line
plotter.plotLine(xMin, f(xMin), xMax, f(xMax), "black");

// Compute Desired Answers
const desired = [];
for (let i = 0; i < numPoints; i++) {
  desired[i] = 0;
  if (yPoints[i] > f(xPoints[i])) {desired[i] = 1}
}

// Create a Perceptron
const ptron = new Perceptron(2, learningRate);

// Train the Perceptron
for (let j = 0; j <= 10000; j++) {
  for (let i = 0; i < numPoints; i++) {
    ptron.train([xPoints[i], yPoints[i]], desired[i]);
  }
}

// Test Against Unknown Data
const counter = 500;
for (let i = 0; i < counter; i++) {
  let x = Math.random() * xMax;
  let y = Math.random() * yMax;
  let guess = ptron.activate([x, y, ptron.bias]);
  let color = "black";
  if (guess == 0) color = "blue";
  plotter.plotPoint(x, y, color);
}
</script>
</body>
</html>

 


Count the Errors

Add a counter to count the number of errors:

Example

<!DOCTYPE html>
<html>
<script src="myperceptron.js"></script>
<script src="myplotlib.js"></script>
<body>
<canvas id="myCanvas" width="400px" height="400px" style="width:100%;max-width:400px;border:1px solid black"></canvas>
<script>
// Initiate Values
const numPoints = 500;
const learningRate = 0.00001;

// Create a Plotter
const plotter = new XYPlotter("myCanvas");
plotter.transformXY();
const xMax = plotter.xMax;
const yMax = plotter.yMax;
const xMin = plotter.xMin;
const yMin = plotter.yMin;

// Create Random XY Points
const xPoints = [];
const yPoints = [];
for (let i = 0; i < numPoints; i++) {
  xPoints[i] = Math.random() * xMax;
  yPoints[i] = Math.random() * yMax;
}

// Line Function
function f(x) {
  return x * 1.2 + 50;
}

//Plot the Line
plotter.plotLine(xMin, f(xMin), xMax, f(xMax), "black");

// Compute Desired Answers
const desired = [];
for (let i = 0; i < numPoints; i++) {
  desired[i] = 0;
  if (yPoints[i] > f(xPoints[i])) {desired[i] = 1}
}

// Create a Perceptron
const ptron = new Perceptron(2, learningRate);

// Train the Perceptron
for (let j = 0; j <= 10000; j++) {
  for (let i = 0; i < numPoints; i++) {
    ptron.train([xPoints[i], yPoints[i]], desired[i]);
  }
}

// Test Against Unknown Data
const counter = 500;
for (let i = 0; i < counter; i++) {
  let x = Math.random() * xMax;
  let y = Math.random() * yMax;
  let guess = ptron.activate([x, y, ptron.bias]);
  let color = "black";
  if (guess == 0) color = "blue";
  plotter.plotPoint(x, y, color);
}
</script>
</body>
</html>

 


Tune the Perceptron

How can you tune the Perceptron?

Here are some suggestions:

  • Adjust the learning rate
  • Increase the number of training data
  • Increase the number of training iterations
 
ML Testing
 

Learning is Looping

An ML model is Trained by Looping over data multiple times.

For each iteration, the Weight Values are adjusted.

Training is complete when the iterations fails to Reduce the Cost.

Gradient Descent

Gradient Descent is a popular algorithm for solving AI problems.

A simple Linear Regression Model can be used to demonstrate a gradient descent.

The goal of a linear regression is to fit a linear graph to a set of (x,y) points. This can be solved with a math formula. But a Machine Learning Algorithm can also solve this.

This is what the example above does.

It starts with a scatter plot and a linear model (y = wx + b).

Then it trains the model to find a line that fits the plot. This is done by altering the weight (slope) and the bias (intercept) of the line.

Below is the code for a Trainer Object that can solve this problem (and many other problems).


A Trainer Object

Create a Trainer object that can take any number of (x,y) values in two arrays (xArr,yArr).

Set weight to zero and the bias to 1.

A learning constant (learnc) has to be set, and a cost variable must be defined:

Example

function Trainer(xArray, yArray) {
  this.xArr = xArray;
  this.yArr = yArray;
  this.points = this.xArr.length;
  this.learnc = 0.00001;
  this.weight = 0;
  this.bias = 1;
  this.cost;


Cost Function

A standard way to solve a regression problem, is with an "Cost Function" that measures how good the solution is.

The function uses the weight and bias from the model (y = wx + b) and returns an error, based on how well the line fits a plot.

The way to compute this error, is to loop through all (x,y) points in the plot, and sum the square distances between the y value of each point and the line.

The most conventional way is to square the distances (to ensure positive values) and to make the error function differentiable.

this.costError = function() {
  total = 0;
  for (let i = 0; i < this.points; i++) {
    total += (this.yArr[i] - (this.weight * this.xArr[i] + this.bias)) **2;
  }
  return total / this.points;
}

 

Another name for the Cost Function is Error Function.

The formula used in the function is actually this:

Formula
  • E is the error (cost)
  • N is the total number of observations (points)
  • y is the value (label) of each observation
  • x is the value (feature) of each observation
  • m is the slope (weight)
  • b is intercept (bias)
  • mx + b is the prediction
  • 1/N * N∑1 is the squared mean value

The Train Function

We will now run a gradient descent.

The gradient descent algorithm should walk the cost function towards the best line.

Each iteration should update both m and b towards a line with a lower cost (error).

To do that, we add a train function that loops over all the data many times:

this.train = function(iter) {
  for (let i = 0; i < iter; i++) {
    this.updateWeights();
  }
  this.cost = this.costError();
}

An Update Weights Function

The train function above should update the weights and biases in each iteration.

The direction to move is calculated using two partial derivatives:

this.updateWeights = function() {
  let wx;
  let w_deriv = 0;
  let b_deriv = 0;
  for (let i = 0; i < this.points; i++) {
    wx = this.yArr[i] - (this.weight * this.xArr[i] + this.bias);
    w_deriv += -2 * wx * this.xArr[i];
    b_deriv += -2 * wx;
  }
  this.weight -= (w_deriv / this.points) * this.learnc;
  this.bias -= (b_deriv / this.points) * this.learnc;
}

Create Your Own Library

Library Code

function Trainer(xArray, yArray) {
  this.xArr = xArray;
  this.yArr = yArray;
  this.points = this.xArr.length;
  this.learnc = 0.000001;
  this.weight = 0;
  this.bias = 1;
  this.cost;

// Cost Function
this.costError = function() {
  total = 0;
  for (let i = 0; i < this.points; i++) {
    total += (this.yArr[i] - (this.weight * this.xArr[i] + this.bias)) **2;
  }
  return total / this.points;
}

// Train Function
this.train = function(iter) {
  for (let i = 0; i < iter; i++) {
    this.updateWeights();
  }
  this.cost = this.costError();
}

// Update Weights Function
this.updateWeights = function() {
  let wx;
  let w_deriv = 0;
  let b_deriv = 0;
  for (let i = 0; i < this.points; i++) {
    wx = this.yArr[i] - (this.weight * this.xArr[i] + this.bias);
    w_deriv += -2 * wx * this.xArr[i];
    b_deriv += -2 * wx;
  }
  this.weight -= (w_deriv / this.points) * this.learnc;
  this.bias -= (b_deriv / this.points) * this.learnc;
}

} // End Trainer Object

Now you can include the library in HTML:

 
<script src="myailib.js"></script>

 

 

 
ML Learning
 

Machine Learning Subcategories

  • Supervised Learning
  • Unsupervised Learning

Supervised Machine Learning uses a set of input variables to predict the value of an output variable.

Unsupervised Machine Learning, uses patterns from any unlabeled dataset, trying to understand patterns (or groupings) in the data.

 


Machine Learning Inference

Model defines the relationship between the label (y) and the features (x).

There are three phases in the life of a model:

  • Data Collection
  • Training
  • Inference

 


Supervised Learning

Supervised learning uses labeled data (data with known answers) to train algorithms to:

  • Classify Data
  • Predict Outcomes

Supervised learning can classify data like "What is spam in an e-mail", based on known spam examples.

Supervised learning can predict outcomes like predicting what kind of video you like, based on the videos you have played.


Unsupervised Learning

Unsupervised learning is used to predict undefined relationships like meaningful patterns in data.

It is about creating computer algorithms than can improve themselves.

It is expected that machine learning will shift to unsupervised learning to allow programmers to solve problems without creating models.


Reinforcement Learning

Reinforcement learning is based on non-supervised learning but receives feedback from the user whether the decisions is good or bad. The feedback contributes to improving the model.


Self-Supervised Learning

Self-supervised learning is similar to unsupervised learning because it works with data without human added labels.

The difference is that unsupervised learning uses clustering, grouping, and dimensionality reduction, while self-supervised learning draw its own conclusions for regression and classification tasks.


Key Machine Learning Terminologies are:

  • Relationships
  • Labels
  • Features
  • Models
  • Training
  • Inference

Relationships

Machine learning systems uses Relationships between Inputs to produce Predictions.

In algebra, a relationship is often written as y = ax + b:

  • y is the label we want to predict
  • a is the slope of the line
  • x are the input values
  • b is the intercept

With ML, a relationship is written as y = b + wx:

  • y is the label we want to predict
  • w is the weight (the slope)
  • x are the features (input values)
  • b is the intercept

Machine Learning Labels

In Machine Learning terminology, the label is the thing we want to predict.

It is like the y in a linear graph:

Algebra Machine Learning
y = ax + b y = b + wx

Machine Learning Features

In Machine Learning terminology, the features are the input.

They are like the x values in a linear graph:

Algebra Machine Learning
y = ax + b y = b + wx

Sometimes there can be many features (input values) with different weights:

y = b + w1x1 + w2x2 + w3x3 + w4x4

 

 
ML Terminology
 

Up to 80% of a Machine Learning project is about Collecting Data:

  • What data is Required?
  • What data is Available?
  • How to Select the data?
  • How to Collect the data?
  • How to Clean the data?
  • How to Prepare the data?
  • How to Use the data?

What is Data?

Data can be many things.

With Machine Learning, data is collections of facts:

Type Examples
Numbers Prices. Dates.
Measurements Size. Height. Weight.
Words Names and Places.
Observations Counting Cars.
Descriptions It is cold.

Intelligence Needs Data

Human intelligence needs data:

A real estate broker needs data about sold houses to estimate prices.

Artificial Intelligence also needs data:

A Machine Learning program needs data to estimate prices.

Data can help us to see and understand.

Data can help us to find new opportunities.

Data can help us to resolve misunderstandings.


Healthcare

Healthcare and life sciences collect public health data and patient data to learn how to improve patient care and save lives.

Business

The most successful companies in many sectors are data driven. They use sophisticated data analytics to learn how the company can perform better.

Finance

Banks and insurance companies collect and evaluate data about customers, loans and deposits to support strategic decision-making.


Storing Data

The most common data to collect are Numbers and Measurements.

Often data are stored in arrays representing the relationship between values.

This table contains house prices versus size:

Price 7 8 8 9 9 9 10 11 14 14 15
Size 50 60 70 80 90 100 110 120 130 140 150

Quantitative vs. Qualitative

Quantitative data are numerical:

  • 55 cars
  • 15 meters
  • 35 children

Qualitative data are descriptive:

  • It is cold
  • It is long
  • It was fun


Census or Sampling

A Census is when we collect data for every member of a group.

Sample is when we collect data for some members of a group.
If we wanted to know how many Americans smoke cigarettes, we could ask every person in the US (a census), or we could ask 10 000 people (a sample).
A census is Accurate, but hard to do. A sample is Inaccurate, but is easier to do.

Sampling Terms

A Population is group of individuals (objects) we want to collect information from.

A Census is information about every individual in a population.

A Sample is information about a part of the population (In order to represent all).


Random Samples

In order for a sample to represent a population, it must be collected randomly.

A Random Sample, is a sample where every member of the population has an equal chance to appear in the sample.


Sampling Bias

A Sampling Bias (Error) occurs when samples are collected in such a way that some individuals are less (or more) likely to be included in the sample.


Big Data

Big data is data that is impossible for humans to process without the assistance of advanced machines.

Big data does not have any definition in terms of size, but datasets are becoming larger and larger as we continously collect more and more data and store data at a lower and lower cost.


Data Mining

With big data comes complicated data structures.

A huge part of big data processing is refining data.

ML Data
 
  • Clusters are collections of similar data
  • Clustering is a type of unsupervised learning
  • The Correlation Coefficient describes the strength of a relationship.

Clusters

Clusters are collections of data based on similarity.

Data points clustered together in a graph can often be classified into clusters.

In the graph below we can distinguish 3 different clusters:

Identifying Clusters

Clusters can hold a lot of valuable information, but clusters come in all sorts of shapes, so how can we recognize them?

The two main methods are:

  • Using Visualization
  • Using an Clustering Algorithm

Clustering

Clustering is a type of Unsupervised Learning.

Clustering is trying to:

  • Collect similar data in groups
  • Collect dissimilar data in other groups

Clustering Methods

  • Density Method
  • Hierarchical Method
  • Partitioning Method
  • Grid-based Method

The Density Method considers points in a dense regions to have more similarities and differences than points in a lower dense region. The density method has a good accuracy. It also has the ability to merge clusters.
Two common algorithms are DBSCAN and OPTICS.

The Hierarchical Method forms the clusters in a tree-type structure. New clusters are formed using previously formed clusters.
Two common algorithms are CURE and BIRCH.

The Grid-based Method formulates the data into a finite number of cells that form a grid-like structure.
Two common algorithms are CLIQUE and STING

The Partitioning Method partitions the objects into k clusters and each partition forms one cluster.
One common algorithm is CLARANS.



Correlation Coefficient

The Correlation Coefficient (r) describes the strength and direction of a linear relationship and x/y variables on a scatterplot.

The value of r is always between -1 and +1:

-1.00 Perfect downhill Negative linear relationship.
-0.70 Strong downhill Negative linear relationship.
-0.50 Moderate downhill Negative linear relationship.
-0.30 Weak downhill Negative linear relationship.
0   No linear relationship.
+0.30 Weak uphill Positive linear relationship.
+0.50 Moderate uphill Positive linear relationship.
+0.70 Strong uphill Positive linear relationship.
+1.00 Perfect uphill Positive linear relationship.
 
ML Clustering
 

A Regression is a method to determine the relationship between one variable (y) and other variables (x).

In statistics, a Linear Regression is an approach to modeling a linear relationship between y and x.

In Machine Learning, a Linear Regression is a supervised machine learning algorithm.

Scatter Plot

This is the scatter plot (from the previous chapter):

Example

<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
const xArray = [50,60,70,80,90,100,110,120,130,140,150];
const yArray = [7,8,8,9,9,9,10,11,14,14,15];

// Define Data
const data = [{
  x:xArray,
  y:yArray,
  mode:"markers"
}];

// Define Layout
const layout = {
  xaxis: {range: [40, 160], title: "Square Meters"},
  yaxis: {range: [5, 16], title: "Price in Millions"},  
  title: "House Prices vs. Size"
};

// Display using Plotly
Plotly.newPlot("myPlot", data, layout);
</script>

</body>
</html>


Predicting Values

From the scattered data above, how can we predict future prices?

  • Use hand drawn linear graph
  • Model a linear relationship
  • Model a linear regression


Linear Graphs

This is a linear graph predicting prices based on the lowest and the highest price:

Example

<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
const xArray = [50,60,70,80,90,100,110,120,130,140,150];
const yArray = [7,8,8,9,9,9,10,11,14,14,15];

const data = [
  {x:xArray, y:yArray, mode:"markers"},
  {x:[50,150], y:[7,15], mode:"line"},
];

const layout = {
  xaxis: {range: [40, 160], title: "Square Meters"},
  yaxis: {range: [5, 16], title: "Price in Millions"},  
  title: "House Prices vs. Size"
};

Plotly.newPlot("myPlot", data, layout);
</script>

</body>
</html>

From a Previous Chapter

A linear graph can be written as y = ax + b

Where:

  • y is the price we want to predict
  • a is the slope of the line
  • x are the input values
  • b is the intercept

Linear Relationships

This Model predicts prices using a linear relationship between price and size:

Example

<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
const xArray = [50,60,70,80,90,100,110,120,130,140,150];
const yArray = [7,8,8,9,9,9,10,11,14,14,15];

// Calculate Slope
let xSum = xArray.reduce(function(a, b){return a + b;}, 0);
let ySum = yArray.reduce(function(a, b){return a + b;}, 0);
let slope = ySum / xSum;

// Generate values
const xValues = [];
const yValues = [];
for (let x = 50; x <= 150; x += 1) {
  xValues.push(x);
  yValues.push(x * slope);
}

const data = [
  {x:xArray, y:yArray, mode:"markers"},
  {x:xValues, y:yValues, mode:"line"}
];

const layout = {
  xaxis: {range: [40, 160], title: "Square Meters"},
  yaxis: {range: [5, 16], title: "Price in Millions"},  
  title: "House Prices vs. Size"
};

Plotly.newPlot("myPlot", data, layout);
</script>

</body>
</html>


In the example above, the slope is a calculated average and the intercept = 0.

Using a Linear Regression Function

This Model predicts prices using a linear regression function:

Example

<!DOCTYPE html>
<html>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
const xArray = [50,60,70,80,90,100,110,120,130,140,150];
const yArray = [7,8,8,9,9,9,10,11,14,14,15];

// Calculate Sums
let xSum=0, ySum=0, xxSum=0, xySum=0;
let count = xArray.length;
for (let i = 0, len = count; i < count; i++) {
  xSum += xArray[i];
  ySum += yArray[i];
  xxSum += xArray[i] * xArray[i];
  xySum += xArray[i] * yArray[i];
}

// Calculate slope and intercept
let slope = (count * xySum - xSum * ySum) / (count * xxSum - xSum * xSum);
let intercept = (ySum / count) - (slope * xSum) / count;

// Generate values
const xValues = [];
const yValues = [];
for (let x = 50; x <= 150; x += 1) {
  xValues.push(x);
  yValues.push(x * slope + intercept);
}

const data = [
  {x:xArray, y:yArray, mode:"markers"},
  {x:xValues, y:yValues, mode:"line"}
];

const layout = {
  xaxis: {range: [40, 160], title: "Square Meters"},
  yaxis: {range: [5, 16], title: "Price in Millions"},  
  title: "House Prices vs. Size"
};

Plotly.newPlot("myPlot", data, layout);
</script>

</body>
</html>


Polynomial Regression

If scattered data points do not fit a linear regression (a straight line through the points), the data may fit an polynomial regression.

A Polynomial Regression, like linear regression, uses the relationship between the variables x and y to find the best way to draw a line through the data points. 

 

Polynormal Regression
ML Regressions
 

The deep learning revolution started around 2010.

Since then, Deep Learning has solved many "unsolvable" problems.

The deep learning revolution was not started by a single discovery. It more or less happened when several needed factors were ready:

  • Computers were fast enough
  • Computer storage was big enough
  • Better training methods were invented
  • Better tuning methods were invented

Neurons

Scientists agree that our brain has between 80 and 100 billion neurons.

These neurons have hundreds of billions connections between them.

Neurons

 

Neurons (aka Nerve Cells) are the fundamental units of our brain and nervous system.

The neurons are responsible for receiving input from the external world, for sending output (commands to our muscles), and for transforming the electrical signals in between.


Neural Networks

Artificial Neural Networks are normally called Neural Networks (NN).

Neural networks are in fact multi-layer Perceptrons.

The perceptron defines the first step into multi-layered neural networks.

Neural Networks is the essence of Deep Learning.

Neural Networks is one of the most significant discoveries in history.

Neural Networks can solve problems that can NOT be solved by algorithms:

  • Medical Diagnosis
  • Face Detection
  • Voice Recognition

The Neural Network Model

Input data (Yellow) are processed against a hidden layer (Blue) and modified against another hidden layer (Green) to produce the final output (Red).

Neural Networks

 


Tom Mitchell

Tom Michael Mitchell (born 1951) is an American computer scientist and University Professor at the Carnegie Mellon University (CMU).

He is a former Chair of the Machine Learning Department at CMU.

"A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E."

Tom Mitchell (1999)

E: Experience (the number of times).
T: The Task (driving a car).
P: The Performance (good or bad).


The Giraffe Story

In 2015, Matthew Lai, a student at Imperial College in London created a neural network called Giraffe.

Giraffe could be trained in 72 hours to play chess at the same level as an international master.

Computers playing chess are not new, but the way this program was created was new.

Smart chess playing programs take years to build, while Giraffe was built in 72 hours with a neural network.

 

  • Supervised Machine Learning
  • Unsupervised Machine Learning
  • Self-Supervised Machine Learning


Deep Learning

Classical programming uses programs (algorithms) to create results:

Traditional Computing

Data + Computer Algorithm = Result

Machine Learning uses results to create programs (algorithms):

Machine Learning

Data + Result = Computer Algorithm


 

Machine Learning

Machine Learning is often considered equivalent with Artificial Intelligence.

This is not correct. Machine learning is a subset of Artificial Intelligence.

Machine Learning is a discipline of AI that uses data to teach machines.

"Machine Learning is a field of study that gives computers the ability to learn without being programmed."

Arthur Samuel (1959)


Intelligent Decision Formula

 

  • Save the result of all actions
  • Simulate all possible outcomes
  • Compare the new action with the old ones
  • Check if the new action is good or bad
  • Choose the new action if it is less bad
  • Do it all over again

The fact that computers can do this millions of times, has proven that computers can take very intelligent decisions.

ML Deep Learning
 

Building a neural network with Brain.js:

Example:

<!DOCTYPE html>
<html>
<script src="//unpkg.com/brain.js"></script>
<body>
<h1>Deep Learning with brain.js</h1>
<div id="demo"></div>

<script>
// Create a Neural Network
const network = new brain.NeuralNetwork();

// Train the Network with 4 input objects
network.train([
  {input:[0,0], output:{zero:1}},
  {input:[0,1], output:{one:1}},
  {input:[1,0], output:{one:1}},
  {input:[1,1], output:{zero:1}},
]);

// What is the expected output of [1,0]?
let result = network.run([1,0]);

// Display the probability for "zero" and "one"
document.getElementById("demo").innerHTML =
"one: " + result["one"] + "<br>" + "zero: " + result["zero"];
</script>
</body>
</html>

Example Explained:

A Neural Network is created with: new brain.NeuralNetwork()

The network is trained with network.train([examples])

The examples represent 4 input values with a corresponding output value.

With network.run([1,0]), you ask "What is the likely output of [1,0]?"

The answer from the network is:

  • one: 93% (close to 1)
  • zero: 6% (close to 0)


How to Predict a Contrast

With CSS, colors can be set by RGB:

 
 

The example below demonstrates how to predict the darkness of a color:

Example:

<!DOCTYPE html>
<html>
<script src="//unpkg.com/brain.js"></script>
<body>
<h1>Deep Learning with brain.js</h1>
<div id="demo"></div>

<script>
// Create a Neural Network
const net = new brain.NeuralNetwork();

// Train the Network with 4 input objects
net.train([
// White RGB(255, 255, 255)
{input:[255/255, 255/255, 255/255], output:{light:1}},
// Lightgrey (192,192,192)
{input:[192/255, 192/255, 192/255], output:{light:1}},
// Darkgrey (64, 64, 64)
{ input:[65/255, 65/255, 65/255], output:{dark:1}},
// Black (0, 0, 0)
{ input:[0, 0, 0], output:{dark:1}},
]);

// What is the expected output of Dark Blue (0, 0, 128)?
let result = net.run([0, 0, 128/255]);

// Display the probability of "dark" and "light"
document.getElementById("demo").innerHTML =
"Dark: " + result["dark"] + "<br>" + "Light: " + result["light"];
</script>
</body>
</html>

Example Explained:

A Neural Network is created with: new brain.NeuralNetwork()

The network is trained with network.train([examples])

The examples represent 4 input values a corresponding output value.

With network.run([0,0,128/255]), you ask "What is the likely output of dark blue?"

The answer from the network is:

  • Dark: 95%
  • Light: 4%

Why not edit the example to test the likely output of yellow or red?

 

 
ML Brain.js
 

TensorFlow

What is TensorFlow.js?

Tensorflow is popular JavaScript library for Machine Learning.

Tensorflow lets us train and deploy machine learning in the Browser.

Tensorflow lets us add machine learning functions to any Web Application.

Using TensorFlow

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
 

If you always want to use the latest version, drop the version number:

Example 2

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
 
 

To use TensorFlow.js, add the following script tag to your HTML file(s):

TensorFlow was developed by the Google Brain Team for internal Google use, but was released as open software in 2015.

In January 2019, Google developers released TensorFlow.js, the JavaScript Implementation of TensorFlow.

Tensorflow.js was designed to provide the same features as the original TensorFlow library written in Python.


Tensors

TensorFlow.js is a JavaScript library to define and operate on Tensors.

The main data type in TensorFlow.js is the Tensor.

A Tensor is much the same as a multidimensional array.

A Tensor contains values in one or more dimensions:

Tensor

 

A Tensor has the following main properties:

Property Description
dtype The data type
rank The number of dimensions
shape The size of each dimension

Sometimes in machine learning, the term "dimension" is used interchangeably with "rank.

[10, 5] is a 2-dimensional tensor or a 2-rank tensor.

In addition the term "dimensionality" can refer to the size of a one dimension.

Example: In the 2-dimensional tensor [10, 5], the dimensionality of the first dimension is 10.



Creating a Tensor

The main data type in TensorFlow is the Tensor.

A Tensor is created from any N-dimensional array with the tf.tensor() method:

Example 1

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h1>TensorFlow JavaScript</h1>
<h3>Creating a tensor:</h3>

<div id="demo"></div>

<script>
const myArr = [[1, 2, 3, 4]];
const tensorA = tf.tensor(myArr);
document.getElementById("demo").innerHTML = tensorA;
</script>

</body>
</html>

 

Example 2

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h1>TensorFlow JavaScript</h1>
<h3>Creating a tensor:</h3>

<div id="demo"></div>

<script>
const myArr = [[1, 2], [3, 4]]
const tensorA = tf.tensor(myArr);
document.getElementById("demo").innerHTML = tensorA;
</script>

</body>
</html>

 

Example 3

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h1>TensorFlow JavaScript</h1>
<h3>Creating a tensor:</h3>

<div id="demo"></div>

<script>
const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
document.getElementById("demo").innerHTML = tensorA;
</script>

</body>
</html>

 


Tensor Shape

A Tensor can also be created from an array and a shape parameter:

Example1

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h1>TensorFlow JavaScript</h1>
<h3>Creating a tensor with a shape:</h3>

<div id="demo"></div>

<script>
const myArr = [1, 2, 3, 4];
const shape = [2, 2];
const tensorA = tf.tensor(myArr, shape);
document.getElementById("demo").innerHTML = tensorA;
</script>

</body>
</html>

 

Example2

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h1>TensorFlow JavaScript</h1>
<h3>Creating a tensor with a shape:</h3>

<div id="demo"></div>

<script>
const tensorA = tf.tensor([1, 2, 3, 4], [2, 2]);
document.getElementById("demo").innerHTML = tensorA;
</script>

</body>
</html>

TFJS Tutorial
 
  • Add
  • Subtract
  • Multiply
  • Divide
  • Square
  • Reshape

Tensor Addition

You can add two tensors using tensorA.add(tensorB):

Example

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h2>JavaScript</h2>
<p>Adding tensors with tensorflow.js</p>

<div id="demo"></div>

<script>
const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
const tensorB = tf.tensor([[1,-1], [2,-2], [3,-3]]);

// Tensor Addition
const tensorNew = tensorA.add(tensorB);

// Result: [ [2, 1], [5, 2], [8, 3] ]
document.getElementById("demo").innerHTML = tensorNew;
</script>

</body>
</html>

 

 


Tensor Subtraction

You can subtract two tensors using tensorA.sub(tensorB):

Example

const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
const tensorB = tf.tensor([[1,-1], [2,-2], [3,-3]]);

// Tensor Subtraction
const tensorNew = tensorA.sub(tensorB);

// Result: [ [0, 3], [1, 6], [2, 9] ]

 

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h2>JavaScript</h2>
<p>Subtracting tensors with tensorflow.js</p>

<div id="demo"></div>

<script>
const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
const tensorB = tf.tensor([[1,-1], [2,-2], [3,-3]]);

// Tensor Subtraction
const tensorNew = tensorA.sub(tensorB);

// Result: [ [0, 3], [1, 6], [2, 9] ]
document.getElementById("demo").innerHTML = tensorNew;
</script>

</body>
</html>



Tensor Multiplication

You can multiply two tensors using tensorA.mul(tensorB):

Example

const tensorA = tf.tensor([1, 2, 3, 4]);
const tensorB = tf.tensor([4, 4, 2, 2]);

// Tensor Multiplication
const tensorNew = tensorA.mul(tensorB);

// Result: [ 4, 8, 6, 8 ]

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h2>JavaScript</h2>
<p>Multiplying tensors with tensorflow.js</p>

<div id="demo"></div>

<script>
const tensorA = tf.tensor([1, 2, 3, 4]);
const tensorB = tf.tensor([4, 4, 2, 2]);

// Tensor Multiplication
const tensorNew = tensorA.mul(tensorB);

// Result: [ 4, 8, 6, 8 ]
document.getElementById("demo").innerHTML = tensorNew;
</script>

</body>
</html>

 


Tensor Division

You can divide two tensors using tensorA.div(tensorB):

Example

const tensorA = tf.tensor([2, 4, 6, 8]);
const tensorB = tf.tensor([1, 2, 2, 2]);

// Tensor Division
const tensorNew = tensorA.div(tensorB);

// Result: [ 2, 2, 3, 4 ]

 

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h2>JavaScript</h2>
<p>Dividing tensors with tensorflow.js</p>

<div id="demo"></div>

<script>
const tensorA = tf.tensor([2, 4, 6, 8]);
const tensorB = tf.tensor([1, 2, 2, 2]);

// Tensor Division
const tensorNew = tensorA.div(tensorB);

// Result: [ 2, 2, 3, 4 ]
document.getElementById("demo").innerHTML = tensorNew;
</script>

</body>
</html>


Tensor Square

You can square a tensor using tensor.square():

Example

const tensorA = tf.tensor([1, 2, 3, 4]);

// Tensor Square
const tensorNew = tensorA.square();

// Result [ 1, 4, 9, 16 ]

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h2>JavaScript</h2>
<p>Tensor square with tensorflow.js</p>

<div id="demo"></div>

<script>
const tensorA = tf.tensor([1, 2, 3, 4]);

// Tensor Square
const tensorNew = tensorA.square();

// Result [ 1, 4, 9, 16 ]
document.getElementById("demo").innerHTML = tensorNew;
</script>

</body>
</html>

 


Tensor Reshape

The number of elements in a tensor is the product of the sizes in the shape.

Since there can be different shapes with the same size, it is often useful to reshape a tensor to other shapes with the same size.

You can reshape a tensor using tensor.reshape():

Example

const tensorA = tf.tensor([[1, 2], [3, 4]]);
const tensorB = tensorA.reshape([4, 1]);

// Result: [ [1], [2], [3], [4] ]

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>

<h2>JavaScript</h2>
<p>Reshape a tensor with tensorflow.js</p>

<div id="demo"></div>

<script>
const tensorA = tf.tensor([[1, 2], [3, 4]]);
const tensorB = tensorA.reshape([4, 1]);

// Result [ [1], [2], [3], [4] ]
document.getElementById("demo").innerHTML = tensorB;
</script>

</body>
</html>

 

 

 
TFJS Operations

TesorFlow.js

A JavaScript Library for

Training and Deploying
Machine Learning Models
In the Browser

 

 

 


Tensorflow Models

Models and Layers are important building blocks in Machine Learning.

For different Machine Learning tasks you must combine different types of Layers into a Model that can be trained with data to predict future values.

TensorFlow.js is supporting different types of Models and different types of Layers.

A TensorFlow Model is a Neural Network with one or more Layers.


A Tensorflow Project

A Tensorflow project has this typical workflow:

  • Collecting Data
  • Creating a Model
  • Adding Layers to the Model
  • Compiling the Model
  • Training the Model
  • Using the Model

Example

Suppose you knew a function that defined a strait line:

Y = 1.2X + 5

Then you could calculate any y value with the JavaScript formula:

y = 1.2 * x + 5;

To demonstrate Tensorflow.js, we could train a Tensorflow.js model to predict Y values based on X inputs.

The TensorFlow model does not know the function.
 
// Create Training Data
const xs = tf.tensor([0, 1, 2, 3, 4]);
const ys = xs.mul(1.2).add(5);

// Define a Linear Regression Model
const model = tf.sequential();
model.add(tf.layers.dense({units:1, inputShape:[1]}));

// Specify Loss and Optimizer
model.compile({loss:'meanSquaredError', optimizer:'sgd'});

// Train the Model
model.fit(xs, ys, {epochs:500}).then(() => {myFunction()});

// Use the Model
function myFunction() {
  const xArr = [];
  const yArr = [];
  for (let x = 0; x <= 10; x++) {
    xArr.push(x);
    let result = model.predict(tf.tensor([Number(x)]));
    result.data().then(y => {
      yArr.push(Number(y));
      if (x == 10) {plot(xArr, yArr)};
    });
  }
}

<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tfjs-vis.umd.min.js"></script>
<body>
<h2>TensorFlow.js</h2>
<p id="message">Model is training!</p>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
// Create Training Data
const xs = tf.tensor([0, 1, 2, 3, 4]);
const ys = xs.mul(1.2).add(5);

// Define a Linear Regression Model
const model = tf.sequential();
model.add(tf.layers.dense({units:1, inputShape:[1]}));

// Specify Loss and Optimizer
model.compile({loss: 'meanSquaredError', optimizer:'sgd'});

// Train the Model
model.fit(xs, ys, {epochs:500}).then(() => {myFunction()});

// Use the Model
function myFunction() {
  const xMax = 10;
  const xArr = [];
  const yArr = [];
  for (let x = 0; x <= xMax; x++) { 
    let result = model.predict(tf.tensor([Number(x)]));
    result.data().then(y => {
      xArr.push(x);
      yArr.push(Number(y));
      if (x == xMax) {plot(xArr, yArr)};
    });
  }
  document.getElementById('message').style.display="none";
}

function plot(xArr, yArr) {
// Define Data
const data = [{x:xArr,y:yArr,mode:"markers",type:"scatter"}];

// Define Layout
const layout = {
  xaxis: {range: [0, 10]},
  yaxis: {range: [0, 20]},  
};

// Display Plot
Plotly.newPlot("myPlot", data, layout);
}
</script>
</body>
</html>

TensorFlow.js

 

The example is explained below:



Collecting Data

Create a tensor (xs) with 5 x values:

const xs = tf.tensor([0, 1, 2, 3, 4]);

Create a tensor (ys) with 5 correct y answers (multiply xs with 1.2 and add 5):

const ys = xs.mul(1.2).add(5);

Creating a Model

Create a sequential mode:.

const model = tf.sequential();
In a sequential model, the output from one layer is the input to the next layer.

Adding Layers

Add one dense layer to the model.

The layer is only one unit (tensor) and the shape is 1 (one dimentional):

model.add(tf.layers.dense({units:1, inputShape:[1]}));
in a dense the layer, every node is connected to every node in the preceding layer.

Compiling the Model

Compile the model using meanSquaredError as loss function and sgd (stochastic gradient descent) as optimizer function:

model.compile({loss:'meanSquaredError', optimizer:'sgd'});

Tensorflow Optimizers

  • Adadelta -Implements the Adadelta algorithm.
  • Adagrad - Implements the Adagrad algorithm.
  • Adam - Implements the Adam algorithm.
  • Adamax - Implements the Adamax algorithm.
  • Ftrl - Implements the FTRL algorithm.
  • Nadam - Implements the NAdam algorithm.
  • Optimizer - Base class for Keras optimizers.
  • RMSprop - Implements the RMSprop algorithm.
  • SGD - Stochastic Gradient Descent Optimizer.

Training the Model

Train the model (using xs and ys) with 500 repeats (epochs):

model.fit(xs, ys, {epochs:500}).then(() => {myFunction()});

Using the Model

After the model is trained, you can use it for many different purposes.

This example predicts 10 y values, given 10 x values, and calls a function to plot the predictions in a graph:

 
function myFunction() {
  const xArr = [];
  const yArr = [];
  for (let x = 0; x <= 10; x++) {
    let result = model.predict(tf.tensor([Number(x)]));
    result.data().then(y => {
      xArr.push(x);
      yArr.push(Number(y));
      if (x == 10) {display(xArr, yArr)};
    });
  }
}

<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tfjs-vis.umd.min.js"></script>
<body>
<h2>TensorFlow.js</h2>
<p id="message">Model is training!</p>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
// Create Training Data
const xs = tf.tensor([0, 1, 2, 3, 4]);
const ys = xs.mul(1.2).add(5);

// Define a Linear Regression Model
const model = tf.sequential();
model.add(tf.layers.dense({units:1, inputShape:[1]}));

// Specify Loss and Optimizer
model.compile({loss: 'meanSquaredError', optimizer:'sgd'});

// Train the Model
model.fit(xs, ys, {epochs:500}).then(() => {myFunction()});

// Use the Model
function myFunction() {
  const xMax = 10;
  const xArr = [];
  const yArr = [];
  for (let x = 0; x <= xMax; x++) { 
    let result = model.predict(tf.tensor([Number(x)]));
    result.data().then(y => {
      xArr.push(x);
      yArr.push(Number(y));
      if (x == xMax) {plot(xArr, yArr)};
    });
  }
  document.getElementById('message').style.display="none";
}

function plot(xArr, yArr) {
// Define Data
const data = [{x:xArr,y:yArr,mode:"markers",type:"scatter"}];

// Define Layout
const layout = {
  xaxis: {range: [0, 10]},
  yaxis: {range: [0, 20]},  
};

// Display Plot
Plotly.newPlot("myPlot", data, layout);
}
</script>
</body>
</html>

TensorFlow.js

 

This example predicts 10 y values, given 10 x values, and calls a function to display the values:

function myFunction() {
  const xArr = [];
  const yArr = [];
  for (let x = 0; x <= 10; x++) {
    let result = model.predict(tf.tensor([Number(x)]));
    result.data().then(y => {
      xArr.push(x);
      yArr.push(Number(y));
      if (x == 10) {display(xArr, yArr)};
    });
  }
}

<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<body>
<h2>TensorFlow.js</h2>
<p id="message">Model is training!</p>

<div id="myPlot" style="width:100%;max-width:700px"></div>

<script>
// Create Training Data
const xs = tf.tensor([0, 1, 2, 3, 4]);
const ys = xs.mul(1.2).add(5);

// Define a Linear Regression Model
const model = tf.sequential();
model.add(tf.layers.dense({units:1, inputShape:[1]}));

// Specify Loss and Optimizer
model.compile({loss: 'meanSquaredError', optimizer:'sgd'});

// Train the Model
model.fit(xs, ys, {epochs:500}).then(() => {myFunction()});

// Use the Model
function myFunction() {
  const xMax = 20;
  const xArr = [];
  const yArr = [];
  for (let x = 10; x <= xMax; x++) { 
    let result = model.predict(tf.tensor([Number(x)]));
    result.data().then(y => {
      xArr.push(x);
      yArr.push(Number(y));
      if (x == xMax) {display(xArr,yArr)};
    });
  }

}

function display(xArr, yArr) {
  let text = "Correct   Predicted<br>";
  for (let i = 0; i < xArr.length; i++) { 
    text += (xArr[i]*1.2+5).toFixed(4) + "   " + yArr[i].toFixed(4) + "<br>";
  }
  document.getElementById('message').innerHTML = text;
}
</script>
</body>
</html>

TensorFlow.js

Model is training!

 
TFJS Models
 
  • TensorFlow Visor is a graphic tools for visualizing Machine Learning
  • It contains functions for visualizing TensorFlow Models
  • Visualizations can be organized in Visors (modal browser windows)
  • Can be used with Custom Tools likes d3, Chart.js, and Plotly.js
  • Often called tfjs-vis

Using tfjs-vis

To use tfjs-vis, add the following script tag to your HTML file(s):

Example

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis"></script>
 

Scatter Plots

Example

const surface = document.getElementById('demo');
const series = ['First', 'Second'];

const serie1 = [];
const serie2 = [];
for (let i = 0; i < 100; i++) {
  serie1[i] = {x:i, y:Math.random() * 100};
  serie2[i] = {x:i, y:Math.random() * 100};
}

const data = {values: [serie1, serie2], series}

tfvis.render.scatterplot(surface, data);

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tfjs-vis.umd.min.js"></script>
<body>

<h2>TensorFlow Visor</h2>
<div id="demo"></div>

<script>

const surface = document.getElementById('demo');
const series = ['First', 'Second'];

const serie1 = []; 
const serie2 = [];
for (let i = 0; i < 100; i++) {
  serie1[i] = {x:i, y:Math.random() * 100};
  serie2[i] = {x:i, y:Math.random() * 100};
}

const data = {values: [serie1, serie2], series}
tfvis.render.scatterplot(surface, data);

</script>
</body>
</html>

 

Visualizations can be organized in a Visor (a modal browser window):

Example with a Visor

const series = ['First', 'Second'];

const serie1 = [];
const serie2 = [];
for (let i = 0; i < 100; i++) {
  serie1[i] = {x:i, y:Math.random() * 100};
  serie2[i] = {x:i, y:Math.random() * 100};
}

const data = {values: [serie1, serie2], series}

tfvis.render.scatterplot({name: "my Plots"}, data);

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tfjs-vis.umd.min.js"></script>
<body>

<h2>TensorFlow Visor</h2>

<script>

const series = ['First', 'Second'];

const serie1 = []; 
const serie2 = [];
for (let i = 0; i < 100; i++) {
  serie1[i] = {x:i, y:Math.random() * 100};
  serie2[i] = {x:i, y:Math.random() * 100};
}

const data = {values: [serie1, serie2], series}

tfvis.render.scatterplot({name: "my Plots"}, data);

</script>
</body>
</html>

TensorFlow Visor

 

 



Bar Graphs

Example

const surface = document.getElementById('demo');
const data = [
  {index: 0, value: 100},
  {index: 1, value: 200},
  {index: 2, value: 150},
  {index: 2, value: 250},
];

tfvis.render.barchart(surface, data);

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tfjs-vis.umd.min.js"></script>
<body>

<h2>Tensorflow Visor</h2>
<div id="demo"></div>

<script>
const surface = document.getElementById('demo');

const data = [
  {index: 0, value: 100},
  {index: 1, value: 200},
  {index: 2, value: 150},
  {index: 3, value: 250},
];

tfvis.render.barchart(surface, data);
</script>

</body>
</html>

 

Visualizations can be organized in a Visor (a modal browser window):

Example with a Visor

const data = [
  {index: 0, value: 100},
  {index: 1, value: 200},
  {index: 2, value: 150},
  {index: 2, value: 250},
];

tfvis.render.barchart({name:"my Graphs"}, data);

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tfjs-vis.umd.min.js"></script>
<body>

<h2>Tensorflow Visor</h2>

<script>
const data = [
  {index: 0, value: 100},
  {index: 1, value: 200},
  {index: 2, value: 150},
  {index: 3, value: 250},
];

tfvis.render.barchart({name:"my Graphs"}, data);
</script>

</body>
</html>

TFJS Visor
 

Input Data

Reduce Loss

Ex1 Intro

 

TensorFlow Data Collection

The data used in Example 1, is a list of car objects like this:

{
  "Name": "chevrolet chevelle malibu",
  "Miles_per_Gallon": 18,
  "Cylinders": 8,
  "Displacement": 307,
  "Horsepower": 130,
  "Weight_in_lbs": 3504,
  "Acceleration": 12,
  "Year": "1970-01-01",
  "Origin": "USA"
},
{
  "Name": "buick skylark 320",
  "Miles_per_Gallon": 15,
  "Cylinders": 8,
  "Displacement": 350,
  "Horsepower": 165,
  "Weight_in_lbs": 3693,
  "Acceleration": 11.5,
  "Year": "1970-01-01",
  "Origin": "USA"
},

The dataset is a JSON file stored at:

 


Cleaning Data

When preparing for machine learning, it is always important to:

  • Remove the data you don't need
  • Clean the data from errors

Remove Data

A smart way to remove unnecessary data, it to extract only the data you need.

This can be done by iterating (looping over) your data with a map function.

The function below takes an object and returns only x and y from the object's Horsepower and Miles_per_Gallon properties:

function extractData(obj) {
  return {x:obj.Horsepower, y:obj.Miles_per_Gallon};
}


Remove Errors

Most datasets contain some type of errors.

A smart way to remove errors is to use a filter function to filter out the errors.

The code below returns false if on of the properties (x or y) contains a null value:

function removeErrors(obj) {
  return obj.x != null && obj.y != null;
}

Fetching Data

When you have your map and filter functions ready, you can write a function to fetch the data.

 

async function runTF() {
  const jsonData = await fetch("cardata.json");
  let values = await jsonData.json();
  values = values.map(extractData).filter(removeErrors);
}

 


Plotting the Data

Here is some code you can use to plot the data:

function tfPlot(values, surface) {
  tfvis.render.scatterplot(surface,
    {values:values, series:['Original','Predicted']},
    {xLabel:'Horsepower', yLabel:'MPG'});
}

 

 

 
Ex1 Data
 

Shuffle Data

Always shuffle data before training.

When a model is trained, the data is divided into small sets (batches). Each batch is then fed to the model. Shuffling is important to prevent the model getting the same data over again. If using the same data twice, the model will not be able to generalize the data and give the right output. Shuffling gives a better variety of data in each batch.

Example

tf.util.shuffle(data);

TensorFlow Tensors

To use TensorFlow, input data needs to be converted to tensor data:

// Map x values to Tensor inputs
const inputs = values.map(obj => obj.x);
// Map y values to Tensor labels
const labels = values.map(obj => obj.y);

// Convert inputs and labels to 2d tensors
const inputTensor = tf.tensor2d(inputs, [inputs.length, 1]);
const labelTensor = tf.tensor2d(labels, [labels.length, 1]);

Data Normalization

Data should be normalized before being used in a neural network.

A range of 0 - 1 using min-max are often best for numerical data:

const inputMin = inputTensor.min();
const inputMax = inputTensor.max();
const labelMin = labelTensor.min();
const labelMax = labelTensor.max();
const nmInputs = inputTensor.sub(inputMin).div(inputMax.sub(inputMin));
const nmLabels = labelTensor.sub(labelMin).div(labelMax.sub(labelMin));


Tensorflow Model

A Machine Learning Model is an algorithm that produces output from input.

This example uses 3 lines to define a ML Model:

const model = tf.sequential();
model.add(tf.layers.dense({inputShape: [1], units: 1, useBias: true}));
model.add(tf.layers.dense({units: 1, useBias: true}));

Sequential ML Model

const model = tf.sequential();

 creates a Sequential ML Model.

In a sequential model, the input flows directly to the output. Other models can have multiple inputs and multiple outputs. Sequential is the easiest ML model. It allows you to build a model layer by layer, with weights that correspond to the next layer.

TensorFlow Layers

model.add() is used to add two layers to the model.

tf.layer.dense is a layer type that works in most cases. It multiplies its inputs by a weight-matrix and adds a number (bias) to the result.

Shapes and Units

inputShape: [1] because we have 1 input (x = horsepower).

units: 1 defines the size of the weight matrix: 1 weight for each input (x value).


Compiling a Model

Compile the model with a specified optimizer and loss function:

model.compile({loss: 'meanSquaredError', optimizer:'sgd'});

The compiler is set to use the sgd optimizer. It is simple to use and quite effective.

meanSquaredError is the function we want to use to compare model predictions and true values.

 

 
Ex1 Model
 

Training Function

async function trainModel(model, inputs, labels, surface) {
  const batchSize = 25;
  const epochs = 100;
  const callbacks = tfvis.show.fitCallbacks(surface, ['loss'], {callbacks:['onEpochEnd']})
  return await model.fit(inputs, labels,
    {batchSize, epochs, shuffle:true, callbacks:callbacks}
  );
}

 

epochs defines how many iterations (loops) the model will do.

model.fit is the function that runs the loops.

callbacks defines the callback function to call when the model wants to redraw the graphics.


Test the Model

When a model is trained, it is important to test and evaluate it.

We do this by inspecting what the model predicts for a range of different inputs.

But, before we can do that, we have to un-normalize the data:

Un Normalize

let unX = tf.linspace(0, 1, 100);
let unY = model.predict(unX.reshape([100, 1]));

const unNormunX = unX.mul(inputMax.sub(inputMin)).add(inputMin);
const unNormunY = unY.mul(labelMax.sub(labelMin)).add(labelMin);

unX = unNormunX.dataSync();
unY = unNormunY.dataSync();

Then we can look at the result:

Plot the Result

const predicted = Array.from(unX).map((val, i) => {
return {x: val, y: unY[i]}
});

// Plot the Result
tfPlot([values, predicted], surface1)
 
Ex1 Training
 

Input Data