是否有一个等于np.empty的张量流? [英] Is there a tensorflow equivalent to np.empty?

查看:128
本文介绍了是否有一个等于np.empty的张量流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Numpy具有此帮助功能, np.empty ,它将:

Numpy has this helper function, np.empty, which will:

返回给定形状和类型的新数组,而无需初始化条目.

Return a new array of given shape and type, without initializing entries.

当我想使用 tf.concat ,因为:

输入张量的维数必须匹配,除轴外的所有维数必须相等.

The number of dimensions of the input tensors must match, and all dimensions except axis must be equal.

所以从一个预期形状的空张量开始很方便.有什么办法可以在张量流中实现这一目标吗?

So it comes in handy to start with an empty tensor of an expected shape. Is there any way to achieve this in tensorflow?

为什么要这个的简化示例

A simplified example of why I want this

    netInput = np.empty([0, 4])
    netTarget = np.empty([0, 4])
    inputWidth = 2

    for step in range(data.shape.as_list()[-2]-frames_width-1):
        netInput = tf.concat([netInput, data[0, step:step + frames_width, :]], -2)
        target = tf.concat([target, data[0, step + frames_width + 1:step + frames_width + 2, :]], -2)

在此示例中,如果初始化了netInput或netTarget,我将在该初始化中串联一个额外的示例.为了使用第一个值初始化它们,我需要修改循环.没有市长,我只是想知道是否有一种张量流"方式来解决这个问题.

In this example, if netInput or netTarget are initialized, I'll be concatenating an extra example with that initialization. And to initialize them with the first value, I need to hack the loop. Nothing mayor, I just wondered if there is a 'tensorflow' way to solve this.

推荐答案

您可以做的最接近的事情是创建一个不初始化的变量.如果使用tf.global_variables_initializer()初始化变量,请通过设置collections=[]禁用在初始化过程中将变量放入全局变量列表中.

The closest thing you can do is create a variable that you do not initialize. If you use tf.global_variables_initializer() to initialize your variables, disable putting your variable in the list of global variables during initialization by setting collections=[].

例如,

import numpy as np
import tensorflow as tf

x = tf.Variable(np.empty((2, 3), dtype=np.float32), collections=[])
y = tf.Variable(np.empty((2, 3), dtype=np.float32))

sess = tf.InteractiveSession()
tf.global_variables_initializer().run()

# y has been initialized with the content of "np.empty"
y.eval()
# x is not initialized, you have to do it yourself later
x.eval()

x此处提供的np.empty仅用于指定其形状和类型,而不用于初始化.

Here np.empty is provided to x only to specify its shape and type, not for initialization.

现在对于tf.concat之类的操作,您实际上并没有(实际上不能)自己管理内存-您无法像某些numpy函数所允许的那样预先分配输出. Tensorflow已经对内存进行了管理,并做了一些巧妙的技巧,例如在检测到输出可以重用输出时重新使用内存块.

Now for operations such as tf.concat, you actually don't have (indeed cannot) manage the memory yourself -- you cannot preallocate the output as some numpy functions allow you to. Tensorflow already manages memory and does smart tricks such as reusing memory block for the output if it detects it can do so.

这篇关于是否有一个等于np.empty的张量流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