-

- -

Showing posts with label artificial-intelligence. Show all posts
Showing posts with label artificial-intelligence. Show all posts

Tuesday, May 31, 2022

Transformer Illustration

 


What Is a Transformer Model?

A transformer model is a neural network that learns context and thus meaning by tracking relationships in sequential data like the words in this sentence.

https://blogs.nvidia.com/blog/2022/03/25/what-is-a-transformer-model/


Transformer Neural Network: Step-By-Step Breakdown of the Beast

https://towardsdatascience.com/transformer-neural-network-step-by-step-breakdown-of-the-beast-b3e096dc857f


The Illustrated Transformer

https://jalammar.github.io/illustrated-transformer/


Drawing the Transformer Network from Scratch

https://towardsdatascience.com/drawing-the-transformer-network-from-scratch-part-1-9269ed9a2c5e


Transformers are RNNs:

Fast Autoregressive Transformers with Linear Attention

https://linear-transformers.com/



Saturday, January 22, 2022

Machine Learning on Tabular Data with Nyckel

. In the video, the instructor used one of the most popular datasets on kaggle - the titanic dataset. It lists data on titanic passengers (name, age, number of siblings, ticket class, etc.) with a column that indicates whether the passenger survived the shipwreck. The challenge is to create a model that predicts which passengers survived. In less that two minutes, the system is able to go from the data to a trained and deployed model. Underneath this serene user experience, there is a lot going on: (1)Training-optimized cloud hardware is allocated, (2)Several state-of-the-art deep neural networks and hyper-parameters are evaluated to find the best fit for the data, (3)The model is deployed on inference-optimized and elastically scalable cloud hardware, behind a secure REST API . . https://www.nyckel.com/blog/fast-machine-learning-tabular-data-automl/

Monday, July 26, 2021

How To: Build Simple Neural Network With TensorFlow JavaScript To Recognize Number Digit Image

 

.

In this article, we will learn how to deploy a machine learning model using NodeJS. While doing so we will make a simple handwritten digit recognizer using NodeJS and tensorflow.js.

.

Tensorflow.js is an ML library for JavaScript. It helps to deploy machine learning models directly into node.js or a web browser.

.

Training the Model: For training the model we are going to use Google Colab. It is a platform where we can run all our python code, and it comes loaded with most of the machine learning libraries that are used.

.

https://www.geeksforgeeks.org/how-to-deploy-a-machine-learning-model-using-node-js/

.

Tuesday, May 25, 2021

TensorFlow.Js Tutorial: Making Predictions from 2D Data

This tutorial is based on the original article at: https://codelabs.developers.google.com/codelabs/tfjs-training-regression

html



javascript

See the Pen Untitled by smartcomputing123 (@smartcomputing123) on CodePen.

Friday, February 19, 2021

Machine Learning In JavaScript

 .

Machine Learning (ML)

Machine Learning is often considered equivalent with Artifical Intelligence.

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

Machine Learning is a disipline of AI that uses data to perform supervised or unsupervised machine training.

What is Machine Learning?

ML systems combines Input to produce Predictions.

Key terminologies are:

  • Labels
  • Features
  • Models
  • Training
  • Inference
  • Functions

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:

y = ax + b


Machine Learning Features

In Machine Learning terminology, the features are the input.

They are like the x values in a linear graph:

y = ax + b


Machine Learning Models

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

Data Collection

Machine Learning can teach a computer to solve many questions like:

  • Is this cancer?
  • Is this a banana?

Before Machine Learning can start, you need to collect some data.

If you want to predict house prices, you need to collect some information about house prices.


Machine Learning Training

The goal of training is to create a model that can answer our question. Like what is the expected price for a house?


Machine Learning Inference

Inference is when the trained model is used to infer (predict) values using live data. Like putting the model into production.


Using a Linear Regression Function

This Model predicts prices using a linear regression function:

Prices

Example

# Name the Axis
plt.title('House Prices vs Size')
plt.xlabel('Square Meters')
plt.ylabel('Price in Millions')

# Set x and y values
x = np.array([50,60,70,80,90,100,110,120,130,140,150,160])
y = np.array([7,8,8,9,9,9,9,10,11,14,14,15])

