Python 将张量流1层迁移到张量流2
我正在试验一段旧代码,它创建了一个非常基本的编码器Python 将张量流1层迁移到张量流2,python,tensorflow,Python,Tensorflow,我正在试验一段旧代码,它创建了一个非常基本的编码器 def make_encoder(data, code_size): x = tf.layers.flatten(data) x = tf.layers.dense(x, 200, tf.nn.relu) x = tf.layers.dense(x, 200, tf.nn.relu) loc = tf.layers.dense(x, code_size) scale = tf.layers.dense(x, code_siz
def make_encoder(data, code_size):
x = tf.layers.flatten(data)
x = tf.layers.dense(x, 200, tf.nn.relu)
x = tf.layers.dense(x, 200, tf.nn.relu)
loc = tf.layers.dense(x, code_size)
scale = tf.layers.dense(x, code_size, tf.nn.softplus)
return tfd.MultivariateNormalDiag(loc, scale)
由于tf.layer.dense等的贬值,我正在尝试将此代码迁移到Tensorflow 2。我不太熟悉tf.keras.layers如何实现上述功能,但我能够实现这一点:
def make_encoder(data, code_size):
model = Sequential()
model.add(Flatten())
model.add(Dense(200, activation='relu'))
model.add(Dense(200, activation='relu'))
x = model(data)
loc = model
scale = model
loc.add(Dense(code_size))
scale.add(Dense(code_size, activation='softplus'))
loc = loc(data)
scale = scale(data)
return tfd.MultivariateNormalDiag(loc, scale)
当我运行这个程序时,我得到的结果与以前非常不同/更差。我肯定我做错了什么/我做得不对。建议使用定义复杂模型,例如多输出模型、有向无环图或具有共享层的模型 您的代码必须如下所示:
def Encoder(data, code_size):
inputs = Input(shape=(data.shape[1:]))
x = Flatten()(inputs)
x = Dense(200, activation='relu')(x)
x = Dense(200, activation='relu')(x)
loc = Dense(code_size)(x)
scale = Dense(code_size, activation='softplus')(x)
return Model(inputs=inputs,ouputs=[loc,scale])
def make_encoder(data, code_size):
loc,scale = Encoder(data, code_size)
return tfd.MultivariateNormalDiag(loc, scale)
产生的错误是
TypeError:error将shape转换为TensorShape:int()参数必须是字符串、类似于对象的字节或数字,而不是“TensorShape”。
当我到达行inputs=Input(shape=(data.shape[1:],)
时,将代码更改为inputs=Input(shape=(data.shape[1:]))
它似乎已经解决了这个问题。但是,我现在在执行行posterior=make\u编码器(data,code\u size=2)
时得到一个关键字参数未理解错误。是因为我仍然在Tensorflow 1而不是Tensorflow 2上运行程序(考虑到程序的其余部分尚未迁移)?我认为它也应该在TF1上运行。从您得到的错误中,可能存在code\u size=2
的问题。因为编码器(数据、代码大小)
的定义没有关键字参数。试一下posterior=make_encoder(数据,2)
我原以为这就是解决办法,但我得到了同样的错误。我再次检查了错误日志,发现我忘了通知您,make\u encoder
在make\u encoder=tf.make\u Template('encoder',make\u encoder)
行中被修改为模板对象。我将编码器函数移动到make_Encoder
中的本地函数,并让它返回loc,scale
,而不是模型,但仍然产生相同的错误。我不熟悉tf。make_template
,但快速浏览文档后,我不确定为什么需要它。我的意思是通过使用在编码器
函数中创建的模型
实现变量共享