文章目录
Tensorflow2 更新之后,越来越多的工作要慢慢迁移到新版本中,但是我个人认为 tf 版本之间的兼容性有时候真的很让人无语。
当找不到对应方法或调用时,大部分可以通过 .compat.v1 来解决,这就不说了;
最难受的是,同一个函数,名字完全一致,在 tf1 和 tf2 中调用方法都一样,可是函数内的具体实现却并不同。
如下面 in_top_k :
top_k_op = tf.nn.in_top_k(logits, label_holder, 1)
在两个版本中都是通过 tf.nn.in_top_k 来调用,所以更换版本后,ide 不会提示新版本中调用错误,可是真的执行的时候就会出现:
ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int32: <tf.Tensor
'Placeholder_1:0' shape=(128,) dtype=int32>
TypeError: Input 'predictions' of 'InTopKV2' Op has type int32 that does not match expected type
of float32.
查看原因的话就是,两个位置参数互换了位置,所以要么 compat 到 v1,要么自己改位置参数……或者使用代码升级脚本升级整个代码(不要先手动修改,升级后再看哪里需要手动修改)。
help(tf.nn.in_top_k)
Help on function in_top_k_v2 in module tensorflow.python.ops.nn_ops:
in_top_k_v2(targets, predictions, k, name=None)
Says whether the targets are in the top `K` predictions.
help(tf.compat.v1.nn.in_top_k)
Help on function in_top_k in module tensorflow.python.ops.nn_ops:
in_top_k(predictions, targets, k, name=None)
Says whether the targets are in the top `K` predictions.