为什么一个Python脚本会引发qt.qpa.plugin错误,而另一个相同的脚本却不会呢?

时间:2019-08-29 23:04:32

标签: python numpy matplotlib pytorch

我在同一PyCharm IDE中运行了两个几乎完全相同的脚本。他们都调用了第三个脚本,该脚本使用matplotlib将Numpy数组输出到PNG。其中一个脚本可以正常工作并输出PNG。另一个脚本引发以下错误:

  

qt.qpa.plugin:即使找到了Qt平台插件“ windows”,也无法在“”中加载。

脚本之间的差异很小-它们的差异仅在于它们各自导入不同的pytorch模型(均为我创建的模型)。这使我认为可能存在某种环境差异,但是它们都是在相同的IDE和Conda环境中启动的。

有人有什么建议吗?

编辑:

这是两个文件的精简版本。我删除的位在字符和空格之间都是相同的。

文件1:

import argparse
from average_meter import AverageMeter
import criteria  # -> NOTE: This is not used, but was not removed in this file
import dataset
from densenet_mapmaker_model import DensenetMapMakerModel  # -> Different model imported
import json
import math
import os
import time
import torch
from torch.autograd import Variable
import torch.nn as nn
from torchvision import transforms
import visualizer

parser = argparse.ArgumentParser(description='Densenet Map Maker Trainer for Steel')

# ...Define args...

##########################################################################################
# These args were defined here, but not in the other file. They are not actually used here, just defined and ignored.
parser.add_argument('--shrinkage_coef', dest='shrinkage_coef', type=int,
                    help='Use a shrinking gaussian loss and multiply its result by this amount.')

parser.add_argument('--multiply', dest='multiply', type=int,
                    help='If 1, in the shrinking gaussian loss, ' +
                         'multiply by 1000 before comparing and then divide the loss by 1000.')

parser.add_argument('--diff_coef', dest='diff_coef', type=int,
                    help='Use the count difference loss and multiply its result by this amount.')

parser.add_argument('--clustering_coef', dest='clustering_coef', type=int,
                    help='Use the clustering loss and multiply its result by this amount.')
##########################################################################################

use_cuda = torch.cuda.is_available()


def main():
    best_mse = 1e6

    version = 1

    args = parser.parse_args()
    # ...set up default arg values...
    args.loss_calc_method = 'DenseNet'  # Defined here, but not in the other file. Not used here and could be removed.

    # ...load dataset lists...

    model = DensenetMapMakerModel()  # -> Note: Different model used
    if use_cuda:
        model = model.cuda()

    # ...Create criteria and optimizer...

    # ...Load weights from last training run...

    for epoch in range(args.start_epoch, args.epochs):
        train(train_list, model, criterion, optimizer, epoch, args)
        mse = validate(val_list, model, criterion, epoch, args)

        # ...Check result and save weights...


def train(...):

    # ...Set up counters and dataset...

    model.train()
    end = time.time()

    # img: torch.Tensor      # Image data
    # location : torch.Tensor. Target annotation locations for the image.
    # image_id : str. Unique ID of image.
    for i, (img, location, image_id) in enumerate(train_loader):

        # ...Run input through model, check result and backpropagate...

        if i % args.print_freq == 0:
            # Note: Print statement has different whitespace formatting from other file...
            print('Epoch: [{0}][{1}/{2}]\t'
                  'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
                  'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
                  'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
                .format(
                epoch, i, len(train_loader), batch_time=batch_time,
                data_time=data_time, loss=losses))


def validate(...) -> float:

    # ...Set up dataset...

    # img: torch.Tensor      # Image data
    # location : torch.Tensor. Target annotation locations for the image.
    # image_id : str. Unique ID of image.
    for i, (img, location, image_id) in enumerate(test_loader):

        # ...Run input through model and check result...

        # Output target and source the first time...
        output_dir = args.output_dir
        if args.output_images == 1 and epoch % 1 == 0 and i == 2:  # -> NOTE: Other file does NOT have additional check i == 2
            visualizer.display_tensor(output, output_dir + "/epoch_" + str(epoch) + "_" + str(i) + "_output")


if __name__ == '__main__':
    main()

文件2:

import argparse
from average_meter import AverageMeter
import dataset
from steel_scanner_model import SteelScanner  # -> Different model imported
import json
import math
import os
import time
import torch
from torch.autograd import Variable
import torch.nn as nn
from torchvision import transforms
import visualizer

parser = argparse.ArgumentParser(description='Densenet Map Maker Trainer for Steel')

# ...Define args...

use_cuda = torch.cuda.is_available()


def main():
    best_mse = 1e6

    version = 1

    args = parser.parse_args()
    # ...set up default arg values...

    # ...load dataset lists...

    model = SteelScanner()  # -> Note: Different model used
    if use_cuda:
        model = model.cuda()

    # ...Create criteria and optimizer...

    # ...Load weights from last training run...

    for epoch in range(args.start_epoch, args.epochs):
        train(train_list, model, criterion, optimizer, epoch, args)
        mse = validate(val_list, model, criterion, epoch, args)

        # ...Check result and save weights...


def train(...):

    # ...Set up counters and dataset...

    model.train()
    end = time.time()

    # img: torch.Tensor      # Image data
    # location : torch.Tensor. Target annotation locations for the image.
    # image_id : str. Unique ID of image.
    for i, (img, location, image_id) in enumerate(train_loader):

        # ...Run input through model, check result and backpropagate...

        if i % args.print_freq == 0:
            # Note: Print statement has different whitespace formatting from other file...
            print('Epoch: [{0}][{1}/{2}]\t'
                  'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t'
                  'Data {data_time.val:.3f} ({data_time.avg:.3f})\t'
                  'Loss {loss.val:.4f} ({loss.avg:.4f})\t'
                  .format(epoch, i, len(train_loader), batch_time=batch_time, data_time=data_time, loss=losses))


def validate(...) -> float:

    # ...Set up dataset...

    # img: torch.Tensor      # Image data
    # location : torch.Tensor. Target annotation locations for the image.
    # image_id : str. Unique ID of image.
    for i, (img, location, image_id) in enumerate(test_loader):

        # ...Run input through model and check result...

        # Output target and source the first time...
        output_dir = args.output_dir
        if args.output_images == 1 and epoch % 1 == 0:  # -> NOTE: Other file has additional check i == 2
            # NOTE: The error occurs inside 'display_tensor'
            visualizer.display_tensor(output, output_dir + "/epoch_" + str(epoch) + "_" + str(i) + "_output")


if __name__ == '__main__':
    main()

从第二个文件调用时,该错误发生在visualizer.display_tensor内部。

0 个答案:

没有答案