pytorch
tongk手势舞
硕士:福州大学
展开
-
计算数据集的均值和方差
cifar10:def unpickle(file): import _pickle as cPickle with open(file, 'rb') as f: dict = cPickle.load(f, encoding='latin1') return dictdef get_mean_and_std(root_dir): train_data = [] train_label = [] for n in range(1, .原创 2021-11-17 10:24:59 · 2516 阅读 · 0 评论 -
pytorch 模型中部分层停止梯度下降的代码
这段代码的意思:有两个模型,一个预训练模型(pre_model),一个分类模型(classifier)。首先对pre_model的部分层中的参数取消参数梯度,停止梯度下降。剩下的带有参数梯度下降的层中对进行filter,符合条件的加进params_to_update列表中,不符合条件的加入params_to_stay列表中去,对classifier模型中所有参数设置可以梯度下降,并加入params_to_stay 中。优化器SGD中对两部分参数进行学习率lr设置,其中params_to_update原创 2021-09-09 10:11:32 · 845 阅读 · 0 评论 -
余弦相似度公式即代码
A是3x2的矩阵, B是4x2的矩阵首先,A * B是A乘以B的转置,得到3x4的矩阵接着A的2范数,得到[3](三个元素的列表,列如:[1, 2, 3])同理,B的2范数,得到[4]A的2范数与B的2范数采用笛卡尔积相乘,得到3x4的矩阵。def cosine_sim(x1, x2, dim=1, eps=1e-8): ip = torch.mm(x1, x2.t()) w1 = torch.norm(x1, 2, dim) w2 = torch.nor...原创 2021-09-08 22:26:48 · 554 阅读 · 0 评论 -
pytorch中用Mnist数据集dataloader 自定义batchsampler
注意:list.extend()与list.append()的区别a = []b = []for i in range(5): temp = [1, 2, 3] a.append(temp) b.extend(temp)print(a)print(b)res:[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]][1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2.原创 2021-07-27 17:45:39 · 2252 阅读 · 1 评论 -
读取当前目录并设置root path
import osa = os.path.dirname(__file__)print(a)b = os.path.join(a, '..')print(b)c = os.path.join(b, 'data')print(c)D:/Program Files (x86)/python_project/github/nlp/Sentence-similarity-classifier-for-pyTorch-master/newD:/Program Files (x86)/pytho.原创 2021-07-09 09:21:46 · 626 阅读 · 0 评论 -
F.binary_cross_entropy()
import torchimport torch.nn as nnimport torch.nn.functional as Fbatchsize = 10num_classes = 4x = torch.randn((batchsize, num_classes))# print(x)target = torch.randint(num_classes, size=(batchsize,), dtype=torch.long)print(target)y = torch.zeros.原创 2021-06-29 09:24:05 · 1565 阅读 · 0 评论 -
torch.dataLoader中的batchSize的作用
dataLoader 中的batchSize 是dataset中的所有数据中一个块的大小。比如:dataset中的所有数据大小为9999个数据,batchSize =32 说明一个块的大小为32,一共有9999 /32 = 313个块。dataset 中 __getItem__ 这个函数如下: def __getitem__(self, index): # print(f'index:{index}') self.index_count += 1 .原创 2021-06-28 20:35:30 · 6071 阅读 · 2 评论 -
torch.nn.Module.Modules()
import torchimport torch.nn as nnclass Module(nn.Module): def __init__(self): super(Module, self).__init__() self.conv1 = nn.Sequential( nn.Conv2d(1,64,kernel_size=3, stride=1, padding=1), torch.nn.ReLU(), .原创 2021-06-18 09:37:27 · 467 阅读 · 0 评论 -
数组切片(numpy)
a = np.arange(12)print(a)# 想要得到特定的序列的数组index = [0,2,1]b = a[index]print(b)half_len = len(a) / 2half_len = int(half_len)print(half_len)# 得到原数组的前一半c = a[:half_len]# 得到原数组的后一半d = a[half_len:]print(c)--------------------------------------------.原创 2021-06-17 17:15:58 · 332 阅读 · 0 评论 -
python 包之间方法的互相调用
如图所示,在dataloader.py中想要调用dataset.py中的方法。可以用。来表示。表示同一目录下的兄弟文件。。表示返回上一级寻找相关文件每个包如果有很多文件(*.py)想要导出,必须要使用__init__.py文件,在__init__.py中如下所示:比如data目录(一个包)包下面有很多文件(dataloader.py,dataset.py,transform.py)导出的文件可以在想要地方使用:比如说train.py文件位于根目录下。想要调用data包中的..原创 2021-06-17 16:56:11 · 1054 阅读 · 0 评论 -
torch.ger
torch.ger(vec1,vec2,out=None)→ TensorOuter product ofvec1andvec2. Ifvec1is a vector of sizea = torch.arange(1., 5.)b = torch.arange(1., 4.)c = torch.ger(a,b)print(a)print(b)print(c)-------------------------------res:tensor([1.,...原创 2021-06-16 16:49:20 · 236 阅读 · 0 评论 -
torch.nn.init
import torchimport torch.nn as nna = torch.Tensor(10, 5)print(a)b = torch.nn.init.uniform_(a, a=0, b=1)print(b)----------------------------------------------res:tensor([[1.6907e-01, 1.7743e+28, 1.1673e-32, 4.6280e+27, 7.2151e+22], [3.6...原创 2021-06-16 16:21:30 · 218 阅读 · 0 评论 -
torch.nn.Parameter
Parameter是Tensor的子类,同时拥有一种非常特殊的性质:当他们与Module S一起使用时,也就是说当它们作为Module参数进行使用时,它们会自动添加到Module的参数列表中,并且出现在parameters()迭代器里。(这样就可以自动计算梯度等)import torch.nn as nnimport torchimport mathimport torch.nn.functional as Fimport numpy as npclass NN_Network(nn.M.原创 2021-06-16 15:59:43 · 634 阅读 · 0 评论 -
pytorch crossEntropy(交叉熵)公式推导
import torch.nn.functional as Fimport torch.nn as nnx = torch.randn(5, 5)print(x)target = torch.tensor([0, 2, 3, 1, 4])one_hot = F.one_hot(target).float()# print(one_hot)softmax = torch.exp(x)/torch.sum(torch.exp(x), dim=1).resha...原创 2021-06-04 20:11:17 · 539 阅读 · 0 评论 -
pytorch crossEntroy(交叉熵)的推导
原创 2021-06-04 20:04:42 · 206 阅读 · 0 评论 -
用高斯分布模型(GMM)对输入进行概率预测
用高斯分布模型(GMM)对输入进行概率预测,输出概率列表,与给定阈值进行比较,最后输出符合条件的下标a = torch.randn(5,1)print(a)gmm = GaussianMixture(n_components=2, max_iter=10, tol=1e-2, reg_covar=5e-4)gmm.fit(a)prob = gmm.predict_proba(a)print(prob)print(gmm.means_)means = gmm.means_.argmin()原创 2021-05-04 17:09:45 · 2254 阅读 · 0 评论 -
pytorch 转为one-hot
scatter_(dim,index, src):dim = 1,a = torch.zeros(5,3)index = [[1],[2],[1],[2],[0]]当a从自身索引,self[0][0] = self[0][index[0][0]]=self[0][1]=1slef[0][1] = self[0][index[0][1]] 因为index[0][1]不存在,无法索引,保持原样self[0][2] = self[0][index[0][2]] 同.原创 2021-05-03 16:03:09 · 780 阅读 · 0 评论 -
os.environ的解释
os.environ 返回一个系统变量和系统变量值 的字典(键值对)res = os.environprint(res)ls = 'home' if 'home' in os.environ else 'no_home'# print(res)print(ls)os.environ['home'] = 'tongk'print(os.environ['home'])----------------------------------------------------------.原创 2021-04-18 19:46:31 · 3200 阅读 · 0 评论 -
pytorch torch数组随着index改变而改变
pt = torch.randperm(192)print(pt.shape)all_targets = torch.randn([192, 14])print(f'all_targets:{all_targets}')all_targets = all_targets[pt]print(all_targets.shape)print(f'all_targets:{all_targets}')-----------------------------------------------t.原创 2021-04-03 19:42:32 · 231 阅读 · 0 评论 -
torch.cat() 维度解析
import torcha = torch.randn((2, 3, 4))print(a)res:tensor([[[ 0.2615, 0.9965, 0.5935, -2.4657], [-2.0211, 0.5055, 0.3128, -0.8843], [-1.3269, -1.0438, 0.3159, -0.8572]], [[ 0.7990, 0.2023, -0.1174, -0.8619], .原创 2021-04-01 15:16:09 · 1300 阅读 · 0 评论 -
pytorch transforms
pytorch transforms fn detail转载 2021-04-01 10:16:17 · 101 阅读 · 0 评论 -
pytorch .detach().cpu().numpy()
原创 2021-03-31 10:05:24 · 4256 阅读 · 0 评论 -
python Image.convert()中YCbCr模式解析
YCbCr颜色空间及与RGB的变换关系原创 2021-03-31 10:00:20 · 1123 阅读 · 0 评论 -
pytorch image to tensor
from PIL import Imageimport os.path as ospimport osfrom torchvision.transforms import ToTensortest_path = '../dataset/BSD500/images/test'images_ls = os.listdir(test_path)images_all_path = []for image in images_ls: s_images_path = osp.join(test_.原创 2021-03-31 09:33:23 · 1316 阅读 · 0 评论 -
torch.autograd.variable()实例用法
import numpy as npimport torchimport torch.nndatas = np.array([[1, 2], [3, 4]])labels = np.array([[2, 3], [4, 5]])loss_fn = torch.nn.MSELoss()input = torch.autograd.Variable(torch.from_numpy(datas).float(), requires_grad=True)target = torch.autog.原创 2021-03-30 10:49:29 · 2625 阅读 · 0 评论 -
pytorch中pixelshuffle的具体操作方式
转载 2021-03-30 10:27:36 · 529 阅读 · 0 评论 -
torch.mean()维度解释
a = torch.arange(6) * 1.# print(a)a = a.reshape(2, 1, 3)print(a)print(a.shape)b = a.mean(dim=0)print(b)print(b.shape)--------------------------------------------res:tensor([[[0., 1., 2.]], [[3., 4., 5.]]])torch.Size([2, 1, 3])tensor(.原创 2021-03-26 18:34:16 · 1487 阅读 · 0 评论 -
torch.sum 维度参数解析
a = torch.ones(2, 3)print(a)print(a.shape)print(a.sum(dim=0))print(a.sum(dim=1))print(a.sum(dim=-1))#restensor([[1., 1., 1.], [1., 1., 1.]])torch.Size([2, 3])tensor([2., 2., 2.])tensor([3., 3.])tensor([3., 3.])个人理解:对于二维数组,dim=0,就是固定.原创 2021-03-18 19:47:17 · 2752 阅读 · 0 评论 -
torchvision.utils.make_grid() 拼接图片 mnist数据集(新手)
import torchfrom torchvision import datasets, transformsfrom torch.utils.data import DataLoaderimport torchvisionimport matplotlib.pyplot as pltdef image_show(images): images = images.numpy() images = images.transpose((1, 2, 0)) print(im.原创 2021-02-05 15:09:00 · 1874 阅读 · 0 评论 -
torch.nn.functional.normalized()的作用
个人认为F·normalize是对输入数据进行标准化使得输入数据满足正态分布。由于输入数据经过隐藏层的时候会发生一些偏移。所以Batch Normal1d是在隐藏层中使用,可以将数据从偏移状态拉回到正态分布。...原创 2020-12-17 21:46:52 · 913 阅读 · 0 评论 -
pytorch 状态字典:state_dict 模型和参数保存
state_dict转载 2020-11-23 19:32:27 · 1276 阅读 · 0 评论 -
torch与numpy的random
torch与numpy的random转载 2020-11-21 14:21:01 · 547 阅读 · 0 评论 -
pytorch torchvison.datasets.Iamgefolder()
class ImageFolder(DatasetFolder): """A generic data loader where the images are arranged in this way: :: root/dog/xxx.png root/dog/xxy.png root/dog/xxz.png root/cat/123.png root/cat/nsdf3.png root/cat/.原创 2020-10-23 12:14:43 · 247 阅读 · 1 评论 -
pytorch DataLoader
class DataLoader(object): r""" Data loader. Combines a dataset and a sampler, and provides single- or multi-process iterators over the dataset. Arguments: dataset (Dataset): dataset from which to load the data. batch_size .原创 2020-10-23 11:56:27 · 292 阅读 · 0 评论 -
特殊函数 __len__(self):
https://www.cnblogs.com/superxuezhazha/p/5792199.html转载 2020-09-21 10:37:38 · 177 阅读 · 0 评论 -
torch.cat()
https://www.jianshu.com/p/bffe96c5d10b转载 2020-09-21 10:11:43 · 211 阅读 · 0 评论 -
运行时错误:应为设备类型cuda的对象,但在中为参数“mat1”获取了设备类型cpu,RuntimeErrorExpectedobjectofdevicetypecudabutgotdevicetyp
https://www.pythonf.cn/read/94009转载 2020-08-01 11:18:38 · 417 阅读 · 0 评论 -
python单步调试
https://www.cnblogs.com/jing1617/p/9396617.html转载 2020-07-31 11:55:33 · 96 阅读 · 0 评论 -
Python中 list, numpy.array, torch.Tensor 格式相互转化
https://www.cnblogs.com/siyuan1998/p/10792481.html转载 2020-07-31 09:39:00 · 342 阅读 · 0 评论 -
pytorch 索引与切片
https://www.cnblogs.com/taosiyu/p/11574467.html转载 2020-06-27 16:23:15 · 221 阅读 · 0 评论