1.RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target'
# 举例说明
import torch
import torch.nn.functional as F
m = torch.rand([5, 3])
n = torch.rand([5])
loss = F.nll_loss(m, n)
print(loss)
上述例子输出会报上面的错误,这里对loss传入的参数稍做修改即可:
loss = F.nll_loss(m, n.long())
2.将class 'pandas.core.frame.DataFrame'格式转化为tensor
features = torch.tensor(features.values)
3.ubuntu下安装python包的镜像问题
# ubuntu查看已有conda环境
conda info --envs
# 激活相应的环境
source activate name(需要激活环境的名称)
# 查看当前下载包的通道
conda config --show channels
# 编辑设置channels的文件(只留下一个defaults即可)
vi ~/.condarc
# 或者在查看channels时,已有defaults可以直接执行下面的命令
conda config --remove-key channels
4.归一化矩阵(使矩阵行和为1)
# 例子
import numpy as np
# 生成一个随机整数矩阵
n = np.random.randint(7, size=(3, 5))
# 输出n
# array([[0, 0, 4, 0, 3],
# [2, 1, 1, 4, 1],
# [1, 6, 5, 0, 5]])
# 求行和
# n.sum(axis=1)
n = n / n.sum(axis=1)[:,None]
# 输出
# array([[0. , 0. , 0.57142857, 0. , 0.42857143],
# [0.22222222, 0.11111111, 0.11111111, 0.44444444, 0.11111111],
# [0.05882353, 0.35294118, 0.29411765, 0. , 0.29411765]])
5.RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
# 出现上述问题是因为我们在对变量求梯度的过程中,系统默认的是False,解决办法有以下两种
# 1.在Variable中加入requires_grad=True, 表示对这个参数求梯度
X = Variable(X, requires_grad=True)
# 2.在pytorch中,tensor需要将requires_grad定义为True才能求梯度,
# 可以在定义tensor时加上requires_grad=True
X = tensor.ones(2, 4, requires_grad=True)
# 可以调用tensor.requires_grad_()改变这个属性
X.requires_grad_(False)
6.手动实现maxpooling
# 这里用的是2*2的核,可以根据需要改动
import torch
x = torch.randn((6, 8), requires_grad=True)
# 获取输入的torch大小
in_height = x.size(0)
in_width = x.size(1)
# 得到输出的torch的大小
out_height = int((in_height - 2)/2) + 1
out_width = int((in_width - 2)/2) + 1
# 将输出的torch置零
out = torch.zeros((out_height, out_width))
# maxpooling过程
for i in range(out_height):
for j in range(out_width):
# stride(x)和stride(y)分别为移动步长,自己设置
start_i = stride(y)*i
start_j = stride(x)*j
end_i = start_i + 2
end_j = start_j + 2
out[i, j] = torch.max(x[start_i:end_i, start_j:end_j])
print(out)
7.pytorch中使用one_hot函数时出现one_hot is only applicable to index tensor问题
# 首先看传入的tensor的size,传入的tensor的维度不够则需要添加维度
# 这里的labels的size是tensor([n])的,传入需要添加维度
# 如果出现上述问题,只需要在后面加上to.(torch.int64)即可解决
# n是要分的种类
labels = torch.nn.functional.one_hot(labels.unsqueeze(0).to(torch.int64), n)