# Call Linear Regression Function
slope, intercept, r, p, std_err = stats.linregress(x, y)

# Plot Data
plt.scatter(x, y)
plt.plot(x, slope * x + intercept)
plt.show()
Try it Yourself »

In the example above, the slope and intercept is calculated by a function called linregress.

From Previous Chapter

A linear relationship is 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

With Machine Learning

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

Where:

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

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

y = b + w1x1 + w2x2 + w3x3 + w4x4


.

https://web.archive.org/web/20210220012931/https://www.w3schools.com/ai/ai_machine_learning.asp

.


Artificial Intelligence In JavaScript

.

Artificial Intelligence

AI in JavaScript

These days, several JavaScript AI framework are emerging.

JavaScript frameworks make it possible to execute AI tasks in the browser.

AI and JavaScript

Artificial Intelligence has changed the science of image processing, computer vision, and natural language applications.

Thanks to new AI libraries, JavaScript developers can now build machine learning and deep learning applications without Python or R. This way JavaScript can help developers to bring AI to the browser and to the web.


Is JavaScript Good for AI?

Most AI applications these days use R or Python.

But JavaScript has a great future as an AI language, and it even has a some advantages:

  • JS is better known. All developers can use it.
  • Security is built in. JS cannot access your files.
  • JS is faster than Python.
  • Modern JS compiles into machine code.
  • Modern JS can use hardware acceleration.

WebGL API

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

WebGL can run on both integrated and stanalone 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.

WebGL 1.0 was released in March 2011.

WebGL 2.0 was released in January 2017.

JellyFish


TensorFlow Playground

TensorFlow Playground 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.


Plotting in JavaScript

01234567891516171819

Plotting provided by: Plotly

.

https://web.archive.org/web/20210220012909/https://www.w3schools.com/ai/ai_javascript.asp

.

Monday, August 24, 2020

Introducing Danfo.js, a Pandas-like Library in JavaScript



.
Danfo.js is an open-source JavaScript library that provides high-performance, intuitive, and easy-to-use data structures for manipulating and processing structured data. Danfo.js is heavily inspired by the Python Pandas library and provides a similar interface/API. This means that users familiar with the Pandas API and know JavaScript can easily pick it up.
.
One of the main goals of Danfo.js is to bring data processing, machine learning and AI tools to JavaScript developers. This is in line with our vision and essentially the vision of the TensorFlow.js team, which is to bring ML to the web. Open-source libraries like Numpy and Pandas revolutionise the ease of manipulating data in Python and lots of tools were built around them, thus driving the bubbling ecosystem of ML in Python.

Danfo.js is built on TensorFlow.js. That is, as Numpy powers Pandas arithmetic operations, we leverage TensorFlow.js to power our low-level arithmetic operations.

Some of the main features of Danfo.js

Danfo.js is fast. It is built on TensorFlow.js, and supports tensors out of the box. This means you can load Tensors in Danfo and also convert Danfo data structure to Tensors. Leveraging these two libraries, you have a data processing library on one hand (Danfo.js), and a powerful ML library on the other hand (TensorFlow.js).

In the example below, we show you how to create a Danfo DataFrame from a tensor object:
const dfd = require("danfojs-node")
const tf = require("@tensorflow/tfjs-node")

let data = tf.tensor2d([[20,30,40], [23,90, 28]])
let df = new dfd.DataFrame(data)
let tf_tensor = df.tensor
console.log(tf_tensor);
tf_tensor.print()
Output:
Tensor {
  kept: false,
  isDisposedInternal: false,
  shape: [ 2, 3 ],
  dtype: 'float32',
  size: 6,
  strides: [ 3 ],
  dataId: {},
  id: 3,
  rankType: '2'
}
Tensor
    [[20, 30, 40],
     [23, 90, 28]]
You can easily convert Arrays, JSONs, or Objects to DataFrame objects for manipulation.

JSON object to DataFrame:
const dfd = require("danfojs-node")
json_data = [{ A: 0.4612, B: 4.28283, C: -1.509, D: -1.1352 },
            { A: 0.5112, B: -0.22863, C: -3.39059, D: 1.1632 },
            { A: 0.6911, B: -0.82863, C: -1.5059, D: 2.1352 },
            { A: 0.4692, B: -1.28863, C: 4.5059, D: 4.1632 }]
