I'm working with Tensorflow.js in typescript and I want to get the cosine similarity of two 1D tensors, but I am having trouble with dealing with the types that tensorflow uses. When I calculate the cosine similarity, using this function I should be getting a number, but instead I get a bunch of different other types including number.
function calculateCosineSimilarity(abstractEmbedding: tf.Tensor1D | Array<number>, queryEmbedding: tf.Tensor1D | Array<number>): number{
const dotProd: tf.Tensor = tf.dot(abstractEmbedding, queryEmbedding);
const lenAbstractEmbedding: tf.Tensor = tf.dot(abstractEmbedding, abstractEmbedding);
const lenQueryEmbedding: tf.Tensor = tf.dot(queryEmbedding, queryEmbedding);
const similarityScore: tf.Tensor = tf.div(dotProd, tf.mul(lenAbstractEmbedding,lenQueryEmbedding));
return similarityScore.arraySync();
}
I get this error at the return statement:
Type 'number | number[] | number[][] | number[][][] | number[][][][] | number[][][][][] | number[][][][][][]' is not assignable to type 'number'.
I know when you take dot products of multidimensional arrays, the dimensions/types of the resulting array will vary, but for my case I know I will be getting a single value back, so I just want to return a single number. Is there a way to resolve this issue without having to change the return type of the function?
CodePudding user response:
I don't believe it is the best practice, but if you do not want the return type of the function to list all of those type options, or be Any, then you can force the coercion of the response variable to unknown, if necessary, and then to the type you are expecting.
return similarityScore.arraySync() as number;
or if the types do not sufficiently overlap
return similarityScore.arraySync() as unknown as number;