Diego Aguado
Diego Aguado

Reputation: 1596

How to build a tensor from 2 scalars in Tensorflow?

I have two scalars resulting from the following operations: a = tf.reduce_sum(tensor1), b = tf.matmul(tf.transpose(tensor2), tensor3) this is a dot product since tensor2 and tensor3 have the same dimensions (1-D vectors). Since these tensors have shape [None, dim1] it becomes difficult to deal with the shapes.

I want to build a tensor that has shape (2,1) using a and b.

I tried tf.Tensor([a,b], dtype=tf.float64, value_index=0) but raises the error

TypeError: op needs to be an Operation: [<tf.Tensor 'Sum_5:0' shape=() dtype=float32>, <tf.Tensor 'MatMul_67:0' shape=(?, ?) dtype=float32>]

Any easier way to build that tensor/vector?

Upvotes: 1

Views: 3878

Answers (2)

Salvador Dali
Salvador Dali

Reputation: 222471

You can use concat or stack to achieve this:

import tensorflow as tf
t1 = tf.constant([1])
t2 = tf.constant([2])
c = tf.reshape(tf.concat([t1, t2], 0), (2, 1))

with tf.Session() as sess:
    print sess.run(c)

In a similar way you can achieve it with tf.stack.

Upvotes: 1

Harsha Pokkalla
Harsha Pokkalla

Reputation: 1802

This would do probably. Change axis based on what you need

a = tf.constant(1)
b = tf.constant(2)
c = tf.stack([a,b],axis=0)

Output:

array([[1],
       [2]], dtype=int32)

Upvotes: 1

Related Questions