Error when creating a model using Core API - javascript

I tried to follow the tutorial on TensorFlow official site to create a machine learning model based on Core API. But I got the following error:
Error: Argument 'b' passed to 'matMul' must be a Tensor or TensorLike, but got 'null'
I am working on windows 10 and with tfjs#1.5.2
const tf = require('#tensorflow/tfjs');
const tfcore = require('#tensorflow/tfjs-core')
const w1 = tf.variable(tf.randomNormal([784, 32]));
const b1 = tf.variable(tf.randomNormal([32]));
const w2 = tf.variable(tf.randomNormal([32, 10]));
const b2 = tf.variable(tf.randomNormal([10]));
function model(x) {
console.log(w1);
return x.matMul(w1).add(b1).relu().matMul(w2).add(b2).softmax();
}
model(tfcore);
Could you please help me with this error?

as #edkeveked stated you need to supply two tensors for tf.matMul:
approach 1
const a = tf.tensor2d([1, 2], [1, 2]);
const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
a.matMul(b);
or approach 2
const a = tf.tensor2d([1, 2], [1, 2]);
const b = tf.tensor2d([1, 2, 3, 4], [2, 2]);
tf.matMul(a, b);
in your example, by passing in tfcore to model() you are using approach 2 and therefore need to pass a second tensor to matMul. however, if you pass a tensor to model() it should work like approach 1.

The error says it all, you are multiplying a tensor by null (the second parameter defaults to null).
tf.matMul(tensor)
You need to supply a second tensor for the matrix multiplication

Related

Excel Office Script - error trying to push a 2D Array

I'm having an issue of understanding and I'll try to be basic with my problem because it involves lots of data. Here is a simple mockup.
From myArray below, I'm trying to create a new 2D array (arrayFinal) in the form of [[element],[element],[element]], to be able to use a setValues() with Excel Office Script. In this example, each element should have more than 2 elements.
But I'm truly not going anywhere with my way.
I only get a return like, with too many [[[]]] (one too many), and only the last element repeating itself.
[[[1,5,7]],[[1,5,7]],[[1,5,7]],[[1,5,7]],[[1,5,7]],[[1,5,7]]]
Could you have a look and tell me what's the problem ?
let myArray: number[][] = [[1, 2, 3], [2, 4], [5, 6, 7],[1],[2,3],[1,5,7]];
let testArray: (string | boolean | number)[][] = [];
let arrayFinal: (string | boolean | number)[][] = [];
myArray.map(x => {
testArray.length = 0;
if (x.length > 2) {
testArray.push(x);
}
arrayFinal.push(testArray);
})
console.log(JSON.stringify(arrayFinal))
Thank you !
If I understand it correctly, you are trying to filter the original 2D array to only contain sub-arrays with more than 2 elements, right?
Wondering if you would want to try something like this:
let myArray: number[][] = [[1, 2, 3], [2, 4], [5, 6, 7],[1],[2,3],[1,5,7]];
let arrayFinal = myArray.filter(arr => arr.length > 2);
console.log(JSON.stringify(arrayFinal))
The output should be:
[[1,2,3],[5,6,7],[1,5,7]]

how to get values from an json array

Guys this might be a simple question, but please help.
i have a data.
var a = { "data":[[1,2,3],[2,4,3],[3,6,7],[1,4],[6,4,3,4],[6,7,3,5]] }
i'm plotting a multiple line chart using chartjs and i want these valus in array to use as datasets.
what i wat is to save each array in different var's
like;
var a = [1,2,3],
var b = [2,4,3]
var c = [3,6,7]
so that i can pass theese values to chart js and plot chart. any help is appreciated. i thought of foreach and getting by each position. but its not working.
regards
Use Array destructuring.
Use spread operator on last node. That will keep all the remaining nodes except the specified number of paramaters, if you are interested on the frst three nodes only.
var data = { "data": [[1, 2, 3], [2, 4, 3], [3, 6, 7], [1, 4], [6, 4, 3, 4], [6, 7, 3, 5]] }
const [a, b, c, ...restNodes] = data.data;
console.log(a);
console.log(b);
console.log(c);
console.log(restNodes);
Please Note Its not mandatory to have the last node with spread operator. You can pick the first three nodes only using
const [a, b, c] = data.data;
I just said you can do this aswell
Spread the data and just assign to three variables.
var x = { "data":[[1,2,3],[2,4,3],[3,6,7],[1,4],[6,4,3,4],[6,7,3,5]] }
let [a,b,c] = [...x.data];
console.log(a);
console.log(b);
console.log(c);
There is no need to even include a fourth variable if all you care about is a,b,c.

