gpt4 book ai didi

python - 如何逐步增加类次并进行训练?

转载 作者:行者123 更新时间:2023-12-01 09:13:28 24 4
gpt4 key购买 nike

我正在尝试创建一个增量分类器,该分类器将在包含一定数量的历元的 n 个类的数据上进行训练,然后在一定数量的历元中包含 n+m 个类,然后是 n+m+k 等,其中每个连续的类集都包含前一组作为子集。

为了做到这一点,而不必训练模型,保存它,手动编辑图表,重新训练,重复,我只是定义了对整个类集进行分类所需的所有权重,但保留与未见过的类相对应的权重卡住为 0,直到将分类器引入这些类。

我的策略是定义一个占位符,该占位符以 bool 值数组形式输入,定义某些给定的权重集是否可训练。

相关代码如下:

output_train = tf.placeholder(tf.int32, shape = (num_incremental_grps), name         = "output_train")
.
.
.
weights = []
biases = []
for i in range(num_incremental_grps):
W = tf.Variable(tf.zeros([batch_size, classes_per_grp]),
trainable=tf.cond(tf.equal(output_train[i], tf.constant(1)),lambda: tf.constant(True), lambda: tf.constant(False)))
weights.append(W)
b = tf.Variable(tf.zeros([classes_per_grp]), trainable=tf.cond(tf.equal(output_train[i],
tf.constant(1)), lambda:tf.constant(True), lambda: tf.constant(False)))
biases.append(b)

out_weights = tf.stack(weights, axis=1).reshape((batch_size, -1))
out_biases = tf.stack(biases, axis=1).reshape((batch_size, -1))
outputs = tf.identity(tf.matmul(inputs, out_weights) + out_biases, name='values')
.
.
.
# Will change this to an array that progressively updates as classes are added.
output_trainable = np.ones(num_incremental_grps, dtype=bool)
.
.
.
with tf.Session() as sess:
init.run()
for epoch in range(epochs):
for iteration in range(iterations):
X_batch, y_batch = batch.getBatch()
fd={X: X_batch, y: y_batch, training: True, output_train: output_trainable}
_, loss_val = sess.run([training_op, loss], feed_dict=fd)

这将返回错误消息

Using a 'tf.Tensor' as a Python `bool` is not allowed. Use `if t is not None:` instead of 
`if t:` to test if a tensor is defined,and use TensorFlow ops such as tf.cond to execute
subgraphs conditioned on the value of a tensor.

我尝试对此进行修改,例如将初始占位符数据类型设置为 tf.bool 而不是 tf.int32。我还尝试过将张量的一部分输入到权重/偏差中的“可训练”参数中,如下所示

W = tf.Variable(tf.zeros([batch_size, classes_per_grp]), trainable=output_variable[i])

但我收到相同的错误消息。除了尝试一种完全不同的方法来更新可预测类的数量之外,我不确定如何从这里开始。任何帮助将不胜感激。

最佳答案

发生错误的原因是 tf.cond 根据单个 bool 值做出决定 - 非常类似于 if 语句。您在这里想要的是对张量的每个元素做出选择。

您可以使用 tf.where 来解决该问题,但随后您会遇到另一个问题,即 trainable 不是您可以修复的属性运行时,它是变量定义的一部分。如果一个变量将在某个时刻被训练,也许不是在开始时,但肯定是稍后,那么它一定是可训练

我建议采取更简单的路线:将output_train定义为tf.float32的数组

output_train = tf.placeholder(tf.float32, shape=(num_incremental_grps), name="output_train")

然后只需将权重和变量与该向量相乘即可。

W = tf.Variable(...)
W = W * output_train
...

向您希望进行训练的 output_train 提供 1 值,否则提供 0 值。

还要小心地掩盖您的损失,以忽略来自不需要的 channel 的输出,因为尽管它们现在总是输出 0,但这仍然可能会影响您的损失。例如,

logits = ...
logits = tf.matrix_transpose(tf.boolean_mask(
tf.matrix_transpose(logits ),
output_train == 1))
loss = tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=labels)

关于python - 如何逐步增加类次并进行训练?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51453073/

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