python取出tensor里面的数据_PyTorch中Tensor的数据统计示例

张量范数:torch.norm(input, p=2) → float

返回输入张量 input 的 p 范数

举个例子:

>>> import torch

>>> a = torch.full([8], 1)

>>> b = a.view(2, 4)

>>> c = a.view(2, 2, 2)

>>> a.norm(1), b.norm(1), c.norm(1)# 求 1- 范数

(tensor(8.), tensor(8.), tensor(8.))

>>> a.norm(2), b.norm(2), c.norm(2)# 求 2- 范数

(tensor(2.8284), tensor(2.8284), tensor(2.8284))

>>> a.norm(3), b.norm(3), c.norm(3)# 求 ∞- 范数

(tensor(2.), tensor(2.), tensor(2.))

>>> b

tensor([[1., 1., 1., 1.],

[1., 1., 1., 1.]])

>>> b.norm(1, 1) # 在 1 维度上求 1- 范数

tensor([4., 4.])

>>> b.norm(2, 1) # 在 1 维度上求 2- 范数

b.norm(1, 2)

>>> c

tensor([[[1., 1.],

[1., 1.]],

[[1., 1.],

[1., 1.]]])

>>> c.norm(1, 0) # 在 0 维度上求 1- 范数

tensor([[2., 2.],

[2., 2.]])

>>> c.norm(2, 0) # 在 0 维度上求 2- 范数

tensor([[1.4142, 1.4142],

[1.4142, 1.4142]])

只有一个参数时,表示对整个张量求范数,参数表示范数的幂指数值。

有两个参数时,表示在张量某一维度对尺寸中每一部分求范数,第一个参数是范数的幂指数值,第二个参数是选择的维度。

张量统计

最基础的统计方法,比如张量中的最小值、最大值、均值、累加、累积。

举个例子:

>>> a = torch.arange(8).view(2, 4).float()

>>> a

tensor([[0., 1., 2., 3.],

[4., 5., 6., 7.]])

>>> a.min(), a.max(), a.mean(), a.sum(), a.prod() # 分别求最小值、最大值、均值、累加、累积

(tensor(0.), tensor(7.), tensor(3.5000), tensor(28.), tensor(0.))

>>> a.argmin(), a.argmax() # 分别是把张量打平后最小值、最大值的索引

(tensor(0), tensor(7))

>>> a.argmin(1), a.argmax(1) # 不打平求 1 维度中每一部分最小值、最大值的索引

(tensor([0, 0]), tensor([3, 3]))

dim和keepdim

>>> a = torch.randn(5, 10)

>>> a

tensor([[-0.6346, -0.9074, 0.1525, 0.1901, -0.5391, -0.2437, 1.0150, -0.0427,

-1.5336, 0.8542],

[-0.1879, 1.9947, -0.3524, -1.2559, -0.8129, -0.3018, 0.5654, 0.8428,

-0.3517, -0.7787],

[ 0.0686, 0.6166, 0.2632, -0.0947, -0.5592, -1.4041, 1.5565, 1.5616,

-1.3076, -0.1137],

[ 0.5205, -1.5716, -1.1277, 0.8096, -0.2123, -0.0974, 0.7698, 1.1373,

0.5165, 0.5256],

[-0.4162, 0.3170, 0.2368, 1.1695, -0.1960, -0.3285, 0.2420, 1.6468,

0.2646, 0.4573]])

>>> a.max(dim=1)

(tensor([1.0150, 1.9947, 1.5616, 1.1373, 1.6468]), tensor([6, 1, 7, 7, 7]))

>>> a.argmax(dim=1)

tensor([6, 1, 7, 7, 7])

max 添加 dim 后不仅显示了 1 维度中每一部分的最大值,还显示了其索引

>>> a.max(dim=1, keepdim=True)

(tensor([[1.0150],

[1.9947],

[1.5616],

[1.1373],

[1.6468]]), tensor([[6],

[1],

[7],

[7],

[7]]))

>>> a.argmax(dim=1, keepdim=True)

tensor([[6],

[1],

[7],

[7],

[7]])

保持维度一致。添加 keepdim 后,得出的结果维度不改变,原来是二维的数据,得出的结果还是二维。不添加得出的结果就是一维的。

比较操作

torch.topk(input, k, dim=None, largest=True, sorted=True, out=None) -> (Tensor, LongTensor)

沿给定 dim 维度返回输入张量 input 中 k 个最大值。 如果不指定 dim,则默认为 input 的最后一维。 如果为 largest 为 False ,则返回最小的 k 个值。

返回一个元组 (values,indices),其中 indices 是原始输入张量 input 中测元素下标。 如果设定布尔值 sorted 为_True_,将会确保返回的 k 个值被排序。

torch.kthvalue(input, k, dim=None, out=None) -> (Tensor, LongTensor) 取输入张量 input 指定维上第 k 个最小值。如果不指定 dim,则默认为 input 的最后一维。

返回一个元组 (values,indices),其中indices是原始输入张量input中沿dim维的第 k 个最小值下标。

