小编sar*_*nns的帖子

在JupyterLab中显示代码行号

在Jupyter笔记本中,cntrl+ m L切换当前单元格中的代码行号但是如何在JupyterLab中引入代码行号?

提到了在github中打开的类似问题

jupyter-notebook jupyter-lab

11
推荐指数
3
解决办法
6352
查看次数

PyTorch CUDA与Numpy进行算术运算?最快的?

我怀疑使用与GPU支持的Torch和使用以下功能的Numpy进行元素逐次乘法,结果发现Numpy的循环速度比Torch快,但事实并非如此。

我想知道如何使用GPU使用Torch执行常规算术运算。

注意:我在Google Colab笔记本中运行了这些代码段

定义默认张量类型以启用全局GPU标志

torch.set_default_tensor_type(torch.cuda.FloatTensor if 
                              torch.cuda.is_available() else 
                              torch.FloatTensor)
Run Code Online (Sandbox Code Playgroud)

初始化Torch变量

x = torch.Tensor(200, 100)  # Is FloatTensor
y = torch.Tensor(200,100) 
Run Code Online (Sandbox Code Playgroud)

有问题的功能

def mul(d,f):
    g = torch.mul(d,f).cuda()  # I explicitly called cuda() which is not necessary
    return g
Run Code Online (Sandbox Code Playgroud)

当调用上面的函数为 %timeit mul(x,y)

返回值:

最慢的运行比最快的运行时间长10.22倍。这可能意味着正在缓存中间结果。10000次循环,最好为3次:每个循环50.1 µs

现在试用numpy,

使用了与割炬变量相同的值

x_ = x.data.cpu().numpy()
y_ = y.data.cpu().numpy()
Run Code Online (Sandbox Code Playgroud)


def mul_(d,f):
    g = d*f
    return g
Run Code Online (Sandbox Code Playgroud)

%timeit mul_(x_,y_)

退货

最慢的运行时间比最快的运行时间长了12.10倍。这可能意味着正在缓存中间结果。100000次循环,每循环3:7.73 µs最佳

需要一些帮助来了解启用GPU的Torch操作。

gpu numpy python-3.x pytorch

4
推荐指数
1
解决办法
1828
查看次数

创建随机字母数组:Python 3

使用下面的函数可以更方便地创建随机整数数组.

def generate_random_strings(x, i, j):

    return np.random.randint(0, 2, size=[x, i, j]).astype(np.float32)

print (generate_random_strings(3, 5, 4))

[[[0. 0. 0. 0.]
[0. 1. 1. 0.]
[0. 1. 1. 0.]
[0. 0. 0. 1.]
[0. 1. 0. 1.]]

[[0. 1. 0. 0.]
[1. 0. 1. 1.]
[0. 1. 1. 0.]
[1. 0. 1. 0.]
[0. 0. 0. 0.]]

[[0. 0. 1. 0.]
[1. 0. 1. 1.]
[0. 0. 0. 1.]
[0. 1. 0. 0.]
[1. 1. 0. 0.]]]
Run Code Online (Sandbox Code Playgroud)

我尝试为字母(az)而不是整数构建类似的函数,但我找不到numpy或任何其他可用库的任何内置函数.

所以我用3 - for循环如下,

# …
Run Code Online (Sandbox Code Playgroud)

python loops numpy python-3.x

2
推荐指数
1
解决办法
704
查看次数

Pytorch:如何通过python字典中的张量(键)访问张量(值)

我有一个带有张量键和张量值的字典。我想通过键访问值。

from torch import tensor
x = {tensor(0): [tensor(1)], tensor(1): [tensor(0)]}
for i in x.keys():
  print(i, x[i]) 
Run Code Online (Sandbox Code Playgroud)

返回:

tensor(0) [tensor(1)]
tensor(1) [tensor(0)]
Run Code Online (Sandbox Code Playgroud)

但是当我尝试访问值而不遍历键时,

try:
    print(x[tensor(0)])

except:
    print(Exception)
    print(x[0])
Run Code Online (Sandbox Code Playgroud)

抛出异常:

 KeyError                                   Traceback (most recent call last)
 <ipython-input-34-746d28dcd450> in <module>()
  6 try:
  ----> 7   print(x[tensor(0)])
  8 

  KeyError: tensor(0)

  During handling of the above exception, another exception occurred:

  KeyError                                  Traceback (most recent call last)
  <ipython-input-34-746d28dcd450> in <module>()
  9 except:
  10   print(Exception)
  ---> 11   print(x[0])
  12 continue

  KeyError: 0
Run Code Online (Sandbox Code Playgroud)

python python-3.x pytorch

2
推荐指数
1
解决办法
2922
查看次数