从tf1到tf2的几个函数转换

hi各位大佬好,我是菜鸟小明哥。在写代码中tf1的代码很多都不能直接转为tf2,需要替换为同样功能的函数,因此本篇暂且统计遇到的几个及使用方法,以备后用。

For Recommendation in Deep learning QQ Group 277356808

For deep learning QQ Second Group 629530787

I'm here waiting for you

不接受这个网页的私聊/私信!!!
欢迎关注微信视频号、快手:小明哥直播间
1-dropout这个已经提及不再赘述

2-全连接dense/MLP也已论述

3-卷积conv如下:1d示例,

提起卷积肯定要说起输入数据的格式,有NCW和NWC两种格式(旧的4个字母的已经废弃),其实就是tf和torch的区别,分别为:就是首字母呗。

NWC:[batch, in_width, in_channels]
NCW:[batch, in_channels, in_width]
tf1中tf.nn.conv1d
conv1d(value=None, filters=None, stride=None, padding=None, use_cudnn_on_gpu=None, data_fo
rmat=None, name=None, input=None, dilations=None)
    Computes a 1-D convolution given 3-D input and filter tensors. (deprecated argument va
lues) (deprecated argument values)
tf1中tf.layers.conv1d
conv1d(inputs, filters, kernel_size, strides=1, padding='valid', data_format='channels_last', dilation_rate=1, activation=None, use_bias=True, kernel_initializer=None, bias_initializer=<tensorflow.python.ops.init_ops.Zeros object at 0x7fd5cbcc3650>, kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, trainable=True, name=None, reuse=None)

tf2
class Conv1D(Conv)
 |  Conv1D(filters, kernel_size, strides=1, padding='valid', data_format='channels_last', dilation_rate=1, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs)

从上面的对比中发现tf1中第一个的缺少kernel_size,下面尝试计算下:举例如下

发现第一个需要指定padding的模式,否则出错。

后两个的out shape 是一样的,但在tf1环境下报错,真是够了,tf2下无错。

inputs=tf.random.normal((4,30,18))
>>> filter=16
>>> kernel_size=1

tf1中
out1=tf.layers.conv1d(inputs,filter,kernel_size)
/tensor_shape.py", line 193, in __init__
    self._value = int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'type'
>>> conv=tf.compat.v2.keras.layers.Conv1D(filter,kernel_size)
>>> out2=conv(inputs)
    self._value = int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'type'


tf2中
>>> out1=tf.compat.v1.layers.conv1d(inputs,filter,kernel_size)
>>> conv=tf.compat.v2.keras.layers.Conv1D(filter,kernel_size)
>>> out2=conv(inputs)
>>> out1.shape
TensorShape([4, 30, 16])
>>> out2.shape
TensorShape([4, 30, 16])

愿我们终有重逢之时,而你还记得我们曾经讨论的话题。

4-数学计算,这种加上math即可

>>> tf.log
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'log'

>>> tf.math.log(2.78)
<tf.Tensor: shape=(), dtype=float32, numpy=1.0224509>

猜你喜欢

转载自blog.csdn.net/SPESEG/article/details/121769000
tf2