- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写代码示例以在 PyTorch 中执行简单的线性投影(如 PCA)。除了随着训练的进行损失不会改变之外,一切似乎都还不错。改变学习率不会对此产生影响,这是一个简单的一维问题,因此损失肯定会发生变化。我在这里缺少什么?
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as nnF
class PCArot2D(nn.Module):
"2D PCA rotation, expressed as a gradient-descent problem"
def __init__(self):
super(PCArot2D, self).__init__()
self.theta = nn.Parameter(torch.tensor(np.random.random() * 2 * np.pi))
def getrotation(self):
sintheta = torch.sin(self.theta)
costheta = torch.cos(self.theta)
return torch.tensor([[costheta, -sintheta], [sintheta, costheta]], requires_grad=True, dtype=torch.double)
def forward(self, x):
xmeans = torch.mean(x, dim=1, keepdim=True)
rot = self.getrotation()
return torch.mm(rot, x - xmeans)
def covariance(y):
"Calculates the covariance matrix of its input (as torch variables)"
ymeans = torch.mean(y, dim=1, keepdim=True)
ycentred = y - ymeans
return torch.mm(ycentred, ycentred.T) / ycentred.shape[1]
net = PCArot2D()
example2 = torch.tensor(np.random.randn(2, 33))
# define a loss function and an optimiser
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.1)
# train the network
num_epochs = 1000
for epoch in range(num_epochs):
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(torch.DoubleTensor(example2))
# the covariance between output channels is the measure that we wish to minimise
covariance = (outputs[0, :] * outputs[1, :]).mean()
loss = criterion(covariance, torch.tensor(0, dtype=torch.double))
loss.backward()
optimizer.step()
running_loss = loss.item()
if ((epoch & (epoch - 1)) == 0) or epoch==(num_epochs-1): # don't print on all epochs
# print statistics
print('[%d] loss: %.8f' %
(epoch, running_loss))
print('Finished Training')
输出:
[0] loss: 0.00629047
[1] loss: 0.00629047
[2] loss: 0.00629047
[4] loss: 0.00629047
[8] loss: 0.00629047
etc
最佳答案
看来问题出在您的 getrotation
函数中。当从其他张量创建一个新张量时,它不再是反向概率:
def getrotation(self):
sintheta = torch.sin(self.theta)
costheta = torch.cos(self.theta)
return torch.tensor([[costheta, -sintheta], [sintheta, costheta]], requires_grad=True, dtype=torch.double)
所以你需要找到一些其他的方法来构造你的返回张量。
这是一个似乎可以使用 torch.cat
的建议:
def getrotation(self):
sintheta = torch.sin(self.theta)
costheta = torch.cos(self.theta)
#return torch.tensor([[costheta, -sintheta], [sintheta, costheta]], requires_grad=True, dtype=torch.double)
A = torch.cat([costheta.unsqueeze(0), -sintheta.unsqueeze(0)], dim=0)
B = torch.cat([sintheta.unsqueeze(0), costheta.unsqueeze(0)], dim=0)
return torch.cat([A.unsqueeze(0), B.unsqueeze(0)], dim=0).double()
实现此更改后,损失发生变化:
[0] loss: 0.00765365
[1] loss: 0.00764726
[2] loss: 0.00764023
[4] loss: 0.00762607
[8] loss: 0.00759777
[16] loss: 0.00754148
[32] loss: 0.00742997
[64] loss: 0.00721117
[128] loss: 0.00679025
[256] loss: 0.00601233
[512] loss: 0.00469085
[999] loss: 0.00288501
Finished Training
希望对您有所帮助!
def getrotation(self):
sintheta = torch.sin(net.theta).double().unsqueeze(0)
costheta = torch.cos(net.theta).double().unsqueeze(0)
return torch.cat([costheta, -sintheta, sintheta, costheta]).reshape((2,2))
关于PyTorch:在这个简单的例子中,为什么损失不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59103555/
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 这个问题似乎与 help center 中定义的范围内的编程无关。 . 已关闭 3 年前。 此帖子于去年编辑
据我所知,在使用 GPU 训练和验证模型时,GPU 内存主要用于加载数据,向前和向后。据我所知,我认为 GPU 内存使用应该相同 1) 训练前,2) 训练后,3) 验证前,4) 验证后。但在我的例子中
我正在尝试在 PyTorch 中将两个复数矩阵相乘,看起来 the torch.matmul functions is not added yet to PyTorch library for com
我正在尝试定义二分类问题的损失函数。但是,目标标签不是硬标签0,1,而是0~1之间的一个 float 。 Pytorch 中的 torch.nn.CrossEntropy 不支持软标签,所以我想自己写
我正在尝试让 PyTorch 与 DataLoader 一起工作,据说这是处理小批量的最简单方法,在某些情况下这是获得最佳性能所必需的。 DataLoader 需要一个数据集作为输入。 大多数关于 D
Pytorch Dataloader 的迭代顺序是否保证相同(在温和条件下)? 例如: dataloader = DataLoader(my_dataset, batch_size=4,
PyTorch 的负对数似然损失,nn.NLLLoss定义为: 因此,如果以单批处理的标准重量计算损失,则损失的公式始终为: -1 * (prediction of model for correct
在PyTorch中,new_ones()与ones()有什么区别。例如, x2.new_ones(3,2, dtype=torch.double) 与 torch.ones(3,2, dtype=to
假设我有一个矩阵 src带形状(5, 3)和一个 bool 矩阵 adj带形状(5, 5)如下, src = tensor([[ 0, 1, 2], [ 3, 4,
我想知道如果不在第 4 行中使用“for”循环,下面的代码是否有更有效的替代方案? import torch n, d = 37700, 7842 k = 4 sample = torch.cat([
我有三个简单的问题。 如果我的自定义损失函数不可微会发生什么? pytorch 会通过错误还是做其他事情? 如果我在我的自定义函数中声明了一个损失变量来表示模型的最终损失,我应该放 requires_
我想知道 PyTorch Parameter 和 Tensor 的区别? 现有answer适用于使用变量的旧 PyTorch? 最佳答案 这就是 Parameter 的全部想法。类(附加)在单个图像中
给定以下张量(这是网络的结果 [注意 grad_fn]): tensor([121., 241., 125., 1., 108., 238., 125., 121., 13., 117., 12
什么是__constants__在 pytorch class Linear(Module):定义于 https://pytorch.org/docs/stable/_modules/torch/nn
我在哪里可以找到pytorch函数conv2d的源代码? 它应该在 torch.nn.functional 中,但我只找到了 _add_docstr 行, 如果我搜索conv2d。我在这里看了: ht
如 documentation 中所述在 PyTorch 中,Conv2d 层使用默认膨胀为 1。这是否意味着如果我想创建一个简单的 conv2d 层,我必须编写 nn.conv2d(in_chann
我阅读了 Pytorch 的源代码,发现它没有实现 convolution_backward 很奇怪。函数,唯一的 convolution_backward_overrideable 函数是直接引发错
我对编码真的很陌生,现在我正在尝试将我的标签变成一种热门编码。我已经完成将 np.array 传输到张量,如下所示 tensor([4., 4., 4., 4., 4., 4., 4., 4., 4.
我正在尝试实现 text classification model使用CNN。据我所知,对于文本数据,我们应该使用一维卷积。我在 pytorch 中看到了一个使用 Conv2d 的示例,但我想知道如何
我有一个多标签分类问题,我正试图用 Pytorch 中的 CNN 解决这个问题。我有 80,000 个训练示例和 7900 个类;每个示例可以同时属于多个类,每个示例的平均类数为 130。 问题是我的
我是一名优秀的程序员,十分优秀!