numpy - 访问张量中索引处的元素
问题描述
我正在尝试在 Keras 中构建自定义损失函数。我的模型是一个图像着色 CNN,其想法是根据每个预测像素在我的数据集上先前测量的像素颜色分布中的稀有性来惩罚它。损失函数从分布中获取每个颜色值与像素总数的预先计算的比率。所以我必须获取每个真实像素的系数,必须在当前像素值索引处的比率数组中访问该系数。
我在 NumPy 中构建了“哑”损失版本,它按预期工作。当我尝试使用 tf.map_fn 将其转换为 Tensorflow 时,我看不到实现该功能的方法。我尝试运行会话或评估张量失败。
下面是我的损失函数。
def color_rebalancing_loss(ratios):
def loss(y_true, y_pred):
err = np.absolute(np.subtract(y_true, y_pred))
pixel_weight = tf.map_fn(lambda x: coefficient(x), y_true)
return err * pixel_weight
def coefficient(x):
x = tf.to_int32(x)
x = x.eval(session = tf.Session())
return 1/ratios[x]
return loss
它在这条线上失败了,
x = x.eval(session = tf.Session())
出现此错误:
ValueError: Operation 'loss/activation_1_loss/map/while/TensorArrayReadV3' has been marked as not fetchable.
我在互联网上的搜索没有发现任何潜在的修复,人们建议不要遍历数组,使用内置的 tensorflow 函数,但访问
ratios[x]
在这种情况下是必须的。任何建议将不胜感激。
解决方案
推荐阅读
- c# - ASP.NET Core Web API:xmlns 不是预期的
- bootstrap-4 - 如何设置 th:来自片段的属性
- python - 在 python 3 中记录 imodule 的 UTF-8 编码问题
- spring-boot - 如何配置 springfox 以解包响应类型,例如 Mono 和 Flux,而无需在 @ApiResponse 中显式指定响应类型
- python-3.x - 想不出办法让这段代码正确
- java - 即使将新数组长度设置为旧数组长度,也会出现 ArrayIndexOutOfBoundsException
- sql-server-2017 - 如果有空格,则首字母应为大写
- apache-spark - HDFS上的批量分析
- html - flexbox中的图像全宽引入间距
- java - API 23 本地位置不可用