- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用这个代码
def train():
model.train()
total_loss, total_accuracy = 0, 0
# empty list to save model predictions
total_preds=[]
# iterate over batches
for step,batch in enumerate(train_dataloader):
# progress update after every 50 batches.
if step % 50 == 0 and not step == 0:
print(' Batch {:>5,} of {:>5,}.'.format(step, len(train_dataloader)))
# push the batch to gpu
#batch = [r for r in batch]
sent_id, mask, labels = batch['input_ids'],batch['attention_mask'],batch['labels']
print(6)
print(sent_id)
print(mask)
print(labels)
print(batch['input_ids'].shape)
print(batch['attention_mask'].shape)
print(batch['labels'].shape)
# clear previously calculated gradients
model.zero_grad()
print(7)
# get model predictions for the current batch
preds = model(sent_id, mask)
print(8)
print(len(preds))
print(len(labels))
print(preds.size())
preds =torch.argmax(preds, dim=1)
preds =torch.argmax(preds, dim=1)
print(preds)
print(labels)
# compute the loss between actual and predicted values
loss = loss_fn(preds, labels)
print(9)
# add on to the total loss
total_loss = total_loss + loss.item()
print(10)
# backward pass to calculate the gradients
loss.backward()
# clip the the gradients to 1.0. It helps in preventing the exploding gradient problem
# clip the the gradients to 1.0. It helps in preventing the exploding gradient problem
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
# update parameters
optimizer.step()
# model predictions are stored on GPU. So, push it to CPU
preds=preds.numpy()
# append the model predictions
total_preds.append(preds)
# compute the training loss of the epoch
avg_loss = total_loss / len(train_dataloader)
# predictions are in the form of (no. of batches, size of batch, no. of classes).
# reshape the predictions in form of (number of samples, no. of classes)
total_preds = np.concatenate(total_preds, axis=0)
#returns the loss and predictions
return avg_loss, total_preds
import torch.nn as nn
loss_fn=nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.00001)
我在计算损失时出错了普雷兹张量([5, 1, 1, 1, 0, 2, 1, 4, 2, 3, 0, 2, 0, 1, 0, 3, 5, 3, 1, 2, 0, 2, 2, 1 ,0, 1, 4, 0, 5, 5, 4, 5, 0, 2, 0, 1, 4, 0, 0, 3, 5, 1, 1, 1, 4, 4, 4, 1,2, 1, 3, 3, 2, 1, 0, 2, 0, 4, 4, 4, 3, 2, 0, 5])
标签张量([0, 0, 1, 2, 3, 0, 0, 0, 0, 1, 1, 0, 0, 0, 4, 0, 0, 2, 1, 0, 0, 0, 0, 0 ,1, 0, 0, 1, 1, 2, 1, 3, 2, 0, 3, 4, 0, 1, 0, 0, 0, 0, 0, 0, 5, 0, 0, 3,0, 0, 1, 0, 0, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 0])我用过它们损失=loss_fn(preds,标签)错误:
in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction, label_smoothing)
2844 if size_average is not None or reduce is not None:
2845 reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2846 return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index, label_smoothing)
2847
2848
RuntimeError: Expected floating point type for target with class probabilities, got Long
最佳答案
RuntimeError: Expected floating point type for target with classprobabilities, got Long
错误非常明显。您需要将目标张量的数据类型转换为 float 。这与您使用的损失函数有关。既然你选择了 CE 损失,你最终会得到概率。而这些概率自然都是 float 。这意味着您的目标也应该是 float 的。例如,您可能有一个目标张量 a= [1, 0, 0, 1] 您需要将其转换为 [1.0 , 0.0 , 0.0 , 1.0]
您可以使用下表来检查所有类型。
╔══════════════════════════╦═══════════════════════════════╦════════════════════╦═════════════════════════╗
║ Data type ║ dtype ║ CPU tensor ║ GPU tensor ║
╠══════════════════════════╬═══════════════════════════════╬════════════════════╬═════════════════════════╣
║ 32-bit floating point ║ torch.float32 or torch.float ║ torch.FloatTensor ║ torch.cuda.FloatTensor ║
║ 64-bit floating point ║ torch.float64 or torch.double ║ torch.DoubleTensor ║ torch.cuda.DoubleTensor ║
║ 16-bit floating point ║ torch.float16 or torch.half ║ torch.HalfTensor ║ torch.cuda.HalfTensor ║
║ 8-bit integer (unsigned) ║ torch.uint8 ║ torch.ByteTensor ║ torch.cuda.ByteTensor ║
║ 8-bit integer (signed) ║ torch.int8 ║ torch.CharTensor ║ torch.cuda.CharTensor ║
║ 16-bit integer (signed) ║ torch.int16 or torch.short ║ torch.ShortTensor ║ torch.cuda.ShortTensor ║
║ 32-bit integer (signed) ║ torch.int32 or torch.int ║ torch.IntTensor ║ torch.cuda.IntTensor ║
║ 64-bit integer (signed) ║ torch.int64 or torch.long ║ torch.LongTensor ║ torch.cuda.LongTensor ║
║ Boolean ║ torch.bool ║ torch.BoolTensor ║ torch.cuda.BoolTensor ║
╚══════════════════════════╩═══════════════════════════════╩════════════════════╩═════════════════════════╝
要将张量转换为另一种数据类型,您可以使用类似的东西
sample_tensor=sample_tensor.type(torch.FloatTensor)
或
sample_tensor=sample_tensor.to(torch.float )
(我不确定是否需要重新分配张量)
关于python - 在输出和目标标签之间使用 nn.Cross entropy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70267810/
In [15]: a = np.array([0.5, 0.5, 0, 0, 0]) In [16]: b = np.array([1, 0, 0, 0, 0]) In [17]: entropy(a
我有一个关于熵解释的问题。对于我数据集中的每个人,我都有一个 17 个字符(年)长的字符串/序列。我特别感兴趣的是在这个观察期内发生了多少变化。 我正在考虑使用 R 的 TraMineR 包为此计算序
我遇到了一个问题,即通过 SSL 使用 java 时速度很慢。解决办法是添加 -Djava.security.egd=file:/dev/./urandom在命令行中运行 java。由于我有多个 JV
我看到在很多地方(包括堆栈)都推荐了这种技术,我无法忘记这会减少熵!毕竟,您正在再次散列一些已经散列并且有碰撞机会的东西。碰撞机会超过碰撞机会会不会导致更多的碰撞机会?经过研究,似乎我错了,但为什么呢
我有一个嵌入式系统。我希望它在开机或以其他方式重置时做的是生成一个唯一的 ID,以便在不同的重新启动时以很高的概率生成一个不同的唯一 ID。 它无法访问实时时钟,但可以访问 ADC 和 UART。我想
我使用这个代码 训练模型的函数 def train(): model.train() total_loss, total_accuracy = 0, 0 # empty list
我正在阅读这本书 ( NLTK ) 并且令人困惑。 熵 是 defined as : Entropy is the sum of the probability of each label times
我遇到了一个问题,即通过 SSL 使用 java 时速度很慢。解决方法是添加 -Djava.security.egd=file:/dev/./urandom在命令行中使用 java。由于我有多个 JV
我在 Ted Talk 链接中看到了 Alex Wissner-gross 和他的智能行为理论 Here .我试图阅读链接的学术论文 Here ,这与他的演讲有关,但我对数学和物理学的理解不够,无法真
我对 BQ 的人有一个建议:我认为如果有一个内置函数可以返回列的熵,那将非常有用。一列离散类别或值相对容易。想法?这是否已经存在,但我没有找到它? 最佳答案 简单的解决方案如下 - 它计算列中不同值的
反熵协议(protocol)是八卦协议(protocol)的一种形式。 http://en.wikipedia.org/wiki/Gossip_protocol 。我想知道是否有人可以解释一下这里词熵
如果我使用 Matlab entropy() 函数估计标准正态随机变量向量的熵,我得到的答案在 4 左右,而 actual entropy应该是 0.5 * log(2*pi*e*sigma^2) 大
我用这个生成随机字符串: $characters = '0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm'; $cl =
我正在尝试使用 scipy.stats.entropy 来估计两个分布之间的 Kullback–Leibler (KL) 散度。更具体地说,我想使用 KL 作为衡量标准来确定两个分布的一致性。 但是,
我很难理解 JPEG 文件格式的 ITU-T T.81 规范。希望这里的其他人已经尝试解析 JPEG 文件和/或了解此文件格式的详细信息。 规范表明 ECS0 段在 SOS 段之后开始,但我无法在规范
我实现了一个简单的神经网络。它适用于“sigmoid + 交叉熵”、“sigmoid + 二次成本”和“tanh + 二次成本”,但不适用于“tanh + 交叉熵”(不比随机猜测好)。谁能帮我弄清楚为
我在 Linux Ubuntu 上运行的 apache 服务器有问题。出于某种原因,我在日志文件中有以下警告:AH01990:PRNG 仍然包含不足的熵!。有时我可以访问该网站,但大多数时候我会收到以
我正在使用 Keras 并尝试从上下文中预测单词,例如来自一句话“我不得不说食物很美味!”我希望得到这样的东西: [say the ? was tasty] -> food, meals, spagh
我的图像有一个非白色区域(例如段落但不处理 OCR)。这些区域之间的空间有些规则,观看图像的人将能够看到这些区域之间有空白。 我打算做的是找到所有区域的顶角和底角,从底角开始到下一个区域的顶角,取每条
我希望通过使用 rpy2 调用 R 的 RTransferEntropy 包来计算 JupyterLab 笔记本中的传输熵,但这样做时遇到问题。 我正在使用 Anaconda 和 Python 3.7
我是一名优秀的程序员,十分优秀!