深度学习中GPU的使用(python)

参考:https://www.jianshu.com/p/076998e3c3dd

记录设备指派情况

为了获取你的 operations 和 Tensor 被指派到哪个设备上运行, 用 log_device_placement 新建一个 session, 并设置为 True.

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

代码中指定GPU

  • 方法一
with tf.Session as sess:  
    with tf.device('/gpu:1'):  
        ...  

//若想在多块GPU上运行  
with tf.Session as sess:  
    for d in ['/gpu:1','/gpu:2']:  
        with tf.device(d):  
            ...  
  • 方法二
import os
os.environ["CUDA_DEVICES_ORDER"]="PCI_BUS_IS"
os.environ["CUDA_VISIBLE_DEVICES"]=1或"1"
//指定使用第二块GPU

终端中指定GPU

CUDA_VISIBLE_DEVICES=O,1 python3 main.py //程序只能使用GPU:1
CUDA_VISIBLE_DEVICES=&
  • 3
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用GPU运行Python代码需要安装CUDA和cuDNN等GPU相关的库,并且需要安装支持GPUPython库,比如TensorFlow和PyTorch等。 以下是使用TensorFlow和PyTorch在GPU上运行Python代码的示例: 1. 使用TensorFlow在GPU上运行Python代码 ```python import tensorflow as tf # 指定使用GPU physical_devices = tf.config.list_physical_devices('GPU') tf.config.experimental.set_memory_growth(physical_devices[0], True) # 定义模型 model = tf.keras.Sequential([ tf.keras.layers.Dense(32, activation='relu', input_shape=(784,)), tf.keras.layers.Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 加载数据 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # 数据预处理 x_train, x_test = x_train / 255.0, x_test / 255.0 # 训练模型 model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test)) ``` 2. 使用PyTorch在GPU上运行Python代码 ```python import torch # 指定使用GPU device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # 定义模型 model = torch.nn.Sequential( torch.nn.Linear(784, 32), torch.nn.ReLU(), torch.nn.Linear(32, 10), torch.nn.Softmax(dim=1) ) # 将模型放到GPU上 model.to(device) # 定义损失函数和优化器 criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters()) # 加载数据 train_dataset = torchvision.datasets.MNIST(root='./data', train=True, transform=torchvision.transforms.ToTensor(), download=True) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True) # 训练模型 for epoch in range(5): for i, (inputs, labels) in enumerate(train_loader): # 将数据放到GPU上 inputs, labels = inputs.to(device), labels.to(device) # 前向传播 outputs = model(inputs) loss = criterion(outputs, labels) # 反向传播和优化 optimizer.zero_grad() loss.backward() optimizer.step() ``` 需要注意的是,使用GPU运行Python代码需要确保你的电脑上有支持GPU的硬件设备(例如NVIDIA的显卡),并且安装了相应的驱动程序
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值