第一个索引是None
和批处理索引,
在下面的示例中,批处理大小为2(两行),输入长度为3
In [12]: ar = [[0,1,2],
...: [2,0,3]]
In [13]: mask = tf.greater(ar, 0)
...: non_zero_array = tf.boolean_mask(ar, mask)
In [14]: non_zero_array.eval(session=sess)
Out[14]: array([1, 2, 2, 3], dtype=int32)
我想要输出[[1,2], [2,3]]
代替[1,2,2,3]
(它将是[None,input_length]的形状)
我尝试自己实现mask_zero
功能,因为一旦将mask_zero=True
赋予嵌入层,就无法将其提供给密集层(我将其他张量连接在一起并展平,然后提供给密集层,不接受Flatten
)
下面我得到mask_zero
,它是item_average
的平均嵌入,我想在不使用prior_ids
的情况下获取嵌入之前从0
除去prior_ids
值。
selected = self.item_embedding_layer(prior_ids)
embedding_sum = tf.reduce_sum(selected, axis=1)
non_zero_count = tf.cast(tf.math.count_nonzero(prior_ids, axis=1), tf.float32)
item_average = embedding_sum / tf.expand_dims(non_zero_count, axis=1)
参考方案
这是一个可能的实现,它可以删除具有任意数量维的张量的最后维中的零:
import tensorflow as tf
def remove_zeros(a):
a = tf.convert_to_tensor(a)
# Mask of selected elements
mask = tf.not_equal(a, 0)
# Take the first "row" of mask
row0 = tf.gather_nd(mask, tf.zeros([tf.rank(mask) - 1], dtype=tf.int32))
# Count number of non-zeros on last axis
n = tf.math.count_nonzero(row0)
# Mask elements
a_masked = tf.boolean_mask(a, mask)
# Reshape
result = tf.reshape(a_masked, tf.concat([tf.shape(a)[:-1], [n]], axis=0))
return result
# Test
with tf.Graph().as_default(), tf.Session() as sess:
print(sess.run(remove_zeros([[0, 1, 2],
[2, 0, 3]])))
# [[1 2]
# [2 3]]
print(sess.run(remove_zeros([[[0, 1, 0], [2, 0, 0], [0, 3, 0]],
[[0, 0, 4], [0, 5, 0], [6, 0, 0]]])))
# [[[1]
# [2]
# [3]]
#
# [[4]
# [5]
# [6]]]
Python sqlite3数据库已锁定 - python我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
python-docx应该在空单元格已满时返回空单元格 - python我试图遍历文档中的所有表并从中提取文本。作为中间步骤,我只是尝试将文本打印到控制台。我在类似的帖子中已经看过scanny提供的其他代码,但是由于某种原因,它并没有提供我正在解析的文档的预期输出可以在https://www.ontario.ca/laws/regulation/140300中找到该文档from docx import Document from…
Python:集群作业管理 - python我在具有两个阶段的计算群集(Slurm)上运行python脚本,它们是顺序的。我编写了两个python脚本,一个用于阶段1,另一个用于阶段2。每天早上,我检查所有第1阶段的工作是否都以视觉方式完成。只有这样,我才开始第二阶段。通过在单个python脚本中组合所有阶段和作业管理,是否有一种更优雅/自动化的方法?我如何知道工作是否完成?工作流程类似于以下内容:w…
TensorFlow操作,在官方API中找不到 - python最近,我尝试重复学习Nvidia在GitHub上发布的代码-progressive_growing_of_gans。但是,我发现以下几种基于官方API找不到的操作参考。feed_dict = {} setter = tf.assign(var, tf.placeholder(var.dtype, var.shape, 'new_value'…
Python-Excel导出 - python我有以下代码:import pandas as pd import requests from bs4 import BeautifulSoup res = requests.get("https://www.bankier.pl/gielda/notowania/akcje") soup = BeautifulSoup(res.cont…