【问题标题】:how to calculate accuracy per epoch如何计算每个时期的准确度
【发布时间】:2021-06-08 05:44:39
【问题描述】:

当我运行这行代码时,我正在训练一个模型,同时计算每次迭代的准确性:

  model = train_model(model,criterion,num_epochs=100,learning_rate=1) # Training the mode
                                                                                              

我在这一行得到一个错误:

 epoch_acc = np.sum(np.equal(totalPreds.cpu().numpy(),np.array(totalLabels)))/50000.0 

出现错误

ValueError: 操作数无法与形状 (50000,) (0,) 一起广播

我还通过以下代码更改了这一行:

    epoch_acc = np.sum(np.equal(totalPreds.cpu().numpy(),totalLabels.numpy()))/50000.0

也出现错误

AttributeError: 'numpy.ndarray' 对象没有属性 'numpy'

这是获取每个时期准确度的代码

每个时期的准确度

    tempLabels = tempLabels.numpy()
    _,totalLabels = np.where(tempLabels==1)                        
    epoch_acc = np.sum(np.equal(totalPreds.cpu().numpy(),np.array(totalLabels)))/50000.0      
    train_acc.append(epoch_acc*100) 
    epochTimeEnd = time.time()-epochStartTime
    print('Average epoch loss: {:.6f}'.format(epoch_loss))
    print('Average epoch accuracy: {:.4f} %'.format(epoch_acc*100))
    print('-' * 25)

【问题讨论】:

    标签: python numpy tensorflow


    【解决方案1】:

    这段代码至少有两个问题。

    1. totalLabels 已经是一个 numpy 数组,因此您不需要执行属于 torch 模块的 .numpy(),而不是 numpy 模块。
    2. 您的np.where() 在元组的第二个元素中返回一个截断的索引数组。您可能想要:totalLabels = tempLabels == 1 进行整形。

    尝试用以下代码替换它:

    totalLabels = (tempLabels == 1).numpy().squeeze()
    epoch_acc = np.sum(np.equal(totalPreds.cpu().numpy(), totalLabels))/50000.0  
    ...
    

    【讨论】:

      猜你喜欢
      • 2013-11-20
      • 2020-11-07
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 2017-07-25
      相关资源
      最近更新 更多