简体   繁体   English

Tensorflow 到 PyTorch - model.predict 等效

[英]Tensorflow to PyTorch - model.predict equivalent

  1. I am attempting to retrieve the mean squared error of my training.我正在尝试检索我的训练的均方误差。 within the original code based in TensorFlow, I am moving this code over to PyTorch (for research reasons).在基于 TensorFlow 的原始代码中,我将此代码移至 PyTorch(出于研究原因)。

    the original TensorFlow code:原 TensorFlow 代码:

    print("Calculating threshold")
    x_opt_predictions = model.predict(x_opt)
    print("Calculating MSE on optimization set...")
    mse = np.mean(np.power(x_opt - x_opt_predictions, 2), axis=1)
    print("mean is %.5f" % mse.mean())
    print("min is %.5f" % mse.min())
    print("max is %.5f" % mse.max())
    print("std is %.5f" % mse.std())
    tr = mse.mean() + mse.std()

the training method of pytorch: pytorch的训练方法:

def train(net, x_train, x_opt, BATCH_SIZE, EPOCHS, input_dim):
    outputs = 0
    mse = 0
    optimizer = optim.SGD(net.parameters(), lr=0.001)
    loss_function = nn.MSELoss()
    loss = 0
    for epoch in range(EPOCHS):
        for i in tqdm(range(0, len(x_train), BATCH_SIZE)):
            batch_y = x_opt[i:i + BATCH_SIZE]
            
            net.zero_grad()
            
            outputs = net(batch_y)
            

            loss = loss_function(outputs, batch_y)
            loss.backward()
            optimizer.step()

        print(f"Epoch: {epoch}. Loss: {loss}")
        print("opt", x_opt.size(), "output", outputs.__sizeof__())

    # VVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
    return np.mean(np.power(x_opt - outputs, 2), axis=1)
    # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1. as seen above the line "outputs" is not a numpy array of predictions, and acquiring this equivalent to generate the threshold如上所示,“输出”行不是 numpy 预测数组,并获取此等价物以生成阈值

  2. If there are any other (improved or missing) ways to acquire this value, appreciation in advance.如果有任何其他(改进的或缺失的)方法可以获取此值,请提前欣赏。

The variable output is a pytorch tensor to convert it to numpy all you have to change is change this line of code return np.mean(np.power(x_opt - outputs, 2), axis=1) to this return np.mean(np.power(x_opt - outputs.cpu().data.numpy(), 2), axis=1) That will convert the tensor to a numpy array.变量 output 是一个 pytorch 张量,可以将其转换为 numpy 只需将这行代码更改为return np.mean(np.power(x_opt - outputs.cpu().data.numpy(), 2), axis=1) return np.mean(np.power(x_opt - outputs, 2), axis=1) return np.mean(np.power(x_opt - outputs.cpu().data.numpy(), 2), axis=1)这会将张量转换为 numpy 数组。 If you are not using cuda with your network you do not need the.cpu() part.如果您的网络没有使用 cuda,则不需要 .cpu() 部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM