首页 > 解决方案 > 如何在 Tensorflow 的自定义层中重新排序张量列?

问题描述

numpy我可以用以下代码替换列:

t1 = np.array([[1.,2.],[3.,4.]])
print(t1)

t2 = np.zeros((2,2))

t2[:,0] = t1[:,1]
t2[:,1] = t1[:,0]

print(t2)

如何使用张量在 Tensorflow 的自定义层中实现类似的代码?我试过这个:

import tensorflow as tf


class CustomLayer(tf.keras.layers.Layer):
    def __init__(self, **kwargs):
        super(CustomLayer, self).__init__(**kwargs)
        
    def call(self, inputs):
        m = tf.Variable(lambda: inputs)
        
        m[:,0] = inputs[:,1]
        m[:,1] = inputs[:,0] # TypeError: 'ResourceVariable' object does not support item assignment
        
        #indices = tf.constant([[0,1],[1,1]])
        #updates = tf.constant([inputs[0,0], inputs[1,0]])
        #m.scatter_nd_update(indices, updates) # TypeError: List of Tensors when single Tensor expected
        
        return m 

然后我尝试创建模型:

from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model


input_1 = Input(shape=(2, 2), name='inp')
output = CustomLayer()(input_1)
model = Model(input_1, output)

模型未创建错误。我尝试应用两种方法:像 numpy 切片和 scatter_nd_update。我使用 Tensorflow 2.0、Eager Execution 和 tf.keras。

标签: tensorflow2.0tf.keraskeras-layer

解决方案


推荐阅读