【问题标题】:How do I get my script in python to use the GPU on google colab?如何在 python 中获取我的脚本以在 google colab 上使用 GPU?
【发布时间】:2020-10-13 13:04:19
【问题描述】:

我知道如何在运行时类型中激活 GPU,但我习惯于使用自动使用 GPU 的 sklearn 或 XGBoost 进行机器学习。现在我已经制作了自己的机器学习算法,但我不知道如何强制它在 GPU 上进行计算。我需要 GPU 运行时类型的额外 RAM,但我不知道如何从 GPU 的速度中受益...

@jit(target ="cuda")
popsize = 1000
  
File "<ipython-input-82-7cb543a75250>", line 2
    popsize = 1000
          ^
SyntaxError: invalid syntax

【问题讨论】:

  • 请注意,scikit-learn 没有任何类型的 GPU 支持,只有 XGBoost 有。
  • @Dr.Snoopy 是对的。该程序必须使用 TensorFlow 或任何其他支持 GPU 使用的框架编写和执行。

标签: python gpu google-colaboratory


【解决方案1】:

see hereNumba 和 Jit 可以将脚本放在 GPU 上,如下所示:

from numba import jit, cuda 
import numpy as np 
# to measure exec time 
from timeit import default_timer as timer 

# normal function to run on cpu 
def func(a):                                 
    for i in range(10000000): 
        a[i]+= 1    

# function optimized to run on gpu 
@jit(target ="cuda")                         
def func2(a): 
    for i in range(10000000): 
        a[i]+= 1
if __name__=="__main__": 
    n = 10000000                            
    a = np.ones(n, dtype = np.float64) 
    b = np.ones(n, dtype = np.float32) 
    
    start = timer() 
    func(a) 
    print("without GPU:", timer()-start)     
    
    start = timer() 
    func2(a) 
    print("with GPU:", timer()-start) 

还有一个reference link你可以使用

【讨论】:

  • 另外,安装Tensorflow(GPU版本)将保证GPU的使用。
  • 在哪里插入@jit(target = "cuda") 有关系吗?或者只是该行发送到 GPU 之后的任何代码,以及发送到 CPU 之前的任何代码?
  • 是的。因为它是一个 Python 装饰器。
  • 如果这个答案有效。不妨接受它作为解决方案。
  • 它没有,它在@jit(target = "cuda") 之后的行上显示无效语法
猜你喜欢
  • 2022-10-06
  • 2020-12-04
  • 1970-01-01
  • 2020-04-14
  • 2020-08-28
  • 2020-06-03
  • 1970-01-01
  • 2018-12-07
  • 2021-05-15
相关资源
最近更新 更多