In this slightly more complicated example, we'll define a 2D planar function to fit 3-dimensional data. The main difference here is that
This general plane formula can be rewritten to solve for
In the dataset defined in our source code, the x
property refers to all the inputs to the function, and the y
property refers to the output. In this example, x
is an array of length 2, representing our 2 independent dimensions. We can call those dimensions the x-axis and y-axis, obtained by x[0]
and x[1]
respectively. In mathematics, this is simply referred to as the input vector we defined as y
property in our dataset is actually our z-axis. It's important to remember that the x
and y
properties in the dataset simply refer to the inputs and output of the function, not necessarily the x-axis and y-axis.
3 points is all that is required to define the equation for a plane. In this example, our data fits to the plane defined by
Let's see if the algorithm can find this out just based on the dataset! Try it for yourself and see if you obtain similar results, and try plotting it in an online 3D calculator!
Follow these steps to create a new project workspace and install the datafit dependency to run this example.
# Create and open project folder
mkdir Multi_Variable_demo
cd Multi_Variable_demo
# Initialize project and install dependencies
npm init -y
npm i datafit@1.4.8
# Create and open source file
touch "Multi Variable.mjs"
open "Multi Variable.mjs"
Copy and paste this source code into Multi Variable.mjs
.
import { fit } from 'datafit';
// Define a general 3D plane function where z = f(x, y)
function f([x, y], cx, cy, cz) {
return cx * x + cy * y + cz;
}
// These 3 points make up the plane
// z = 2x - y + 1
const data = [
{ x: [0, 0], y: 1 },
{ x: [1, 0], y: 3 },
{ x: [0, 1], y: 0 },
];
// Run the curve fitting algorithm
const summary = fit(f, data);
console.log(summary);
In Multi_Variable_demo/
, execute Multi Variable.mjs
with NodeJS to generate an output.
node "Multi Variable.mjs"
You should expect to see an output similar to the one below.
{
f: [Function: f],
params: [ 1.9891381557293835, -1.0084708293517537, 1.009462198985414 ],
error: 0.00009247503031450267,
errorAvgAbs: 0.005552027567009571
}