【问题标题】:InternalError: Failed copying input tensor from CPU:0 to GPU:0 in order to run _EagerConst: Dst tensor is not initializedInternalError:将输入张量从 CPU:0 复制到 GPU:0 以运行 _EagerConst 失败:Dst 张量未初始化
【发布时间】:2022-11-13 05:09:33
【问题描述】:

我正在运行 10 折的 Tensorflow 交叉验证训练代码。该代码在 for 循环中工作,我必须在每次循环时运行 model.fit。当我第一次运行它时,它运行良好,然后 GPU 内存变满。 这是我的for循环:

acc_per_fold = []
loss_per_fold = []
for train, test in kfold.split(x_train, y_train):
    fold_no = 1
    # Define the model architecture
    model = Sequential()
    model.add(Conv2D(32, kernel_size=(3,3), input_shape = x_train[0].shape, activation = "relu"))
    model.add(MaxPooling2D(2,2))
    model.add(Conv2D(32, kernel_size=(3,3), activation = "relu"))
    model.add(MaxPooling2D(2,2))

    model.add(Flatten())
    model.add(Dense(64, activation = "relu"))
    model.add(Dropout(0.1))
    model.add(Dense(32, activation = "tanh"))
    model.add(Dense(1, activation = "sigmoid"))

    # Compile the model
    model.compile(loss = "binary_crossentropy", 
              optimizer = tf.keras.optimizers.Adam(learning_rate = 0.001), 
              metrics = ["accuracy"])


    # Generate a print
    print('------------------------------------------------------------------------')
    print(f'Training for fold {fold_no} ...')
    # Fit data to model
    history = model.fit(np.array(x_train)[train], np.array(y_train)[train],
              batch_size=32,
              epochs=10,
              verbose=1)

    # Generate generalization metrics
    scores = model.evaluate(np.array(x_train)[test], np.array(y_train)[test], verbose=0)
    print(f"Score for fold {fold_no}: {model.metrics_names[0]} of {scores[0]}; {model.metrics_names[1]} of {scores[1]*100}%")
    acc_per_fold.append(scores[1] * 100)
    loss_per_fold.append(scores[0])

    # Increase fold number
    fold_no += fold_no
    

另外,我搜索并发现使用 numba 库是释放 GPU 内存的一个选项,它可以工作,但是 Jupyter 笔记本中的内核死了,我不得不重置,所以这个解决方案在我的情况下不起作用。

【问题讨论】:

  • 嗨@Neuro_Coder,请尝试减小batch_size 并重试。也请参考 cmets herehere。谢谢!

标签: python tensorflow deep-learning


【解决方案1】:

我很久以前就遇到过这个问题,即使减少了批量大小也没有用。我的 GPU 是 rtx 3060 12 GB RAM,它可以在 Google Collab Pro 上运行 但是,对于这个问题,有一个可行的解决方案。您可以使用 gc 库在每次迭代后清理 GPU

import gc

您可以将此语句放在循环中

gc.collect()

并希望它能通过在每次循环后清理 RAM 来工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2019-07-30
    • 2016-09-15
    • 2020-12-06
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多