Arthur Guiot
Arthur Guiot

Reputation: 721

How to predict a value from a dataset in JavaScript?

The point

My question is "How to predict a value from a dataset in JavaScript?". To explain my problem, I'm going to take an example of the result I want.

If you're using Mathematica, you probably know that there is a Predict[] function. And I thought that it could be awesome if I could do a similar function in JavaScript. I know that the Mathematica function is using Machine Learning and other cool and technical stuff that I don't really know more about, so, to keep it simple, I tried to implement this Predict[] function through what I call "Affine transformation prediction".

If you remember from school, affine functions are written like f(x)=ax+b.

and I know that from 2 values, you can easily know what is a and b.

My implementation

Here is my code for the moment:

function predict(array1, array2, val) {
    var first = array1[0]
    var second = array2[0]
    var firstVal = array1[1]
    var secondVal = array2[1]
    var a = (firstVal - secondVal) / (first - second)
    var b = secondVal - (second * a)
    return val * b;
}

So, the array1 one will be the "start" value (I don't know the word in English, but in French it's "antecedent"), and the image of the function.

The array2 will be the same, but for a different "start" value and image.

The val will be where does the function have to predict the value.

Example of how it works:

Let's say we have the function f(x)=2x+1, we know that 1->3 and 2->5 works. So, we want to know (without knowing the function of course 😊) what f(3) will give us, so we write:

predict([1,3],[2,5],3)

And, normally, it will return 7.

My problem

The main problem of this function is the way it works. I would like to simplify it. Let me explain, I would a function that looks like that:

function predict(object, val) {
    ...
}

Where object is something like: { 1: 3, 2: 5, 4: 9}. Something like a JSON object with 2 or more values in it, to be I guess more precise, but also to have the word "dataset" in it. Because, the problem is that currently, the function can't be called a predict function because it's more an affineTransformationFinder function.

Manipulating object in JavaScript is way simpler than an array for many many reasons that you'll understand.

I tried to explain my point and I hope 🤞 you'll agree with me. If you have any question, don't hesitate to add a comment, I'll be happy 😊 to answer it.

Upvotes: 2

Views: 1615

Answers (1)

Jonah
Jonah

Reputation: 1545

Object.keys() is what you're looking for - when passed an object, it returns an array of its keys, which you can iterate through and pass back into the object to retrieve the property values.

Upvotes: 1

Related Questions