python 神经网络实验时的小知识3

1.mac升级torch 1.10

 直接运行pytorch官网给的终端命令:

conda install pytorch==1.10.1 torchvision==0.11.2 torchaudio==0.10.1 -c pytorch

出现以下错误:

PackagesNotFoundError: The following packages are not available from current channels:

针对该问题,具体参考:🏠 (亲测有效)

2.plt.savefig得到空白图片

关于这个bug我一点都不想多说,表示无语。。

原理请看下面这段话:

当使用如下代码保存使用 plt.savefig 保存生成的图片时,结果打开生成的图片却是一片空白。其实产生这个现象的原因很简单:在 plt.show() 后调用了 plt.savefig() ,在 plt.show() 后实际上已经创建了一个新的空白的图片(坐标轴),这时候你再 plt.savefig() 就会保存这个新生成的空白图片。 

所以,你应该知道怎么修改噜~savefig要放在show前面....

3.多进程实现多终端运行多个.py文件

编写python程序时,有时我们需要多个py文件在不同终端内同时运行以提高运行效率,这就涉及到多进程和多线程编程的概念。

多进程

python的多进程编程主要依靠multiprocess模块,我们可以利用multiprocess模块的Process方法创建多个进程来进行并行计算。Process方法接收两个参数, 第一个是target,一般指向函数名,第二个时args,需要向函数传递的参数。对于创建的新进程,调用start()方法即可让其开始。我们可以使用os.getpid()打印出当前进程的名字。

import multiprocessing
import time
import os

def fun3():
    os.system(f'python ../test.py result3 3')
    # 终端运行python ../test.py result3 3
def fun4():
    os.system(f'python ../test.py result4 4')
    # 终端运行python ../test.py result4 4
if __name__ == '__main__':
    p1 = multiprocessing.Process(target=fun3, )
    p2 = multiprocessing.Process(target=fun4, ) # target

    # 启动进程
    p1.start()
    p2.start()

多线程

python 3中的多进程编程主要依靠threading模块。创建新线程与创建新进程的方法非常类似。threading.Thread方法可以接收两个参数, 第一个是target,一般指向函数名,第二个时args,需要向函数传递的参数。对于创建的新线程,调用start()方法即可让其开始。我们还可以使用current_thread().name打印出当前线程的名字。

#coding=utf-8
import time
import threading
import os
 


def fun1():
    os.system('python ./test1.py')
 
def fun2():
    os.system('python ./test2.py')

threads = []
threads.append(threading.Thread(target=test1))   #args为函数接受的参数
threads.append(threading.Thread(target=test2))

print(threads)

if __name__ == '__main__':
    for t in threads:
        t.setDaemon(True) 
        t.start()
    t.join()

代码参考: 🏠

原理参考:🏠

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chococolate

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值