RuntimeError: An attempt has been made to start a new process before the current process has finishe

问题描述:在运行下面代码时出现RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase.

#评估任意模型的精度
def evaluate_accuracy(net, data_iter):  #@save
    """计算在指定数据集上模型的精度"""
    if isinstance(net, torch.nn.Module):
        net.eval()  # 将模型设置为评估模式
    metric = Accumulator(2)  # 正确预测数、预测总数
    with torch.no_grad():
        for X, y in data_iter:
            metric.add(accuracy(net(X), y), y.numel())
    return metric[0] / metric[1]

class Accumulator:  #@save
    """在n个变量上累加"""
    def __init__(self, n):
        self.data = [0.0] * n

    def add(self, *args):
        self.data = [a + float(b) for a, b in zip(self.data, args)]

    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]


acc = evaluate_accuracy(net, test_iter)

RuntimeError: An attempt has been made to start a new process before the current process has finishe_第1张图片
解决方法:1、通过main方法来执行python文件

def evaluate_accuracy(net, data_iter):  #@save
    """计算在指定数据集上模型的精度"""
    if isinstance(net, torch.nn.Module):
        net.eval()  # 将模型设置为评估模式
    metric = Accumulator(2)  # 正确预测数、预测总数
    with torch.no_grad():
        for X, y in data_iter:
            metric.add(accuracy(net(X), y), y.numel())
    return metric[0] / metric[1]

class Accumulator:  #@save
    """在n个变量上累加"""
    def __init__(self, n):
        self.data = [0.0] * n

    def add(self, *args):
        self.data = [a + float(b) for a, b in zip(self.data, args)]

    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]

def main():
    acc = evaluate_accuracy(net, test_iter)
    print(acc)

if __name__ == '__main__':
    main()

2、 num_workers的默认值置0,单线程
3、 回去检查一下初始化函数,可能把__init__写成了__int__!!!更改之后,就可以成功调用了

你可能感兴趣的:(深度学习,python,pytorch,深度学习)