简体   繁体   English

Python 中的并行化

[英]Parallelizing in Python

I've got something I'd like to do in parallel in python.我有一些我想在 python 中并行做的事情。 The following function:以下 function:

def _train_users_locally(self):
        for i in self.users:
            self.users[i].train()

Gets a bunch of instances of the 'user' class to train a pytorch neural net:获取“用户”class 的一组实例来训练 pytorch 神经网络:

def train(self):
        self.current_model.train()
        optim = self.optim(self.current_model.parameters(), lr=self.lr)
        criterion = self.criterion()
        for epoch in range(self.epochs):
            loss_per_epoch = 0
            counter = 0
            for i, data in enumerate(self.dataloader):
                x, y = data
                fx = self.current_model(x.unsqueeze(1))
                loss = criterion(fx, y)
                optim.zero_grad()
                loss.backward(retain_graph=True)
                optim.step()
                loss_per_epoch += loss.item()
                print('\rEpoch {}\tBatch: {:.3f}, Loss: {:.3f}'.format(epoch+1, i, loss.item()), end="")
                counter += 1
            print('\nEpoch {}\t Average Loss: {:.3f}'.format(epoch+1, loss_per_epoch / counter))

Nothing is being output; output 什么都没有; the model assigned to the object is being updated.分配给 object 的 model 正在更新。 I would like each user object to do its training simultaneously, but I can't for the life of me figure out how to do this, as all the examples I've been able to find involve some processing of list elements.我希望每个用户 object 同时进行培训,但我无法终生弄清楚如何做到这一点,因为我能够找到的所有示例都涉及对列表元素的一些处理。

Figured something out, thanks Gautam.想出来了,谢谢高塔姆。

from threading import Thread

def _train_users_locally(self):
        threads = []
        for i in self.users:
            t = Thread(target=self.users[i].train)
            threads.append(t)
        for t in threads:
            t.start()
        for t in threads:
            t.join()

It seems to work as intended;它似乎按预期工作; but I'm unsure if I might be missing something terrible that'll pop up unexpectedly.但我不确定我是否会遗漏一些会意外弹出的可怕东西。

Use the module called "threading"使用名为“线程”的模块

it will run the func.它将运行函数。 simuntainously同时

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

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