df = new dfd.DataFrame(json_data)
df.print()
Output:

Object array with column labels to DataFrame:
const dfd = require("danfojs-node")
obj_data = {'A': [“A1”, “A2”, “A3”, “A4”],
            'B': ["bval1", "bval2", "bval3", "bval4"],
            'C': [10, 20, 30, 40],
            'D': [1.2, 3.45, 60.1, 45],
            'E': ["test", "train", "test", "train"]
            }
df = new dfd.DataFrame(obj_data)
df.print()
Output:

You can easily handle missing data (represented as NaN) in floating point as well as non-floating point data:
const dfd = require("danfojs-node")
let data = {"Name":["Apples", "Mango", "Banana", undefined],
            "Count": [NaN, 5, NaN, 10], 
            "Price": [200, 300, 40, 250]}        
let df = new dfd.DataFrame(data)
let df_filled = df.fillna({columns: ["Name", "Count"], values: ["Apples", 
df["Count"].mean()]})
df_filled.print()
Output:

Intelligent label-based slicing, fancy indexing, and querying of large data sets:
const dfd = require("danfojs-node")
let data = { "Name": ["Apples", "Mango", "Banana", "Pear"] ,
            "Count": [21, 5, 30, 10],
             "Price": [200, 300, 40, 250] }

let df = new dfd.DataFrame(data)
let sub_df = df.loc({ rows: ["0:2"], columns: ["Name", "Price"] })
sub_df.print()
Output:

Robust IO tools for loading data from flat-files (CSV and delimited). Both in full and chunks:
const dfd = require("danfojs-node")
//read the first 10000 rows
dfd.read_csv("file:///home/Desktop/bigdata.csv", chunk=10000)
  .then(df => {
    df.tail().print()
  }).catch(err=>{
       console.log(err);
  })
Robust data preprocessing functions like OneHotEncodersLabelEncoders, and scalers like StandardScaler and MinMaxScaler are supported on DataFrame and Series:
const dfd = require("danfojs-node")
let data = ["dog","cat","man","dog","cat","man","man","cat"]
let series = new dfd.Series(data)
let encode = new dfd.LabelEncoder()
encode.fit(series)
let sf_enc = encode.transform(series)
let new_sf = encode.transform(["dog","man"])
Output:

Interactive, flexible and intuitive API for plotting DataFrames and Series in the browser:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/danfojs@0.1.1/dist/index.min.js"></script>
    <title>Document</title>
</head>
<body>
    <div id="plot_div"></div>
    <script>
         dfd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")

            .then(df => {
                var layout = {
                    title: 'A financial charts',
                    xaxis: {title: 'Date'},
                    yaxis: {title: 'Count'}
                }
    new_df = df.set_index({ key: "Date" })
   new_df.plot("plot_div").line({ columns: ["AAPL.Open", "AAPL.High"], layout: layout 
})
            }).catch(err => {
                console.log(err);
            })
    </script>
</body>
</html>
Output:

Titanic Survival Prediction using Danfo.js and Tensorflow.js
Below we show a simple end-to-end classification task using Danfo.js and TensorFlow.js. We use Danfo for data loading, manipulating and preprocessing of the dataset, and then export the tensor object.
const dfd = require("danfojs-node")
const tf = require("@tensorflow/tfjs-node")

