Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 很难得到张量的值_Python_Tensorflow_Keras - Fatal编程技术网

Python 很难得到张量的值

Python 很难得到张量的值,python,tensorflow,keras,Python,Tensorflow,Keras,我试图在我的层中的训练过程中研究输入和权重张量的值,我使用了keras教程中关于编写训练循环的代码,并使用了我在另一个线程中找到的辍学层定义,以获得掩码,这有点粗糙,但不是这里的主要问题: from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops class MyDR(tf.keras.layers.Layer): def __init__(self,rate,paren

我试图在我的层中的训练过程中研究输入和权重张量的值,我使用了keras教程中关于编写训练循环的代码,并使用了我在另一个线程中找到的辍学层定义,以获得掩码,这有点粗糙,但不是这里的主要问题:

from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops

class MyDR(tf.keras.layers.Layer):
    def __init__(self,rate,parentLayer,**kwargs):
        super(MyDR, self).__init__(**kwargs)
        
        self.parentLayer = parentLayer
        self.noise_shape = None
        self.rate = rate


    def _get_noise_shape(self,x, noise_shape=None):
        # If noise_shape is none return immediately.
        if noise_shape is None:
            return array_ops.shape(x)
        try:
            # Best effort to figure out the intended shape.
            # If not possible, let the op to handle it.
            # In eager mode exception will show up.
            noise_shape_ = tensor_shape.as_shape(noise_shape)
        except (TypeError, ValueError):
            return noise_shape

        if x.shape.dims is not None and len(x.shape.dims) == len(noise_shape_.dims):
            new_dims = []
            for i, dim in enumerate(x.shape.dims):
                if noise_shape_.dims[i].value is None and dim.value is not None:
                    new_dims.append(dim.value)
                else:
                    new_dims.append(noise_shape_.dims[i].value)
            return tensor_shape.TensorShape(new_dims)

        return noise_shape

    def build(self, input_shape):
        self.noise_shape = input_shape
        print(self.noise_shape)
        super(MyDR,self).build(input_shape)

    @tf.function
    def call(self,input):
        self.noise_shape = self._get_noise_shape(input)
        random_tensor = tf.random.uniform(self.noise_shape, seed=1235, dtype=input.dtype)
        keep_prob = 1 - self.rate
        scale = 1 / keep_prob
        # NOTE: if (1.0 + rate) - 1 is equal to rate, then we want to consider that
        # float to be selected, hence we use a >= comparison.
        self.keep_mask = random_tensor >= self.rate
        #pdb.set_trace()
        #NOTE: here is where I save the binary masks. 
        #the file grows quite big!
        #tf.print(self.keep_mask,output_stream="file://temp/droput_mask.txt")

        ret = input * scale * math_ops.cast(self.keep_mask, input.dtype)
        return ret
以下是我如何实例化我的模型:

dropout = 0.05

inputs = keras.Input(shape=(1,))
newl = layers.Dense(100, activation="relu", name="layer1")
inter = newl(inputs)
inter = MyDR(dropout,parentLayer=newl)(inter)
newl = layers.Dense(100, activation="relu", name="layer2")
inter = newl(inter)
inter = MyDR(dropout,parentLayer=newl)(inter)
newl = layers.Dense(100, activation="relu", name="layer3")
inter = newl(inter)
inter = MyDR(dropout,parentLayer=newl)(inter)
outputs = layers.Dense(1, name="layer4")(inter)

model = keras.Model(inputs, outputs)
我在一个简单的回归问题上尝试了它,效果很好,但我想在训练期间检查张量的值,这就是为什么我在对我的退出层的调用中使用了pdb.set_trace()(这样调试器将在调用中停止,我可以检查我的掩码和输入值),但是如果我尝试,我会得到一个错误:

ipdb> input
<tf.Tensor 'input:0' shape=(20, 100) dtype=float32>
ipdb> keras.backend.eval(input)
*** AttributeError: 'Tensor' object has no attribute '_numpy'
ipdb>输入
ipdb>keras.backend.eval(输入)
***AttributeError:“Tensor”对象没有属性“\u numpy”
我已经读到,它可能来自不启用的急切执行,但由于我使用TF2.0,它在默认情况下是启用的
我不明白为什么仅仅获得价值观就这么难。。。如果有人有办法得到它,那就可以救我一天。

正如我提到的,
tf.keras.Input
只是一个规范层,它保存即将到来的张量的形状信息。所以如果你想得到这个层的输出值,你需要传递一些张量。例如:

model.layers[0](tf.ones(1,1)).numpy() 
array([1.], dtype=float32)

tf.keras.backend.eval(model.layers[0](tf.ones(1,1)))
array([1.], dtype=float32)

因为图层输入不是保存值的东西,它只是一个规范图层。请问,您所说的规范图层是什么意思?
keras.Input
-它是一个规范图层,这意味着它不保存任何要返回的值。你只能得到它的
形状
。谢谢你的回答,但这不是训练循环中已经发生的事情吗?在keras教程中,我们使用tf.data.Dataset.from_tensor_切片来获得x_batch_训练并将其传递给模型,它不包含值吗?这是真的。但是你看,你只需要建立一个模型
model=keras.model(inputs,outputs)
,所有的内部层都只包含即将到来的张量的形状(例如tf.data.)。我明白了,模型首先只用输入形状初始化,但是当我开始训练时,它只停止一次,仍然只有形状,然后在调用方法中再也不会停止。培训的每一步都应该通过呼叫功能吗?对不起,我不明白你的意思。什么意思?它只停止一次,从不停止…?哦,对不起,我是说在调试器pdb上。在层调用方法中注释了set_trace()