标签: pytorch

类型错误:“DiscreteFactor”对象不可下标

我有一个要执行的贝叶斯算法程序,我使用的是 python 3

import numpy as np
import csv
import pandas as pd
from pgmpy.models import BayesianModel
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination


heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)

print('Few examples from the dataset are given below')
print(heartDisease.head())

model = BayesianModel([('age','trestbps'),('age','fbs'),('sex','trestbps'),('exang','trestbps'),('trestbps','heartdisease'),('fbs','heartdisease'),('heartdisease','restecg'),('heartdisease','thalach'),('heartdisease','chol')])

print('\nLearning CPD using Maximum likelihood estimators')
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)

print('\n Inferencing with Bayesian Network:')
HeartDisease_infer = VariableElimination(model)

print('\n 1. Probability of HeartDisease given Age=28')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
print(q['heartdisease'])

print('\n 2. Probability of HeartDisease given cholesterol=100')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'chol':100})
print(q['heartdisease'])
Run Code Online (Sandbox Code Playgroud)

当我运行贝叶斯网络程序时收到的错误是:

TypeError                                 Traceback (most …
Run Code Online (Sandbox Code Playgroud)

python bayesian-networks pandas pytorch pgmpy

1
推荐指数
1
解决办法
2504
查看次数

即使在loss.backward()之后,output.grad也没有

我很困惑...

我的模型输出: tensor([[0.0000,0.1537],...],grad_fn=<ReluBackward0>)

If I use print(output.grad) it gives me None but even after gradient computation with loss.backward() I get the same result, which again is None...

Even with with torch.set_grad_enabled(True): added, still the same.

I've tried now with multiple model variants, always the same.

I was achieving good result with my model there seemed no problem, now I see this and I'm not sure any more if there not might be a major flaw I didn't recognized so …

python machine-learning pytorch

1
推荐指数
1
解决办法
6413
查看次数

Pytorch - 在 GPU 上训练时,在设备 1 上的副本 1 中捕获 StopIteration 错误

我正在尝试在 git 链接中使用的 train2012 数据上训练 BertPunc 模型: https: //github.com/nkrnrnk/BertPunc。在启用 4 个 GPU 的服务器上运行时,出现以下错误:

StopIteration: Caught StopIteration in replica 1 on device 1.
Original Traceback (most recent call last):
  File "/home/stenoaimladmin/.local/lib/python3.8/site-packages/torch/nn/parallel/parallel_apply.py", line 61, in _worker
    output = module(*input, **kwargs)
  File "/home/stenoaimladmin/.local/lib/python3.8/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/stenoaimladmin/notebooks/model_BertPunc.py", line 16, in forward
    x = self.bert(x)
  File "/home/stenoaimladmin/.local/lib/python3.8/site-packages/torch/nn/modules/module.py", line 727, in _call_impl
    result = self.forward(*input, **kwargs)
  File "/home/stenoaimladmin/anaconda3/lib/python3.8/site-packages/pytorch_pretrained_bert/modeling.py", line 861, in forward
    sequence_output, _ = self.bert(input_ids, token_type_ids, attention_mask, …
Run Code Online (Sandbox Code Playgroud)

python-3.x pytorch bert-language-model

1
推荐指数
1
解决办法
4837
查看次数

如何将 Pytorch 模型直接保存在 s3 Bucket 中?

标题说明了一切 - 我想将 pytorch 模型保存在 s3 存储桶中。我尝试的是以下内容:

import boto3

s3 = boto3.client('s3')
saved_model = model.to_json()
output_model_file = output_folder + "pytorch_model.json"
s3.put_object(Bucket="power-plant-embeddings", Key=output_model_file, Body=saved_model)
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用,因为.to_json()仅适用于张量流模型。有谁知道如何在pytorch中做到这一点?

python amazon-s3 boto3 pytorch

1
推荐指数
1
解决办法
7978
查看次数

Keras 和 Pytorch 具有相同的权重、实现但结果不同

我有一个编码器和一个解码器模型(monodepth2)。我尝试使用将它们从 Pytorch 转换为 Keras Onnx2Keras,但是:

  • 编码器(ResNet-18)成功
  • 我自己在 Keras 中构建解码器(使用TF2.3),并将每一层的权重(numpy 数组,包括权重和偏差)从 Pytorch 复制到 Keras,无需任何修改。

但事实证明,Onnx2Keras转换后的编码器和自建解码器都无法重现相同的结果。下面是交叉对比图,首先介绍一下Decoder的代码。

首先是核心层,所有的 conv2d 层(Conv3x3, ConvBlock)都是基于此,但是不同的 dims 或者添加一个激活:

# Conv3x3 (normal conv2d without BN nor activation)
# There's also a ConvBlock, which is just "Conv3x3 + ELU activation", so I don't list it here.
def TF_Conv3x3(input_channel, filter_num, pad_mode='reflect', activate_type=None):

    # Actually it's 'reflect, but I implement it with tf.pad() outside this
    padding = 'valid' …
Run Code Online (Sandbox Code Playgroud)

python computer-vision keras tensorflow pytorch

1
推荐指数
1
解决办法
871
查看次数

pytorch交叉熵损失权重不起作用

我正在尝试一些代码,它的行为与我的预期不同。所以我把它简化为一个最低限度的工作示例:

import torch

test_act = torch.tensor([[2.,0.]])
test_target = torch.tensor([0])

loss_function_test = torch.nn.CrossEntropyLoss()
loss_test = loss_function_test(test_act, test_target)
print(loss_test)
> tensor(0.1269)

weights=torch.tensor([0.1,0.5])
loss_function_test = torch.nn.CrossEntropyLoss(weight=weights)
loss_test = loss_function_test(test_act, test_target)
print(loss_test)
> tensor(0.1269)
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,无论是否存在权重,输出都是相同的。但我预计第二个输出是 0.0127

是否有一些我不知道的正常化正在发生?或者它可能被窃听了吗?

python cross-entropy pytorch

1
推荐指数
1
解决办法
2874
查看次数

了解重塑张量时的顺序

对于张量:

x = torch.tensor([
    [
        [[0.4495, 0.2356],
          [0.4069, 0.2361],
          [0.4224, 0.2362]],
                   
         [[0.4357, 0.6762],
          [0.4370, 0.6779],
          [0.4406, 0.6663]]
    ],    
    [
        [[0.5796, 0.4047],
          [0.5655, 0.4080],
          [0.5431, 0.4035]],
         
         [[0.5338, 0.6255],
          [0.5335, 0.6266],
          [0.5204, 0.6396]]
    ]
])
Run Code Online (Sandbox Code Playgroud)

首先想将其分成 2 个 (x.shape[0]) 张量,然后将它们连接起来。在这里,只要获得正确的输出,我实际上并不需要将其拆分,但在视觉上将其拆分然后将它们连接在一起对我来说更有意义。

例如:

# the shape of the splits are always the same
split1 = torch.tensor([
    [[0.4495, 0.2356],
    [0.4069, 0.2361],
    [0.4224, 0.2362]],

    [[0.4357, 0.6762],
    [0.4370, 0.6779],
    [0.4406, 0.6663]]
])
split2 = torch.tensor([
    [[0.5796, 0.4047],
    [0.5655, 0.4080],
    [0.5431, 0.4035]],

    [[0.5338, 0.6255],
    [0.5335, 0.6266],
    [0.5204, 0.6396]] …
Run Code Online (Sandbox Code Playgroud)

python numpy reshape pytorch tensor

1
推荐指数
1
解决办法
6423
查看次数

我使用 PyTorch 收到此错误: RuntimeError: Gather_out_cpu(): Expected dtype int64 for index

我正在尝试使用 PyTorch 制作 AI,但出现以下错误:

RuntimeError: gather_out_cpu(): Expected dtype int64 for index
Run Code Online (Sandbox Code Playgroud)

这是我的功能:

def learn(self, batch_state, batch_next_state, batch_reward, batch_action):
    outputs = self.model(batch_state).gather(1, batch_action.unsqueeze(1)).squeeze(1)
    next_outputs = self.model(batch_next_state).detach().max(1)[0]
    target = self.gamma * next_outputs + batch_reward
    td_loss = F.smooth_l1_loss(outputs, target)
    self.optimizer.zero_grad()
    td_loss.backward(retain_variables = True)
    self.optimizer.step()
Run Code Online (Sandbox Code Playgroud)

artificial-intelligence python-3.x pytorch

1
推荐指数
1
解决办法
1万
查看次数

PyTorch:我可以按长度对批次进行分组吗?

我正在开发一个 ASR 项目,其中使用 HuggingFace ( ) 的模型wav2vec2。我现在的目标是将训练过程转移到 PyTorch,因此我尝试重新创建 HuggingFace\xe2\x80\x99sTrainer()类提供的所有内容。

\n

这些实用程序之一是能够按长度对批次进行分组并将其与动态填充相结合(通过数据整理器)。但说实话,我什至不知道如何在 PyTorch 中开始这一点。

\n

在我的例子中,输入是一维数组,表示 .wav 文件的原始波形。因此,在训练之前,我需要确保将相似大小的数组分批在一起。我是否需要创建一个自定义 Dataloader 类并对其进行更改,以便每次它都能为我提供长度尽可能接近的批量大小?

\n

我的一个想法是以某种方式将数据从最短到最长(或相反)排序,并每次从中提取batch_size样本。这样,第一批将包含最大长度的样本,第二批将包含第二大长度的样本,依此类推。

\n

尽管如此,我不确定如何实现这个实现。任何建议将不胜感激。

\n

提前致谢。

\n

pytorch pytorch-dataloader huggingface-datasets

1
推荐指数
1
解决办法
3196
查看次数

PyTorch 的 torch.as_strided 具有负步长,用于制作托普利茨矩阵

我正在编写临时的 PyTorch 版本scipy.linalg.toeplitz,目前具有以下形式:

def toeplitz_torch(c, r=None):
    c = torch.tensor(c).ravel()
    if r is None:
        r = torch.conj(c)
    else:
        r = torch.tensor(r).ravel()

    # Flip c left to right.
    idx = [i for i in range(c.size(0)-1, -1, -1)]
    idx = torch.LongTensor(idx)
    c = c.index_select(0, idx)

    vals = torch.cat((c, r[1:]))
    out_shp = len(c), len(r)
    n = vals.stride(0)

    return torch.as_strided(vals[len(c)-1:], size=out_shp, stride=(-n, n)).copy()
Run Code Online (Sandbox Code Playgroud)

torch.as_strided目前不支持负步幅。因此,我的函数抛出错误:

RuntimeError : as_strided: 目前不支持负步幅,得到步幅: [-1, 1]

我(可能不正确)的理解as_strided是,它将第一个参数的值插入到一个新数组中,该数组的大小由第二个参数指定,并且它是通过在原始数组中线性索引这些值并将它们放置在下标索引的步幅中来实现的由最后一个参数给出。

NumPy 和 PyTorch 文档都有关于as_strided“极度小心”使用该函数的可怕警告,我不完全理解这个函数,所以我想问: …

python numpy scipy stride pytorch

1
推荐指数
1
解决办法
1263
查看次数