Constant Array in JavaScript

How can I keep an array of constants in JavaScript?
And likewise, when comparing, it gives me the correct result.
Example,
const vector = [1, 2, 3, 4];
vector[2] = 7; // An element is not constant!
console.log(JSON.stringify(vector));
// [1,2,7,4] ... Was edited
// OR
const mirror = [1, 2, 7, 4];
console.log(`are equals? ${vector == mirror}`);
// false !
With Object.freeze you can prevent values from being added or changed on the object:
'use strict';
const vector = Object.freeze([1, 2, 3, 4]);
vector[2] = 7; // An element is not constant!
'use strict';
const vector = Object.freeze([1, 2, 3, 4]);
vector.push(5);
That said, this sort of code in professional JS is unusual and a bit overly defensive IMO. A common naming convention for absolute constants is to use ALL_CAPS, eg:
const VECTOR =
Another option for larger projects (that I prefer) is to use TypeScript to enforce these sorts of rules at compile-time without introducing extra runtime code. There, you can do:
const VECTOR: ReadonlyArray<Number> = [1, 2, 3, 4];
or
const VECTOR = [1, 2, 3, 4] as const;
I have not investigated thoroughly, but it is inferred that JS will have immutable native types, here is a presentation:
https://2ality.com/2020/05/records-tuples-first-look.html
const vector = #[1, 2, 3, 4]; // immutable
The const keyword can be confusing, since it allows for mutability. What you would need is immutability. You can do this with a library like Immutable or Mori, or with Object.freeze:
const array = [1,2,3]
Object.freeze(array)
array[0] = 4
array // [1,2,3]

TensorFlow.js: Are those two Tensors equal?

I am reading the TensorflowJS documentation. In their example code they state
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
See here
I am confused since they use a 2 dimensional array here. Does anyone know why?
For completeness, here is the full code snippet.
// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
// Train the model using the data.
model.fit(xs, ys).then(() => {
// Use the model to do inference on a data point the model hasn't seen before:
// Open the browser devtools to see the output
model.predict(tf.tensor2d([5], [1, 1])).print();
});
Would it not be simpler to use a 1 dimensional array here, since the array does not make use of a second dimension anyways?
const xs = tf.tensor1d([1, 2, 3, 4]);
The features xs tensor is a two dimensionnal tensor. More generally the features tensor is one dimension bigger than the inputShape of the first layer. The added dimension is the batches dimension which indicates how many elements of shape the inputShape, the model are either trained with or predicted.
In the example, the inputShape being of size [1], the features shape need to be of shape [b,1], therefore a two dimensionnal tensor

Method Set.prototype.has called on incompatible receiver undefined

After years of using JavaScript I met an error that I had never seen.
I wanted to calculate the intersection between two Sets, so I wrote:
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
let intersection = [...a].filter(x => b.has(x));
console.log(intersection);
And it works, but I noticed that I can shorten the above code. Since the filter method just wants a function and invokes it no matter how it is defined, and I wrote:
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
let intersection = [...a].filter(b.has);
console.log(intersection);
And in this case, unexpectedly, I receive the following error:
Uncaught TypeError: Method Set.prototype.has called on incompatible receiver undefined
I also noticed that this doesn't happen if I bind Set.prototype.add to the variable:
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
let intersection = [...a].filter(Set.prototype.bind(b));
console.log(intersection);
My question is: why does it happen? Why b.has is not a valid callback?
has method loses internal this context when you pass it as a callback.
That is the reason it works when you use bind to provide it right context.
For more info it has been documented here
You can use the Array#filter function and pass thisArg as the second parameter. So the has will take this second parameter as it's this, and proceeds to evaluate or compare.
Here's an example:
function compare(a, b) {
return [...a].filter(Set.prototype.has, b);
}
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
console.log(compare(a, b));
Another idea:
function compare(a, b) {
return new Set([...a].filter(Set.prototype.has, b));
}
let a = new Set([1, 2, 3]);
let b = new Set([2, 3, 4]);
console.log([...compare(a, b).values()]);

Categories

Resources