Python tf.GradientTape()不能帮助我训练好CNN。它是混乱的。有人能帮我吗?

Python tf.GradientTape()不能帮助我训练好CNN。它是混乱的。有人能帮我吗?,python,machine-learning,keras,conv-neural-network,tensorflow2.0,Python,Machine Learning,Keras,Conv Neural Network,Tensorflow2.0,我不能这样训练我的CNN。但在其他情况下,这种方式是有效的。特别是,损耗是摆动的,如下所示: for i in range(epoch): for j in range(iteration): with tf.GradientTape() as tape: start = j * batch_size end = start + batch_size img_x = train_x[start:end

我不能这样训练我的CNN。但在其他情况下,这种方式是有效的。特别是,损耗是摆动的,如下所示:

for i in range(epoch):
    for j in range(iteration):
        with tf.GradientTape() as tape:
            start = j * batch_size
            end = start + batch_size
            img_x = train_x[start:end]
            img_y = train_y[start:end]
            y_pre = my_model(img_x)
            loss = SCC(img_y, y_pre)
            grads = tape.gradient(loss, my_model.trainable_variables)
            wei=my_model.weights
            classifier_optimizer.apply_gradients(zip(grads, my_model.trainable_variables))
            print('\r' + str(j) + ":" + str(loss))

模型的acc较低。但当我使用model.fit()训练同一个模型时,一切都是正常的。我真的不明白发生了什么,谁能帮我。谢谢*

将所有行移动到
grads=tape.gradient(丢失,我的\u模型。可训练的\u变量)
超出
tape
@Susmit Agrawal的范围谢谢,我已经解决了这个问题。这是因为批量太小。在我增加批量大小后,问题得到了解决。
0:tf.Tensor(2.3027625, shape=(), dtype=float32)
1:tf.Tensor(2.3013003, shape=(), dtype=float32)
2:tf.Tensor(2.3009686, shape=(), dtype=float32)
3:tf.Tensor(2.300927, shape=(), dtype=float32)
4:tf.Tensor(2.2975554, shape=(), dtype=float32)
5:tf.Tensor(2.2977755, shape=(), dtype=float32)
6:tf.Tensor(2.2971885, shape=(), dtype=float32)
7:tf.Tensor(2.3017051, shape=(), dtype=float32)
8:tf.Tensor(2.3027241, shape=(), dtype=float32)
9:tf.Tensor(2.3008144, shape=(), dtype=float32)
10:tf.Tensor(2.2972112, shape=(), dtype=float32)
11:tf.Tensor(2.3008654, shape=(), dtype=float32)