if-statement - 使用 K.switch() 进行 keras(张量流后端)条件分配
问题描述
我正在尝试实现类似的东西
if np.max(subgrid) == np.min(subgrid):
middle_middle = cur_subgrid + 1
else:
middle_middle = cur_subgrid
由于条件只能在运行时确定,我使用 Keras 语法如下
middle_middle = K.switch(K.max(subgrid) == K.min(subgrid), lambda: tf.add(cur_subgrid,1), lambda: cur_subgrid)
但我收到了这个错误:
<ipython-input-112-0504ce070e71> in col_loop(j, gray_map, mask_A)
56
57
---> 58 middle_middle = K.switch(K.max(subgrid) == K.min(subgrid), lambda: tf.add(cur_subgrid,1), lambda: cur_subgrid)
59
60 print ('ml',middle_left.shape)
/nfs/isicvlnas01/share/anaconda3/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py in switch(condition, then_expression, else_expression) 2561 The selected tensor. 2562 """
-> 2563 if condition.dtype != tf.bool: 2564 condition = tf.cast(condition, 'bool') 2565 if not callable(then_expression):
AttributeError: 'bool' object has no attribute 'dtype'
middle_middle
, cur_subgrid
, 和 subgrid 都是NxN
张量。任何帮助表示赞赏。
解决方案
我认为问题在于K.max(subgrid) == K.min(subgrid)
您正在创建一个比较两个张量对象的python布尔值,而不是一个包含两个输入张量值比较值的张量流布尔张量。
换句话说,您所写的将被评估为
K.switch(False, lambda: tf.add(cur_subgrid,1), lambda: cur_subgrid)
代替
comparison = ... # Some tensor, that at runtime will contain True if min and max are the same, False otherwise.
K.switch(comparison , lambda: tf.add(cur_subgrid,1), lambda: cur_subgrid)
所以你需要做的是使用keras.backend.equal()而不是==
:
K.switch(K.equal(K.max(subgrid),K.min(subgrid)), lambda: tf.add(cur_subgrid,1), lambda: cur_subgrid)
推荐阅读
- node.js - 导入语法Node js的问题
- mysql - 由于 secure_file_priv,无法在 MySQL Server 8.0 上导入 txt 文件
- apache-kafka - Kafka Streams:如何在申请重新处理之前获得偏移限制以及如何停止它
- javascript - 如何从玉 URL 传递整数数组来表达 js 路由
- c# - 仅为屏幕上的范围获取范围坐标
- linux - 使用 PyQt 获取显示器序列号
- android - 无法解析构造函数'Order(Java.lang.string,Java.lang.string,Java.lang.string,void,void)
- coreml - Core ML 和 Turi Create 使用什么模型?
- javascript - Testcafe - 处理视频
- c# - NopCommerce 源代码部署显示:InvalidOperationException: No database provider has been configured for this DbContext