gll89的个人博客分享 http://blog.sciencenet.cn/u/gll89

博文

Python and Pytorch knowledge

已有 3042 次阅读 2019-7-16 15:58 |个人分类:Python|系统分类:科研笔记

1. 找到数组中最大值的下标:使用np.argmax()

    例如:>>> a = np.arange(6).reshape(2,3) + 10  

                  >>> a = array([[10, 11, 12],

                                           [13, 14, 15]])

                  >>> np.argmax(a)

                  输出为:5

     

    若需要输出具体的维度,可使用 np.unravel_index(a, a.shape)

    例如:>>>ind = np.unravel_index(np.argmax(a, axis=None), a.shape)

                  >>> ind(1, 2)

                 >>> a[ind]

                输出为:15  

2. 找到pytorch中一个数组tensor的下标: 使用torch.argmax()

    但是,pytorch中没有对应的np.unravel_index()。可以根据

      >>>ind = torch.argmax()

       >>>row = ind%a.shape[1]    #注意:由于最大值的下标ind是以列为单位进行得到的,故此处除以a.shape[1]

       >>>column = ind%a.shape[0]

   

3. 将numpy数组写入Excel文件

>>>import pandas as pd
>>>a = np.array([[1, 2], [3, 2], [1, 1], [3, 5], [5,2]])
>>>data = pd.DataFrame(a)
>>>writer = pd.ExcelWriter('A.xlsx')# 写入Excel文件
>>>data.to_excel(writer, 'page_1', float_format='%.5f')# ‘page_1’是写入excel的sheet名
>>>writer.save()
>>>writer.close()

--------------------- 

原文:https://blog.csdn.net/qq_41938858/article/details/87867237 


3. 张量类型之间的转换

 1) CPU和GPU的Tensor之间转换

     从cpu –> gpu,使用

>>>data.cuda()

    若从gpu –> cpu,则使用

>>>data.cpu()

  2) Tensor与Numpy Array之间的转换

      Tensor –> Numpy.ndarray 可以使用

>>>data.numpy()

其中,data的类型为torch.Tensor。 

      Numpy.ndarray –> Tensor 可以使用

>>>torch.from_numpy(data)

其中,data的类型为numpy.ndarray。

  3) Tensor类型之间的相互转换

torch.long() 将tensor投射为long类型 

>>>tensor = torch.Tensor(2, 5)
>>>newtensor = tensor.long()       #tensor为变量名

torch.half()将tensor投射为半精度浮点(16位浮点)类型 

>>>newtensor = tensor.half()

torch.int()将该tensor投射为int类型 

>>>newtensor = tensor.int()

torch.double()将该tensor投射为double类型 

>>>newtensor = tensor.double()

torch.float()将该tensor投射为float类型 

>>>newtensor = tensor.float()

torch.char()将该tensor投射为char类型 

>>>newtensor = tensor.char()

torch.byte()将该tensor投射为byte类型 

>>>newtensor = tensor.byte()

torch.short()将该tensor投射为short类型 

>>>newtensor = tensor.short()

tensor_type.PNG

--------------------- 

原文:https://blog.csdn.net/g11d111/article/details/80896137 


4. 去除一个数组中维度为1的维度: 使用np.squeeze(aa)。  例如:

>>>print (aa.shape)
>>>bb = np.squeeze(aa)
>>>print (bb.shape)

   输出为: (1,2,1)

                    (2)


5. Extract probability after a Pytorch model with the last layer being nn.Linear

   Giver the

  >>>output = self.model(input)
 >>>prob = torch.nn.functional.softmax(output)


6. 



https://blog.sciencenet.cn/blog-1969089-1189805.html

上一篇:Python之list下标访问
下一篇:Pytorch bugs
收藏 IP: 60.191.2.*| 热度|

0

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-4-20 06:04

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部