tensor

深度学习NLP任务中一些功能性代码块pytoch实现记录

喜你入骨 提交于 2020-01-10 10:58:18
有一些NLP任务中需要实现一些小功能,还是不是很熟练,但是自己写起来又有点难度,故此记录下来。以后每遇到新的就添加上来——不定时更新添加! 1、由predictions和labels计算准确率、正确率、recall和F1 #准确率的计算 correct += (predict == label).sum().item() total += label.size(0) train_acc = correct / total #精确率、recall和F1的计算 for i in range(self.number_of_classes): if i == self.none_label: continue #TP和FP self._true_positives += ((predictions==i)*(gold_labels==i)*mask.bool()).sum() self._false_positives += ((predictions==i)*(gold_labels!=i)*mask.bool()).sum() #TN和FN self._true_negatives += ((predictions!=i)*(gold_labels!=i)*mask.bool()).sum() self._false_negatives += ((predictions!=i)*

torch.bmm() 与 torch.matmul()

空扰寡人 提交于 2020-01-10 08:47:33
torch.bmm() torch.matmul() torch.bmm()强制规定维度和大小相同 torch.matmul()没有强制规定维度和大小,可以用利用广播机制进行不同维度的相乘操作 当进行操作的两个tensor都是3D时,两者等同。 torch.bmm() 官网: https://pytorch.org/docs/stable/torch.html#torch.bmm torch. bmm ( input , mat2 , out=None ) → Tensor torch.bmm()是tensor中的一个相乘操作,类似于矩阵中的A*B。 参数: input,mat2:两个要进行相乘的tensor结构,两者必须是3D维度的,每个维度中的大小是相同的。 output:输出结果 并且相乘的两个矩阵,要满足一定的维度要求:input(p,m, n ) * mat2(p, n ,a) ->output(p,m,a)。这个要求,可以类比于矩阵相乘。前一个矩阵的列等于后面矩阵的行才可以相乘。 例子: import torch x = torch.rand(2,3,6) y = torch.rand(2,6,7) print(torch.bmm(x,y).size()) output: torch.Size([2, 3, 7]) ###########################

python库--tensorflow--数学函数

故事扮演 提交于 2020-01-10 01:48:34
官方API(需翻墙) 中文API 方法 返回值类型 参数 说明 算数运算符 .add() Tensor x, y, name=N 加法(若x,y都为tensor, 数据类型需一致, 以下所有x,y都如此) .subtract() Tensor 同add 减法 .multiply() Tensor 同add 元素级乘法 .scalar_mul() Tensor scalar, x 标量*tensor .div() Tensor 同add 除法(结果dtype同x,y) .divide() Tensor 同add 同Python除法 int8, int16 --> float32 int32, int64 --> float64 .truediv() Tensor 同add 同上 .floordiv() Tensor 同add 结果向下取整, 但结果dtype与输入保持一致 .realdiv() Tensor 同add 貌似仅支持浮点型除法 .truncatediv() Tensor 同add 结果截取整数部分, 貌似仅支持整数除法 .floor_div() Tensor 同add 没发现跟floordiv有什么不同 .truncatemod() Tensor 同add 取余, 跟truncatediv对应的取余 .floormod() Tensor 同add 取余,

Pytorch:将图像tensor数据用Opencv显示

时光毁灭记忆、已成空白 提交于 2020-01-09 13:21:24
* Pytorch:将图像tensor数据用Opencv显示 首先导入相关库: * import torch from torchvision import transforms from PIL import Image import numpy as np import cv2 利用PIL中的Image打开一张图片 image2 = Image . open ( 'pikachu.jpg' ) 这里print看一下image2的图像数据类型,这里可以直接调用image2.show()直接显示: print ( image2 ) < PIL . JpegImagePlugin . JpegImageFile image mode = RGB size = 814x982 at 0x1E988BA74A8 > 将image2转化为tensor数据(为什么转化为tensor,当然是为了方便计算) transform2 = transforms . Compose ( [ transforms . ToTensor ( ) ] ) tensor2 = transform2 ( image2 ) print ( 'tensor2:' , tensor2 ) #打印看一下tensor的数据 print ( tensor2 . dtype ) #torch.float32 print (

torch.ones(),torch.add(),torch.zeros(),torch.squeeze()

独自空忆成欢 提交于 2020-01-07 17:39:02
Tensor与numpy相互转换 import torch x=torch.Tensor(2,3)#生成一个2*3的Tensor张量 将Tensor转换为numpy数组 y=x.numpy() 将numpy数组转换为Tensor import numpy as np z=torch.from_numpy(x) torch.ones() torch.ones(*sizes, out=None) → Tensor 返回一个全为 1 的张量,形状由可变参数 sizes 定义。 参数: sizes (int...) – 整数序列,定义了 输出形状 out (Tensor, optional) – 结果张量 例子: >>> torch.ones(2, 3) 1 1 1 1 1 1 [torch.FloatTensor of size 2x3] >>> torch.ones(5) 1 1 1 1 1 [torch.FloatTensor of size 5] torch.add() torch.add(input, value, out=None) 对输入张量input逐元素加上标量值value,并返回结果到一个新的张量out,即 out=tensor+value。 torch.add(input, value=1, other, out=None) other

