简体   繁体   English

如何在Tensorflow中从2个标量构建张量?

[英]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). 我通过以下操作得到两个标量: a = tf.reduce_sum(tensor1)b = tf.matmul(tf.transpose(tensor2), tensor3)这是一个点积,因为tensor2tensor3具有相同的尺寸(1- D个向量)。 Since these tensors have shape [None, dim1] it becomes difficult to deal with the shapes. 由于这些张量具有形状[None, dim1]因此很难处理这些形状。

I want to build a tensor that has shape (2,1) using a and b . 我想使用ab构建具有形状(2,1)的张量。

I tried tf.Tensor([a,b], dtype=tf.float64, value_index=0) but raises the error 我尝试了tf.Tensor([a,b], dtype=tf.float64, value_index=0)但引发了错误

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: 您可以使用concat或stack来实现此目的:

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 . 以类似的方式,您可以使用tf.stack来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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