- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
尽管已经有很多关于这个主题的答案,但在下面的例子中没有看到(摘自 https://gist.github.com/lirnli/c16ef186c75588e705d9864fb816a13c on Variational Recurrent Networks)是哪个输入和输出维度触发了错误。
试图在 torch.cat
中更改尺寸并抑制对 squeeze()
的调用,错误仍然存在,
<ipython-input-51-cdc928891ad7> in generate(self, hidden, temperature)
56 x_sample = x = x_out.div(temperature).exp().multinomial(1).squeeze()
57 x = self.phi_x(x)
---> 58 tc = torch.cat([x,z], dim=1)
59
60 hidden_next = self.rnn(tc,hidden)
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
因此如何塑造
x
中的尺寸和
z
在
tc = torch.cat([x,z], dim=1)
?
import torch
from torch import nn, optim
from torch.autograd import Variable
class VRNNCell(nn.Module):
def __init__(self):
super(VRNNCell,self).__init__()
self.phi_x = nn.Sequential(nn.Embedding(128,64), nn.Linear(64,64), nn.ELU())
self.encoder = nn.Linear(128,64*2) # output hyperparameters
self.phi_z = nn.Sequential(nn.Linear(64,64), nn.ELU())
self.decoder = nn.Linear(128,128) # logits
self.prior = nn.Linear(64,64*2) # output hyperparameters
self.rnn = nn.GRUCell(128,64)
def forward(self, x, hidden):
x = self.phi_x(x)
# 1. h => z
z_prior = self.prior(hidden)
# 2. x + h => z
z_infer = self.encoder(torch.cat([x,hidden], dim=1))
# sampling
z = Variable(torch.randn(x.size(0),64))*z_infer[:,64:].exp()+z_infer[:,:64]
z = self.phi_z(z)
# 3. h + z => x
x_out = self.decoder(torch.cat([hidden, z], dim=1))
# 4. x + z => h
hidden_next = self.rnn(torch.cat([x,z], dim=1),hidden)
return x_out, hidden_next, z_prior, z_infer
def calculate_loss(self, x, hidden):
x_out, hidden_next, z_prior, z_infer = self.forward(x, hidden)
# 1. logistic regression loss
loss1 = nn.functional.cross_entropy(x_out, x)
# 2. KL Divergence between Multivariate Gaussian
mu_infer, log_sigma_infer = z_infer[:,:64], z_infer[:,64:]
mu_prior, log_sigma_prior = z_prior[:,:64], z_prior[:,64:]
loss2 = (2*(log_sigma_infer-log_sigma_prior)).exp() \
+ ((mu_infer-mu_prior)/log_sigma_prior.exp())**2 \
- 2*(log_sigma_infer-log_sigma_prior) - 1
loss2 = 0.5*loss2.sum(dim=1).mean()
return loss1, loss2, hidden_next
def generate(self, hidden=None, temperature=None):
if hidden is None:
hidden=Variable(torch.zeros(1,64))
if temperature is None:
temperature = 0.8
# 1. h => z
z_prior = self.prior(hidden)
# sampling
z = Variable(torch.randn(z_prior.size(0),64))*z_prior[:,64:].exp()+z_prior[:,:64]
z = self.phi_z(z)
# 2. h + z => x
x_out = self.decoder(torch.cat([hidden, z], dim=1))
# sampling
x_sample = x = x_out.div(temperature).exp().multinomial(1).squeeze()
x = self.phi_x(x)
# 3. x + z => h
# hidden_next = self.rnn(torch.cat([x,z], dim=1),hidden)
tc = torch.cat([x,z], dim=1)
hidden_next = self.rnn(tc,hidden)
return x_sample, hidden_next
def generate_text(self, hidden=None,temperature=None, n=100):
res = []
hidden = None
for _ in range(n):
x_sample, hidden = self.generate(hidden,temperature)
res.append(chr(x_sample.data[0]))
return "".join(res)
# Test
net = VRNNCell()
x = Variable(torch.LongTensor([12,13,14]))
hidden = Variable(torch.rand(3,64))
output, hidden_next, z_infer, z_prior = net(x, hidden)
loss1, loss2, _ = net.calculate_loss(x, hidden)
loss1, loss2
hidden = Variable(torch.zeros(1,64))
net.generate_text()
最佳答案
错误
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
IndexError
你正在经历。
# sample input tensors
In [210]: x = torch.arange(4)
In [211]: z = torch.arange(6)
# trying to concatenate along the second dimension
# but the tensors have only one dimension (i.e., `0`).
In [212]: torch.cat([x, z], dim=1)
因此,克服这个问题的一种方法是在串联之前将张量提升到更高的维度,如果这是您需要的。
# promoting tensors to 2D before concatenation
In [216]: torch.cat([x[None, :], z[None, :]], dim=1)
Out[216]: tensor([[0, 1, 2, 3, 0, 1, 2, 3, 4, 5]])
因此,就您而言,您必须分析和了解
x
所需的形状。以便它可以与
z
连接沿着维度 1,然后是
tc
作为输入传递给
self.rnn()
连同
hidden
.
x[None, :]
,
z[None, :]
应该管用。
v0.4.1
.从那时起,PyTorch Python API 发生了很多变化,但代码没有更新。
def generate(self, hidden=None, temperature=None):
if hidden is None:
hidden=Variable(torch.zeros(1,64))
if temperature is None:
temperature = 0.8
# 1. h => z
z_prior = self.prior(hidden)
# sampling
z = Variable(torch.randn(z_prior.size(0),64))*z_prior[:,64:].exp()+z_prior[:,:64]
z = self.phi_z(z)
# 2. h + z => x
x_out = self.decoder(torch.cat([hidden, z], dim=1))
# sampling
x_sample = x = x_out.div(temperature).exp().multinomial(1).squeeze()
x = self.phi_x(x)
# 3. x + z => h
x = x[None, ...] # changed here
xz = torch.cat([x,z], dim=1) # changed here
hidden_next = self.rnn(xz,hidden) # changed here
return x_sample, hidden_next
def generate_text(self, hidden=None,temperature=None, n=100):
res = []
hidden = None
for _ in range(n):
x_sample, hidden = self.generate(hidden,temperature)
res.append(chr(x_sample.data)) # changed here
return "".join(res)
for epoch in range(max_epoch):
batch = next(g)
loss_seq = 0
loss1_seq, loss2_seq = 0, 0
optimizer.zero_grad()
for x in batch:
loss1, loss2, hidden = net.calculate_loss(Variable(x),hidden)
loss1_seq += loss1.data # changed here
loss2_seq += loss2.data # changed here
loss_seq = loss_seq + loss1+loss2
loss_seq.backward()
optimizer.step()
hidden.detach_()
if epoch%100==0:
print('>> epoch {}, loss {:12.4f}, decoder loss {:12.4f}, latent loss {:12.4f}'.format(epoch, loss_seq.data, loss1_seq, loss2_seq)) # changed here
print(net.generate_text())
print()
v1.7.1
上没有任何错误。 .看看评论
# changed here
了解变化。
关于python - IndexError : Dimension out of range - PyTorch dimension expected to be in range of [-1, 0],但得到 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65993928/
我的代码如下所示: unemp n)) stop("wrong embedding dimension") : argument is of length zero Called from: emb
Macports 更新后,我认为更新了 numpy,我收到警告: VisibleDeprecationWarning: boolean index did not match indexed arra
我试图使用 MNIST 数据集实现简单的神经网络,但我不断收到此错误 将 matplotlib.pyplot 导入为 plt import torch from torchvision import
我编写了自己的相机 Activity ,我在FrameLayout中显示照片的实时预览,但是实时图片看起来不自然,有点高,我认为这是因为尺寸FrameLayout 的尺寸与相机的尺寸不匹配。我应该做什
tf.reduce_mean() 函数以 axis 参数中引用的索引的方式对数组元素求和。 在下面的代码中: import tensorflow as tf x = tf.Variable([1, 2
我有一个航类延误数据电子表格,我正在处理一个显示每个机场总延误时间的工作表。我想过滤维度“机场”,即根据每个机场的起飞次数创建机场类别,“小型”、“中型”和“大型”,这是通过计算维度“航类号”计算得出
如何在 3 列 X_train 数据上使用以下代码。错误 "ValueError: query data dimension must match training data dimension" 在
JavaScript:给定一个字符串数组: ['properties.dimensions.length', 'properties.name'] 在散列中使用这些来验证或访问它们(实际上只是想验证
JavaScript:给定一个字符串数组: ['properties.dimensions.length', 'properties.name'] 在散列中使用这些来验证或访问它们(实际上只是想验证
我有以下代码用于整数 vector 的 vector (即整数矩阵..) vector > scores (3, vector(2,0)); cout<
尽管已经有很多关于这个主题的答案,但在下面的例子中没有看到(摘自 https://gist.github.com/lirnli/c16ef186c75588e705d9864fb816a13c on
我有一堆保证有的图片: 最小宽度 = 200 像素 最大宽度 = 250 像素 最小高度 = 150 像素 最大高度 = 175 像素 我想要做的是显示一个由 200 像素 x 150 像素组成的图像
转tensorrt时报错: input: kMAX dimensions in profile 0 are [2,3,128,128] but input has static dimensions
我正在尝试对在 UCI 机器学习数据库中找到的一些文本识别数据进行 k 最近邻预测。 (https://archive.ics.uci.edu/ml/datasets/Letter+Recogniti
如何有效地在更高维空间上追踪等值面 最佳答案 你有一个 N 维的标量成本函数, f(y0, y1, .., yN) ∊ ℝ, y ∊ ℝ 但仅在规则的矩形网格中采样, yk = Ψk + ψk x
我正在尝试根据《Doing Bayesian Data Analysis: A Tutorial with R, JAGS, and Stan (2015)》一书来学习贝叶斯分析。 这本书里有例子。所
LEt x_t = F(x_{t-1}) 是 chaotic regime. 中的一个时间离散动力系统 从初始条件x_0开始,我们可以生成一个时间序列=x_t,其中t =1,2,...,T 表示时间索
当我尝试使用: const {width, height} = Dimensions.get('window'); 在 React Native 组件上,我收到一个以前从未见过的奇怪错误: 找不到变量
关闭。这个问题是opinion-based .它目前不接受答案。 想要改进这个问题? 更新问题,以便 editing this post 可以用事实和引用来回答它. 关闭 2 年前。 Improve
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 这个问题似乎与 help center 中定义的范围内的编程无关。 . 已关闭 9 年前。 Improve
我是一名优秀的程序员,十分优秀!