tensorflow2.0 - 如何在 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。
解决方案
推荐阅读
- xml - 如何使用 Google 表格获取播客元信息(例如图像、完整描述)?
- python - Apache Beam 中到 BigQuery 的窗口化 Pub/Sub 消息
- android - ./gradlew 后无法通知项目评估侦听器
- sql-server - 通过存储过程游标/循环从数据流任务 (DTS) 中获取行集
- python - matplotlib。savefig() 将图像保存在错误的文件夹中
- javascript - 无法将功能部署到 Firebase
- html - 如何对齐包含无线电输入的三个 div
- html - 链接到文件时使用不带初始斜线的 href
- r - 如何在 R 中使用分类变量在堆积条形图上放置数据标签?
- kubernetes - 使用 Google Cloud Code ItelliJ 时如何让 Google Kubernetes Engine LoadBalancer Service 接收外部流量?