Python 数组维度 大小 形状 dim size shape
PEP 8: W292 no newline at end of file
结尾需要一个空行
PEP 8: E302 expected 2 blank lines, found 1
函数和类前后需要两个空行
从外部作用域隐藏名称
函数内外部变量名称一样导致
字典创建可以作为字典文字进行重写
字典初始化时为空导致
如dict_name = {} 修改为 dict_name = dict() 或 下一行加pass即可
PEP 8: E731 do not assign a lambda expression, use a def
Lamba函数转化为def函数即可
Index Error: tensors used as indices must be long, byte or bool tensors
作为索引/下标的量为多维矩阵
PEP 8: E127 continuation line over-indented for visual indent
一行内容写不下 换行续写时 需要对齐缩进
PEP 8: E402 module level import not at top of file
Import模块没有在python文件的最前面
位置实参位于关键字实参后面:
位置实参:通过参数所在的位置决定其对应的形参
关键字实参:通过实参关键字和形参的名称对应
形参:函数定义/声明/实现;实参:函数调用时使用
torch.set_default_tensor_type('torch.cuda.FloatTensor')
可以设置所有张量默认在GPU上进行运算
Torch张量的形状、大小、长度:tensor.shape 或 tensor.size()
z=numpy.c_[x,y]和numpy.r_[x,y]
将向量x,y按照列(行数增加)或行(列数增加)连接
Rng=numpy.random.RandomState(z)
设置随机数种子z,rng.uniform均匀分布,rng.random随机分布
Pyplot.subplot(x,y,z) / (xyz)
设置子图,一共x行y列,当前第z个,后面再用plot绘图
Numpy.resize和numpy.reshape
通常是使用resize改变数组的尺寸大小,使用reshape用来增加数组的维度
for i, data in enumerate(datas):
在循环时获取循环次数
Torch.tensor / from_numpy / as_tensor
都可以将ndarray转化为tensor
Tensor和as_tensor不会改变ndarray默认double数据类型,还得加.float()
From_numpy生成的tensor在cpu上,还得加tensor/as_tensor(device=cuda)
Lstm预测时序序列趋势正确但是数量级不对或者均值方差不一致
原始数据未归一化、训练epoch不足(error看似收敛其实没有)
if __name__ == '__main__':
python导入其他模块时,里面的程序都会执行;若加了这一行,则它下面的程序只有运行当前模块才会执行,被其他模块导入运行时不会执行。
这里super一行的作用是继承使用父类nn.Module的初始化方法
class BiGRUnet(nn.Module):
def __init__(self, ……):
super(BiGRUnet, self).__init__()
有序无序
{}是集合,里面的元素没有顺序
[]是列表,里面的元素有序
()是元组,里面的元素不可改变,因此也有序
类的函数类型
@staticmethod 静态方法 内部没有调用self、clf
@classmethod 类方法 形参第一个为clf 即类对象
什么都不加 实例方法 形参第一个为self 即实例对象
构建优化器时报错:optimizer got an empty parameter list
网络中各层没有加上self.前缀
向量反向
Ndarray反向:x=x[::-1].copy() 或者 x=numpy.filpud(x)
Tensor反向:x=x.flip(dims=?) 或者x=torch.flip(dims=?)
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same or input should be a MKLDNN tensor and weight is a dense tensor
输入向量不在cuda上,而网络参数向量都在cuda上
输入向量后加.cuda()即可
RuntimeError: CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling cublasCreate(handle)`
表明在使用CUDA时,cuBLAS无法为其操作分配所需的内存
网络输出维度与分类标签维度不一致可能会导致这个报错
RuntimeError: Expected a 'cpu' device type for generator but found 'cuda'
构建迭代器时报错,程序主函数开头加上下面的代码即可:
torch.set_default_tensor_type('torch.cuda.FloatTensor')
TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
Matplotlib绘图时需要先把tensor放到cpu上 不需要再转化为ndarray
tqdm不可调用
正确引用方法是 from tqdm impor tqdm 而不是 import tdqm
for file in files → for file in tqdm(files)
则在循环进行时生成进度条 每循环一次进度条前进一步
查看list的形状
先用 numpy.array 转化为 ndarray 再用 size 或者 shape
读取txt文件
with open ('path') as file:
strings = file.read() 读取所有 视作一整个长字符串
string = file.readline() 读取第一行 视作一个字符串
list = file.readlines() 读取所有行存进列表 表每一行是一个字符串
for line in file 读取每一行 line 是每一行对应的字符串
for line in file.readlines() 和上一行代码效果一样
for char in file.readline() 读取第一行的每个字符
跳过第一行的三种方法
with open('file_name', 'r') as f:
lines = f.readlines()[1:] # skip the first line.
for line in lines:
print(line)
with open('file_name', 'r') as f:
next(f) # skip the first line.
for line in f.readlines():
print(line)
from itertools import islice
with open('file_name', 'r') as f:
for line in islice(f, 1, None):
print(line)
处理空格
string.strip() 去除前后空格
string.split() 以空格划分字符串 包含去除前后空格
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-4: ordinal not in range(256)
中文编码问题
添加`str_2 = str_1.encode(“utf-8”).decode(“latin1”)`解决不了
文件路径命名使用全英文即可
切片相关问题
x = x [ 0 , : , : ] 和 x = x [ 0 : 1 , : , : ] 的区别
前者将 x 从三维降维二维
后者不降维 只是维度一长度为一
二者取得切片数据相同
路径拼接
file = os.path.join(file_path, file_name)
判断文件是否存在
if os.path.isfile(file)
判断字典中是否存在某个键
if dict.has_key(key)
if key in dict
if key in dict.keys()
字符串相加减
相加可以直接用+
相减需要用replace('.mat', '')(删掉.mat后缀)
Assertion `t >= 0 && t < n_classes` failed.
报错原因:标签数量与网络输出层大小不匹配
标签数量大于网络输出层大小
修改为相等即可
AttributeError: 'generator' object has no attribute 'requires_grad'
报错原因:冻结参数时选择了没有参数需要训练的层
PermissionError: [Errno 13] Permission denied: 'E:/Desktop/PYTHON/PGML'
保存预训练好的网络模型时出错,原因跟文件夹是否只读无关
而是路径名不完整,完整的应该是'E:/Desktop/PYTHON/PGML/model.pth'
ValueError: Classification metrics can't handle a mix of multilabel-indicator and continuous-multioutput targets
计算混淆矩阵时,预测值和目标值的数据类型不同导致,通常预测值为0~1之间的小数
而目标值为0、1、2之类的表示不同类别的整数,或者独热编码的01向量
需要将预测值转换为独热编码/或利用argmax转化为表示不同类别的整数