简体   繁体   中英

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?

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)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM