gpt4 book ai didi

tensorflow - 无法卡住 Tensorflow 工作流程中的 Keras 层

转载 作者:行者123 更新时间:2023-12-03 09:09:29 26 4
gpt4 key购买 nike

我正在尝试卡住 Tensorflow 工作流程中的 Keras 层。这就是我定义图表的方式:

import tensorflow as tf
from keras.layers import Dropout, Dense, Embedding, Flatten
from keras import backend as K
from keras.objectives import binary_crossentropy


import tensorflow as tf
sess = tf.Session()

from keras import backend as K
K.set_session(sess)

labels = tf.placeholder(tf.float32, shape=(None, 1))
user_id_input = tf.placeholder(tf.float32, shape=(None, 1))
item_id_input = tf.placeholder(tf.float32, shape=(None, 1))



max_user_id = all_ratings['user_id'].max()
max_item_id = all_ratings['item_id'].max()

embedding_size = 30
user_embedding = Embedding(output_dim=embedding_size, input_dim=max_user_id+1,
input_length=1, name='user_embedding', trainable=all_trainable)(user_id_input)
item_embedding = Embedding(output_dim=embedding_size, input_dim=max_item_id+1,
input_length=1, name='item_embedding', trainable=all_trainable)(item_id_input)



user_vecs = Flatten()(user_embedding)
item_vecs = Flatten()(item_embedding)


input_vecs = concatenate([user_vecs, item_vecs])

x = Dense(30, activation='relu')(input_vecs)
x1 = Dropout(0.5)(x)
x2 = Dense(30, activation='relu')(x1)
y = Dense(1, activation='sigmoid')(x2)

loss = tf.reduce_mean(binary_crossentropy(labels, y))

train_step = tf.train.AdamOptimizer(0.004).minimize(loss)

然后我只是训练模型:

with sess.as_default():

train_step.run(..)

当可训练标志设置为True时,一切工作正常。然后,当我将其设置为 False 时,它​​不会卡住图层。

我还尝试使用 train_step_freeze = tf.train.AdamOptimizer(0.004).minimize(loss, var_list=[user_embedding]) 来最小化我想要训练的变量,并且我得到:

('Trying to optimize unsupported type ', <tf.Tensor 'Placeholder_33:0' shape=(?, 1) dtype=float32>)

是否可以在 Tensorflow 中使用 Keras 层并卡住它们?

编辑

为了让事情变得清楚,我想使用 Tensorflow 来训练模型,而不是使用 model.fit()。在 Tensorflow 中执行此操作的方法似乎是将 var_list=[] 传递给 minimize() 方法。但我在执行此操作时遇到错误:

('Trying to optimize unsupported type ', <tf.Tensor 'Placeholder_33:0' shape=(?, 1) dtype=float32>)

最佳答案

我终于找到了一种方法来做到这一点。

TensorFlow 不会显式卡住 Keras 模型,而是让您可以选择指定要训练的变量。

在以下示例中,我实例化了 Keras 中的预训练 VGG16 模型,在该模型上定义了几个层,然后卡住该模型(即仅训练 Keras 模型后面的层):

import tensorflow as tf
from tensorflow.python.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.python.keras import backend as K
import numpy as np

inputs = tf.placeholder(dtype=tf.float32, shape=(None, 224, 224, 3))
labels = tf.placeholder(dtype=tf.float32, shape=(None, 1))
model = VGG16(include_top=False, weights='imagenet')

features = model(preprocess_input(inputs))

# Define the further layers

conv = tf.layers.Conv2D(filters=1, kernel_size=(3, 3), strides=(2, 2), activation=tf.nn.relu, use_bias=True)
conv_output = conv(features)
flat = tf.layers.Flatten()
flat_output = flat(conv_output)
dense = tf.layers.Dense(1, activation=tf.nn.tanh)
dense_output = dense(flat_output)

# Define the loss and training ops

loss = tf.losses.mean_squared_error(labels, dense_output)
optimizer = tf.train.AdamOptimizer()

# Specify which variables you want to train in `var_list`
train_op = optimizer.minimize(loss, var_list=[conv.variables, flat.variables, dense.variables])

要使用此方法,您必须为每个层实例化一个对象,因为这将允许您使用layer_name.variables显式访问该层的变量。或者,您可以使用低级 API 并定义自己的 tf.Variable 对象并使用它们创建图层。

您可以轻松验证上述方法是否有效:

sess = K.get_session()
K.set_session(sess)

image = np.random.randint(0, 255, size=(1, 224, 224, 3))

for _ in range(100):

old_features = sess.run(features, feed_dict={inputs: image})
sess.run(train_op, feed_dict={inputs: np.random.randint(0, 255, size=(2, 224, 224, 3)), labels: np.random.randint(0, 10, size=(2, 1))})
new_features = sess.run(features, feed_dict={inputs: image})

print(np.all(old_features == new_features))

这将打印 True 一百次,这意味着模型的权重在运行训练操作时不会改变。

关于tensorflow - 无法卡住 Tensorflow 工作流程中的 Keras 层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44000647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com