torch中的torch.view() torch.permute()和 torch.transpose()以及numpy中的numpy.random.permutation()

回眸只為那壹抹淺笑 提交于 2020-01-06 16:13:22
直入主题: 1.torch.view()是先把所有的Tensor()变成一维数据,然后按需(数据的维度)索取。举个例子 如果参数中出现-1值,那么这个位置的数据就要按照其他位置来判断了。比如上述例子中, 这个-1的值是4,是由其他位置(这里是2)计算得来的,只要保证数据的数量一致就可以。 2.torch.permute() 相比之下permute()的理解要稍微复杂一点。 其作用是把原来Tensor的维数重置,取用的方式稍微复杂一点。举个例子: a是一个1×2×3的Tensor,1是a的第0维,2是a的第1维,3是a的第2维,permute()的作用就是重置这些维数。比如上述例子中就把第0维还是放在第0维,把原来的第2维放到现在的第一维,把原来的第一维放到现在的第二维,也就是我们希望b的维数是1×3×2。 但其选取数据的方式是,每一个最小的单位抽取一个数据出来,得到满足要求的维数。 3.torch.transpose(dim1,dim2) 此函数的参数有两个,表示交换这两维。举个例子: 4.numpy.random.permutation(x) (以下摘自官方文档numpy.org) 1)若x是int数据,则返回range(x)随机排列的数列 2)若x是array数组,那么只打乱第一维数据(以a为例,a原来是3×4的数组,打乱第一维之后结果如下 第二维次序一点没变) 来源:

RuntimeError: Given groups=1, weight of size [64, 3, 7, 7], expected input[3, 1, 224, 224] to have 3 channels, but got 1 channels instead

こ雲淡風輕ζ 提交于 2020-01-06 08:07:57
问题 In the code below: model_ft.eval() test_data, test_target = image_datasets['train'][idx] test_data = test_data.cuda() #test_target = test_target.cuda() test_target = torch.tensor(test_target) test_target = test_target.cuda() test_data.unsqueeze_(1) test_target.unsqueeze_(0) print(test_data.shape) output = model_ft(test_data) I get the following error: Traceback (most recent call last): File "test_loocv.py", line 245, in <module> output = model_ft(test_data) File "/scratch/sjn-p3/anaconda

Numpy change shape from (3, 512, 660, 4) to (3,2048,660,1)

让人想犯罪 __ 提交于 2020-01-06 04:42:08
问题 I am working on tensorflow and I am having some images of cars in an numpy array with shape (3, 512, 660, 4) . In this, 3 corresponds to a car index, 512*660 is an image size and 4 corresponds to the different sides of a car. That is, (1, 512, 660, 1) corresponds to Car1 - front side image, (1, 512, 660, 2) corresponds to Car1 - Left side image and so on. Now, I want to concat all the images of a car into one image ( 2048*660 ). That is, I want to reshape (3, 512, 660, 4) to (3, 2048, 660, 1)

Pytorch闪电战——autograd

六月ゝ 毕业季﹏ 提交于 2020-01-03 19:58:18
基本概念 autograd 是pytorch中所有神经网络的核心 torch.tensor 是程序包的中心类 其存在一个属性: .requires_grad 如果 .requires_grad 为 True ,那么它将开始跟踪对其的所有操作。 在完成计算后,可以调用 .backward() 并自动计算所有梯度 如果要停止tensor跟踪历史记录,可以调用 .detach() 将其从计算历史记录中分离出来,并防止跟踪将来的计算。 Function 对autograd的实作也十分重要 tensor 和 function 相互连接并建立一个非循环图 每一个 tensor 都有一个属性 .grad_fn 。该属性引用 Function 已创建的 Tensor 结合代码理解 代码 import torch x = torch . ones ( 3 , 3 , requires_grad = True ) print ( x ) y = x + 2 z = y * y * 3 out = z . mean ( ) print ( z , out ) out . backward ( ) print ( x . grad ) 结果 参考链接:AUTOGRAD 来源: CSDN 作者: whale998 链接: https://blog.csdn.net/weixin_42265958

Pytorch batch matrix vector outer product

家住魔仙堡 提交于 2020-01-02 15:25:37
问题 I am trying to generate a vector-matrix outer product (tensor) using PyTorch. Assuming the vector v has size p and the matrix M has size qXr , the result of the product should be pXqXr. Example: #size: 2 v = [0, 1] #size: 2X3 M = [[0, 1, 2], [3, 4, 5]] #size: 2X2X3 v*M = [[[0, 0, 0], [0, 0, 0]], [[0, 1, 2], [3, 4, 5]]] For two vectors v1 and v2 , I can use torch.bmm(v1.view(1, -1, 1), v2.view(1, 1, -1)) . This can be easily extended for a batch of vectors. However, I am not able to find a