async function load_process_data() {
    let df = await dfd.read_csv("https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuff/titanic.csv")

    //A feature engineering: Extract all titles from names columns
    let title = df['Name'].apply((x) => { return x.split(".")[0] }).values
    //replace in df
    df.addColumn({ column: "Name", value: title })

    //label Encode Name feature
    let encoder = new dfd.LabelEncoder()
    let cols = ["Sex", "Name"]
    cols.forEach(col => {
        encoder.fit(df[col])
        enc_val = encoder.transform(df[col])
        df.addColumn({ column: col, value: enc_val })
    })

    let Xtrain,ytrain;
    Xtrain = df.iloc({ columns: [`1:`] })
    ytrain = df['Survived']

    // Standardize the data with MinMaxScaler
    let scaler = new dfd.MinMaxScaler()
    scaler.fit(Xtrain)
    Xtrain = scaler.transform(Xtrain)

    return [Xtrain.tensor, ytrain.tensor] //return the data as tensors
}
Next, we create a simple neural network using TensorFlow.js.
function get_model() {
    const model = tf.sequential();
    model.add(tf.layers.dense({ inputShape: [7], units: 124, activation: 'relu', kernelInitializer: 'leCunNormal' }));
    model.add(tf.layers.dense({ units: 64, activation: 'relu' }));
    model.add(tf.layers.dense({ units: 32, activation: 'relu' }));
    model.add(tf.layers.dense({ units: 1, activation: "sigmoid" }))
    model.summary();
    return model
}
Finally, we perform training, by first loading the model and the processed data as tensors. This can be fed directly to the neural network.
async function train() {
    const model = await get_model()
    const data = await load_process_data()
    const Xtrain = data[0]
    const ytrain = data[1]

    model.compile({
        optimizer: "rmsprop",
        loss: 'binaryCrossentropy',
        metrics: ['accuracy'],
    });

    console.log("Training started....")
    await model.fit(Xtrain, ytrain,{
        batchSize: 32,
        epochs: 15,
        validationSplit: 0.2,
        callbacks:{
            onEpochEnd: async(epoch, logs)=>{
                console.log(`EPOCH (${epoch + 1}): Train Accuracy: ${(logs.acc * 100).toFixed(2)},
                                                     Val Accuracy:  ${(logs.val_acc * 100).toFixed(2)}\n`);
            }
        }
    });
};

train()
The reader will notice that the API of Danfo is very similar to Pandas, and a non-Javascript programmer can easily read and understand the code. You can find the full source code of the demo above here (https://gist.github.com/risenW/f54e4e5b6d92e7b1b9b1f30e884ca83c).

Closing Remarks

As web-based machine learning has matured, it is imperative to have efficient data science tools built specifically for it. Tools like Danfo.js will enable web-based applications to easily support ML features, thus opening the space to an ecosystem of exciting applications. TensorFlow.js started the revolution by providing ML capabilities available in Python, and we hope to see Danfo.js as an efficient partner in this journey. We can’t wait to see what Danfo.js grows into! Hopefully, it becomes indispensable to the web community as well.
  • Play with Danfo.js on CodePen
  • Link to the official getting started guide
  • Link to Github repository
.

Thursday, January 30, 2020

[ebook] Deep Learning with JavaScript Neural networks in TensorFlow.js



.

Deep learning has transformed the fields of computer vision, image processing, and natural language applications. Thanks to TensorFlow.js, now JavaScript developers can build deep learning apps without relying on Python or R. Deep Learning with JavaScript shows developers how they can bring DL technology to the web. Written by the main authors of the TensorFlow library, this new book provides fascinating use cases and in-depth instruction for deep learning apps in JavaScript in your browser or on Node.

about the technology

Running deep learning applications in the browser or on Node-based backends opens up exciting possibilities for smart web applications. With the TensorFlow.js library, you build and train deep learning models with JavaScript. Offering uncompromising production-quality scalability, modularity, and responsiveness, TensorFlow.js really shines for its portability. Its models run anywhere JavaScript runs, pushing ML farther up the application stack.

about the book

In Deep Learning with JavaScript, you’ll learn to use TensorFlow.js to build deep learning models that run directly in the browser. This fast-paced book, written by Google engineers, is practical, engaging, and easy to follow. Through diverse examples featuring text analysis, speech processing, image recognition, and self-learning game AI, you’ll master all the basics of deep learning and explore advanced concepts, like retraining existing models for transfer learning and image generation.

what's inside

  • Image and language processing in the browser
  • Tuning ML models with client-side data
  • Text and image creation with generative deep learning
  • Source code samples to test and modify

about the reader

For JavaScript programmers interested in deep learning.

about the author

Shanging CaiStanley Bileschi and Eric D. Nielsen are software engineers with experience on the Google Brain team, and were crucial to the development of the high-level API of TensorFlow.js. This book is based in part on the classic, Deep Learning with Python by François Chollet.

.

https://www.manning.com/books/deep-learning-with-javascript