举个例子:

>>> b = torch.randn(5, 10)

>>> b

tensor([[ 0.1863, 0.0160, -1.0657, -1.8984, 2.3274, 0.6534, 1.8126, 1.8666,

0.4830, -0.7800],

[-0.9359, -1.0655, 0.8321, 1.6265, 0.6812, -0.2870, 0.6987, 0.6067,

-0.1318, 0.7819],

[-3.1129, 0.9571, -0.1319, -1.0016, 0.7267, 0.1060, -0.2926, 0.3492,

1.0026, 0.2924],

[-0.7101, -0.8327, 0.5463, 0.3805, -0.8720, -1.6723, 0.0365, 1.5540,

0.1940, 1.4294],

[ 0.4174, -0.9414, -0.0351, -1.6142, -0.7802, -2.3916, -2.4822, 0.7233,

-0.7037, 0.2725]])

>>> b.topk(3, dim=1)

(tensor([[2.3274, 1.8666, 1.8126],

[1.6265, 0.8321, 0.7819],

[1.0026, 0.9571, 0.7267],

[1.5540, 1.4294, 0.5463],

[0.7233, 0.4174, 0.2725]]), tensor([[4, 7, 6],

[3, 2, 9],

[8, 1, 4],

[7, 9, 2],

[7, 0, 9]]))

>>> b.topk(3, dim=1, largest=False)

(tensor([[-1.8984, -1.0657, -0.7800],

[-1.0655, -0.9359, -0.2870],

[-3.1129, -1.0016, -0.2926],

[-1.6723, -0.8720, -0.8327],

[-2.4822, -2.3916, -1.6142]]), tensor([[3, 2, 9],

[1, 0, 5],

[0, 3, 6],

[5, 4, 1],

[6, 5, 3]]))

>>> a.kthvalue(8, dim=1)

(tensor([0.1034, 0.8940, 0.6155, 0.4210, 0.1955]), tensor([1, 2, 6, 4, 7]))

topk 添加 largest=False 就是返回最小,不添加就是返回最大。

kthvalue 返回以从大到小排列的指定位置的数。上面代码中即为返回第 8 小的数。

torch.eq(input, other, out=None) → Tensor

比较元素相等性。第二个参数可为一个数或与第一个参数同类型形状的张量。

torch.equal(tensor1, tensor2) → bool

如果两个张量有相同的形状和元素值,则返回 True ,否则 False。

举个例子:

>>> a = torch.ones(2, 3)

>>> b = torch.randn(2, 3)

>>> torch.eq(a, b)

tensor([[0, 0, 0],

[0, 0, 0]], dtype=torch.uint8)

>>> torch.eq(a, a)

tensor([[1, 1, 1],

[1, 1, 1]], dtype=torch.uint8)

>>> torch.equal(a, a)

True

eq 比较张量中的每个数据,equal 比较整个张量

以上这篇PyTorch中Tensor的数据统计示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持python博客。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是使用PyTorch对Fashion MNIST数据集进行分类的示例代码: 首先,我们需要导入必要的库和模块: ```python import torch import torch.nn as nn import torch.optim as optim import torchvision.datasets as datasets import torchvision.transforms as transforms from torch.utils.data import DataLoader ``` 然后,我们需要下载并加载数据集。Fashion MNIST数据集可以通过以下方式下载: ```python train_data = datasets.FashionMNIST( root="data", train=True, download=True, transform=transforms.ToTensor() ) test_data = datasets.FashionMNIST( root="data", train=False, download=True, transform=transforms.ToTensor() ) ``` 接下来,我们需要定义一个神经网络模型。在这个例子,我们使用了一个简单的卷积神经网络: ```python class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.layer1 = nn.Sequential( nn.Conv2d(1, 32, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2) ) self.layer2 = nn.Sequential( nn.Conv2d(32, 64, kernel_size=3, padding=1), nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2) ) self.fc = nn.Sequential( nn.Linear(7 * 7 * 64, 128), nn.ReLU(), nn.Linear(128, 10) ) def forward(self, x): out = self.layer1(x) out = self.layer2(out) out = out.reshape(out.size(0), -1) out = self.fc(out) return out ``` 然后,我们需要定义损失函数和优化器: ```python model = CNN() criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) ``` 最后,我们可以开始训练模型并评估其性能: ```python train_loader = DataLoader(train_data, batch_size=100, shuffle=True) test_loader = DataLoader(test_data, batch_size=100, shuffle=False) for epoch in range(10): for i, (images, labels) in enumerate(train_loader): optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() if (i + 1) % 100 == 0: print(f"Epoch [{epoch + 1}/{10}], Step [{i + 1}/{len(train_loader)}], Loss: {loss.item():.4f}") with torch.no_grad(): correct = 0 total = 0 for images, labels in test_loader: outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() accuracy = 100 * correct / total print(f"Test Accuracy: {accuracy:.2f}%") ``` 这就是使用PyTorch对Fashion MNIST数据集进行分类的示例代码。希望能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值