Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
How to take tf.Tensor type to number type in Typescript

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda