instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
How to run Pytorch model in normal non-parallel way?
I am going through this script, and there is a code block which takes 2 options into account, DataParallel and DistributedDataParallel here: if not args.distributed: if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): model.features = torch.nn.DataParallel(model.features) model.cuda() else: model = torch.nn.DataParallel(model).cuda() else: model.cuda() model = torch.nn.parallel.DistributedDataParallel(model) What if I don't want either of these options, and I want to run it without even DataParallel. How do I do it? How do I define my model so that it runs as a plain nn and not parallelizing anything?
DataParallel is a wrapper object to parallelize the computation on multiple GPUs of the same machine, see here. DistributedDataParallel is also a wrapper object that lets you distribute the data on multiple devices, see here. If you don't want it, you can simply remove the wrapper and use the model as it is: if not args.distributed: if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): model.features = model.features model.cuda() else: model = model.cuda() else: model.cuda() model = model This is to keep code modification to a minimum. Of course, since parallelization is of no interest to you, you could drop this whole if statement to something along the lines of: if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): model.features = model.features model = model.cuda() Note that this code assumes you are running on the GPU.
https://stackoverflow.com/questions/45858524/
Spyder just "kernel died,restarting" when I run net.forward in pytorch
I am using PYTHON IDE spyder3.2.1 in anaconda2, with python2.7, ubuntu14.04 code is just simple as follows: import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import numpy as np """ input:[batch_size,in_channel,height,width] kernel:[out_channel,in_channel,kh,kw] """ class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 5) #(28-5+1)/2=12 self.conv2 = nn.Conv2d(6, 16, 5) #(12-5+1)/2=4 # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # Max pooling over a (2, 2) window x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # If the size is a square you can only specify a single number print "after conv1 size is {}".format(x.size()) x = F.max_pool2d(F.relu(self.conv2(x)), 2) print "after conv2 size is {}".format(x.size()) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s return num_features net = Net() print(net) print "hello wrold" input = Variable(torch.Tensor(np.random.randint(1,10,size=(1,1,32,32)))) print net.forward(input) when I use jupyter notebook or console, it runs normally, it means the code has no error. But when I use it from Spyder, it just hangs likes this: As I am not allowed to embed the error image: it says "Kernel died, restarting" I just try to shrink my code to find where the problem is. The problem is absolutely around the very start F.max_pool2d(), in the forward method function. But after I searched a lot, I still have no idea how to fix it. conda list: alabaster 0.7.10 py27_0 anaconda 4.4.0 np112py27_0 anaconda-client 1.6.3 py27_0 anaconda-navigator 1.6.2 py27_0 anaconda-project 0.6.0 py27_0 asn1crypto 0.22.0 py27_0 astroid 1.4.9 py27_0 astroid 1.5.3 <pip> astropy 1.3.2 np112py27_0 Babel 2.5.0 <pip> babel 2.4.0 py27_0 backports 1.0 py27_0 backports.functools-lru-cache 1.4 <pip> backports.weakref 1.0rc1 <pip> backports_abc 0.5 py27_0 beautifulsoup4 4.6.0 py27_0 bitarray 0.8.1 py27_0 blaze 0.10.1 py27_0 bleach 1.5.0 py27_0 bleach 2.0.0 <pip> bokeh 0.12.5 py27_1 boto 2.46.1 py27_0 bottleneck 1.2.1 np112py27_0 cairo 1.14.8 0 cdecimal 2.3 py27_2 certifi 2017.7.27.1 <pip> cffi 1.10.0 py27_0 chardet 3.0.3 py27_0 chardet 3.0.4 <pip> click 6.7 py27_0 cloudpickle 0.2.2 py27_0 clyent 1.2.2 py27_0 colorama 0.3.9 py27_0 conda 4.3.21 py27_0 conda-env 2.6.0 0 configparser 3.5.0 py27_0 contextlib2 0.5.5 py27_0 cryptography 1.8.1 py27_0 curl 7.52.1 0 cycler 0.10.0 py27_0 cython 0.25.2 py27_0 cytoolz 0.8.2 py27_0 dask 0.14.3 py27_1 datashape 0.5.4 py27_0 dbus 1.10.10 0 decorator 4.0.11 py27_0 distributed 1.16.3 py27_0 docutils 0.14 <pip> docutils 0.13.1 py27_0 entrypoints 0.2.2 py27_1 entrypoints 0.2.3 <pip> enum34 1.1.6 py27_0 et_xmlfile 1.0.1 py27_0 expat 2.1.0 0 fastcache 1.0.2 py27_1 flask 0.12.2 py27_0 flask-cors 3.0.2 py27_0 fontconfig 2.12.1 3 freetype 2.5.5 2 funcsigs 1.0.2 py27_0 functools32 3.2.3.2 py27_0 futures 3.1.1 py27_0 get_terminal_size 1.0.0 py27_0 gevent 1.2.1 py27_0 glib 2.50.2 1 greenlet 0.4.12 py27_0 grin 1.2.1 py27_3 gst-plugins-base 1.8.0 0 gstreamer 1.8.0 0 h5py 2.7.0 np112py27_0 harfbuzz 0.9.39 2 hdf5 1.8.17 1 heapdict 1.0.0 py27_1 html5lib 0.999999999 <pip> html5lib 0.999 py27_0 icu 54.1 0 idna 2.5 py27_0 idna 2.6 <pip> imagesize 0.7.1 py27_0 ipaddress 1.0.18 py27_0 ipykernel 4.6.1 py27_0 ipython 5.3.0 py27_0 ipython_genutils 0.2.0 py27_0 ipywidgets 6.0.0 py27_0 isort 4.2.5 py27_0 isort 4.2.15 <pip> itsdangerous 0.24 py27_0 jbig 2.1 0 jdcal 1.3 py27_0 jedi 0.10.2 py27_2 jinja2 2.9.6 py27_0 jpeg 9b 0 jsonschema 2.6.0 py27_0 jupyter 1.0.0 py27_3 jupyter-client 5.1.0 <pip> jupyter_client 5.0.1 py27_0 jupyter_console 5.1.0 py27_0 jupyter_core 4.3.0 py27_0 lazy-object-proxy 1.2.2 py27_0 lazy-object-proxy 1.3.1 <pip> libffi 3.2.1 1 libgcc 4.8.5 2 libgfortran 3.0.0 1 libiconv 1.14 0 libpng 1.6.27 0 libsodium 1.0.10 0 libtiff 4.0.6 3 libtool 2.4.2 0 libxcb 1.12 1 libxml2 2.9.4 0 libxslt 1.1.29 0 llvmlite 0.18.0 py27_0 locket 0.2.0 py27_1 lxml 3.7.3 py27_0 Markdown 2.6.8 <pip> markupsafe 0.23 py27_2 MarkupSafe 1.0 <pip> matplotlib 2.0.2 np112py27_0 mccabe 0.6.1 <pip> mistune 0.7.4 py27_0 mkl 2017.0.1 0 mkl-service 1.1.2 py27_3 mock 2.0.0 <pip> mpmath 0.19 py27_1 msgpack-python 0.4.8 py27_0 multipledispatch 0.4.9 py27_0 navigator-updater 0.1.0 py27_0 nbconvert 5.2.1 <pip> nbconvert 5.1.1 py27_0 nbformat 4.4.0 <pip> nbformat 4.3.0 py27_0 networkx 1.11 py27_0 nltk 3.2.3 py27_0 nose 1.3.7 py27_1 notebook 5.0.0 py27_0 numba 0.33.0 np112py27_0 numexpr 2.6.2 np112py27_0 numpy 1.12.1 py27_0 numpy 1.13.1 <pip> numpydoc 0.6.0 py27_0 numpydoc 0.7.0 <pip> odo 0.5.0 py27_1 olefile 0.44 py27_0 opencv 1.0.1 <pip> opencv-python 3.3.0.9 <pip> openpyxl 2.4.7 py27_0 openssl 1.0.2l 0 packaging 16.8 py27_0 pandas 0.20.1 np112py27_0 pandocfilters 1.4.1 py27_0 pandocfilters 1.4.2 <pip> pango 1.40.3 1 partd 0.3.8 py27_0 path.py 10.3.1 py27_0 pathlib2 2.3.0 <pip> pathlib2 2.2.1 py27_0 patsy 0.4.1 py27_0 pbr 3.1.1 <pip> pcre 8.39 1 pep8 1.7.0 py27_0 pexpect 4.2.1 py27_0 pickleshare 0.7.4 py27_0 pillow 4.1.1 py27_0 pip 9.0.1 py27_1 pixman 0.34.0 0 ply 3.10 py27_0 prompt_toolkit 1.0.14 py27_0 protobuf 3.3.0 <pip> psutil 5.2.2 py27_0 ptyprocess 0.5.1 py27_0 py 1.4.33 py27_0 pycairo 1.10.0 py27_0 pycodestyle 2.3.1 <pip> pycosat 0.6.2 py27_0 pycparser 2.17 py27_0 pycrypto 2.6.1 py27_6 pycurl 7.43.0 py27_2 pyflakes 1.5.0 py27_0 pyflakes 1.6.0 <pip> pygments 2.2.0 py27_0 pylint 1.6.4 py27_1 pylint 1.7.2 <pip> pylzma 0.4.9.post0 <pip> pyodbc 4.0.16 py27_0 PyOpenGL 3.1.0 <pip> pyopenssl 17.0.0 py27_0 pyparsing 2.1.4 py27_0 pyqt 5.6.0 py27_2 pytables 3.3.0 np112py27_0 pytest 3.0.7 py27_0 python 2.7.13 0 python-dateutil 2.6.1 <pip> python-dateutil 2.6.0 py27_0 pytz 2017.2 py27_0 pywavelets 0.5.2 np112py27_0 pyyaml 3.12 py27_0 pyzmq 16.0.2 py27_0 qt 5.6.2 4 qtawesome 0.4.4 py27_0 qtconsole 4.3.0 py27_0 qtconsole 4.3.1 <pip> qtpy 1.2.1 py27_0 QtPy 1.3.1 <pip> readline 6.2 2 requests 2.18.4 <pip> requests 2.14.2 py27_0 rope 0.10.7 <pip> rope 0.9.4 py27_1 ruamel_yaml 0.11.14 py27_1 scandir 1.5 py27_0 scikit-image 0.13.0 np112py27_0 scikit-learn 0.18.1 np112py27_1 scipy 0.19.0 np112py27_0 seaborn 0.7.1 py27_0 setuptools 27.2.0 py27_0 setuptools 36.2.7 <pip> simplegeneric 0.8.1 py27_1 singledispatch 3.4.0.3 py27_0 sip 4.18 py27_0 six 1.10.0 py27_0 snowballstemmer 1.2.1 py27_0 sortedcollections 0.5.3 py27_0 sortedcontainers 1.5.7 py27_0 Sphinx 1.6.3 <pip> sphinx 1.5.6 py27_0 sphinxcontrib-websupport 1.0.1 <pip> spyder 3.2.1 <pip> spyder 3.1.4 py27_0 sqlalchemy 1.1.9 py27_0 sqlite 3.13.0 0 ssl_match_hostname 3.4.0.2 py27_1 statsmodels 0.8.0 np112py27_0 subprocess32 3.2.7 py27_0 sympy 1.0 py27_0 tblib 1.3.2 py27_0 tensorflow 1.2.1 <pip> tensorlayer 1.6.0 <pip> terminado 0.6 py27_0 testpath 0.3.1 <pip> testpath 0.3 py27_0 tk 8.5.18 0 toolz 0.8.2 py27_0 torch-0.2.0 1 <pip> torchvision 0.1.9 <pip> tornado 4.5.1 py27_0 tqdm 4.15.0 <pip> traitlets 4.3.2 py27_0 typing 3.6.2 <pip> unicodecsv 0.14.1 py27_0 unixodbc 2.3.4 0 urllib3 1.22 <pip> wcwidth 0.1.7 py27_0 webencodings 0.5.1 <pip> werkzeug 0.12.2 py27_0 wheel 0.29.0 py27_0 widgetsnbextension 2.0.0 py27_0 wrapt 1.10.11 <pip> wrapt 1.10.10 py27_0 xlrd 1.0.0 py27_0 xlsxwriter 0.9.6 py27_0 xlwt 1.2.0 py27_0 xz 5.2.2 1 yaml 0.1.6 0 zeromq 4.1.5 0 zict 0.1.2 py27_0 zlib 1.2.8 3
(Spyder developer here) I don't know why this is happening, but I opened an issue in our issue tracker so we don't forget to take a look at it in the future. Update: This problem was solved by the OP by updating PyTorch.
https://stackoverflow.com/questions/45875837/
Pytorch install with anaconda error
I get this error: C:\Users>conda install pytorch torchvision -c soumith Fetching package metadata ............. PackageNotFoundError: Package missing in current win-64 channels: - pytorch I got conda install pytorch torchvision -c soumith from Pytorch official website and I have OSX/conda/3.6/none for settings on Pytorch site(should be correct). I am new to conda, any tips how to solve this?
Use the following commands to install pytorch on windows for Windows 10 and Windows Server 2016, CUDA 8 conda install -c peterjc123 pytorch cuda80 for Windows 10 and Windows Server 2016, CUDA 9 conda install -c peterjc123 pytorch cuda90 for Windows 7/8/8.1 and Windows Server 2008/2012, CUDA 8 conda install -c peterjc123 pytorch_legacy cuda80
https://stackoverflow.com/questions/45906706/
How should I save the model of PyTorch if I want it loadable by OpenCV dnn module
I train a simple classification model by PyTorch and load it by opencv3.3, but it throw exception and say OpenCV Error: The function/feature is not implemented (Unsupported Lua type) in readObject, file /home/ramsus/Qt/3rdLibs/opencv/modules/dnn/src/torch/torch_importer.cpp, line 797 /home/ramsus/Qt/3rdLibs/opencv/modules/dnn/src/torch/torch_importer.cpp:797: error: (-213) Unsupported Lua type in function readObject Model definition class conv_block(nn.Module): def __init__(self, in_filter, out_filter, kernel): super(conv_block, self).__init__() self.conv1 = nn.Conv2d(in_filter, out_filter, kernel, 1, (kernel - 1)//2) self.batchnorm = nn.BatchNorm2d(out_filter) self.maxpool = nn.MaxPool2d(2, 2) def forward(self, x): x = self.conv1(x) x = self.batchnorm(x) x = F.relu(x) x = self.maxpool(x) return x class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = conv_block(3, 6, 3) self.conv2 = conv_block(6, 16, 3) self.fc1 = nn.Linear(16 * 8 * 8, 120) self.bn1 = nn.BatchNorm1d(120) self.fc2 = nn.Linear(120, 84) self.bn2 = nn.BatchNorm1d(84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = x.view(x.size()[0], -1) x = F.relu(self.bn1(self.fc1(x))) x = F.relu(self.bn2(self.fc2(x))) x = self.fc3(x) return x This model use Conv2d, ReLU, BatchNorm2d, MaxPool2d and Linear layer only, every layers are supported by opencv3.3 I save it by state_dict torch.save(net.state_dict(), 'cifar10_model') Load it by c++ as std::string const model_file("/home/some_folder/cifar10_model"); std::cout<<"read net from torch"<<std::endl; dnn::Net net = dnn::readNetFromTorch(model_file); I guess I save the model with the wrong way, what is the proper way to save the model of PyTorch in order to load using OpenCV? Thanks Edit : I use another way to save the model, but it cannot be loaded either torch.save(net, 'cifar10_model.net') Is this a bug?Or I am doing something wrong?
I found the answer, opencv3.3 do not support PyTorch (https://github.com/pytorch/pytorch) but pytorch (https://github.com/hughperkins/pytorch), it is a big surprise, I never know there are another version of pytorch exist(looks like a dead project, long time haven't updated), I hope they could mention which pytorch they support on wiki.
https://stackoverflow.com/questions/45929573/
Why does autograd not produce gradient for intermediate variables?
trying to wrap my head around how gradients are represented and how autograd works: import torch from torch.autograd import Variable x = Variable(torch.Tensor([2]), requires_grad=True) y = x * x z = y * y z.backward() print(x.grad) #Variable containing: #32 #[torch.FloatTensor of size 1] print(y.grad) #None Why does it not produce a gradient for y? If y.grad = dz/dy, then shouldn't it at least produce a variable like y.grad = 2*y?
By default, gradients are only retained for leaf variables. non-leaf variables' gradients are not retained to be inspected later. This was done by design, to save memory. -soumith chintala See: https://discuss.pytorch.org/t/why-cant-i-see-grad-of-an-intermediate-variable/94 Option 1: Call y.retain_grad() x = Variable(torch.Tensor([2]), requires_grad=True) y = x * x z = y * y y.retain_grad() z.backward() print(y.grad) #Variable containing: # 8 #[torch.FloatTensor of size 1] Source: https://discuss.pytorch.org/t/why-cant-i-see-grad-of-an-intermediate-variable/94/16 Option 2: Register a hook, which is basically a function called when that gradient is calculated. Then you can save it, assign it, print it, whatever... from __future__ import print_function import torch from torch.autograd import Variable x = Variable(torch.Tensor([2]), requires_grad=True) y = x * x z = y * y y.register_hook(print) ## this can be anything you need it to be z.backward() output: Variable containing: 8 [torch.FloatTensor of size 1 Source: https://discuss.pytorch.org/t/why-cant-i-see-grad-of-an-intermediate-variable/94/2 Also see: https://discuss.pytorch.org/t/why-cant-i-see-grad-of-an-intermediate-variable/94/7
https://stackoverflow.com/questions/45988168/
pytorch inception model outputs the wrong label for every input image
For the pytorch models I found this tutorial explaining how to classify an image. I tried to apply the same prcedure for an inception model. However the model fails for every image I load in Code: # some people need these three lines to make it work #from torchvision.models.inception import model_urls #name = 'inception_v3_google' #model_urls[name] = model_urls[name].replace('https://', 'http://') from torch.autograd import Variable import torchvision import requests from torchvision import models, transforms from PIL import Image import io from PIL import Image LABELS_URL = 'https://s3.amazonaws.com/outcome-blog/imagenet/labels.json' # cat IMG_URL1 = 'http://farm2.static.flickr.com/1029/762542019_4f197a0de5.jpg' # dog IMG_URL2 = 'http://farm3.static.flickr.com/2314/2518519714_98b01968ee.jpg' # lion IMG_URL3 = 'http://farm1.static.flickr.com/62/218998565_62930f10fc.jpg' labels = {int(key):value for (key, value) in requests.get(LABELS_URL).json().items()} model = torchvision.models.inception_v3(pretrained=True) model.training = False model.transform_input = False def predict_url_img(url): response = requests.get(url) img_pil = Image.open(io.BytesIO(response.content)) normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) preprocess = transforms.Compose([ transforms.Scale(256), transforms.CenterCrop(299), transforms.ToTensor(), normalize ]) img_tensor = preprocess(img_pil) img_tensor.unsqueeze_(0) img_variable = Variable(img_tensor) fc_out = model(img_variable) print("prediction:", labels[fc_out.data.numpy().argmax()]) predict_url_img(IMG_URL1) predict_url_img(IMG_URL2) predict_url_img(IMG_URL3) As output I get this: ('prediction:', u"plunger, plumber's helper") ('prediction:', u'plastic bag') ('prediction:', u"plunger, plumber's helper")
I found out that one needs to call model.eval() before applying the model. Because of the batch normalisations and also dropout layers, the model bahaves differently for training and testing.
https://stackoverflow.com/questions/46005286/
How to do scatter and gather operations in numpy?
I want to implement scatter and gather operations of Tensorflow or PyTorch in Numpy. I have been scratching my head for a while. Any pointers are greatly appreciated! PyTorch Scatter PyTorch Gather
The scatter method turned out to be way more work than I anticipated. I did not find any ready made function in NumPy for it. I'm sharing it here in the interest of anyone who may need to implement it with NumPy. (p.s. self is the destination or output of the method.) def scatter_numpy(self, dim, index, src): """ Writes all values from the Tensor src into self at the indices specified in the index Tensor. :param dim: The axis along which to index :param index: The indices of elements to scatter :param src: The source element(s) to scatter :return: self """ if index.dtype != np.dtype('int_'): raise TypeError("The values of index must be integers") if self.ndim != index.ndim: raise ValueError("Index should have the same number of dimensions as output") if dim >= self.ndim or dim < -self.ndim: raise IndexError("dim is out of range") if dim < 0: # Not sure why scatter should accept dim < 0, but that is the behavior in PyTorch's scatter dim = self.ndim + dim idx_xsection_shape = index.shape[:dim] + index.shape[dim + 1:] self_xsection_shape = self.shape[:dim] + self.shape[dim + 1:] if idx_xsection_shape != self_xsection_shape: raise ValueError("Except for dimension " + str(dim) + ", all dimensions of index and output should be the same size") if (index >= self.shape[dim]).any() or (index < 0).any(): raise IndexError("The values of index must be between 0 and (self.shape[dim] -1)") def make_slice(arr, dim, i): slc = [slice(None)] * arr.ndim slc[dim] = i return slc # We use index and dim parameters to create idx # idx is in a form that can be used as a NumPy advanced index for scattering of src param. in self idx = [[*np.indices(idx_xsection_shape).reshape(index.ndim - 1, -1), index[make_slice(index, dim, i)].reshape(1, -1)[0]] for i in range(index.shape[dim])] idx = list(np.concatenate(idx, axis=1)) idx.insert(dim, idx.pop()) if not np.isscalar(src): if index.shape[dim] > src.shape[dim]: raise IndexError("Dimension " + str(dim) + "of index can not be bigger than that of src ") src_xsection_shape = src.shape[:dim] + src.shape[dim + 1:] if idx_xsection_shape != src_xsection_shape: raise ValueError("Except for dimension " + str(dim) + ", all dimensions of index and src should be the same size") # src_idx is a NumPy advanced index for indexing of elements in the src src_idx = list(idx) src_idx.pop(dim) src_idx.insert(dim, np.repeat(np.arange(index.shape[dim]), np.prod(idx_xsection_shape))) self[idx] = src[src_idx] else: self[idx] = src return self There could be a simpler solution for gather, but this is what I settled on: (here self is the ndarray that the values are gathered from.) def gather_numpy(self, dim, index): """ Gathers values along an axis specified by dim. For a 3-D tensor the output is specified by: out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0 out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1 out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2 :param dim: The axis along which to index :param index: A tensor of indices of elements to gather :return: tensor of gathered values """ idx_xsection_shape = index.shape[:dim] + index.shape[dim + 1:] self_xsection_shape = self.shape[:dim] + self.shape[dim + 1:] if idx_xsection_shape != self_xsection_shape: raise ValueError("Except for dimension " + str(dim) + ", all dimensions of index and self should be the same size") if index.dtype != np.dtype('int_'): raise TypeError("The values of index must be integers") data_swaped = np.swapaxes(self, 0, dim) index_swaped = np.swapaxes(index, 0, dim) gathered = np.choose(index_swaped, data_swaped) return np.swapaxes(gathered, 0, dim)
https://stackoverflow.com/questions/46065873/
what is the equivalent of theano.tensor.clip in pytorch?
I want to clip my tensor (not gradient) values to some range. Is there any function in pytorch like there is a function theano.tensor.clip() in theano?
The function you are searching for is called torch.clamp. You can find the documentation here
https://stackoverflow.com/questions/46093577/
How do I write a PyTorch sequential model?
How do I write a sequential model in PyTorch, just like what we can do with Keras? I tried: import torch import torch.nn as nn net = nn.Sequential() net.add(nn.Linear(3, 4)) net.add(nn.Sigmoid()) net.add(nn.Linear(4, 1)) net.add(nn.Sigmoid()) net.float() But I get the error: AttributeError: 'Sequential' object has no attribute 'add'
As described by the correct answer, this is what it would look as a sequence of arguments: device = torch.device('cpu') if torch.cuda.is_available(): device = torch.device('cuda') net = nn.Sequential( nn.Linear(3, 4), nn.Sigmoid(), nn.Linear(4, 1), nn.Sigmoid() ).to(device) print(net) Sequential( (0): Linear(in_features=3, out_features=4, bias=True) (1): Sigmoid() (2): Linear(in_features=4, out_features=1, bias=True) (3): Sigmoid() )
https://stackoverflow.com/questions/46141690/
Pytorch Pre-trained RESNET18 Model
I have trained a pre-trained RESNET18 model in pytorch and saved it. While testing the model is giving different accuracy for different mini-batch size. Does anyone know why?
Yes, I think so. RESNET contains batch normalisation layers. At evaluation time you need to fix these; otherwise the running means are continuously being adjusted after processing each batch hence giving you different accuracy . Try setting: model.eval() before evaluation. Note before getting back into training, call model.train().
https://stackoverflow.com/questions/46167566/
How to train pytorch model with numpy data and batch size?
I am learning the basics of pytorch and thought to create a simple 4 layer nerual network with dropout to train IRIS dataset for classification. After refering to many tutorials I wrote this code. import pandas as pd from sklearn.datasets import load_iris import torch from torch.autograd import Variable epochs=300 batch_size=20 lr=0.01 #loading data as numpy array data = load_iris() X=data.data y=pd.get_dummies(data.target).values #convert to tensor X= Variable(torch.from_numpy(X), requires_grad=False) y=Variable(torch.from_numpy(y), requires_grad=False) print(X.size(),y.size()) #neural net model model = torch.nn.Sequential( torch.nn.Linear(4, 10), torch.nn.ReLU(), torch.nn.Dropout(), torch.nn.Linear(10, 5), torch.nn.ReLU(), torch.nn.Dropout(), torch.nn.Linear(5, 3), torch.nn.Softmax() ) print(model) # Loss and Optimizer optimizer = torch.optim.Adam(model.parameters(), lr=lr) loss_func = torch.nn.CrossEntropyLoss() for i in range(epochs): # Forward pass y_pred = model(X) # Compute and print loss. loss = loss_func(y_pred, y) print(i, loss.data[0]) # Before the backward pass, use the optimizer object to zero all of the # gradients for the variables it will update (which are the learnable weights # of the model) optimizer.zero_grad() # Backward pass loss.backward() # Calling the step function on an Optimizer makes an update to its parameters optimizer.step() There are currently two problems I am facing. I want to set a batch size of 20. How should I do this? At this step y_pred = model(X) its showing this error Error TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.DoubleTensor, torch.FloatTensor), but expected one of: * (torch.DoubleTensor mat1, torch.DoubleTensor mat2) * (torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2) * (float beta, torch.DoubleTensor mat1, torch.DoubleTensor mat2) * (float alpha, torch.DoubleTensor mat1, torch.DoubleTensor mat2) * (float beta, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2) * (float alpha, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2) * (float beta, float alpha, torch.DoubleTensor mat1, torch.DoubleTensor mat2) didn't match because some of the arguments have invalid types: (int, int, torch.DoubleTensor, !torch.FloatTensor!) * (float beta, float alpha, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2) didn't match because some of the arguments have invalid types: (int, int, !torch.DoubleTensor!, !torch.FloatTensor!)
I want to set a batch size of 20. How should I do this? For data processing and loading, PyTorch provide two classes, one is Dataset, which is used to represent your dataset. Specifically, Dataset provide the interface to get one sample from the whole dataset using the sample index. But Dataset is not enough, for large dataset, we need to do batch processing. So PyTorch provide a second class Dataloader, which is used to generate batches from the Dataset given the batch size and other parameters. For your specific case, I think you should try TensorDataset. Then use a Dataloader to set batch size to 20. Just look through the PyTorch official examples to get a sense how to do it. At this step y_pred = model(X) its showing this error The error message is pretty informative. Your input X to the model is type DoubleTensor. But your model parameters have type FloatTensor. In PyTorch, you can not do operation between Tensors of different types. What you should do is replace the line X= Variable(torch.from_numpy(X), requires_grad=False) with X= Variable(torch.from_numpy(X).float(), requires_grad=False) Now, X has type FloatTensor, the error message should disappear. Also, as a gentle reminder, there are pretty much materials on the Internet about your question which can sufficiently solve your problem. You should try hard to solve it by yourself.
https://stackoverflow.com/questions/46170814/
How does pytorch compute the gradients for a simple linear regression model?
I am using pytorch and trying to understand how a simple linear regression model works. I'm using a simple LinearRegressionModel class: class LinearRegressionModel(nn.Module): def __init__(self, input_dim, output_dim): super(LinearRegressionModel, self).__init__() self.linear = nn.Linear(input_dim, output_dim) def forward(self, x): out = self.linear(x) return out model = LinearRegressionModel(1, 1) Next I instantiate a loss criterion and an optimizer criterion = nn.MSELoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01) Finally to train the model I use the following code: for epoch in range(epochs): if torch.cuda.is_available(): inputs = Variable(torch.from_numpy(x_train).cuda()) if torch.cuda.is_available(): labels = Variable(torch.from_numpy(y_train).cuda()) # Clear gradients w.r.t. parameters optimizer.zero_grad() # Forward to get output outputs = model(inputs) # Calculate Loss loss = criterion(outputs, labels) # Getting gradients w.r.t. parameters loss.backward() # Updating parameters optimizer.step() My question is how does the optimizer get the loss gradient, computed by loss.backward(), to update the parameters using the step() method? How are the model, the loss criterion and the optimizer tied together?
PyTorch has this concept of tensors and variables. When you use nn.Linear the function creates 2 variables namely W and b.In pytorch a variable is a wrapper that encapsulates a tensor , its gradient and information about its create function. you can directly access the gradients by w.grad When you try it before calling the loss.backward() you get None. Once you call the loss.backward() it will contain now gradients. Now you can update these gradient manually with the below simple steps. w.data -= learning_rate * w.grad.data When you have a complex network ,the above simple step could grow complex. So optimisers like SGD , Adam takes care of this. When you create the object for these optimisers we pass in the parameters of our model. nn.Module contains this parameters() function which will return all the learnable parameters to the optimiser. Which can be done using the below step. optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
https://stackoverflow.com/questions/46278124/
Static graph is fast. Dynamic graph is slow. Is there any specific benchmark demonstrating this?
I've see some benchmark about tensorflow and pytorch. Tensorflow maybe faster but seems not that faster even sometimes slower. Is there any benchmark on specifically testing on static graph and dynamic graph demonstrating that static graph is much faster that dynamic graph?
To be more precise, the speed benefit comes from "deferred execution with graph rewriting." It's typically associated with explicit graph frameworks (Theano/TF), but with enough engineering you could add it to execution models like numpy/PyTorch which don't have explicit graph. See Bohrium for an example of hacking numpy to do rewriting. Note that presence of this feature makes the framework less friendly for prototyping, so if you add this to PyTorch, you'll get the same problems that people complain about in TensorFlow Deferred execution means exceptions can be triggered much later, not when you entered the problematic line Rewriting means the errors can now be thrown in nodes you didn't create, which gives uninformative error messages As far as performance, here's a toy benchmark in TensorFlow showing 5x speed-up when you turn on graph rewriting. I crafted the example to be bottlenecked by memory bandwidth, so it's a no-brainer that graph rewriting (cwise fusion), will give significant speed-boost there. For production LSTM model Google reported 1.8 speed-up when turning on graph optimizations (through XLA)
https://stackoverflow.com/questions/46312238/
When to use individual optimizers in PyTorch?
The example given here uses two optimizers for encoder and decoder individually. Why? And when to do like that?
If you have multiple networks (in the sense of multiple objects that inherit from nn.Module), you have to do this for a simple reason: When construction a torch.nn.optim.Optimizer object, it takes the parameters which should be optimized as an argument. In your case: encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate) decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate) This also gives you the freedom to vary parameters as the learning rate independently. If you don't need that, you could create a new class inheriting from nn.Module and containing both networks, encoder and decoder or create a set of parameters to give to the optimizer as explained here: nets = [encoder, decoder] parameters = set() for net in nets: parameters |= set(net.parameters()) where | is the union operator for sets in this context.
https://stackoverflow.com/questions/46377599/
n*m*3 input image to an nxm label in PyTorch
The input to my network is an RGB image with dimensions nm, how can I get the output to have dimensions of nm. class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 20, kernel_size = 5) self.conv2 = nn.Conv2d(20, 50, kernel_size = 3) self.conv3 = nn.ConvTranspose2d(50,20, kernel_size = 5) self.conv4 = nn.ConvTranspose2d(20,1, kernel_size = 3) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) x = F.relu(self.conv4(x)) return x I currently output a 1 * n * m. How can I output an n*m?
If you want to reshape a Tensor into a different size but with the same number of elements, generally you can use torch.view. For your case, there is an even simpler solution: torch.squeeze returns a Tensor with all dimensions of size 1 removed.
https://stackoverflow.com/questions/46382732/
CUDNN error using pretrained vgg16 model
I am trying to extract the activations of the last layer in a VGG16 model. For that end I used a decorator over the model as shown below. When I pass a cuda tensor to the model I get a CUDNN_STATUS_INTERNAL_ERROR with the following traceback. Anyone knows where I went wrong? traceback: File "/media/data1/iftachg/frame_glimpses/parse_files_to_vgg.py", line 80, in get_activation return model(image) File "/media/data1/iftachg/miniconda2/lib/python2.7/site-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "/media/data1/iftachg/frame_glimpses/partial_vgg.py", line 24, in forward x = self.vgg16.features(x) File "/media/data1/iftachg/miniconda2/lib/python2.7/site-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "/media/data1/iftachg/miniconda2/lib/python2.7/site-packages/torch/nn/modules/container.py", line 64, in forward input = module(input) File "/media/data1/iftachg/miniconda2/lib/python2.7/site-packages/torch/nn/modules/module.py", line 206, in __call__ result = self.forward(*input, **kwargs) File "/media/data1/iftachg/miniconda2/lib/python2.7/site-packages/torch/nn/modules/conv.py", line 237, in forward self.padding, self.dilation, self.groups) File "/media/data1/iftachg/miniconda2/lib/python2.7/site-packages/torch/nn/functional.py", line 39, in conv2d return f(input, weight, bias) RuntimeError: CUDNN_STATUS_INTERNAL_ERROR Class: class partial_vgg(nn.Module): def __init__(self): super(partial_vgg, self).__init__() self.vgg16 = models.vgg16(pretrained=True).cuda() for param in self.vgg16.parameters(): param.requires_grad = False def forward(self, x): x = self.vgg16.features(x) x = x.view(x.size(0), -1) for l in list(self.vgg16.classifier.children())[:-3]: x = l(x) return x
Apparently cudnn errors are extremely unhelpful and there was no problem with the code itself - it is simply the GPUs I was trying to access were already in use.
https://stackoverflow.com/questions/46391244/
Running a portion of Python code in parallel on two different GPUs
I have a PyTorch script similar to the following: # Loading data train_loader, test_loader = someDataLoaderFunction() # Define the architecture model = ResNet18() model = model.cuda() # Get method from program argument method = args.method # Training train(method, model, train_loader, test_loader) In order to run the script with two different methods (method1 and method2), it suffices to run the following commands in two different terminals: CUDA_VISIBLE_DEVICES=0 python program.py --method method1 CUDA_VISIBLE_DEVICES=1 python program.py --method method2 The problem is, the above data loader function contains some randomness in it, which means that the two methods were applied to two different sets of training data. I would like them to train the exact same set of data, so I modified the script as follows: # Loading data train_loader, test_loader = someDataLoaderFunction() # Define the architecture model = ResNet18() model = model.cuda() ## Run for the first method method = 'method1' # Training train(method, model, train_loader, test_loader) ## Run for the second method method = 'method2' # Must re-initialize the network first model = ResNet18() model = model.cuda() # Training train(method, model, train_loader, test_loader) Is it possible to make it run in parallel for each method? Thank you so much in advance for your help!
I guess the easiest way would be to fix the seeds as below. myseed=args.seed np.random.seed(myseed) torch.manual_seed(myseed) torch.cuda.manual_seed(myseed) This should force the data loaders to get the same samples every time. The parallel way is to use multithreading but I hardly see it worth the hassle for the problem you posted.
https://stackoverflow.com/questions/46438877/
NumPy/PyTorch extract subsets of images
In Numpy, given a stack of large images A of size(N,hl,wl), and coordinates x of size(N) and y of size(N) I want to get smaller images of size (N,16,16) In a for loop it would look like this: B=numpy.zeros((N,16,16)) for i in range(0,N): B[i,:,:]=A[i,y[i]:y[i]+16,x[i]:x[i]+16] But can I do this just with indexing? Bonus question: Will this indexing also work in pytorch? If not how can I implement this there?
Pretty simple really with view_as_windows from scikit-image, to get those sliding windowed views as a 6D array with the fourth axis being singleton. Then, use advanced-indexing to select the ones we want based off the y and x indices for indexing into the second and third axes of the windowed array to get our B. Hence, the implementation would be - from skimage.util.shape import view_as_windows BSZ = 16, 16 # Blocksize A6D = view_as_windows(A,(1,BSZ[0],BSZ[1])) B_out = A6D[np.arange(N),y,x,0] Explanation To explain to other readers on what's really going on with the problem, here's a sample run on a smaller dataset and with a blocksize of (2,2) - 1) Input array (3D) : In [78]: A Out[78]: array([[[ 5, 5, 3, 5, 3, 8], [ 5, *2, 6, 2, 2, 4], [ 4, 3, 4, 9, 3, 8], [ 6, 3, 3, 10, 4, 5], [10, 2, 5, 7, 6, 7], [ 5, 4, 2, 5, 2, 10]], [[ 4, 9, 8, 4, 9, 8], [ 7, 10, 8, 2, 10, 9], [10, *9, 3, 2, 4, 7], [ 5, 10, 8, 3, 5, 4], [ 6, 8, 2, 4, 10, 4], [ 2, 8, 6, 2, 7, 5]], [[ *4, 8, 7, 2, 9, 9], [ 2, 10, 2, 3, 8, 8], [10, 7, 5, 8, 2, 10], [ 7, 4, 10, 9, 6, 9], [ 3, 4, 9, 9, 10, 3], [ 6, 4, 10, 2, 6, 3]]]) 2) y and x indices to index into the second and third axes : In [79]: y Out[79]: array([1, 2, 0]) In [80]: x Out[80]: array([1, 1, 0]) 3) Finally the desired output, which is a block each from each of the 2D slice along the first axis and whose starting point (top left corner point) is (y,x) on that 2D slice. Refer to the asterisks in A for those - In [81]: B Out[81]: array([[[ 2, 6], [ 3, 4]], [[ 9, 3], [10, 8]], [[ 4, 8], [ 2, 10]]])
https://stackoverflow.com/questions/46450040/
error occurs when loading data in pytorch: 'Image' object has no attribute 'shape'
I am finetuning resnet152 using the code based on ImageNet training in PyTorch, and error occurs when I load the data, and it occured only after handling several batches of images. How can I solve the problem. Following code is the simplified code that produces the same error : code # Data loading code normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_loader = torch.utils.data.DataLoader( datasets.ImageFolder(train_img_dir, transforms.Compose([ transforms.RandomSizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ])), batch_size=256, shuffle=True, num_workers=1, pin_memory=True) for i, (input_x, target) in enumerate(train_loader): if i % 10 == 0: print(i) print(input_x.shape) print(target.shape) error 0 torch.Size([256, 3, 224, 224]) torch.Size([256]) 10 torch.Size([256, 3, 224, 224]) torch.Size([256]) 20 torch.Size([256, 3, 224, 224]) torch.Size([256]) 30 torch.Size([256, 3, 224, 224]) torch.Size([256]) ---------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-48-792d6ca206df> in <module>() ----> 1 for i, (input_x, target) in enumerate(train_loader): 2 if i % 10 == 0: 3 # sample_img = input_x[0] 4 print(i) 5 print(input_x.shape) /usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py in __next__(self) 200 self.reorder_dict[idx] = batch 201 continue --> 202 return self._process_next_batch(batch) 203 204 next = __next__ # Python 2 compatibility /usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py in _process_next_batch(self, batch) 220 self._put_indices() 221 if isinstance(batch, ExceptionWrapper): --> 222 raise batch.exc_type(batch.exc_msg) 223 return batch 224 AttributeError: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 41, in _worker_loop samples = collate_fn([dataset[i] for i in batch_indices]) File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 41, in <listcomp> samples = collate_fn([dataset[i] for i in batch_indices]) File "/usr/local/lib/python3.5/dist-packages/torchvision-0.1.9-py3.5.egg/torchvision/datasets/folder.py", line 118, in __getitem__ img = self.transform(img) File "/usr/local/lib/python3.5/dist-packages/torchvision-0.1.9-py3.5.egg/torchvision/transforms.py", line 369, in __call__ img = t(img) File "/usr/local/lib/python3.5/dist-packages/torchvision-0.1.9-py3.5.egg/torchvision/transforms.py", line 706, in __call__ i, j, h, w = self.get_params(img) File "/usr/local/lib/python3.5/dist-packages/torchvision-0.1.9-py3.5.egg/torchvision/transforms.py", line 693, in get_params w = min(img.size[0], img.shape[1]) AttributeError: 'Image' object has no attribute 'shape'
There's a bug in transforms.RandomSizedCrop.get_params(). In the last line of your error message, it should be img.size instead of img.shape. The lines containing the bug will only be executed if the cropping failed for 10 consecutive times (where it falls back to central crop). That's why this error does not occur for every batch of images. I've submitted a PR to fix it. For a quick fix, you can edit your /usr/local/lib/python3.5/dist-packages/torchvision-0.1.9-py3.5.egg/torchvision/transforms.py file and change all img.shape to img.size. EDIT: the PR is merged. You can install the latest torchvision on GitHub to fix it.
https://stackoverflow.com/questions/46482787/
Using Augmented Data Images in Testing
I am working on a Person Re-Identification problem and am showing the results using a CMC curve. I used augmented data/Image along with the normal images (Currently training on CUHK01) in the training set. While testing if I don't use the augmented data along with my normal test images for Calculating Rank let's say Rank_1 I get Rank_1 of ~30% on the other hand on using augmented data gives me a Rank_1 of ~65-70% (which is weirdly high regarding the current Rank_1 accuracy in the world). So my questions are a) How does augmented data affect the testing set especially in my case. b) Am I over-fitting or something of that sort. c) Is it a general rule to avoid usage of augmented images in the test case.
The reason behind using data augmentation is to reduce the chance of overfitting. This way you want to tell your model that the parameters (theta) are not correlated with the data that you are augmenting (alpha). That is achievable by augmenting each input by every possible alpha. But this is far from reality for a number of reasons, e.g. time/memory limitation, you might not be able to construct every possible augmentation, etc. so there might be some bias. Nevertheless, it still reduces the chance of overfitting to your dataset, but it might overfit to your augmentation. Thus, if you have the augmentation, you might get more accuracy by matching to the augmented data due to the overfitting, which is an answer to question a. So I believe that the answer to the question b is yes. In order to answer question c, I have not read about rules for data augmentation but in the literature of machine learning I presume that they avoid any augmentation on the test set. e.g. I quote from a paper We augment the training images by replacing the green screen with random background images, and vary the appearance in terms of color and shading by intrinsic recoloring
https://stackoverflow.com/questions/46495978/
pytorch backprop through volatile variable error
I'm trying to minimize some input relative to some target by running it through several backward pass iterations and updating the input at each step. The first pass runs successfully but I get the following error on the second pass: RuntimeError: element 0 of variables tuple is volatile This code snippet demonstrates the problem import torch from torch.autograd import Variable import torch.nn as nn inp = Variable(torch.Tensor([1]), requires_grad=True) target = Variable(torch.Tensor([3])) loss_fn = nn.MSELoss() for i in range(2): loss = loss_fn(inp, target) loss.backward() gradient = inp.grad inp = inp - inp.grad * 0.01 When I inspect the value of inp, before it is reassigned on the last line, inp.volatile => False and inp.requires_grad => True but after it is reassigned those switch to True and False, respectively. Why does being a volatile variable prevent the second backprop run?
You must zero out the gradient before each update like this: inp.grad.data.zero_() But in your code every time you update the gradient you are creating another Variable object, so you must update entire history like this: import torch from torch.autograd import Variable import torch.nn as nn inp_hist = [] inp = Variable(torch.Tensor([1]), requires_grad=True) target = Variable(torch.Tensor([3])) loss_fn = nn.MSELoss() for i in range(2): loss = loss_fn(inp, target) loss.backward() gradient = inp.grad inp_hist.append(inp) inp = inp - inp.grad * 0.01 for inp in inp_hist: inp.grad.data.zero_() But this way you will compute the gradient for all previous inputs you have created in the history(and it's bad, it's a wast of everything), a correct implementation looks like this: import torch from torch.autograd import Variable import torch.nn as nn inp = Variable(torch.Tensor([1]), requires_grad=True) target = Variable(torch.Tensor([3])) loss_fn = nn.MSELoss() for i in range(2): loss = loss_fn(inp, target) loss.backward() gradient = inp.grad inp.data = inp.data - inp.grad.data * 0.01 inp.grad.data.zero_()
https://stackoverflow.com/questions/46513276/
How to get ouput from a particular layer from pretrained CNN in pytorch
I have pretrained CNN (RESNET18) on imagenet dataset , now what i want is to get output of my input image from a particular layer, for example. my input image is of FloatTensor(3, 224, 336) and i send a batch of size = 10 in my resnet model , now what i want is the output returned by model.layer4, Now what i tried is out = model.layer4(Variable(input)) but it gave me input dimensions mismatch error(As expected), this is the exact error returned RuntimeError: Need input of dimension 4 and input.size[1] == 64 but got input to be of shape: [10 x 3 x 224 x 336] at /Users/soumith/miniconda2/conda-bld/pytorch_1501999754274/work/torch/lib/THNN/generic/SpatialConvolutionMM.c:47 So i'm confused , how to proceed now to get my layer4 output PS: My ultimate task is to combine layer4 output and fullyconnected layer output together (Tweeking in CNN, kind of gated CNN ), so if anyone have any insight in this case then please do tell me, maybe my above approach is not right
You must create a module with all layers from start to the block you want: resnet = torchvision.models.resnet18(pretrained=True) f = torch.nn.Sequential(*list(resnet.children())[:6]) features = f(imgs)
https://stackoverflow.com/questions/46513886/
How to use groups parameter in PyTorch conv2d function
I am trying to compute a per-channel gradient image in PyTorch. To do this, I want to perform a standard 2D convolution with a Sobel filter on each channel of an image. I am using the torch.nn.functional.conv2d function for this In my minimum working example code below, I get an error: import torch import torch.nn.functional as F filters = torch.autograd.Variable(torch.randn(1,1,3,3)) inputs = torch.autograd.Variable(torch.randn(1,3,10,10)) out = F.conv2d(inputs, filters, padding=1) RuntimeError: Given groups=1, weight[1, 1, 3, 3], so expected input[1, 3, 10, 10] to have 1 channels, but got 3 channels instead This suggests that groups need to be 3. However, when I make groups=3, I get a different error: import torch import torch.nn.functional as F filters = torch.autograd.Variable(torch.randn(1,1,3,3)) inputs = torch.autograd.Variable(torch.randn(1,3,10,10)) out = F.conv2d(inputs, filters, padding=1, groups=3) RuntimeError: invalid argument 4: out of range at /usr/local/src/pytorch/torch/lib/TH/generic/THTensor.c:440 When I check that code snippet in the THTensor class, it refers to a bunch of dimension checks, but I don't know where I'm going wrong. What does this error mean? How can I perform my intended convolution with this conv2d function? I believe I am misunderstanding the groups parameter.
If you want to apply a per-channel convolution then your out-channel should be the same as your in-channel. This is expected, considering each of your input channels creates a separate output channel that it corresponds to. In short, this will work import torch import torch.nn.functional as F filters = torch.autograd.Variable(torch.randn(3,1,3,3)) inputs = torch.autograd.Variable(torch.randn(1,3,10,10)) out = F.conv2d(inputs, filters, padding=1, groups=3) whereas, filters of size (2, 1, 3, 3) or (1, 1, 3, 3) will not work. Additionally, you can also make your out-channel a multiple of in-channel. This works for instances where you want to have multiple convolution filters for each input channel. However, This only makes sense if it is a multiple. If not, then pytorch falls back to its closest multiple, a number less than what you specified. This is once again expected behavior. For example a filter of size (4, 1, 3, 3) or (5, 1, 3, 3), will result in an out-channel of size 3.
https://stackoverflow.com/questions/46536971/
expected Double tensor (got Float tensor) in Pytorch
I want to create nn.Module in Pytorch. I used following code for text related problem (In fact I use Glove 300d pre-trained embedding and weighted average of words in a sentence to do classification). class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv1d(300, 128, kernel_size=5) self.conv2 = nn.Conv1d(128, 64, kernel_size=2) self.conv2_drop = nn.Dropout() self.fc1 = nn.Linear(64, 20) self.fc2 = nn.Linear(20, 2) def forward(self, x): x = F.relu(F.avg_pool1d(self.conv1(x), 2)) x = F.relu(F.avg_pool1d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(-1, 1) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) return self.fc2(x) But it gives me following error: Traceback (most recent call last): x = F.relu(F.avg_pool1d(self.conv1(x), 2)) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/torch/nn/modules/module.py", line 224, in __call__ result = self.forward(*input, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/torch/nn/modules/conv.py", line 154, in forward self.padding, self.dilation, self.groups) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/torch/nn/functional.py", line 83, in conv1d return f(input, weight, bias) RuntimeError: expected Double tensor (got Float tensor) I fairly new to Conv1d, and most of tutorial used Conv1d for image problems. Can anybody give me some idea what's the problem? I also added model.double() inside forward method but gives me another error: RuntimeError: Given input size: (300 x 1 x 1). Calculated output size: (128 x 1 x -3). Output size is too small
Error 1 RuntimeError: expected Double tensor (got Float tensor) This happens when you pass a double tensor to the first conv1d function. Conv1d only works with float tensor. Either do, conv1.double() , or model.double(). Which is what you have done, and that is correct. Error 2 RuntimeError: Given input size: (300 x 1 x 1). Calculated output size: (128 x 1 x -3). Output size is too small This is because you are passing an input to which a convolution with a window size of 5 is not valid. You will have to add padding to your Conv1ds for this to work, like so: self.conv1 = nn.Conv1d(300, 128, kernel_size=5, padding=2) If you dont wish to add padding, then given (batch_size, in_channels, inp_size) as the size of the input tensor, you have to make sure that your inp_size is greater than 5. All fixes combined Make sure that your sizes are correct for the rest of your network. Like so: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv1d(300, 128, kernel_size=5, padding=2) self.conv2 = nn.Conv1d(128, 64, kernel_size=2, padding=1) self.conv2_drop = nn.Dropout() self.fc1 = nn.Linear(64, 20) self.fc2 = nn.Linear(20, 2) def forward(self, x): x = F.relu(F.avg_pool1d(self.conv1(x), 2, padding=1)) x = F.relu(F.avg_pool1d(self.conv2_drop(self.conv2(x)), 2)) x = x.view(1, -1) # bonus fix, Linear needs (batch_size, in_features) and not (in_features, batch_size) as input. x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) return self.fc2(x) if __name__ == '__main__': t = Variable(torch.randn((1, 300, 1))).double() # t is a double tensor model = Net() model.double() # this will make sure that conv1d will process double tensor out = model(t)
https://stackoverflow.com/questions/46546217/
Jupyter Kernel crash/dies when use large Neural Network layer, any idea pls?
I am experimenting Autoencoder with Pytorch. It seems when I use relatively larger neural network for instance nn.Linear(250*250, 40*40) as the first layer, the Jupyter kernel keep crashing. when I use smaller layer size e.g. nn.Linear(250*250, 20*20). the Jupyter kernel is ok. Any idea how to fix this? So I can run larger network.Thank you. The entire network is as below. # model: class AutoEncoder(nn.Module): def __init__(self): super().__init__() self.encoder = nn.Sequential( nn.Linear(250*250, 20*20), nn.BatchNorm1d(20*20,momentum=0.5), nn.Dropout(0.5), nn.LeakyReLU(), nn.Linear(20*20, 20*20), nn.BatchNorm1d(20*20,momentum=0.5), nn.Dropout(0.5), nn.LeakyReLU(), nn.Linear(20*20, 20*20), nn.BatchNorm1d(20*20,momentum=0.5), nn.Dropout(0.5), nn.LeakyReLU(), nn.Linear(20*20, 15*15), nn.BatchNorm1d(15*15,momentum=0.5), nn.Dropout(0.5), nn.LeakyReLU(), nn.Linear(15*15, 3), nn.BatchNorm1d(3,momentum=0.5), #nn.Dropout(0.5), #nn.Tanh(), #nn.Linear(5*5,5), ) self.decoder = nn.Sequential( #nn.Linear(5, 5*5), #nn.BatchNorm1d(5*5,momentum=0.5), #nn.Dropout(0.5), #nn.Tanh(), nn.Linear(3, 15*15), nn.BatchNorm1d(15*15,momentum=0.5), nn.Dropout(0.5), nn.LeakyReLU(), nn.Linear(15*15, 20*20), nn.BatchNorm1d(20*20,momentum=0.5), nn.Dropout(0.5), nn.LeakyReLU(), nn.Linear(20*20, 20*20), nn.BatchNorm1d(20*20,momentum=0.5), nn.Dropout(0.5), nn.LeakyReLU(), nn.Linear(20*20, 250*250), nn.BatchNorm1d(250*250,momentum=0.5), nn.Dropout(0.5), nn.Sigmoid(), ) def forward(self, x): encoded = self.encoder(x) decoded = self.decoder(encoded) return encoded, decoded
I have found the root cause. I am running a docker ubuntu image/package on windows. the memory setting is set too low, when I increase the memory setting on docker. my ubuntu environment got more memory, then I can larger matrix operations.
https://stackoverflow.com/questions/46624247/
PyTorch Broadcasting Failing. "Rules" Followed
I have a few PyTorch examples that confuse me and am hoping to clear it up. Firstly, as per the PyTorch page, I would expect these example to work as do their numpy equivalents namely these. The first example is very intuitive. These are compatible for broadcasting: Image (3d array): 256 x 256 x 3 Scale (1d array): 3 Result (3d array): 256 x 256 x 3 Take for instance these: torch.Tensor([[1,2,3]])/torch.Tensor([1,2,3]) Out[5]: 1 1 1 [torch.FloatTensor of size 1x3] torch.Tensor([[1,2,3]])/torch.Tensor([1,2,3]) Out[6]: 1 1 1 [torch.FloatTensor of size 1x3] torch.Tensor([[[1,2,3]]])/torch.Tensor([1,2,3]) Out[7]: (0 ,.,.) = 1 1 1 [torch.FloatTensor of size 1x1x3] However, this is the result of the numpy example: torch.randn(256,256,3)/torch.Tensor([1,2,3]) Traceback (most recent call last): File "<ipython-input-12-4c328d453e24>", line 1, in <module> torch.randn(256,256,3)/torch.Tensor([1,2,3]) File "/home/nick/anaconda3/lib/python3.6/site-packages/torch/tensor.py", line 313, in __div__ return self.div(other) RuntimeError: inconsistent tensor size at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/TH/generic/THTensorMath.c:873 Here is an excerpt which says this ought to work: Two tensors are “broadcastable” if the following rules hold: Each tensor has at least one dimension. When iterating over the dimension sizes, starting at the trailing dimension, the dimension sizes must either be equal, one of them is 1, or one of them does not exist. If one converts the tensors to numpy arrays the arithmetic works as expected. What's going wrong? Have I misinterpreted the docs and if so what syntax results in the same results?
Verify that you are using the correct version of pytorch. It must be 0.2.0, which is when broadcasting was introduced in pytorch. In[2]: import torch In[3]: torch.__version__ Out[3]: '0.2.0_4'
https://stackoverflow.com/questions/46625967/
Porting PyTorch code from CPU to GPU
Following the tutorial from https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation.ipynb There is a USE_CUDA flag that is used to control the variable and tensor types between CPU (when False) to GPU (when True) types. Using the data from en-fr.tsv and converting the sentences to variables: import unicodedata import string import re import random import time import math from gensim.corpora.dictionary import Dictionary import torch import torch.nn as nn from torch.autograd import Variable from torch import LongTensor, FloatTensor from torch import optim import torch.nn.functional as F import numpy as np MAX_LENGTH = 10 USE_CUDA = False # Turn a Unicode string to plain ASCII, thanks to http://stackoverflow.com/a/518232/2809427 def unicode_to_ascii(s): return ''.join( c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn' ) # Lowercase, trim, and remove non-letter characters def normalize_string(s): s = unicode_to_ascii(s.lower().strip()) s = re.sub(r"([.!?])", r" \1", s) s = re.sub(r"[^a-zA-Z.!?]+", r" ", s) return s SOS_IDX, SOS_TOKEN = 0, '<s>' EOS_IDX, EOS_TOKEN = 1, '</s>' UNK_IDX, UNK_TOKEN = 2, '<unk>' PAD_IDX, PAD_TOKEN = 3, '<blank>' lines = open('en-fr.tsv').read().strip().split('\n') pairs = [[normalize_string(s).split() for s in l.split('\t')] for l in lines] src_sents, trg_sents = zip(*pairs) src_dict = Dictionary([[SOS_TOKEN, EOS_TOKEN, UNK_TOKEN, PAD_TOKEN]]) src_dict.add_documents(src_sents) trg_dict = Dictionary([[SOS_TOKEN, EOS_TOKEN, UNK_TOKEN, PAD_TOKEN]]) trg_dict.add_documents(trg_sents) def variablize_sentences(sentence, dictionary): indices = [dictionary.token2id[tok] for tok in sentence] + [dictionary.token2id[EOS_TOKEN]] var = Variable(LongTensor(indices).view(-1, 1)) return var.cuda() if USE_CUDA else var input_variables = [variablize_sentences(sent, src_dict) for sent in src_sents] output_variables = [variablize_sentences(sent, trg_dict) for sent in trg_sents] And using a Encoder-Attn-Decoder network: class EncoderRNN(nn.Module): def __init__(self, input_size, hidden_size, n_layers=1): super(EncoderRNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.n_layers = n_layers self.embedding = nn.Embedding(input_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size, n_layers) self.embedding = self.embedding.cuda() if USE_CUDA else self.embedding self.gru = self.gru.cuda() if USE_CUDA else self.gru def forward(self, word_inputs, hidden): seq_len = len(word_inputs) embedded = self.embedding(word_inputs).view(seq_len, 1, -1) embedded = embedded.cuda() if USE_CUDA else embedded output, hidden = self.gru(embedded, hidden) output = output.cuda() if USE_CUDA else output hiddne = hidden.cuda() if USE_CUDA else hidden return output, hidden def init_hidden(self): hidden = Variable(torch.zeros(self.n_layers, 1, self.hidden_size)) return hidden.cuda() if USE_CUDA else hidden class Attn(nn.Module): def __init__(self, method, hidden_size, max_length=MAX_LENGTH): super(Attn, self).__init__() self.method = method self.hidden_size = hidden_size if self.method == 'general': self.attn = nn.Linear(self.hidden_size, hidden_size) elif self.method == 'concat': self.attn = nn.Linear(self.hidden_size * 2, hidden_size) self.other = nn.Parameter(FloatTensor(1, hidden_size)) def forward(self, hidden, encoder_outputs): seq_len = len(encoder_outputs) # Create variable to store attention energies attn_energies = Variable(torch.zeros(seq_len)) # B x 1 x S attn_energies = attn_energies.cuda() if USE_CUDA else attn_energies # Calculate energies for each encoder output for i in range(seq_len): attn_energies[i] = self.score(hidden, encoder_outputs[i]) # Normalize energies to weights in range 0 to 1, resize to 1 x 1 x seq_len return F.softmax(attn_energies).unsqueeze(0).unsqueeze(0) def score(self, hidden, encoder_output): if self.method == 'dot': energy =torch.dot(hidden.view(-1), encoder_output.view(-1)) elif self.method == 'general': energy = self.attn(encoder_output) energy = torch.dot(hidden.view(-1), energy.view(-1)) elif self.method == 'concat': energy = self.attn(torch.cat((hidden, encoder_output), 1)) energy = torch.dot(self.v.view(-1), energy.view(-1)) return energy class AttnDecoderRNN(nn.Module): def __init__(self, attn_model, hidden_size, output_size, n_layers=1, dropout_p=0.1): super(AttnDecoderRNN, self).__init__() # Keep parameters for reference self.attn_model = attn_model self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.dropout_p = dropout_p # Define layers self.embedding = nn.Embedding(output_size, hidden_size) self.gru = nn.GRU(hidden_size * 2, hidden_size, n_layers, dropout=dropout_p) self.out = nn.Linear(hidden_size * 2, output_size) self.embedding = self.embedding.cuda() if USE_CUDA else self.embedding self.gru = self.gru.cuda() if USE_CUDA else self.gru self.out = self.out.cuda() if USE_CUDA else self.out # Choose attention model if attn_model != 'none': self.attn = Attn(attn_model, hidden_size) self.attn = self.attn.cuda() if USE_CUDA else self.attn def forward(self, word_input, last_context, last_hidden, encoder_outputs): # Note: we run this one step at a time # Get the embedding of the current input word (last output word) word_embedded = self.embedding(word_input).view(1, 1, -1) # S=1 x B x N # Combine embedded input word and last context, run through RNN rnn_input = torch.cat((word_embedded, last_context.unsqueeze(0)), 2) rnn_output, hidden = self.gru(rnn_input, last_hidden) # Calculate attention from current RNN state and all encoder outputs; apply to encoder outputs attn_weights = self.attn(rnn_output.squeeze(0), encoder_outputs) context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # B x 1 x N # Final output layer (next word prediction) using the RNN hidden state and context vector rnn_output = rnn_output.squeeze(0) # S=1 x B x N -> B x N context = context.squeeze(1) # B x S=1 x N -> B x N output = F.log_softmax(self.out(torch.cat((rnn_output, context), 1))) if USE_CUDA: return output.cuda(), context.cuda(), hidden.cuda(), attn_weights.cuda() else: return output, context, hidden, attn_weights And testing the network: encoder_test = EncoderRNN(10, 10, 2) # I, H , L decoder_test = AttnDecoderRNN('general', 10, 10, 2) # A, H, O, L encoder_hidden = encoder_test.init_hidden() if USE_CUDA: word_inputs = Variable(torch.LongTensor([1, 2, 3]).cuda()) else: word_inputs = Variable(torch.LongTensor([1, 2, 3])) encoder_outputs, encoder_hidden = encoder_test(word_inputs, encoder_hidden) decoder_attns = torch.zeros(1, 3, 3) decoder_hidden = encoder_hidden decoder_context = Variable(torch.zeros(1, decoder_test.hidden_size)) decoder_output, decoder_context, decoder_hidden, decoder_attn = decoder_test(word_inputs[0], decoder_context, decoder_hidden, encoder_outputs) print(decoder_output) print(decoder_hidden) print(decoder_attn) The code works fine on CPU, [out]: EncoderRNN ( (embedding): Embedding(10, 10) (gru): GRU(10, 10, num_layers=2) ) AttnDecoderRNN ( (embedding): Embedding(10, 10) (gru): GRU(20, 10, num_layers=2, dropout=0.1) (out): Linear (20 -> 10) (attn): Attn ( (attn): Linear (10 -> 10) ) ) Variable containing: -2.4378 -2.3556 -2.3391 -2.5070 -2.3439 -2.3415 -2.3976 -2.1832 -1.9976 -2.2213 [torch.FloatTensor of size 1x10] Variable containing: (0 ,.,.) = Columns 0 to 8 -0.2325 0.0775 0.5415 0.4876 -0.5771 -0.0687 0.1832 -0.5285 0.2508 Columns 9 to 9 -0.1837 (1 ,.,.) = Columns 0 to 8 -0.1389 -0.2605 -0.0518 0.3405 0.0774 0.1815 0.0297 -0.1304 -0.1015 Columns 9 to 9 0.2602 [torch.FloatTensor of size 2x1x10] Variable containing: (0 ,.,.) = 0.3334 0.3291 0.3374 [torch.FloatTensor of size 1x1x3] but when changing the flag to USE_GPU=True, it throws the error when initializing the decoder_test object, it throws a TypeError: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-76-b3c660013934> in <module>() 12 decoder_context = Variable(torch.zeros(1, decoder_test.hidden_size)) 13 ---> 14 decoder_output, decoder_context, decoder_hidden, decoder_attn = decoder_test(word_inputs[0], decoder_context, decoder_hidden, encoder_outputs) 15 print(decoder_output) 16 print(decoder_hidden) ~/.local/lib/python3.5/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 222 for hook in self._forward_pre_hooks.values(): 223 hook(self, input) --> 224 result = self.forward(*input, **kwargs) 225 for hook in self._forward_hooks.values(): 226 hook_result = hook(self, input, result) <ipython-input-75-34ecfe9b3112> in forward(self, word_input, last_context, last_hidden, encoder_outputs) 32 33 # Combine embedded input word and last context, run through RNN ---> 34 rnn_input = torch.cat((word_embedded, last_context.unsqueeze(0)), 2) 35 rnn_output, hidden = self.gru(rnn_input, last_hidden) 36 ~/.local/lib/python3.5/site-packages/torch/autograd/variable.py in cat(iterable, dim) 895 @staticmethod 896 def cat(iterable, dim=0): --> 897 return Concat.apply(dim, *iterable) 898 899 @staticmethod ~/.local/lib/python3.5/site-packages/torch/autograd/_functions/tensor.py in forward(ctx, dim, *inputs) 315 ctx.dim = dim 316 ctx.input_sizes = [i.size(dim) for i in inputs] --> 317 return torch.cat(inputs, dim) 318 319 @staticmethod TypeError: cat received an invalid combination of arguments - got (tuple, int), but expected one of: * (sequence[torch.cuda.FloatTensor] seq) * (sequence[torch.cuda.FloatTensor] seq, int dim) didn't match because some of the arguments have invalid types: (tuple, int) The question is why are that types not matching in CUDA but it works on CPU and how to resolve this? Does PyTorch have a global flag to just change all types to CUDA types and not mess around with CPU/GPU types?
You can also try: net = YouNetworkClass() device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") net.to(device) After that, you have to send the word_inputs, encoder_hidden and decoder_context to the GPU too: word_inputs, encoder_hidden, decoder_context = word_inputs.to(device), encoder_hidden.to(device), decoder_context.to(device) Look here: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#training-on-gpu
https://stackoverflow.com/questions/46704352/
RNN is not training (PyTorch)
I can't get what I am doing wrong when training RNN. I am trying to train RNN for AND operation on sequences (to learn how it works on simple task). But my network is not learning, loss stays the same and it can't event overfit the model. Can you please help me to find the problem? Data I am using: data = [ [1, 1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 1], [0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1], [1, 1], [0], [1], [1, 0]] labels = [ 0, 1, 0, 0, 1, 1, 0, 1, 0 ] Code for NN: class AndRNN(nn.Module): def __init__(self): super(AndRNN, self).__init__() self.rnn = nn.RNN(1, 10, 5) self.fc = nn.Sequential( nn.Linear(10, 30), nn.Linear(30, 2) ) def forward(self, input, hidden): x, hidden = self.rnn(input, hidden) x = self.fc(x[-1]) return x, hidden def initHidden(self): return Variable(torch.zeros((5, 1, 10))) Training loop: criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9) correct = 0 for e in range(20): for i in range(len(data)): tensor = torch.FloatTensor(data[i]).view(-1, 1, 1) label = torch.LongTensor([labels[i]]) hidden = net.initHidden() optimizer.zero_grad() out, hidden = net(Variable(tensor), Variable(hidden.data)) _, l = torch.topk(out, 1) if label[0] == l[0].data[0]: correct += 1 loss = criterion(out, Variable(label)) loss.backward() optimizer.step() print("Loss ", loss.data[0], "Accuracy ", (correct / (i + 1))) Shape for tensor will be (sequence_len, 1 (which is batch size), 1), that is correct according to the PyTorch docs for RNN
The problem is this line: out, hidden = net(Variable(tensor), Variable(hidden.data)) It should be simply out, hidden = net(Variable(tensor), hidden) By having Variable(hidden.data) here you are creating a new hidden_state variable (with all zeros) at very step instead of passing the hidden state from the previous state. I tried your example, and changed the optimizer to Adam. There are the complete code. class AndRNN(nn.Module): def __init__(self): super(AndRNN, self).__init__() self.rnn = nn.RNN(1, 10, 5) self.fc = nn.Sequential( nn.Linear(10, 30), nn.Linear(30, 2) ) def forward(self, input, hidden): x, hidden = self.rnn(input, hidden) x = self.fc(x[-1]) return x, hidden def initHidden(self): return Variable(torch.zeros((5, 1, 10))) net = AndRNN() criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(net.parameters()) correct = 0 for e in range(100): for i in range(len(data)): tensor = torch.FloatTensor(data[i]).view(-1, 1, 1) label = torch.LongTensor([labels[i]]) hidden = net.initHidden() optimizer.zero_grad() out, hidden = net(Variable(tensor), hidden) loss = criterion(out, Variable(label)) loss.backward() optimizer.step() if e % 25 == 0: print("Loss ", loss.data[0]) Result Loss 0.6370733976364136 Loss 0.25336754322052 Loss 0.006924811284989119 Loss 0.002351854695007205
https://stackoverflow.com/questions/46705634/
What does the parameter retain_graph mean in the Variable's backward() method?
I'm going through the neural transfer pytorch tutorial and am confused about the use of retain_variable(deprecated, now referred to as retain_graph). The code example show: class ContentLoss(nn.Module): def __init__(self, target, weight): super(ContentLoss, self).__init__() self.target = target.detach() * weight self.weight = weight self.criterion = nn.MSELoss() def forward(self, input): self.loss = self.criterion(input * self.weight, self.target) self.output = input return self.output def backward(self, retain_variables=True): #Why is retain_variables True?? self.loss.backward(retain_variables=retain_variables) return self.loss From the documentation retain_graph (bool, optional) – If False, the graph used to compute the grad will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph. So by setting retain_graph= True, we're not freeing the memory allocated for the graph on the backward pass. What is the advantage of keeping this memory around, why do we need it?
@cleros is pretty on the point about the use of retain_graph=True. In essence, it will retain any necessary information to calculate a certain variable, so that we can do backward pass on it. An illustrative example Suppose that we have a computation graph shown above. The variable d and e is the output, and a is the input. For example, import torch from torch.autograd import Variable a = Variable(torch.rand(1, 4), requires_grad=True) b = a**2 c = b*2 d = c.mean() e = c.sum() when we do d.backward(), that is fine. After this computation, the parts of the graph that calculate d will be freed by default to save memory. So if we do e.backward(), the error message will pop up. In order to do e.backward(), we have to set the parameter retain_graph to True in d.backward(), i.e., d.backward(retain_graph=True) As long as you use retain_graph=True in your backward method, you can do backward any time you want: d.backward(retain_graph=True) # fine e.backward(retain_graph=True) # fine d.backward() # also fine e.backward() # error will occur! More useful discussion can be found here. A real use case Right now, a real use case is multi-task learning where you have multiple losses that maybe be at different layers. Suppose that you have 2 losses: loss1 and loss2 and they reside in different layers. In order to backprop the gradient of loss1 and loss2 w.r.t to the learnable weight of your network independently. You have to use retain_graph=True in backward() method in the first back-propagated loss. # suppose you first back-propagate loss1, then loss2 (you can also do the reverse) loss1.backward(retain_graph=True) loss2.backward() # now the graph is freed, and next process of batch gradient descent is ready optimizer.step() # update the network parameters
https://stackoverflow.com/questions/46774641/
PyTorch: How to get the shape of a Tensor as a list of int
In numpy, V.shape gives a tuple of ints of dimensions of V. In tensorflow V.get_shape().as_list() gives a list of integers of the dimensions of V. In pytorch, V.size() gives a size object, but how do I convert it to ints?
For PyTorch v1.0 and possibly above: >>> import torch >>> var = torch.tensor([[1,0], [0,1]]) # Using .size function, returns a torch.Size object. >>> var.size() torch.Size([2, 2]) >>> type(var.size()) <class 'torch.Size'> # Similarly, using .shape >>> var.shape torch.Size([2, 2]) >>> type(var.shape) <class 'torch.Size'> You can cast any torch.Size object to a native Python list: >>> list(var.size()) [2, 2] >>> type(list(var.size())) <class 'list'> In PyTorch v0.3 and 0.4: Simply list(var.size()), e.g.: >>> import torch >>> from torch.autograd import Variable >>> from torch import IntTensor >>> var = Variable(IntTensor([[1,0],[0,1]])) >>> var Variable containing: 1 0 0 1 [torch.IntTensor of size 2x2] >>> var.size() torch.Size([2, 2]) >>> list(var.size()) [2, 2]
https://stackoverflow.com/questions/46826218/
Pytorch to Keras code equivalence
Given a below code in PyTorch what would be the Keras equivalent? class Network(nn.Module): def __init__(self, state_size, action_size): super(Network, self).__init__() # Inputs = 5, Outputs = 3, Hidden = 30 self.fc1 = nn.Linear(5, 30) self.fc2 = nn.Linear(30, 3) def forward(self, state): x = F.relu(self.fc1(state)) outputs = self.fc2(x) return outputs Is it this? model = Sequential() model.add(Dense(units=30, input_dim=5, activation='relu')) model.add(Dense(units=30, activation='relu')) model.add(Dense(units=3, activation='linear')) or is it this? model = Sequential() model.add(Dense(units=30, input_dim=5, activation='linear')) model.add(Dense(units=30, activation='relu')) model.add(Dense(units=3, activation='linear')) or is it? model = Sequential() model.add(Dense(units=30, input_dim=5, activation='relu')) model.add(Dense(units=30, activation='linear')) model.add(Dense(units=3, activation='linear')) Thanks
None of them looks correct according to my knowledge. A correct Keras equivalent code would be: model = Sequential() model.add(Dense(30, input_shape=(5,), activation='relu')) model.add(Dense(3)) model.add(Dense(30, input_shape=(5,), activation='relu')) Model will take as input arrays of shape (*, 5) and output arrays of shape (*, 30). Instead of input_shape, you can use input_dim also. input_dim=5 is equivalent to input_shape=(5,). model.add(Dense(3)) After the first layer, you don't need to specify the size of the input anymore. Moreover, if you don't specify anything for activation, no activation will be applied (equivalent to linear activation). Another alternative would be: model = Sequential() model.add(Dense(30, input_dim=5)) model.add(Activation('relu')) model.add(Dense(3)) Hopefully this makes sense!
https://stackoverflow.com/questions/46866763/
Indexing one PyTorch tensor by another using index_select
I have a 3 x 3 PyTorch LongTensor that looks something like this: A = [0, 0, 0] [1, 2, 2] [1, 2, 3] I want to us it to index a 4 x 2 FloatTensor like this one: B = [0.4, 0.5] [1.2, 1.4] [0.8, 1.9] [2.4, 2.9] My intended output is the 2 x 3 x 3 FloatTensor below: C[0,:,:] = [0.4, 0.4, 0.4] [1.2, 0.8, 0.8] [1.2, 0.8, 2.4] C[1,:,:] = [0.5, 0.5, 0.5] [1.4, 1.9, 1.9] [1.4, 1.9, 2.9] In other words, matrix A is indexing and broadcasting matrix B. A is the matrix of indices of B, so this operation is essentially an indexing operation. How can this be done using the torch.index_select() function? If the solution involves adding or permuting dimensions, that's fine.
Using index_select() requires that the indexing values are in a vector rather than a tensor. But as long as that is formatted correctly, the function handles the broadcasting for you. The last thing that must be done is reshaping the output, I believe due to the broadcasting. The one-liner that will do this operation successfully is torch.index_select(B, 0, A.view(-1)).view(3,-1,2).permute(2,0,1) A.view(-1) vectorizes the indices matrix. __.view(3,-1,2) reshapes back to the shape of the indexing matrix, but accounting for the new extra dimension of size 2 (as I am indexing an N x 2 matrix). Lastly, __.permute(2,0,1) reshapes the matrix so that the output views each dimension of B in a separate channel (rather than each column).
https://stackoverflow.com/questions/46876131/
How to input a matrix to CNN in pytorch
I'm very new to pytorch and I want to figure out how to input a matrix rather than image into CNN. I have try it in the following way, but some errors occur. I define my dataset as following: class FrameDataSet(tud.Dataset): def __init__(self, data): targets = data['class'].values.tolist() features = data.drop('class', axis=1).astype(np.int64).values self.datalist = features.reshape((-1, feature_num, frame_size)) self.labellist = targets def __getitem__(self, index): return torch.Tensor(self.datalist[index].astype(float)), self.labellist[index] def __len__(self): return self.datalist.shape[0] And my CNN is: self.conv = nn.Sequential( nn.Conv2d(1, 12, 3), nn.ReLU(True), nn.MaxPool2d(3, 3)) self.fc1 = nn.Linear(80, 100) self.fc2 = nn.Linear(100, 30) self.fc3 = nn.Linear(30, 5) But when the data was inputted to CNN, the error brings: File "/home/sparks/anaconda2/lib/python2.7/site-packages/torch/nn/functional.py", line 48, in conv2d raise ValueError("Expected 4D tensor as input, got {}D tensor instead.".format(input.dim())) Expected 4D tensor as input, got 3D tensor instead.
Your input probably missing one dimension. It should be: (batch_size, channels, width, height) If you only have one element in the batch, the tensor have to be in your case e.g (1, 1, 28, 28) because your first conv2d-layer expected a 1-channel input.
https://stackoverflow.com/questions/46901973/
Why detach needs to be called on variable in this example?
I was going through this example - https://github.com/pytorch/examples/blob/master/dcgan/main.py and I have a basic question. fake = netG(noise) label = Variable(label.fill_(fake_label)) output = netD(fake.detach()) # detach to avoid training G on these labels errD_fake = criterion(output, label) errD_fake.backward() D_G_z1 = output.data.mean() errD = errD_real + errD_fake optimizerD.step() I understand that why we call detach() on variable fake, so that no gradients are computed for the Generator parameters. My question is, does it matter since optimizerD.step() is going to update the parameters associated with Discriminator only? OptimizerD is defined as: optimizerD = optim.Adam(netD.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999)) Besides, in the next step when we will update parameters for Generator, before that we will call netG.zero_grad() which eventually removes all previously computed gradients. Moreover, when we update parameters for G network, we do this - output = netD(fake). Here, we are not using detach. Why? So, why detaching the variable (line 3) is necessary in the above code?
ORIGINAL ANSWER (WRONG / INCOMPLETE) You're right, optimizerD only updates netD and the gradients on netG are not used before netG.zero_grad() is called, so detaching is not necessary, it just saves time, because you're not computing gradients for the generator. You're basically also answering your other question yourself, you don't detach fake in the second block because you specifically want to compute gradients on netG to be able to update its parameters. Note how in the second block real_label is used as the corresponding label for fake, so if the discriminator finds the fake input to be real, the final loss is small, and vice versa, which is precisely what you want for the generator. Not sure if that's what confused you, but it's really the only difference compared to training the discriminator on fake inputs. EDIT Please see FatPanda's comment! My original answer is in fact incorrect. Pytorch destroys (parts of) the compute graph when .backward() is called. Without detaching before errD_fake.backward() the errG.backward() call later would not be able to backprop into the generator because the required graph is no longer available (unless you specify retain_graph=True). I'm relieved Soumith made the same mistake :D
https://stackoverflow.com/questions/46944629/
sequence to sequence learning for language translation, what about unseen words
sequence to sequence learning is a powerful mechanism for language translation, especially using it locally in a context specific case. I am following this pytorch tutorial for the task. However, the tutorial did not split the data into training and testing. You might think its not a big deal, just split it up, use one chunk for training and the other for testing. But it is not that simple. Essentially, the tutorial creates the indices of the seen words while leading the dataset. The indices are simply stored in the dictionary. This is before going to the encoder RNN, just a simple conversion kind of task from words to the numbers. If data is split up at random, what happens is, one of the keyword may not appear in the sentences from the training set, and so may not have an index at all. If it shows up at the time of testing, what should be done? Extend the dictionary?
Sequence to sequence models performance strongly depend on count of unique words in vocabulary. Each unique word has to be encountered a number of times in training set, such that model can learn it correct usage. Words that appears few times cannot be used by the model, as model can't learn enough information about such words. In practice, the size of the dictionary is usually reduced, replacing the rare words with a special "UNK" token. Therefore, if a new word occurs during testing, it can be assumed that it is rare (since it never appears in the training set) and replace it with "UNK".
https://stackoverflow.com/questions/46962582/
A proper way to adjust input size of CNN (e.g. VGG)
I want to train VGG on 128x128-sized images. I don't want to rescale them to 224x224 to save GPU-memory and training time. What would be the proper way to do so?
The best way is to keep the convolutional part as it is and replace the fully connected layers. This way it is even possible to take pretrained weights for the convolutional part of the network. The fully connected layers must be randomly initialized. This way one can finetune a network with a smaller input size. Here some pytorch code import torch from torch.autograd import Variable import torchvision import torch.nn as nn from torchvision.models.vgg import model_urls VGG_TYPES = {'vgg11' : torchvision.models.vgg11, 'vgg11_bn' : torchvision.models.vgg11_bn, 'vgg13' : torchvision.models.vgg13, 'vgg13_bn' : torchvision.models.vgg13_bn, 'vgg16' : torchvision.models.vgg16, 'vgg16_bn' : torchvision.models.vgg16_bn, 'vgg19_bn' : torchvision.models.vgg19_bn, 'vgg19' : torchvision.models.vgg19} class Custom_VGG(nn.Module): def __init__(self, ipt_size=(128, 128), pretrained=True, vgg_type='vgg19_bn', num_classes=1000): super(Custom_VGG, self).__init__() # load convolutional part of vgg assert vgg_type in VGG_TYPES, "Unknown vgg_type '{}'".format(vgg_type) vgg_loader = VGG_TYPES[vgg_type] vgg = vgg_loader(pretrained=pretrained) self.features = vgg.features # init fully connected part of vgg test_ipt = Variable(torch.zeros(1,3,ipt_size[0],ipt_size[1])) test_out = vgg.features(test_ipt) self.n_features = test_out.size(1) * test_out.size(2) * test_out.size(3) self.classifier = nn.Sequential(nn.Linear(self.n_features, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, num_classes) ) self._init_classifier_weights() def forward(self, x): x = self.features(x) x = x.view(x.size(0), -1) x = self.classifier(x) return x def _init_classifier_weights(self): for m in self.classifier: if isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01) m.bias.data.zero_() To create a vgg just call this: vgg = Custom_VGG(ipt_size=(128, 128), pretrained=True)
https://stackoverflow.com/questions/46963372/
deep reinforcement learning parameters and training time for a simple game
I want to learn how deep reinforcement algorithm works and what time it takes to train itself for any given environment. I came up with a very simple example of environment: There is a counter which holds an integer between 0 to 100. counting to 100 is its goal. there is one parameter direction whose value can be +1 or -1. it simply show the direction to move. out neural network takes this direction as input and 2 possible action as output. Change the direction Do not change the direction 1st action will simply flip the direction (+1 => -1 or -1 =>+1). 2nd action will keep the direction as it is. I am using python for backend and javascript for frontend. It seems to take too much time, and still it is pretty random. i have used 4 layer perceptron. training rate of 0.001 . memory learning with batch of 100. Code is of Udemy tutorial of Artificial Intelligence and is working properly. My question is, What should be the reward for completion and for each state.? and how much time it is required to train simple example as that.?
In Reinforcement Learning the underlining reward function is what defines the game. Different reward functions lead to different games with different optimal strategies. In your case there are a few different possibilities: Give +1 for reaching 100 and only then. Give +1 for reaching 100 and -0.001 for every time step it is not at 100. Give +1 for going up -1 for going down. The third case is way too easy there is no long term planing involved. In the first too cases the agent will only start learning once it accidentally reaches 100 and sees that it is good. But in the first case once it learns to go up it doesn't matter how long it takes to get there. The second is the most interesting where it needs to get there as fast as possible. There is no right answer for what reward to use, but ultimately the reward you choose defines the game you are playing. Note: 4 layer perceptron for this problem is Big Time Overkill. One layer should be enough (this problem is very simple). Have you tried the reinforcement learning environments at OpenAI's gym? Highly recommend it, they have all the "classical" reinforcement learning problems.
https://stackoverflow.com/questions/46979986/
pip to install Pytorch for usr/bin/python
I have set up Malmo on my mac and got into a trouble. I am using Malmo-0.17.0-Mac-64bit, python 2.7, macOS Sierra. As it is explained on the Malmo installation instruction, mac users require to run the python scripts with the default mac python located on /usr/bin/python. I am aiming to implement a neural nets with Pytorch and doing some experiments. However, when I run the command /usr/bin/python -m pip install http://download.pytorch.org/whl/torch-0.2.0.post3-cp27-none-macosx_10_7_x86_64.whl to install Pytorch I am getting this error: Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/c7/24z_lgxx4b7107ynf4cy34qh0000gn/T/pip-build-kLOmTh/pyyaml/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /var/folders/c7/24z_lgxx4b7107ynf4cy34qh0000gn/T/pip-YxAJnq-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/c7/24z_lgxx4b7107ynf4cy34qh0000gn/T/pip-build-kLOmTh/pyyaml/. I was wondering if anyone has faced the same problem. Many Thanks,
I figured it out what the problem was. It is so stupid. I just needed to add sudo at the beginning of the command.
https://stackoverflow.com/questions/46991226/
Neural network in pytorch predict two binary variables
Suppose I want to have the general neural network architecture: ---> BinaryOutput_A / Input --> nnLayer - \ ---> BinaryOutput_B An input is put through a neural network layer which then goes to predict two binary variables (i.e., A is [0 or 1] and B is [0 or 1]. In pytorch, you can make such a network with: class NN(nn.Module): def __init__(self, inputs): super(NN, self).__init__() # -- first layer self.lin = nn.Linear(inputs,10) # -- firstLayer --> binaryOutputA self.l2a = nn.Linear(10,2) # -- firstLayer --> binaryOutputB self.l2b = nn.Linear(10,2) def forward(self, inputs): o = self.lin(inputs) o1 = F.log_softmax(self.l2a(o)) o2 = F.log_softmax(self.l2b(o)) return o1, o2 In my train function, I calculate the loss with loss = loss_function(output, target). If that's the case, to properly backpropagate the loss to both the l2a and l2b layers using loss.backward(), could I simply concat the target with the proper label for l2a and l2b? In that sense, the output would be [outputPredictionA, outputPredictionB] and I could make the target be [labelA, labelB], Would pytorch know to properly assign the loss to each layer?
It turns out that torch is actually really smart, and you can just calculate the total loss as: loss = 0 loss += loss_function(pred_A, label_A) loss += loss_function(pred_B, label_B) loss.backward() and the error will be properly backpropagated through the network. No torch.cat() needed or anything.
https://stackoverflow.com/questions/47016302/
Cross entropy loss in pytorch nn.CrossEntropyLoss()
maybe someone is able to help me here. I am trying to compute the cross entropy loss of a given output of my network print output Variable containing: 1.00000e-02 * -2.2739 2.9964 -7.8353 7.4667 4.6921 0.1391 0.6118 5.2227 6.2540 -7.3584 [torch.FloatTensor of size 1x10] and the desired label, which is of the form print lab Variable containing: x [torch.FloatTensor of size 1] where x is an integer between 0 and 9. According to the pytorch documentation (http://pytorch.org/docs/master/nn.html) criterion = nn.CrossEntropyLoss() loss = criterion(output, lab) this should work, but unfortunately I get a weird error TypeError: FloatClassNLLCriterion_updateOutput received an invalid combination of arguments - got (int, torch.FloatTensor, !torch.FloatTensor!, torch.FloatTensor, bool, NoneType, torch.FloatTensor, int), but expected (int state, torch.FloatTensor input, torch.LongTensor target, torch.FloatTensor output, bool sizeAverage, [torch.FloatTensor weights or None], torch.FloatTensor total_weight, int ignore_index) Can anyone help me? I am really confused and tried almost everything I could imagined to be helpful. Best
Please check this code import torch import torch.nn as nn from torch.autograd import Variable output = Variable(torch.rand(1,10)) target = Variable(torch.LongTensor([1])) criterion = nn.CrossEntropyLoss() loss = criterion(output, target) print(loss) This will print out the loss nicely: Variable containing: 2.4498 [torch.FloatTensor of size 1]
https://stackoverflow.com/questions/47065172/
Elegant way to compare to torch.FloatTensor on GPU
I try to compare two torch.FloatTensor (with only one entry) lying on GPU like this: if (FloatTensor_A > FloatTensor_B): do something The problem is, that (FloatTensor_A > FloatTensor_B) gives ByteTensor back. Is there a way to do boolean comparison between these two scalar FloatTensors, without loading the tensors on CPU and converting them back to numpy or conventional floats?
The comparison operations in PyTorch return ByteTensors (see docs). In order to convert your result back to a float datatype, you can call .float() on your result. For example: (t1 > t2).float() (t1 > t2) will return a ByteTensor. The inputs to the operation must be on the same memory (either CPU or GPU). The return result will be on the same memory. Of course, any Tensor can be moved to the respective memory by callin .cpu() or .cuda() on it.
https://stackoverflow.com/questions/47096651/
How do I use a ByteTensor in a contrastive cosine loss function?
I'm trying to implement the loss function in http://anthology.aclweb.org/W16-1617 in PyTorch. It is shown as follows: I've implemented the loss as follows: class CosineContrastiveLoss(nn.Module): """ Cosine contrastive loss function. Based on: http://anthology.aclweb.org/W16-1617 Maintain 0 for match, 1 for not match. If they match, loss is 1/4(1-cos_sim)^2. If they don't, it's cos_sim^2 if cos_sim < margin or 0 otherwise. Margin in the paper is ~0.4. """ def __init__(self, margin=0.4): super(CosineContrastiveLoss, self).__init__() self.margin = margin def forward(self, output1, output2, label): cos_sim = F.cosine_similarity(output1, output2) loss_cos_con = torch.mean((1-label) * torch.div(torch.pow((1.0-cos_sim), 2), 4) + (label) * torch.pow(cos_sim * torch.lt(cos_sim, self.margin), 2)) return loss_cos_con However, I'm getting an error saying: TypeError: mul received an invalid combination of arguments - got (torch.cuda.ByteTensor), but expected one of: * (float value) didn't match because some of the arguments have invalid types: (torch.cuda.ByteTensor) * (torch.cuda.FloatTensor other) didn't match because some of the arguments have invalid types: (torch.cuda.ByteTensor) I know that torch.lt() returns a ByteTensor, but if I try to coerce it to a FloatTensor with torch.Tensor.float() I get AttributeError: module 'torch.autograd.variable' has no attribute 'FloatTensor'. I'm really not sure where to go from here. It seems logical to me to do an element-wise multiplication between the cosine similarity tensor and a tensor with 0 or 1 based on a less-than rule.
Maybe you can try float() method on the variable directly? Variable(torch.zeros(5)).float() - works for me, for instance
https://stackoverflow.com/questions/47107589/
Upsampling in Semantic Segmentation
I am trying to implement a paper on Semantic Segmentation and I am confused about how to Upsample the prediction map produced by my segmentation network to match the input image size. For example, I am using a variant of Resnet101 as the segmentation network (as used by the paper). With this network structure, an input of size 321x321 (again used in the paper) produces a final prediction map of size 41x41xC (C is the number of classes). Because I have to make pixel-level predictions, I need to upsample it to 321x321xC. Pytorch provides function to Upsample to an output size which is a multiple of the prediction map size. So, I can not directly use that method here. Because this step is involved in every semantic segmentation network, I am sure there should be a standard way to implement this. I would appreciate any pointers. Thanks in advance.
Maybe the simpliest thing you can try is: upsample 8 times. Then you 41x41 input turns into 328x328 perform center cropping to get your desired shape 321x321 (for instance, something like this input[3:,3:,:-4,:-4])
https://stackoverflow.com/questions/47117302/
how to calculate loss over a number of images and then back propagate the average loss and update network weight
I am doing a task where the batch size is 1, i.e, each batch contains only 1 image. So I have to do manual batching: when the the number of accumulated losses reach a number, average the loss and then do back propagation. My original code is: real_batchsize = 200 for epoch in range(1, 5): net.train() total_loss = Variable(torch.zeros(1).cuda(), requires_grad=True) iter_count = 0 for batch_idx, (input, target) in enumerate(train_loader): input, target = Variable(input.cuda()), Variable(target.cuda()) output = net(input) loss = F.nll_loss(output, target) total_loss = total_loss + loss if batch_idx % real_batchsize == 0: iter_count += 1 ave_loss = total_loss/real_batchsize ave_loss.backward() optimizer.step() if iter_count % 10 == 0: print("Epoch:{}, iteration:{}, loss:{}".format(epoch, iter_count, ave_loss.data[0])) total_loss.data.zero_() optimizer.zero_grad() This code will give the error message RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time. I have tried the following way, First way (failed) I read some post about this error message, but can not understand it fully. Change ave_loss.backward() to ave_loss.backward(retain_graph=True) prevent the error message, but the loss doesn't improve the soon becomes nan. Second way (failed) I also tried to change total_loss = total_loss + loss.data[0], this will also prevent the error message. But the loss are always the same. So there must be something wrong. Third way (success) Following the instruction in this post, for each image's loss,I divide the loss by real_batchsize and backprop it. When the number of input image reach the real_batchsize, I do one update of parameter using optimizer.step(). The loss is slowly decreasing as the training process goes. But the training speed is really slow, because we backprop for each image. My question What does the error message mean in my case? Also, why doesn't first way and second way work? How to write the code correctly so that we can backprop gradient every real_batchsize images and update gradient once so that the training speed a faster? I know my code is nearly correct, but I just do not know how to change it.
The problem you encounter here is related to how PyTorch accumulates gradients over different passes. (see here for another post on a similar question) So let's have a look at what happens when you have code of the following form: loss_total = Variable(torch.zeros(1).cuda(), requires_grad=True) for l in (loss_func(x1,y1), loss_func(x2, y2), loss_func(x3, y3), loss_func(x4, y4)): loss_total = loss_total + l loss_total.backward() Here, we do a backward pass when loss_total has the following values over the different iterations: total_loss = loss(x1, y1) total_loss = loss(x1, y1) + loss(x2, y2) total_loss = loss(x1, y1) + loss(x2, y2) + loss(x3, y3) total_loss = loss(x1, y1) + loss(x2, y2) + loss(x3, y3) + loss(x4, y4) so when you call .backward() on total_loss each time, you actually call .backward() on loss(x1, y1) four times! (and on loss(x2, y2) three times, etc). Combine that with what is discussed in the other post, namely that to optimize memory usage, PyTorch will free the graph attached to a Variable when calling .backward() (and thereby destroying the gradients connecting x1 to y1, x2 to y2, etc), you can see what the error message means - you try to do backward passes over a loss for several times, but the underlying graph was freed up after the first pass. (unless to specify retain_graph=True, of course) As for the specific variations you have tried: First way: here, you will accumulate (i.e. sum up - again, see the other post) gradients forever, with them (potentially) adding up to inf. Second way: here, you convert loss to a tensor by doing loss.data, removing the Variable wrapper, and thereby deleting the gradient information (since only Variables hold gradients). Third way: here, you only do one pass through each xk, yk tuple, since you immediately do a backprop step, avoiding the above problem alltogether. SOLUTION: I have not tested it, but from what I gather, the solution should be pretty straightforward: create a new total_loss object at the beginning of each batch, then sum all of the losses into that object, and then do one final backprop step at the end.
https://stackoverflow.com/questions/47120126/
Calculating input and output size for Conv2d in PyTorch for image classification
I'm trying to run the PyTorch tutorial on CIFAR10 image classification here - http://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py I've made a small change and I'm using a different dataset. I have images from the Wikiart dataset that I want to classify by artist (label = artist name). Here is the code for the Net - class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16*5*5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16*5*5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x Then there is this section of the code where I start training the Net. for epoch in range(2): running_loss = 0.0 for i, data in enumerate(wiki_train_dataloader, 0): inputs, labels = data['image'], data['class'] print(inputs.shape) inputs, labels = Variable(inputs), Variable(labels) optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.data[0] if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0 This line print(inputs.shape) gives me torch.Size([4, 32, 32, 3]) with my Wikiart dataset whereas in the original example with CIFAR10, it prints torch.Size([4, 3, 32, 32]). Now, I'm not sure how to change the Conv2d in my Net to be compatible with torch.Size([4, 32, 32, 3]). I get this error: RuntimeError: Given input size: (3 x 32 x 3). Calculated output size: (6 x 28 x -1). Output size is too small at /opt/conda/conda-bld/pytorch_1503965122592/work/torch/lib/THNN/generic/SpatialConvolutionMM.c:45 While reading the images for the Wikiart dataset, I resize them to (32, 32) and these are 3-channel images. Things I tried: 1) The CIFAR10 tutorial uses a transform which I am not using. I could not incorporate the same into my code. 2) Changing self.conv2 = nn.Conv2d(6, 16, 5) to self.conv2 = nn.Conv2d(3, 6, 5). This gave me the same error as above. I was only changing this to see if the error message changes. Any resources on how to calculate input & output sizes in PyTorch or automatically reshape Tensors would be really appreciated. I just started learning Torch & I find the size calculations complicated.
You have to shape your input to this format (Batch, Number Channels, height, width). Currently you have format (B,H,W,C) (4, 32, 32, 3), so you need to swap 4th and 2nd axis to shape your data with (B,C,H,W). You can do it this way: inputs, labels = Variable(inputs), Variable(labels) inputs = inputs.transpose(1,3) ... the rest
https://stackoverflow.com/questions/47128044/
Error reading images with pandas (+pyTorch,scikit)
I'm trying to read images to work with a CNN, but I'm getting a pandas error while trying to load the images. This is some of the code (omitted imports and irrelevant nn class for clarity): file_name = "annotation.csv" image_files = pd.read_csv(file_name) class SimpsonsDataset(Dataset): def __init__(self, csv_file, root_dir, transform=None): self.image_file = pd.read_csv(csv_file) self.root_dir = root_dir self.transform = transform def __len__(self): return len(self.image_file) def __getitem__(self, idx): img_name = os.path.join(self.root_dir, self.image_file.iloc[idx,0][1:]) image = io.imread(img_name) sample = {'image': image} if self.transform: sample = self.transform(sample) return sample simpsons = SimpsonsDataset(csv_file=image_files,root_dir="folder/") I use the iloc[idx,0][1:] to format the filepath, and the filepath is joined, with the folders and filenames matching. However, when I try to run the file, I get the following error: File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 710, in runfile execfile(filename, namespace) File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 101, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/.../image_extractor.py", line 41, in <module> simpsons = SimpsonsDataset(csv_file=image_files,root_dir="folder/") File "C:/.../image_extractor.py", line 26, in __init__ self.image_file = pd.read_csv(csv_file) File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 655, in parser_f return _read(filepath_or_buffer, kwds) File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 392, in _read filepath_or_buffer, encoding, compression) File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\common.py", line 210, in get_filepath_or_buffer raise ValueError(msg.format(_type=type(filepath_or_buffer))) ValueError: Invalid file path or buffer object type: <class 'pandas.core.frame.DataFrame'> Would love some insights on why this is happening. Thanks!
Your variable image_files is a pandas DataFrame, since it holds the return value of pd.read_csv(), which returns a DataFrame. Try deleting the line image_files = pd.read_csv(file_name) and changing the last line to this: simpsons = SimpsonsDataset(csv_file=file_name, root_dir="folder/")
https://stackoverflow.com/questions/47145683/
pytorch: Convert a tuple of FloatTensors into a numpy array
I just got a torchvision.datasets object with MNIST data train_dataset= dsets.MNIST(root='./data',train=True,transform=transforms.ToTensor(),download=True) I want to convert this tuple into a set of numpy arrays of shape 60000x28x28 and labels of 60000 I know that the form that the data is provided, can be directly applied into a pytorch neuron in order to be used as training data, but I would like to convert this data into numpy arrays. the first thing I did was to divide the tuples of (data,labels) with zip(*train_dataset) data,labels = zip(*train_dataset) labels is easy to convert into a numpy array, however I have not been able to convert "data" into a numpy array the way I would like. When I try to convert all of the data into numpy.array like data[:].numpy() I receive an error telling me 'tuple' object has no attribute 'numpy'. and if I convert this data[:] into numpy, just the first dimension (the 60000 data) is converted into numpy.array but the rest remains as Tensors. I can convert all of the data using a loop (actually I did it) and it works, however it is really slow. Has anyone done any conversion like this before? Thanks.
Maybe something like this will work for you: train_dataset.train_data.numpy() #contains (60000, 28, 28) numpy array train_dataset.train_labels.numpy() # contains labels
https://stackoverflow.com/questions/47146768/
Pytorch-tutorial: Strange input argument in class definition
I'm reading through some pytorch tutorials. Below is the definition of a residual block. However in the forward method each function handle only takes one argument out while in the __init__ function these functions have different number of input arguments: # Residual Block class ResidualBlock(nn.Module): def __init__(self, in_channels, out_channels, stride=1, downsample=None): super(ResidualBlock, self).__init__() self.conv1 = conv3x3(in_channels, out_channels, stride) self.bn1 = nn.BatchNorm2d(out_channels) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(out_channels, out_channels) self.bn2 = nn.BatchNorm2d(out_channels) self.downsample = downsample def forward(self, x): residual = x out = self.conv1(x) out = self.bn1(out) out = self.relu(out) out = self.conv2(out) out = self.bn2(out) if self.downsample: residual = self.downsample(x) out += residual out = self.relu(out) return out Does anyone know how this works? Is it a standard python class inheritance feature or is this specific to pytorch?
you define the layer in the init function, which means the parameters. In the forward function you only input the data that needs to be processed with the predefined settings from init. The nn.whatever builds a function with the settings you pass to it. Then this function can be used in forward and this function only takes one argument.
https://stackoverflow.com/questions/47151826/
Pytorch Tensor help in LongTensor
a=[1,2,3]; context_var = autograd.Variable(torch.LongTensor(a)) This is giving an error RuntimeError: tried to construct a tensor from a int sequence, but found an item of type numpy.int32 at index I am not able to figure out how to get over this.
Your code works perfectly fine in the recent version of pytorch. But for older versions, you can convert the numpy array to list using .tolist() method as follows to get rid of the error. a=[1,2,3]; context_var = autograd.Variable(torch.LongTensor(a.tolist()))
https://stackoverflow.com/questions/47194626/
How to do fully connected batch norm in PyTorch?
torch.nn has classes BatchNorm1d, BatchNorm2d, BatchNorm3d, but it doesn't have a fully connected BatchNorm class? What is the standard way of doing normal Batch Norm in PyTorch?
Ok. I figured it out. BatchNorm1d can also handle Rank-2 tensors, thus it is possible to use BatchNorm1d for the normal fully-connected case. So for example: import torch.nn as nn class Policy(nn.Module): def __init__(self, num_inputs, action_space, hidden_size1=256, hidden_size2=128): super(Policy, self).__init__() self.action_space = action_space num_outputs = action_space self.linear1 = nn.Linear(num_inputs, hidden_size1) self.linear2 = nn.Linear(hidden_size1, hidden_size2) self.linear3 = nn.Linear(hidden_size2, num_outputs) self.bn1 = nn.BatchNorm1d(hidden_size1) self.bn2 = nn.BatchNorm1d(hidden_size2) def forward(self, inputs): x = inputs x = self.bn1(F.relu(self.linear1(x))) x = self.bn2(F.relu(self.linear2(x))) out = self.linear3(x) return out
https://stackoverflow.com/questions/47197885/
Embedding 3D data in Pytorch
I want to implement character-level embedding. This is usual word embedding. Word Embedding Input: [ [‘who’, ‘is’, ‘this’] ] -> [ [3, 8, 2] ] # (batch_size, sentence_len) -> // Embedding(Input) # (batch_size, seq_len, embedding_dim) This is what i want to do. Character Embedding Input: [ [ [‘w’, ‘h’, ‘o’, 0], [‘i’, ‘s’, 0, 0], [‘t’, ‘h’, ‘i’, ‘s’] ] ] -> [ [ [2, 3, 9, 0], [ 11, 4, 0, 0], [21, 10, 8, 9] ] ] # (batch_size, sentence_len, word_len) -> // Embedding(Input) # (batch_size, sentence_len, word_len, embedding_dim) -> // sum each character embeddings # (batch_size, sentence_len, embedding_dim) The final output shape is same as Word embedding. Because I want to concat them later. Although I tried it, I am not sure how to implement 3-D embedding. Do you know how to implement such a data? def forward(self, x): print('x', x.size()) # (N, seq_len, word_len) bs = x.size(0) seq_len = x.size(1) word_len = x.size(2) embd_list = [] for i, elm in enumerate(x): tmp = torch.zeros(1, word_len, self.embd_size) for chars in elm: tmp = torch.add(tmp, 1.0, self.embedding(chars.unsqueeze(0))) Above code got an error because output of self.embedding is Variable. TypeError: torch.add received an invalid combination of arguments - got (torch.FloatTensor, float, Variable), but expected one of: * (torch.FloatTensor source, float value) * (torch.FloatTensor source, torch.FloatTensor other) * (torch.FloatTensor source, torch.SparseFloatTensor other) * (torch.FloatTensor source, float value, torch.FloatTensor other) didn't match because some of the arguments have invalid types: (torch.FloatTensor, float, Variable) * (torch.FloatTensor source, float value, torch.SparseFloatTensor other) didn't match because some of the arguments have invalid types: (torch.FloatTensor, float, Variable) Update I could do this. But for is not effective for batch. Do you guys know more efficient way? def forward(self, x): print('x', x.size()) # (N, seq_len, word_len) bs = x.size(0) seq_len = x.size(1) word_len = x.size(2) embd = Variable(torch.zeros(bs, seq_len, self.embd_size)) for i, elm in enumerate(x): # every sample for j, chars in enumerate(elm): # every sentence. [ [‘w’, ‘h’, ‘o’, 0], [‘i’, ‘s’, 0, 0], [‘t’, ‘h’, ‘i’, ‘s’] ] chars_embd = self.embedding(chars.unsqueeze(0)) # (N, word_len, embd_size) [‘w’,‘h’,‘o’,0] chars_embd = torch.sum(chars_embd, 1) # (N, embd_size). sum each char's embedding embd[i,j] = chars_embd[0] # set char_embd as word-like embedding x = embd # (N, seq_len, embd_dim) Update2 This is my final code. Thank you, Wasi Ahmad! def forward(self, x): # x: (N, seq_len, word_len) input_shape = x.size() bs = x.size(0) seq_len = x.size(1) word_len = x.size(2) x = x.view(-1, word_len) # (N*seq_len, word_len) x = self.embedding(x) # (N*seq_len, word_len, embd_size) x = x.view(*input_shape, -1) # (N, seq_len, word_len, embd_size) x = x.sum(2) # (N, seq_len, embd_size) return x
I am assuming you have a 3d tensor of shape BxSxW where: B = Batch size S = Sentence length W = Word length And you have declared embedding layer as follows. self.embedding = nn.Embedding(dict_size, emsize) Where: dict_size = No. of unique characters in the training corpus emsize = Expected size of embeddings So, now you need to convert the 3d tensor of shape BxSxW to a 2d tensor of shape BSxW and give it to the embedding layer. emb = self.embedding(input_rep.view(-1, input_rep.size(2))) The shape of emb will be BSxWxE where E is the embedding size. You can convert the resulting 3d tensor to a 4d tensor as follows. emb = emb.view(*input_rep.size(), -1) The final shape of emb will be BxSxWxE which is what you are expecting.
https://stackoverflow.com/questions/47205762/
How to get the value of a feature in a layer that match a the state dict in PyTorch?
I have some cnn, and I want to fetch the value of some intermediate layer corresponding to a some key from the state dict. How could this be done? Thanks.
I think you need to create a new class that redefines the forward pass through a given model. However, most probably you will need to create the code regarding the architecture of your model. You can find here an example: class extract_layers(): def __init__(self, model, target_layer): self.model = model self.target_layer = target_layer def __call__(self, x): return self.forward(x) def forward(self, x): module = self.model._modules[self.target_layer] # get output of the desired layer features = module(x) # get output of the whole model x = self.model(x) return x, features model = models.vgg19(pretrained=True) target_layer = 'features' extractor = extract_layers(model, target_layer) image = Variable(torch.randn(1, 3, 244, 244)) x, features = extractor(image) In this case, I am using the pre-defined vgg19 network given in the pytorch models zoo. The network has the layers structured in two modules the features for the convolutional part and the classifier for the fully-connected part. In this case, since features wraps all the convolutional layers of the network it is straightforward. If your architecture has several layers with different names, you will need to store their output using something similar to this: for name, module in self.model._modules.items(): x = module(x) # forward the module individually if name in self.target_layer: features = x # store the output of the desired layer Also, you should keep in mind that you need to reshape the output of the layer that connects the convolutional part to the fully-connected one. It should be easy to do if you know the name of that layer.
https://stackoverflow.com/questions/47260715/
Pytorch FloatClassNLLCriterion_updateOutput error
I am getting the following error message while computing the loss of my neural net: TypeError: FloatClassNLLCriterion_updateOutput received an invalid combination of arguments - got (int, torch.FloatTensor, !torch.FloatTensor!, torch.FloatTensor, bool, NoneType, torch.FloatTensor, int), but expected (int state, torch.FloatTensor input, torch.LongTensor target, torch.FloatTensor output, bool sizeAverage, [torch.FloatTensor weights or None], torch.FloatTensor total_weight, int ignore_index) on this line: loss = criterion(outputs,one_hot_target). I have tried several things and searched the web, but I can't seem to find my mistake. Does someone have an idea? The code used: class Net(nn.Module): def _init_(self,input_size,hidden_size, num_classes): super(Net, self)._init_() self.l1 = nn.Linear(input_size,hidden_size) self.l2 = nn.Linear(hidden_size,num_classes) def forward(self,x): x = self.l1(x) x = F.tanh(x) x = self.l2(x) x = F.softmax(x) return x mlp = Net(input_size,hidden_size,num_classes) criterion = nn.NLLLoss() optimizer = torch.optim.SGD(mlp.parameters(), lr=learning_rate) for i in range(N-1,len(word_list)): # Define input vector x x = None for j in range(0,N-1): try: x = np.r_[x,w2v[word_list[j]]] except: x = w2v[word_list[j-N+1]] # Done with defining x np.reshape(x,(len(x),1)) x = autograd.Variable(torch.FloatTensor(x)) optimizer.zero_grad() outputs = mlp(x) outputs = outputs.unsqueeze(0) outputs = outputs.transpose(0,1) index = w2i[word_list[i]] one_hot_target = np.zeros([num_classes,1],dtype=float) one_hot_target[index] = float(1) one_hot_target = autograd.Variable(torch.Tensor(one_hot_target)) print (one_hot_target) loss = criterion(outputs,one_hot_target) #loss.backward() #optimizer.step()
The target tensor you are passing to your loss function is of type Float Tensor. That's happening here: one_hot_target = autograd.Variable(torch.Tensor(one_hot_target)) That is, because the default Tensor type in PyTorch is FloatTensor. However, the NLLLoss() function is expecting a LongTensor as target. You can double check in the example in the documentation, which you can find here: NLLLoss Pytorch docs. You can simply convert your target Tensor to a LongTensor like this: one_hot_target = autograd.Variable(torch.Tensor(one_hot_target)).long()
https://stackoverflow.com/questions/47267293/
How to generate a new Tensor with different vectors in PyTorch?
I want to generate new a○b vector with a and b (○ means element wise multiply). My code is below, but the performance looks bad because of for. Are there any efficient way? a = torch.rand(batch_size, a_len, hid_dim) b = torch.rand(batch_size, b_len, hid_dim) # a_elmwise_mul_b = torch.zeros(batch_size, a_len, b_len, hid_dim) for sample in range(batch_size): for ai in range(a_len): for bi in range(b_len): a_elmwise_mul_b[sample, ai, bi] = torch.mul(a[sample, ai], b[sample, bi]) Update I updated my code refer to Ahmad! Thank you. N = 16 hid_dim = 50 a_seq_len = 10 b_seq_len = 20 a = torch.randn(N, a_seq_len, hid_dim) b = torch.randn(N, b_seq_len, hid_dim) shape = (N, a_seq_len, b_seq_len, hid_dim) a_dash = a.unsqueeze(2) # (N, a_len, 1, hid_dim) b_dash = b.unsqueeze(1) # (N, 1, b_len, hid_dim) a_dash = a_dash.expand(shape) b_dash = b_dash.expand(shape) print(a_dash.size(), b_dash.size()) mul = a_dash * b_dash print(mul.size()) ---------- torch.Size([16, 10, 20, 50]) torch.Size([16, 10, 20, 50]) torch.Size([16, 10, 20, 50])
From your problem definition, it looks like you want to multiply two tensors, say A and B of shape AxE and BxE and want to get a tensor of shape AxBxE. It means you want to multiply, each row of tensor A with the whole tensor B. If it is correct, then we don't call it element-wise multiplication. You can accomplish your goal as follows. import torch # batch_size = 16, a_len = 10, b_len = 20, hid_dim = 50 a = torch.rand(16, 10, 50) b = torch.rand(16, 20, 50) c = a.unsqueeze(2).expand(*a.size()[:-1], b.size(1), a.size()[-1]) d = b.unsqueeze(1).expand(b.size()[0], a.size(1), *b.size()[1:]) print(c.size(), d.size()) print(c.size(), d.size()) mul = c * d # shape of c, d: 16 x 10 x 20 x 50 print(mul.size()) # 16 x 10 x 20 x 50 Here, mul tensor is your desired result. Just to clarify, the above two lines realted to c and d computation, are equivalent to: c = a.unsqueeze(2).expand(a.size(0), a.size(1), b.size(1), a.size(2)) d = b.unsqueeze(1).expand(b.size(0), a.size(1), b.size(1), b.size(2))
https://stackoverflow.com/questions/47267433/
Assign torch.cuda.FloatTensor
I'd like to know how can I do the following code, but now using pytorch, where dtype = torch.cuda.FloatTensor. There's the code straight python (using numpy): import numpy as np import random as rand xmax, xmin = 5, -5 pop = 30 x = (xmax-xmin)*rand.random(pop,1) y = x**2 [minz, indexmin] = np.amin(y), np.argmin(y) best = x[indexmin] This is my attempt to do it: import torch dtype = torch.cuda.FloatTensor def fit (position): return position**2 def main(): pop = 30 xmax, xmin = 5, -5 x= (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin y = fit(x) [miny, indexmin] = torch.min(y,0) best = x[indexmin] print(best) The last part where I define the variable best as the value of x with index equal to indexmin it doesn't work. What am I doing wrong here. The following messenge appears: RuntimeError: expecting vector of indices at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/THC/generic/THCTensorIndex.cu:405
The above code works fine in pytorch 0.2. Let me analyze your code so that you can identify the problem. x= (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin y = fit(x) Here, x and y is a 2d tensor of shape 30x1. In the next line: [miny, indexmin] = torch.min(y,0) The returned tensor miny is a 2d tensor of shape 30x1 and indexmin is a 1d tensor of size 1. So, when you execute: best = x[indexmin] It (probably) gives error (in old pytorch version) because x is a 2d tensor of shape 30x1 and indexmin is a 1d tensor of size 1. To resolve this error, you can simply do: best = x.squeeze()[indexmin] # x.squeeze() returns a 1d tensor of size `30` Please note, a 2d tensor of shape 30x1 is same as a 1d tensor of size 30. So, you can modify your program as follows. import torch dtype = torch.cuda.FloatTensor def main(): pop, xmax, xmin = 30, 5, -5 x= (xmax-xmin)*torch.rand(pop).type(dtype)+xmin y = torch.pow(x, 2) minz, indexmin = y.min(0) best = x[indexmin] print(best) main()
https://stackoverflow.com/questions/47267612/
Assign variable in pytorch
I'd like to know if it is possble to the following code, but now using pytorch, where dtype = torch.cuda.FloatTensor. There's the code straight python (using numpy): Basically I want to get the value of x that produces the min value of fitness. import numpy as np import random as rand xmax, xmin = 5, -5 pop = 30 x = (xmax-xmin)*rand.random(pop,1) y = x**2 [minz, indexmin] = np.amin(y), np.argmin(y) best = x[indexmin] This is my attempt to do it: import torch dtype = torch.cuda.FloatTensor def fit (x): return x**2 def main(): pop = 30 xmax, xmin = 5, -5 x = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin y = fit(x) [miny, indexmin] = torch.min(y,0) best = x[indexmin] main() The last part where I define the variable best as the value of x with index equal to indexmin it doesn't work. What am I doing wrong here. The following messenge appears: RuntimeError: expecting vector of indices at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/THC/generic/THCTensorIndex.cu:405
You can simply do as follows. import torch dtype = torch.cuda.FloatTensor def main(): pop, xmax, xmin = 30, 5, -5 x = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin y = torch.pow(x, 2) [miny, indexmin] = y.min(0) best = x.squeeze()[indexmin] # squeeze x to make it 1d main()
https://stackoverflow.com/questions/47271631/
Add a constant variable to a cuda.FloatTensor
I have two question: 1) I'd like to know how can I add/subtract a constante torch.FloatTensor of size 1 to all of the elemets of a torch.FloatTensor of size 30. 2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each). My code: import torch dtype = torch.cuda.FloatTensor def main(): pop, xmax, xmin = 30, 5, -5 x = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin y = torch.pow(x, 2) [miny, indexmin] = y.min(0) gxbest = x[indexmin] pxbest = x pybest = y v = torch.rand(pop) vnext = torch.rand()*v + torch.rand()*(pxbest - x) + torch.rand()*(gxbest - x) main() What is the best way to do it? I think I should so how convert the gxbest into a torch.FloatTensor of size 30 but how can I do that? I've try to create a vector: Variable(torch.from_numpy(np.ones(pop)))*gxbest But it did not work. The multiplication is not working also. RuntimeError: inconsistent tensor size Thank you all for your help!
1) How can I add/subtract a constant torch.FloatTensor of size 1 to all of the elements of a torch.FloatTensor of size 30? You can do it directly in pytorch 0.2. import torch a = torch.randn(30) b = torch.randn(1) print(a-b) In case if you get any error due to size mismatch, you can make a small change as follows. print(a-b.expand(a.size(0))) # to make both a and b tensor of same shape 2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each)? In pytorch 0.2, you can do it directly as well. import torch a = torch.randn(30) b = torch.randn(1) print(a*b) In case, if you get an error due to size mismatch, do as follows. print(a*b.expand(a.size(0))) So, in your case you can simply change the size of gxbest tensor from 1 to 30 as follows. gxbest = gxbest.expand(30)
https://stackoverflow.com/questions/47273868/
How to `dot` weights to batch data in PyTorch?
I have batch data and want to dot() to the data. W is trainable parameters. How to dot between batch data and weights? hid_dim = 32 data = torch.randn(10, 2, 3, hid_dim) data = data.view(10, 2*3, hid_dim) W = torch.randn(hid_dim) # assume trainable parameters via nn.Parameter result = torch.bmm(data, W).squeeze() # error, want (N, 6) result = result.view(10, 2, 3) Update How about this one? hid_dim = 32 data = torch.randn(10, 2, 3, hid_dim) data = tdata.view(10, 2*3, hid_dim) W = torch.randn(hid_dim, 1) # assume trainable parameters via nn.Parameter W = W.unsqueeze(0).expand(10, hid_dim, 1) result = torch.bmm(data, W).squeeze() # error, want (N, 6) result = result.view(10, 2, 3)
Expand W tensor to match the shape of data tensor. The following should work. hid_dim = 32 data = torch.randn(10, 2, 3, hid_dim) data = data.view(10, 2*3, hid_dim) W = torch.randn(hid_dim) W = W.unsqueeze(0).unsqueeze(0).expand(*data.size()) result = torch.sum(data * W, 2) result = result.view(10, 2, 3) Edit: Your updated code is correct. Since you are converting W to a Bxhid_dimx1 and your data is of shape Bxdxhid_dim, so doing batch matrix multiplication will result in Bxdx1 which is essentially the dot product between W parameter and all the row vectors in data (dxhid_dim).
https://stackoverflow.com/questions/47274655/
Generating new images with PyTorch
I am studying GANs I've completed the one course which gave me an example of a program that generates images based on examples inputed. The example can be found here: https://github.com/davidsonmizael/gan So I decided to use that to generate new images based on a dataset of frontal photos of faces, but I am not having any success. Differently from the example above, the code only generates noise, while the input has actual images. Actually I don't have any clue about what should I change to make the code point to the right direction and learn from images. I haven't change a single value on the code provided in the example, yet it does not work. If anyone can help me understand this and point me to the right direction would be very helpful. Thanks in advance. My Discriminator: class D(nn.Module): def __init__(self): super(D, self).__init__() self.main = nn.Sequential( nn.Conv2d(3, 64, 4, 2, 1, bias = False), nn.LeakyReLU(0.2, inplace = True), nn.Conv2d(64, 128, 4, 2, 1, bias = False), nn.BatchNorm2d(128), nn.LeakyReLU(0.2, inplace = True), nn.Conv2d(128, 256, 4, 2, 1, bias = False), nn.BatchNorm2d(256), nn.LeakyReLU(0.2, inplace = True), nn.Conv2d(256, 512, 4, 2, 1, bias = False), nn.BatchNorm2d(512), nn.LeakyReLU(0.2, inplace = True), nn.Conv2d(512, 1, 4, 1, 0, bias = False), nn.Sigmoid() ) def forward(self, input): return self.main(input).view(-1) My Generator: class G(nn.Module): def __init__(self): super(G, self).__init__() self.main = nn.Sequential( nn.ConvTranspose2d(100, 512, 4, 1, 0, bias = False), nn.BatchNorm2d(512), nn.ReLU(True), nn.ConvTranspose2d(512, 256, 4, 2, 1, bias = False), nn.BatchNorm2d(256), nn.ReLU(True), nn.ConvTranspose2d(256, 128, 4, 2, 1, bias = False), nn.BatchNorm2d(128), nn.ReLU(True), nn.ConvTranspose2d(128, 64, 4, 2, 1, bias = False), nn.BatchNorm2d(64), nn.ReLU(True), nn.ConvTranspose2d(64, 3, 4, 2, 1, bias = False), nn.Tanh() ) def forward(self, input): return self.main(input) My function to start the weights: def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1: m.weight.data.normal_(0.0, 0.02) elif classname.find('BatchNorm') != -1: m.weight.data.normal_(1.0, 0.02) m.bias.data.fill_(0) Full code can be seen here: https://github.com/davidsonmizael/criminal-gan Noise generated on epoch number 25: Input with real images:
The code from your example (https://github.com/davidsonmizael/gan) gave me the same noise as you show. The loss of the generator decreased way too quickly. There were a few things buggy, I'm not even sure anymore what - but I guess it's easy to figure out the differences yourself. For a comparison, also have a look at this tutorial: GANs in 50 lines of PyTorch .... same as your code print("# Starting generator and descriminator...") netG = G() netG.apply(weights_init) netD = D() netD.apply(weights_init) if torch.cuda.is_available(): netG.cuda() netD.cuda() #training the DCGANs criterion = nn.BCELoss() optimizerD = optim.Adam(netD.parameters(), lr = 0.0002, betas = (0.5, 0.999)) optimizerG = optim.Adam(netG.parameters(), lr = 0.0002, betas = (0.5, 0.999)) epochs = 25 timeElapsed = [] for epoch in range(epochs): print("# Starting epoch [%d/%d]..." % (epoch, epochs)) for i, data in enumerate(dataloader, 0): start = time.time() time.clock() #updates the weights of the discriminator nn netD.zero_grad() #trains the discriminator with a real image real, _ = data if torch.cuda.is_available(): inputs = Variable(real.cuda()).cuda() target = Variable(torch.ones(inputs.size()[0]).cuda()).cuda() else: inputs = Variable(real) target = Variable(torch.ones(inputs.size()[0])) output = netD(inputs) errD_real = criterion(output, target) errD_real.backward() #retain_graph=True #trains the discriminator with a fake image if torch.cuda.is_available(): D_noise = Variable(torch.randn(inputs.size()[0], 100, 1, 1).cuda()).cuda() target = Variable(torch.zeros(inputs.size()[0]).cuda()).cuda() else: D_noise = Variable(torch.randn(inputs.size()[0], 100, 1, 1)) target = Variable(torch.zeros(inputs.size()[0])) D_fake = netG(D_noise).detach() D_fake_ouput = netD(D_fake) errD_fake = criterion(D_fake_ouput, target) errD_fake.backward() # NOT:backpropagating the total error # errD = errD_real + errD_fake optimizerD.step() #for i, data in enumerate(dataloader, 0): #updates the weights of the generator nn netG.zero_grad() if torch.cuda.is_available(): G_noise = Variable(torch.randn(inputs.size()[0], 100, 1, 1).cuda()).cuda() target = Variable(torch.ones(inputs.size()[0]).cuda()).cuda() else: G_noise = Variable(torch.randn(inputs.size()[0], 100, 1, 1)) target = Variable(torch.ones(inputs.size()[0])) fake = netG(G_noise) G_output = netD(fake) errG = criterion(G_output, target) #backpropagating the error errG.backward() optimizerG.step() if i % 50 == 0: #prints the losses and save the real images and the generated images print("# Progress: ") print("[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f" % (epoch, epochs, i, len(dataloader), errD_real.data[0], errG.data[0])) #calculates the remaining time by taking the avg seconds that every loop #and multiplying by the loops that still need to run timeElapsed.append(time.time() - start) avg_time = (sum(timeElapsed) / float(len(timeElapsed))) all_dtl = (epoch * len(dataloader)) + i rem_dtl = (len(dataloader) - i) + ((epochs - epoch) * len(dataloader)) remaining = (all_dtl - rem_dtl) * avg_time print("# Estimated remaining time: %s" % (time.strftime("%H:%M:%S", time.gmtime(remaining)))) if i % 100 == 0: vutils.save_image(real, "%s/real_samples.png" % "./results", normalize = True) vutils.save_image(fake.data, "%s/fake_samples_epoch_%03d.png" % ("./results", epoch), normalize = True) print ("# Finished.") Result after 25 epochs (batchsize 256) on CIFAR-10:
https://stackoverflow.com/questions/47275395/
PyTorch loss function evaluation
I am trying to optimise a function (fit) using the acceleration of GPU in PyTorch. This is the straight Python code, where I doing the evaluation of fit: import numpy as np ... for j in range(P): e[:,j] = z - h[:,j]; fit[j] = 1/(sqrt(2*pi)*sigma*N)*np.sum(exp(-(e[:,j]**2)/(2*sigma**2))); The dimension of the variables are: z[Nx1], h[NxP], e[NxP], fit[1xP]. where P is the number of dimension of fit and N is the length of each dimension. I am aware that for loops should be avoided, so where it is my attempt to do it using PyTorch through torch.cuda.FloatTensor. import torch dtype = torch.cuda.FloatTensor e = z - h; fit = 1/(torch.sqrt(2*pi)*sigma*N)*torch.sum(torch.exp(-(torch.pw(e,2))/(2*torch.pow(sigma,2)))); Unfortunately it is not working. What is wrong? Thank you!
I guess you are getting size mismatch error at the following line. e = z - h In your example, z is a vector (2d tensor of shape Nx1) and h is a 2d tensor of shape NxP. So, you can't directly subtract h from z. You can do the following to avoid size mismatch error. e = z.expand(*h.size()) - h Here, z.expand(*h.size()) will convert the tensor z from Nx1 to NxP shape by duplicating the column vector P times.
https://stackoverflow.com/questions/47275847/
How to update a Tensor?
I've had some troubles updating a tensor using a previous one. My problem: let's suppose that I have a tensor x1 [Nx1] and a new one calculated through the previous, x2 [Nx1]. Now I want to update the elements of x2 that are less than x1. I'm using dtype=torch.cuda.FloatTensor. This is the straight code in Python: import numpy as np ... index = np.where(x1 > x2) x2[index] = x1[index] Why can I do this using PyTorch with dtype=torch.cuda.FloatTensor? And if the x1 change to [NxD] Thank you!
The code looks really similar to numpy: idx = (x1 > x2) x2[idx] = x1[idx] Using some predefined arrays and printing x2: x1 = torch.from_numpy(np.array([1, 2, 3, 4, 5])).float().cuda() x2 = torch.from_numpy(np.array([3, 3, 3, 3, 3])).float().cuda() 3 3 3 4 5 [torch.cuda.FloatTensor of size 5 (GPU 0)] Code would be the same for NxN dimensional tensors. Using: x1 = torch.from_numpy(np.array([[1, 2, 5], [1, 4, 5]])).float().cuda() x2 = torch.from_numpy(np.array([[3, 3, 3], [3, 3, 3]])).float().cuda() 3 3 5 3 4 5 [torch.cuda.FloatTensor of size 2x3 (GPU 0)]
https://stackoverflow.com/questions/47287858/
How to use if statement PyTorch using torch.FloatTensor
I am trying to use the if statement in my PyTorch code using torch.FloatTensor as data type, to speed it up into the GPU. This is my code: import torch import time def fitness(x): return torch.pow(x, 2) def velocity(v, gxbest, pxbest, pybest, x, pop): return torch.rand(pop).type(dtype)*v + \ torch.rand(pop).type(dtype)*(pxbest - x) + \ torch.rand(pop).type(dtype)*(gxbest.expand(x.size(0)) - x) dtype = torch.cuda.FloatTensor def main(): pop, xmax, xmin, niter = 300000, 50, -50, 100 v = torch.rand(pop).type(dtype) x = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin y = fitness(x) [miny, indexminy] = y.min(0) gxbest = x[indexminy] pxbest = x pybest = y for K in range(niter): vnext = velocity(v, gxbest, pxbest, pybest, x, pop) xnext = x + vnext ynext = fitness(x) [minynext, indexminynext] = ynext.min(0) if (minynext < miny): miny = minynext gxbest = xnext[indexminynext] indexpbest = (ynext < pybest) pxbest[indexpbest] = xnext[indexpbest] pybest[indexpbest] = ynext[indexpbest] x = xnext v = vnext main() Unfortanally it is not working. It is giving me a error message and I can not figure it out what is the problem. RuntimeError: bool value of non-empty torch.cuda.ByteTensor objects is ambiguous How can I use the if in PyTorch? I tried to convert the cuda.Tensor into a numpy array but it did not work also. minynext = minynext.cpu().numpy() miny = miny.cpu().numpy() PS: Am I doing the code the efficient/faster way possible ? Or should I change something to achieve faster results?
If you look into the following simple example: import torch a = torch.LongTensor([1]) b = torch.LongTensor([5]) print(a > b) Output: 0 [torch.ByteTensor of size 1] Comparing tensors a and b results in a torch.ByteTensor which is obviously not equivalent to boolean. So, you can do the following. print(a[0] > b[0]) # False So, you should change your if condition as follows. if (minynext[0] < miny[0])
https://stackoverflow.com/questions/47290053/
Separate optimizer for discriminator and the rest of the model in adversarial setting
I have a model with the following components. embedding layer encoder generator discriminator feed-forward neural network I want to define two optimizers. One for the discriminator only and one for the rest. I am doing the following. optimizers = [] model_params = chain(model.embedding.parameters(), model.encoder.parameters(), model.generator.parameters(), model.ffnn.parameters()) optimizers.append(optim.Adam(model_params, args.lr)) optimizers.append(optim.Adam(model.discriminator.parameters(), args.lr)) Is there any better way to do the same? For example, can I take the difference between model.parameters() and model.discriminator.parameters()? If yes, how can I do that?
no, because model.parameters() returns a generator. If you want to modify a generator like you want it you have to convert it to a list anyway.
https://stackoverflow.com/questions/47299549/
Fine Tuning dimensionality error
I am trying to use Resnet50 for image classification problem. However it shows error and I could not fix it. RuntimeError: inconsistent tensor size, expected tensor [120 x 2048] and src [1000 x 2048] to have the same number of elements, but got 245760 and 2048000 elements respectively at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/TH/generic/THTensorCopy.c:86 and error happens below. self.resnet = models.resnet50(num_classes=num_breeds, pretrained='imagenet') Model is below class Resnet(nn.Module): def __init__(self): super(Resnet,self).__init__() self.resnet = models.resnet50(num_classes=num_breeds, pretrained='imagenet') #self.resnet = nn.Sequential(*list(resnet.children())[:-2]) #self.fc = nn.Linear(2048,num_breeds) def forward(self,x): x = self.resnet(x) return x
When you create your models.resnet50 with num_classes=num_breeds, the last layer is a fully connected layer from 2048 to num_classes (which is 120 in your case). Having pretrained='imagenet' asks pytorch to load all the corresponding weights into your network, but it has for its last layer 1000 classes, not 120. This is the source of the error since the 2048x120 tensor doesn't match the loaded weights 2048x1000. You should either create your network with 1000 classes and load the weights, then "trim" to the classes you want to keep. Or you could create the network you wished for with 120 classes, but manually load the weights. In the last case, you only need to pay specific attention to the last layer.
https://stackoverflow.com/questions/47311570/
Pytorch AssertionError: Torch not compiled with CUDA enabled
I am trying to run code from this repo. I have disabled cuda by changing lines 39/40 in main.py from parser.add_argument('--type', default='torch.cuda.FloatTensor', help='type of tensor - e.g torch.cuda.HalfTensor') to parser.add_argument('--type', default='torch.FloatTensor', help='type of tensor - e.g torch.HalfTensor') Despite this, running the code gives me the following exception: Traceback (most recent call last): File "main.py", line 190, in <module> main() File "main.py", line 178, in main model, train_data, training=True, optimizer=optimizer) File "main.py", line 135, in forward for i, (imgs, (captions, lengths)) in enumerate(data): File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 201, in __next__ return self._process_next_batch(batch) File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 221, in _process_next_batch raise batch.exc_type(batch.exc_msg) AssertionError: Traceback (most recent call last): File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 62, in _pin_memory_loop batch = pin_memory_batch(batch) File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 123, in pin_memory_batch return [pin_memory_batch(sample) for sample in batch] File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 123, in <listcomp> return [pin_memory_batch(sample) for sample in batch] File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 117, in pin_memory_batch return batch.pin_memory() File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/tensor.py", line 82, in pin_memory return type(self)().set_(storage.pin_memory()).view_as(self) File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/storage.py", line 83, in pin_memory allocator = torch.cuda._host_allocator() File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 220, in _host_allocator _lazy_init() File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 84, in _lazy_init _check_driver() File "/Users/lakshay/anaconda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 51, in _check_driver raise AssertionError("Torch not compiled with CUDA enabled") AssertionError: Torch not compiled with CUDA enabled Spent some time looking through the issues in the Pytorch github, to no avail. Help, please?
If you look into the data.py file, you can see the function: def get_iterator(data, batch_size=32, max_length=30, shuffle=True, num_workers=4, pin_memory=True): cap, vocab = data return torch.utils.data.DataLoader( cap, batch_size=batch_size, shuffle=shuffle, collate_fn=create_batches(vocab, max_length), num_workers=num_workers, pin_memory=pin_memory) which is called twice in main.py file to get an iterator for the train and dev data. If you see the DataLoader class in pytorch, there is a parameter called: pin_memory (bool, optional) – If True, the data loader will copy tensors into CUDA pinned memory before returning them. which is by default True in the get_iterator function. And as a result you are getting this error. You can simply pass the pin_memory param value as False when you are calling get_iterator function as follows. train_data = get_iterator(get_coco_data(vocab, train=True), batch_size=args.batch_size, ..., ..., ..., pin_memory=False)
https://stackoverflow.com/questions/47312396/
Tensorflow: Hierarchical Softmax Implementation
I'm currently having text inputs represented by vector, and I want to classify their categories. Because they are multi-level categories, I meant to use Hierarchical Softmax. Example: - Computer Science - Machine Learning - NLP - Economics - Maths - Algebra - Geometry I don't know how to implement it in Tensorflow. All examples I've met is using other frameworks. Thanks
Finally, I have changed to use Pytorch. It's easier and more straight-forward than Tensorflow. For anyone further interested in implement HS, you can have a look at my sample instructions: https://gist.github.com/paduvi/588bc95c13e73c1e5110d4308e6291ab For anyone still want a Tensorflow implementation, this one is for you: https://github.com/tansey/sdp/blob/87e701c9b0ff3eacab29713cb2c9e7181d5c26aa/tfsdp/models.py#L205. But it's a little messy, and the author recommended using Pytorch or other dynamic graph framework
https://stackoverflow.com/questions/47313656/
ValueError: Floating point image RGB values must be in the 0..1 range. while using matplotlib
I want to visualize weights of the layer of a neural network. I'm using pytorch. import torch import torchvision.models as models from matplotlib import pyplot as plt def plot_kernels(tensor, num_cols=6): if not tensor.ndim==4: raise Exception("assumes a 4D tensor") if not tensor.shape[-1]==3: raise Exception("last dim needs to be 3 to plot") num_kernels = tensor.shape[0] num_rows = 1+ num_kernels // num_cols fig = plt.figure(figsize=(num_cols,num_rows)) for i in range(tensor.shape[0]): ax1 = fig.add_subplot(num_rows,num_cols,i+1) ax1.imshow(tensor[i]) ax1.axis('off') ax1.set_xticklabels([]) ax1.set_yticklabels([]) plt.subplots_adjust(wspace=0.1, hspace=0.1) plt.show() vgg = models.vgg16(pretrained=True) mm = vgg.double() filters = mm.modules body_model = [i for i in mm.children()][0] layer1 = body_model[0] tensor = layer1.weight.data.numpy() plot_kernels(tensor) The above gives this error ValueError: Floating point image RGB values must be in the 0..1 range. My question is should I normalize and take absolute value of the weights to overcome this error or is there anyother way ? If I normalize and use absolute value I think the meaning of the graphs change. [[[[ 0.02240197 -1.22057354 -0.55051649] [-0.50310904 0.00891289 0.15427093] [ 0.42360783 -0.23392732 -0.56789106]] [[ 1.12248898 0.99013627 1.6526649 ] [ 1.09936976 2.39608836 1.83921957] [ 1.64557672 1.4093554 0.76332706]] [[ 0.26969245 -1.2997849 -0.64577204] [-1.88377869 -2.0100112 -1.43068039] [-0.44531786 -1.67845118 -1.33723605]]] [[[ 0.71286005 1.45265901 0.64986968] [ 0.75984162 1.8061738 1.06934202] [-0.08650422 0.83452386 -0.04468433]] [[-1.36591709 -2.01630116 -1.54488969] [-1.46221244 -2.5365622 -1.91758668] [-0.88827479 -1.59151018 -1.47308767]] [[ 0.93600738 0.98174071 1.12213969] [ 1.03908169 0.83749604 1.09565806] [ 0.71188802 0.85773659 0.86840987]]] [[[-0.48592842 0.2971966 1.3365227 ] [ 0.47920835 -0.18186836 0.59673625] [-0.81358945 1.23862112 0.13635623]] [[-0.75361633 -1.074965 0.70477796] [ 1.24439156 -1.53563368 -1.03012812] [ 0.97597247 0.83084011 -1.81764793]] [[-0.80762428 -0.62829626 1.37428832] [ 1.01448071 -0.81775147 -0.41943246] [ 1.02848887 1.39178836 -1.36779451]]] ..., [[[ 1.28134537 -0.00482408 0.71610934] [ 0.95264435 -0.09291686 -0.28001019] [ 1.34494913 0.64477581 0.96984017]] [[-0.34442815 -1.40002513 1.66856039] [-2.21281362 -3.24513769 -1.17751861] [-0.93520379 -1.99811196 0.72937071]] [[ 0.63388056 -0.17022935 2.06905985] [-0.7285465 -1.24722099 0.30488953] [ 0.24900314 -0.19559766 1.45432627]]] [[[-0.80684513 2.1764245 -0.73765725] [-1.35886598 1.71875226 -1.73327696] [-0.75233924 2.14700699 -0.71064663]] [[-0.79627383 2.21598244 -0.57396138] [-1.81044972 1.88310981 -1.63758397] [-0.6589964 2.013237 -0.48532376]] [[-0.3710472 1.4949851 -0.30245575] [-1.25448656 1.20453358 -1.29454732] [-0.56755757 1.30994892 -0.39370224]]] [[[-0.67361742 -3.69201088 -1.23768616] [ 3.12674141 1.70414758 -1.76272404] [-0.22565465 1.66484773 1.38172317]] [[ 0.28095332 -2.03035069 0.69989491] [ 1.97936332 1.76992691 -1.09842575] [-2.22433758 0.52577412 0.18292744]] [[ 0.48471382 -1.1984663 1.57565165] [ 1.09911084 1.31910467 -0.51982772] [-2.76202297 -0.47073677 0.03936549]]]]
It sounds as if you already know your values are not in that range. Yes, you must re-scale them to the range 0.0 - 1.0. I suggest that you want to retain visibility of negative vs positive, but that you let 0.5 be your new "neutral" point. Scale such that current 0.0 values map to 0.5, and your most extreme value (largest magnitude) scale to 0.0 (if negative) or 1.0 (if positive). Thanks for the vectors. It looks like your values are in the range -2.25 to +2.0. I suggest a rescaling new = (1/(2*2.25)) * old + 0.5
https://stackoverflow.com/questions/47318871/
Is it possible to check if elements of a tensor are out of boundaries?
Is it possible to check if elements of a tensor are out of boundaries using torch.cuda.FloatTensor on PyTorch, GPU approach? Example (check limits): for i in range(pop): if (x[i]>xmax): x[i]=xmax elif (x[i]<xmin): x[i]=xmin I tried the following, but did not speed up: idxmax = (x > xmax) # elements that are bigger that upper limit idxmim = (x < min) # elements that are smaller that upper limit x[idxmax] = xmax x[idxmin] = xmin If not, is it possible to do this check limits part, using only the CPU? How?
You can get a CPU copy of tensor x, do your operations and then push the tensor to GPU memory again. x = x.cpu() # get the CPU copy # do your operations x = x.cuda() # move the object back to cuda memory
https://stackoverflow.com/questions/47319704/
how pytorch nn.module save submodule
I have some question about how pytorch nn.module works import torch import torch.nn as nn class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.sub_module = nn.Linear(10, 5) self.value = 3 net = Net() print(net.__dict__) output {'_modules': OrderedDict([('sub_module', Linear (10 -> 5))]), 'value': 3, ...} I know that every attribute of a class should be stored in __dict__, why value(a int value) is in it, but sub_module(a nn.Module) is not, instead, sub_module is stored in _modules I read the code of nn.Module implementation, but I didn't figure that out. do anyone have any ideas? thank you !!
I will try to keep it simple. Every time you create a new item in the class Net for instance: self.sub_module = nn.Linear(10, 5) it calls the method __setattr__ of its parent class, in this case nn.Module. Then, inside __setattr__ method, the parameters are stored to the dict they belong. In this case since nn.Linear is a module, it is stored to the _modules dict. Here is the piece of code that does this inside the Module class https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/module.py#L389
https://stackoverflow.com/questions/47324354/
torch.nn.LSTM runtime error
I'm trying to implement the structure from "Livelinet: A multimodal Deep Recurrent Neural Network to Predict Liveliness in Educational Videos". For a brief explanation, I split 10-second audio clip into ten 1-second audio clip and get a spectrogram (a picture) from that 1-second audio clip. Then I use CNN to get a representation vector from the picture, finally getting 10 vectors of each 1-second video clips. Next, I feed those 10 vectors to LSTM, and I got some errors there. My code and the error traceback are as follows: class AudioCNN(nn.Module): def __init__(self): super(AudioCNN,self).__init__() self.features = alexnet.features self.features2 = nn.Sequential(*classifier) self.lstm = nn.LSTM(512, 256,2) self.classifier = nn.Linear(2*256,2) def forward(self, x): x = self.features(x) print x.size() x = x.view(x.size(0),256*6*6) x = self.features2(x) x = x.view(10,1,512) h_0,c_0 = self.init_hidden() _, (_, _) = self.lstm(x,(h_0,c_0)) # x dim : 2 x 1 x 256 assert False x = x.view(1,1,2*256) x = self.classifier(x) return x def init_hidden(self): h_0 = torch.randn(2,1,256) #layer * batch * input_dim c_0 = torch.randn(2,1,256) return h_0, c_0 audiocnn = AudioCNN() input = torch.randn(10,3,223,223) input = Variable(input) audiocnn(input) Error: RuntimeErrorTraceback (most recent call last) <ipython-input-64-2913316dbb34> in <module>() ----> 1 audiocnn(input) /home//local/lib/python2.7/site-packages/torch/nn/modules/module.pyc in __call__(self, *input, **kwargs) 222 for hook in self._forward_pre_hooks.values(): 223 hook(self, input) --> 224 result = self.forward(*input, **kwargs) 225 for hook in self._forward_hooks.values(): 226 hook_result = hook(self, input, result) <ipython-input-60-31881982cca9> in forward(self, x) 15 x = x.view(10,1,512) 16 h_0,c_0 = self.init_hidden() ---> 17 _, (_, _) = self.lstm(x,(h_0,c_0)) # x dim : 2 x 1 x 256 18 assert False 19 x = x.view(1,1,2*256) /home/local/lib/python2.7/site-packages/torch/nn/modules/module.pyc in __call__(self, *input, **kwargs) 222 for hook in self._forward_pre_hooks.values(): 223 hook(self, input) --> 224 result = self.forward(*input, **kwargs) 225 for hook in self._forward_hooks.values(): 226 hook_result = hook(self, input, result) /home//local/lib/python2.7/site-packages/torch/nn/modules/rnn.pyc in forward(self, input, hx) 160 flat_weight=flat_weight 161 ) --> 162 output, hidden = func(input, self.all_weights, hx) 163 if is_packed: 164 output = PackedSequence(output, batch_sizes) /home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, *fargs, **fkwargs) 349 else: 350 func = AutogradRNN(*args, **kwargs) --> 351 return func(input, *fargs, **fkwargs) 352 353 return forward /home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, weight, hidden) 242 input = input.transpose(0, 1) 243 --> 244 nexth, output = func(input, hidden, weight) 245 246 if batch_first and batch_sizes is None: /home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, hidden, weight) 82 l = i * num_directions + j 83 ---> 84 hy, output = inner(input, hidden[l], weight[l]) 85 next_hidden.append(hy) 86 all_output.append(output) /home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in forward(input, hidden, weight) 111 steps = range(input.size(0) - 1, -1, -1) if reverse else range(input.size(0)) 112 for i in steps: --> 113 hidden = inner(input[i], hidden, *weight) 114 # hack to handle LSTM 115 output.append(hidden[0] if isinstance(hidden, tuple) else hidden) /home//local/lib/python2.7/site-packages/torch/nn/_functions/rnn.pyc in LSTMCell(input, hidden, w_ih, w_hh, b_ih, b_hh) 29 30 hx, cx = hidden ---> 31 gates = F.linear(input, w_ih, b_ih) + F.linear(hx, w_hh, b_hh) 32 33 ingate, forgetgate, cellgate, outgate = gates.chunk(4, 1) /home//local/lib/python2.7/site-packages/torch/nn/functional.pyc in linear(input, weight, bias) 551 if input.dim() == 2 and bias is not None: 552 # fused op is marginally faster --> 553 return torch.addmm(bias, input, weight.t()) 554 555 output = input.matmul(weight.t()) /home//local/lib/python2.7/site-packages/torch/autograd/variable.pyc in addmm(cls, *args) 922 @classmethod 923 def addmm(cls, *args): --> 924 return cls._blas(Addmm, args, False) 925 926 @classmethod /home//local/lib/python2.7/site-packages/torch/autograd/variable.pyc in _blas(cls, args, inplace) 918 else: 919 tensors = args --> 920 return cls.apply(*(tensors + (alpha, beta, inplace))) 921 922 @classmethod RuntimeError: save_for_backward can only save input or output tensors, but argument 0 doesn't satisfy this condition
The error message RuntimeError: save_for_backward can only save input or output tensors, but argument 0 doesn't satisfy this condition generally indicates that you are passing a tensor or something else that cannot store history as an input into a module. In your case, your problem is that you return tensors in init_hidden() instead of Variable instances. Therefore, when the LSTM runs it cannot compute the gradient for the hidden layer as its initial input is not a part of the backprop graph. Solution: def init_hidden(self): h_0 = torch.randn(2,1,256) #layer * batch * input_dim c_0 = torch.randn(2,1,256) return Variable(h_0), Variable(c_0) It is also likely that a mean of 0 and a variance of 1 is not helpful as initial values for the LSTM hidden state. Ideally, you would make the initial state trainable as well, e.g.: h_0 = torch.zeros(2,1,256) # layer * batch * input_dim c_0 = torch.zeros(2,1,256) h_0_param = torch.nn.Parameter(h_0) c_0_param = torch.nn.Parameter(c_0) def init_hidden(self): return h_0_param, c_0_param In this case the network can learn what initial state suits best. Note that in this case there is no need to wrap h_0_param in a Variable as a Parameter is essentially a Variable with require_grad=True.
https://stackoverflow.com/questions/47347098/
Rosenbrock function with D dimension using PyTorch
How can I implement the Rosenbrock function with D dimension, using PyTorch? Create the variables, where D is the number of dimensions and N is the number of elements. x = (xmax - xmin)*torch.rand(N,D).type(dtype) + xmin Function : Using straight Python I'd do something like this: fit = 0 for i in range(D-1): term1 = x[i + 1] - x[i]**2 term2 = 1 - x[i] fit = fit + 100 * term1**2 + term2**2 My attempt using Pytorch: def Rosenbrock(x): return torch.sum(100*(x - x**2)**2 + (x-1)**2) I just do not know how to do the x[i+1] without using a for loop. How can I deal with it? Thank you!
Numpy has the function roll which I think can be really helpful. Unfortunately, I am not aware of any function similar to numpy.roll for pytorch. In my attempt, x is a numpy array in the form DxN. First we use roll to move the items in the first dimension (axis=0) one position to the left. Like this, everytime we compare x_1[i] is like if we do x[i+1]. Then, since the function takes only D-1 elements for the sum, we remove the last column slicing the pytorch tensor with [:-1, :]. Then the summation is really similar to the code you posted, just changing x for x_1 at the correct place. def Rosenbrock(x): x_1 = torch.from_numpy(np.roll(x, -1, axis=0)).float()[:-1, :] x = torch.from_numpy(x).float()[:-1, :] return torch.sum(100 * (x_1 - x ** 2) ** 2 + (x - 1) ** 2, 0) Similarly, by using roll you could remove you for loop in the numpy version
https://stackoverflow.com/questions/47350058/
How to construct a 3D Tensor where every 2D sub tensor is a diagonal matrix in PyTorch?
Consider I have 2D Tensor, index_in_batch * diag_ele. How can I get a 3D Tensor index_in_batch * Matrix (who is a diagonal matrix, construct by drag_ele)? The torch.diag() construct diagonal matrix only when input is 1D, and return diagonal element when input is 2D.
import torch a = torch.rand(2, 3) print(a) b = torch.eye(a.size(1)) c = a.unsqueeze(2).expand(*a.size(), a.size(1)) d = c * b print(d) Output 0.5938 0.5769 0.0555 0.9629 0.5343 0.2576 [torch.FloatTensor of size 2x3] (0 ,.,.) = 0.5938 0.0000 0.0000 0.0000 0.5769 0.0000 0.0000 0.0000 0.0555 (1 ,.,.) = 0.9629 0.0000 0.0000 0.0000 0.5343 0.0000 0.0000 0.0000 0.2576 [torch.FloatTensor of size 2x3x3]
https://stackoverflow.com/questions/47372508/
How to select index over two dimension in PyTorch?
Given a = torch.randn(3, 2, 4, 5), how I can select sub tensor like (2, :, 0, :), (1, :, 1, :), (2, :, 2, :), (0, :, 3, :) (a resulting tensor of size (2, 4, 5) or (4, 2, 5)? While a[2, :, 0, :] gives 0.5580 -0.0337 1.0048 -0.5044 0.6784 -1.6117 1.0084 1.1886 0.1278 0.3739 [torch.FloatTensor of size 2x5] however, a[[2, 1, 2, 0], :, [0, 1, 2, 3], :] gives TypeError: Performing basic indexing on a tensor and encountered an error indexing dim 0 with an object of type list. The only supported types are integers, slices, numpy scalars, or if indexing with a torch.LongTensor or torch.ByteTensor only a single Tensor may be passed. though numpy returns a (4, 2, 5) tensor successfully.
Does it work for you? import torch a = torch.randn(3, 2, 4, 5) print(a.size()) b = [a[2, :, 0, :], a[1, :, 1, :], a[2, :, 2, :], a[0, :, 3, :]] b = torch.stack(b, 0) print(b.size()) # torch.Size([4, 2, 5])
https://stackoverflow.com/questions/47374172/
transfer learning [resnet18] using PyTorch. Dataset: Dog-Breed-Identification
I am trying to implement a transfer learning approach in PyTorch. This is the dataset that I am using: Dog-Breed Here's the step that I am following. 1. Load the data and read csv using pandas. 2. Resize (60, 60) the train images and store them as numpy array. 3. Apply stratification and split the train data into 7:1:2 (train:validation:test) 4. use the resnet18 model and train. Location of dataset LABELS_LOCATION = './dataset/labels.csv' TRAIN_LOCATION = './dataset/train/' TEST_LOCATION = './dataset/test/' ROOT_PATH = './dataset/' Reading CSV (labels.csv) def read_csv(csvf): # print(pandas.read_csv(csvf).values) data=pandas.read_csv(csvf).values labels_dict = dict(data) idz=list(labels_dict.keys()) clazz=list(labels_dict.values()) return labels_dict,idz,clazz I did this because of a constraint which I will mention next when I am loading the data using DataLoader. def class_hashmap(class_arr): uniq_clazz = Counter(class_arr) class_dict = {} for i, j in enumerate(uniq_clazz): class_dict[j] = i return class_dict labels, ids, class_names = read_csv(LABELS_LOCATION) train_images = os.listdir(TRAIN_LOCATION) class_numbers = class_hashmap(class_names) Next, I resize the image to 60,60 using opencv, and store the result as numpy array. resize = [] indexed_labels = [] for t_i in train_images: # resize.append(transform.resize(io.imread(TRAIN_LOCATION+t_i), (60, 60, 3))) # (60,60) is the height and widht; 3 is the number of channels resize.append(cv2.resize(cv2.imread(TRAIN_LOCATION+t_i), (60, 60)).reshape(3, 60, 60)) indexed_labels.append(class_numbers[labels[t_i.split('.')[0]]]) resize = np.asarray(resize) print(resize.shape) Here in indexed_labels, I give each label a number. Next, I split the data into 7:1:2 part X = resize # numpy array of images [training data] y = np.array(indexed_labels) # indexed labels for images [training labels] sss = StratifiedShuffleSplit(n_splits=3, test_size=0.2, random_state=0) sss.get_n_splits(X, y) for train_index, test_index in sss.split(X, y): X_temp, X_test = X[train_index], X[test_index] # split train into train and test [data] y_temp, y_test = y[train_index], y[test_index] # labels sss = StratifiedShuffleSplit(n_splits=3, test_size=0.123, random_state=0) sss.get_n_splits(X_temp, y_temp) for train_index, test_index in sss.split(X_temp, y_temp): print("TRAIN:", train_index, "VAL:", test_index) X_train, X_val = X[train_index], X[test_index] # training and validation data y_train, y_val = y[train_index], y[test_index] # training and validation labels Next, I loaded the data from the previous step into torch DataLoaders batch_size = 500 learning_rate = 0.001 train = torch.utils.data.TensorDataset(torch.from_numpy(X_train), torch.from_numpy(y_train)) train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=False) val = torch.utils.data.TensorDataset(torch.from_numpy(X_val), torch.from_numpy(y_val)) val_loader = torch.utils.data.DataLoader(val, batch_size=batch_size, shuffle=False) test = torch.utils.data.TensorDataset(torch.from_numpy(X_test), torch.from_numpy(y_test)) test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False) # print(train_loader.size) dataloaders = { 'train': train_loader, 'val': val_loader } Next, I load the pretrained rensnet model. model_ft = models.resnet18(pretrained=True) # freeze all model parameters # for param in model_ft.parameters(): # param.requires_grad = False num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs, len(class_numbers)) if use_gpu: model_ft = model_ft.cuda() model_ft.fc = model_ft.fc.cuda() criterion = nn.CrossEntropyLoss() # Observe that all parameters are being optimized optimizer_ft = optim.SGD(model_ft.fc.parameters(), lr=0.001, momentum=0.9) # Decay LR by a factor of 0.1 every 7 epochs exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1) model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=25) And then I use the train_model, a method described here in PyTorch's docs. However, when I run this I get an error. Traceback (most recent call last): File "/Users/nirvair/Sites/pyTorch/TL.py", line 244, in <module> num_epochs=25) File "/Users/nirvair/Sites/pyTorch/TL.py", line 176, in train_model outputs = model(inputs) File "/Library/Python/2.7/site-packages/torch/nn/modules/module.py", line 224, in __call__ result = self.forward(*input, **kwargs) File "/Library/Python/2.7/site-packages/torchvision/models/resnet.py", line 149, in forward x = self.avgpool(x) File "/Library/Python/2.7/site-packages/torch/nn/modules/module.py", line 224, in __call__ result = self.forward(*input, **kwargs) File "/Library/Python/2.7/site-packages/torch/nn/modules/pooling.py", line 505, in forward self.padding, self.ceil_mode, self.count_include_pad) File "/Library/Python/2.7/site-packages/torch/nn/functional.py", line 264, in avg_pool2d ceil_mode, count_include_pad) File "/Library/Python/2.7/site-packages/torch/nn/_functions/thnn/pooling.py", line 360, in forward ctx.ceil_mode, ctx.count_include_pad) RuntimeError: Given input size: (512x2x2). Calculated output size: (512x0x0). Output size is too small at /Users/soumith/code/builder/wheel/pytorch-src/torch/lib/THNN/generic/SpatialAveragePooling.c:64 I can't seem to figure out what's going wrong here.
Your network is too deep for the size of images you are using (60x60). As you know, the CNN layers do produce smaller and smaller feature maps as the input image propagate through the layers. This is because you are not using padding. The error you have simply says that the next layer is expecting 512 feature maps with a size of 2 pixels by 2 pixels. The actual feature map produced from the forward pass was 512 maps of size 0x0. This mismatch is what triggered the error. Generally, all stock networks, such as RESNET-18, Inception, etc, require the input images to be of the size 224x224 (at least). You can do this easier using the torchvision transforms[1]. You can also use larger image sizes with one exception for the AlexNet which has the size of feature vector hardcoded as explained in my answer in [2]. Bonus Tip: If you are using the network in pre-tained mode, you will need to whiten the data using the parameters in the pytorch documentation at [3]. Links http://pytorch.org/docs/master/torchvision/transforms.html https://stackoverflow.com/a/46865203/7387369 http://pytorch.org/docs/master/torchvision/models.html
https://stackoverflow.com/questions/47403634/
`for` loop to a multi dimensional array in PyTorch
I want to implement Q&A systems with attention mechanism. I have two inputs; context and query which shapes are (batch_size, context_seq_len, embd_size) and (batch_size, query_seq_len, embd_size). I am following the below paper. Machine Comprehension Using Match-LSTM and Answer Pointer. https://arxiv.org/abs/1608.07905 Then, I want to obtain a attention matrix which shape is (batch_size, context_seq_len, query_seq_len, embd_size). In the thesis, they calculate values for each row (it means each context word, G_i, alpha_i in the paper). My code is below and it is running. But I am not sure my way is good or not. For example, I use for loop for generating sequence data (for i in range(T):). And to obtain each row, I use in-place operator like G[:,i,:,:], embd_context[:,i,:].clone() is a good manner in pytorch? If not, where should I change the code? And if you notice other points, let me know. I am a new in this field and pytorch. Sorry for my ambiguous question. class MatchLSTM(nn.Module): def __init__(self, args): super(MatchLSTM, self).__init__() self.embd_size = args.embd_size d = self.embd_size self.answer_token_len = args.answer_token_len self.embd = WordEmbedding(args) self.ctx_rnn = nn.GRU(d, d, dropout = 0.2) self.query_rnn = nn.GRU(d, d, dropout = 0.2) self.ptr_net = PointerNetwork(d, d, self.answer_token_len) # TBD self.w = nn.Parameter(torch.rand(1, d, 1).type(torch.FloatTensor), requires_grad=True) # (1, 1, d) self.Wq = nn.Parameter(torch.rand(1, d, d).type(torch.FloatTensor), requires_grad=True) # (1, d, d) self.Wp = nn.Parameter(torch.rand(1, d, d).type(torch.FloatTensor), requires_grad=True) # (1, d, d) self.Wr = nn.Parameter(torch.rand(1, d, d).type(torch.FloatTensor), requires_grad=True) # (1, d, d) self.match_lstm_cell = nn.LSTMCell(2*d, d) def forward(self, context, query): # params d = self.embd_size bs = context.size(0) # batch size T = context.size(1) # context length J = query.size(1) # query length # LSTM Preprocessing Layer shape = (bs, T, J, d) embd_context = self.embd(context) # (N, T, d) embd_context, _h = self.ctx_rnn(embd_context) # (N, T, d) embd_context_ex = embd_context.unsqueeze(2).expand(shape).contiguous() # (N, T, J, d) embd_query = self.embd(query) # (N, J, d) embd_query, _h = self.query_rnn(embd_query) # (N, J, d) embd_query_ex = embd_query.unsqueeze(1).expand(shape).contiguous() # (N, T, J, d) # Match-LSTM layer G = to_var(torch.zeros(bs, T, J, d)) # (N, T, J, d) wh_q = torch.bmm(embd_query, self.Wq.expand(bs, d, d)) # (N, J, d) = (N, J, d)(N, d, d) hidden = to_var(torch.randn([bs, d])) # (N, d) cell_state = to_var(torch.randn([bs, d])) # (N, d) # TODO bidirectional H_r = [hidden] for i in range(T): wh_p_i = torch.bmm(embd_context[:,i,:].clone().unsqueeze(1), self.Wp.expand(bs, d, d)).squeeze() # (N, 1, d) -> (N, d) wh_r_i = torch.bmm(hidden.unsqueeze(1), self.Wr.expand(bs, d, d)).squeeze() # (N, 1, d) -> (N, d) sec_elm = (wh_p_i + wh_r_i).unsqueeze(1).expand(bs, J, d) # (N, J, d) G[:,i,:,:] = F.tanh( (wh_q + sec_elm).view(-1, d) ).view(bs, J, d) # (N, J, d) # TODO bias attn_i = torch.bmm(G[:,i,:,:].clone(), self.w.expand(bs, d, 1)).squeeze() # (N, J) attn_query = torch.bmm(attn_i.unsqueeze(1), embd_query).squeeze() # (N, d) z = torch.cat((embd_context[:,i,:], attn_query), 1) # (N, 2d) hidden, cell_state = self.match_lstm_cell(z, (hidden, cell_state)) # (N, d), (N, d) H_r.append(hidden) H_r = torch.stack(H_r, dim=1) # (N, T, d) indices = self.ptr_net(H_r) # (N, M, T) , M means (start, end) return indices
I think your code is fine. You can't avoid the loop: for i in range(T): because in equation (2) in the paper (https://openreview.net/pdf?id=B1-q5Pqxl), there is a hidden state coming from Match-LSTM cell which is involved in computing G_i and alpha_i vector and they are used to compute the input for next timestep of the Match-LSTM. So, you need to run the loop for every timestep of the Match-LSTM, I don't see an alternative to avoid the for loop anyway.
https://stackoverflow.com/questions/47417159/
Taking subsets of a pytorch dataset
I have a network which I want to train on some dataset (as an example, say CIFAR10). I can create data loader object via trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) My question is as follows: Suppose I want to make several different training iterations. Let's say I want at first to train the network on all images in odd positions, then on all images in even positions and so on. In order to do that, I need to be able to access to those images. Unfortunately, it seems that trainset does not allow such access. That is, trying to do trainset[:1000] or more generally trainset[mask] will throw an error. I could do instead trainset.train_data=trainset.train_data[mask] trainset.train_labels=trainset.train_labels[mask] and then trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) However, that will force me to create a new copy of the full dataset in each iteration (as I already changed trainset.train_data so I will need to redefine trainset). Is there some way to avoid it? Ideally, I would like to have something "equivalent" to trainloader = torch.utils.data.DataLoader(trainset[mask], batch_size=4, shuffle=True, num_workers=2)
You can define a custom sampler for the dataset loader avoiding recreating the dataset (just creating a new loader for each different sampling). class YourSampler(Sampler): def __init__(self, mask): self.mask = mask def __iter__(self): return (self.indices[i] for i in torch.nonzero(self.mask)) def __len__(self): return len(self.mask) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) sampler1 = YourSampler(your_mask) sampler2 = YourSampler(your_other_mask) trainloader_sampler1 = torch.utils.data.DataLoader(trainset, batch_size=4, sampler = sampler1, shuffle=False, num_workers=2) trainloader_sampler2 = torch.utils.data.DataLoader(trainset, batch_size=4, sampler = sampler2, shuffle=False, num_workers=2) PS: You can find more info here: http://pytorch.org/docs/master/_modules/torch/utils/data/sampler.html#Sampler
https://stackoverflow.com/questions/47432168/
AttributeError on variable input of custom loss function in PyTorch
I've made a custom loss function to compute cross-entropy (CE) for a multi-output multi-label problem. Within the class, I want to set the target variable I'm feeding to not require a gradient. I do this within the forward function using a pre-defined function (taken from pytorch source code) outside the class. def _assert_no_grad(variable): assert not variable.requires_grad def forward(self, predicted, target): """ Computes cross entropy between targets and predictions. """ # No gradient over target _assert_no_grad(target) # Define variables p = predicted.clamp(0.01, 0.99) t = target.float() #Compute cross entropy h1 = p.log()*t h2 = (1-t)*((1-p).log()) ce = torch.add(h1, h2) ce_out = torch.mean(ce, 1) ce_out = torch.mean(ce_out, 0) # Save for backward step self.save_for_backward(ce_out) At this point when I run the code in a batched for-loop (see below), I get the following error: AttributeError: 'torch.FloatTensor' object has no attribute 'requires_grad' It seems simple enough as we should be passing a torch.autograd.Variable, however I am already doing this as can be seen in the snippet below. for t in range(50): print('Epoch {}'.format(t)) if t > 0: print('Loss ->', loss) for batch_idx, (x_batch, y_batch) in enumerate(train_loader): # Wrap in Variable x_in, target = Variable(x_batch), Variable(y_batch) predicted = model(x_in) # Compute and print loss loss = criterion(predicted, target) # Zero gradients, perform a backward pass, and update the weights. optimizer.zero_grad() loss.backward() optimizer.step() To add a note, my final goal is to generate a class which behaves like BCELoss except for multiple labels and not just binary. I feel like I've already scoured the entire PyTorch docs and primarily been using this and some forum entries. http://pytorch.org/docs/master/notes/extending.html So
The problem is in "target.float()" line which converts your t Variable to Tensor. You can directly use target without any problems in your CE calculation. Also, I guess you do not really need "self.save_for_backward(ce_out)" as I guess you are defining nn.Module class which will take care of the backward pass internally.
https://stackoverflow.com/questions/47432905/
How can I feed a batch into LSTM without reordering them by length in PyTorch?
I am new to Pytorch and I have got into some trouble. I want to build a rank-model to judge the similarity of question and its answers (including right answers and wrong answers). And I use LSTM as an encoder. There are two LSTMs in my model and they share the weights. So my model’s input is two sequences (question and answer). But if I use batch, reordering will disrupt the correspondence between questions and answers. What should I do?
Maybe a starting point could be to use similar RNN wrapper as here https://github.com/facebookresearch/DrQA/blob/master/drqa/reader/layers.py#L20 You can encode question and asnwer separately (this module will pack and unpack internally and will take care of sorting) and then you can work on the encoded representations
https://stackoverflow.com/questions/47433199/
torch.addmm received an invalid combination of arguments
In the official webpage of pytorch I saw the following code with answers: >> a = torch.randn(4, 4) >> a 0.0692 0.3142 1.2513 -0.5428 0.9288 0.8552 -0.2073 0.6409 1.0695 -0.0101 -2.4507 -1.2230 0.7426 -0.7666 0.4862 -0.6628 torch.FloatTensor of size 4x4] >>> torch.max(a, 1) ( 1.2513 0.9288 1.0695 0.7426 [torch.FloatTensor of size 4] , 2 0 0 0 [torch.LongTensor of size 4] ) I know that the first result corresponds to the maximum number per row, however I do not get the second tensor (LongTensor) I tried other random example and after a pytorch.max, I came to find these results 0.9477 1.0090 0.8348 -1.3513 -0.4861 1.2581 0.3972 1.5751 -1.2277 -0.6201 -1.0553 0.6069 0.1688 0.1373 0.6544 -0.7784 [torch.FloatTensor of size 4x4] ( 1.0090 1.5751 0.6069 0.6544 [torch.FloatTensor of size 4] , 1 3 3 2 [torch.LongTensor of size 4] ) Can anyone tell me what does it really mean these LongTensor data? I thought it was a strange casting between tensors, however after a simple casting of a float tensor, I see that it just cuts decimals Thanks
It just tells the index of the max element in your original tensor along the queried dimension. E.g. 0.9477 1.0090 0.8348 -1.3513 -0.4861 1.2581 0.3972 1.5751 -1.2277 -0.6201 -1.0553 0.6069 0.1688 0.1373 0.6544 -0.7784 [torch.FloatTensor of size 4x4] # torch.max(a, 1) ( 1.0090 1.5751 0.6069 0.6544 [torch.FloatTensor of size 4] , 1 3 3 2 [torch.LongTensor of size 4] ) In the above example in torch.LongTensor, 1 is the index of 1.0090 in your original tensor (torch.FloatTensor) 3 is the index of 1.5751 in your original tensor (torch.FloatTensor) 3 is the index of 0.6069 in your original tensor (torch.FloatTensor) 2 is the index of 0.6544 in your original tensor (torch.FloatTensor) along dimension 1. Instead, if you'd have requested torch.max(a, 0), the entries in torch.LongTensor would correspond to the indices of max elements in your original tensor along dimension 0.
https://stackoverflow.com/questions/47461625/
torch.pow does not work
I'm trying to create a custom loss function using PyTorch, and am running into a simple error. When I try to use torch.pow to take the exponent of a PyTorch Variable, I get the following error message: AttributeError: 'torch.LongTensor' object has no attribute 'pow' In the python terminal, I created a simple Variable, and attempted to do the same, and received the same error. Here's a snippet that should recreate the problem: import torch from torch.autograd import Variable import numpy as np v = Variable(torch.from_numpy(np.array([1, 2, 3, 4]))) torch.pow(v, 2) I can't find any information on this issue, and nothing is showing up in search results. Help? EDIT: this problem also occurs when I try to use torch.sqrt() EDIT: same problem also happens if I try to do v.pow(2) pow is definitely a method of v, and the docs clearly state that pow is a method that exists and takes a tensor as it's argument. I really don't see how this is happening, and it seems to me that the docs are just flat out wrong and these methods don't actually work.
You need to initialize the tensor as floats, because pow always returns a Float. import torch from torch.autograd import Variable import numpy as np v = Variable(torch.from_numpy(np.array([1, 2, 3, 4], dtype="float32"))) torch.pow(v, 2) You can cast it back to integers afterwards torch.pow(v, 2).type(torch.LongTensor) yields Variable containing: 1 4 9 16 [torch.LongTensor of size 4]
https://stackoverflow.com/questions/47470152/
Print exact value of PyTorch tensor (floating point precision)
I'm trying to print torch.FloatTensor like: a = torch.FloatTensor(3,3) print(a) This way I can get a value like: 0.0000e+00 0.0000e+00 3.2286e-41 1.2412e-40 1.2313e+00 1.6751e-37 2.6801e-36 3.5873e-41 9.4463e+21 But I want to get more accurate value, like 10 decimal point: 0.1234567891+01 With other python numerical objects, I could get it with: print('{:.10f}'.format(a)) but in the case of a tensor, I get this error: TypeError: unsupported format string passed to torch.FloatTensor.__format__ How can I print more precise values of tensors?
You can set the precision options: torch.set_printoptions(precision=10) There are more formatting options on the documentation page, it is very similar to numpy's.
https://stackoverflow.com/questions/47483733/
AttributeError: 'CrossEntropyLoss' object has no attribute 'backward'
i am trying to train a very basic CNN on CIFAR10 data set and getting the following error : AttributeError: 'CrossEntropyLoss' object has no attribute 'backward' criterion =nn.CrossEntropyLoss optimizer=optim.SGD(net.parameters(),lr=0.001,momentum=0.9) for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 0): # get the inputs inputs, labels = data # wrap them in Variable inputs, labels = Variable(inputs), Variable(labels) # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.data[0] if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0
Issue resolved. My mistake, I was missing the parenthesis criterion = nn.CrossEntropyLoss()  
https://stackoverflow.com/questions/47488598/
binarize input for pytorch
may I ask how to make data loaded in pytorch become binarized once it is loaded? Like Tensorflow can done this through: train_data = mnist.input_data.read_data_sets(data_directory, one_hot=True) How can pytorch achieve the one_hot=True effect. The data_loader I have now is: torch.set_default_tensor_type('torch.FloatTensor') train_loader = torch.utils.data.DataLoader( datasets.MNIST('data/', train=True, download=True, transform=transforms.Compose([ # transforms.RandomHorizontalFlip(), transforms.ToTensor()])), batch_size=batch_size, shuffle=False) I want to make data in train_loader be binarized. Now what I am doing is: After loading the data, for data,_ in train_loader: torch.round(data) data = Variable(data) Use the torch.round() function. Is this correct?
The one-hot encoding idea is used for classification. It sounds like you are trying to create an autoencoder perhaps. If you are creating an autoencoder then there is no need to round as BCELoss can handle values between 0 and 1. Note when training it is better not to apply the sigmoid and instead to use BCELossWithLogits as it provides numerical stability. Here is an example of an autoencoder with MNIST If instead you are attempting to do classifcation then there is no need for a one hot vector, you simply output the number of neurons equal to the number of classes i.e for MNIST output 10 neurons and then pass it to CrossEntropyLoss along with a LongTensor with corresponding expected class values Here is an example of classification on MNIST
https://stackoverflow.com/questions/47493135/
Implementing a tutorial for Tensorflow and SaaK Transform: Handwritten Digits Recognition
I am learning to work with Tensorflow. I have installed most of the libraries. # load libs import torch import argparse from torchvision import datasets, transforms import matplotlib.pyplot as plt import numpy as np from data.datasets import MNIST import torch.utils.data as data_utils from sklearn.decomposition import PCA import torch.nn.functional as F from torch.autograd import Variable But I am facing an error like this: ImportError Traceback (most recent call last) <ipython-input-8-257b7af364e1> in <module>() 5 import matplotlib.pyplot as plt 6 import numpy as np ----> 7 from data.datasets import MNIST 8 import torch.utils.data as data_utils 9 from sklearn.decomposition import PCA ImportError: No module named data.datasets I have installed the "dataset" library using the following command: sudo -H pip install dataset But I am still seeing this error. I am using python 2.7. I am pretty new to python. Can anyone help me in identifying the missing thing. Thanks in advance.
The dataset directory is placed next to main.py, so probably when you tried sudo -H pip install dataset you actually installed a irrelevant package. So uninstall the wrong package and it would work: sudo -H pip uninstall dataset
https://stackoverflow.com/questions/47493423/
Load pytorch model from different working directory
I want to load and access a pretrained model from the directory outside where all files are saved. Here is how directory structure is: -MyProject ----Model_checkpoint_and_scripts ------access_model.py --run_model.py --other files When run model calls access_model.py it looks for model.py in current working directory and does not find it. As suggested here, I could use the_model = TheModelClass(*args, **kwargs) the_model.load_state_dict(torch.load(PATH)) But in this case what is a good way to save all the arguments to initialize the model? I am thinking to pickle the command line args but there are some arguments like vocab size which are calculated. Thanks
I was able to load it by adding the following lines: here = os.path.dirname(os.path.abspath(__file__)) sys.path.append(here)
https://stackoverflow.com/questions/47494314/
Why should the training label for Generator in GAN be always True?
I am currently learning deep learning especially GAN. I found a simple code of GAN from a web site below. https://medium.com/@devnag/generative-adversarial-networks-gans-in-50-lines-of-code-pytorch-e81b79659e3f However, in the code, I don't understand why we always need to give true label to Generator as below. for g_index in range(g_steps): # 2. Train G on D's response (but DO NOT train D on these labels) G.zero_grad() gen_input = Variable(gi_sampler(minibatch_size, g_input_size)) g_fake_data = G(gen_input) dg_fake_decision = D(preprocess(g_fake_data.t())) g_error = criterion(dg_fake_decision, Variable(torch.ones(1))) # we want to fool, so pretend it's all genuine g_error.backward() g_optimizer.step() # Only optimizes G's parameters Specifically, on this line. g_error = criterion(dg_fake_decision, Variable(torch.ones(1))) # we want to fool, so pretend it's all genuine Input data for Generator is fake data(includes noise), so if we assign True labels on those input data, I think Generator ends up creating data which is similar to fake data(doesn't look like genuine). Is my understanding wrong? Sorry for the silly question, but if you have knowledge, plz help me out. I'll put a whole code below. #!/usr/bin/env python # Generative Adversarial Networks (GAN) example in PyTorch. # See related blog post at https://medium.com/@devnag/generative-adversarial-networks-gans-in-50-lines-of-code-pytorch-e81b79659e3f#.sch4xgsa9 import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable # Data params data_mean = 4 data_stddev = 1.25 # Model params g_input_size = 1 # Random noise dimension coming into generator, per output vector g_hidden_size = 50 # Generator complexity g_output_size = 1 # size of generated output vector d_input_size = 100 # Minibatch size - cardinality of distributions d_hidden_size = 50 # Discriminator complexity d_output_size = 1 # Single dimension for 'real' vs. 'fake' minibatch_size = d_input_size d_learning_rate = 2e-4 # 2e-4 g_learning_rate = 2e-4 optim_betas = (0.9, 0.999) num_epochs = 30000 print_interval = 200 d_steps = 1 # 'k' steps in the original GAN paper. Can put the discriminator on higher training freq than generator g_steps = 1 # ### Uncomment only one of these #(name, preprocess, d_input_func) = ("Raw data", lambda data: data, lambda x: x) (name, preprocess, d_input_func) = ("Data and variances", lambda data: decorate_with_diffs(data, 2.0), lambda x: x * 2) print("Using data [%s]" % (name)) # ##### DATA: Target data and generator input data def get_distribution_sampler(mu, sigma): return lambda n: torch.Tensor(np.random.normal(mu, sigma, (1, n))) # Gaussian def get_generator_input_sampler(): return lambda m, n: torch.rand(m, n) # Uniform-dist data into generator, _NOT_ Gaussian # ##### MODELS: Generator model and discriminator model class Generator(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(Generator, self).__init__() self.map1 = nn.Linear(input_size, hidden_size) self.map2 = nn.Linear(hidden_size, hidden_size) self.map3 = nn.Linear(hidden_size, output_size) def forward(self, x): x = F.elu(self.map1(x)) x = F.sigmoid(self.map2(x)) return self.map3(x) class Discriminator(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(Discriminator, self).__init__() self.map1 = nn.Linear(input_size, hidden_size) self.map2 = nn.Linear(hidden_size, hidden_size) self.map3 = nn.Linear(hidden_size, output_size) def forward(self, x): x = F.elu(self.map1(x)) x = F.elu(self.map2(x)) return F.sigmoid(self.map3(x)) def extract(v): return v.data.storage().tolist() def stats(d): return [np.mean(d), np.std(d)] def decorate_with_diffs(data, exponent): mean = torch.mean(data.data, 1, keepdim=True) mean_broadcast = torch.mul(torch.ones(data.size()), mean.tolist()[0][0]) diffs = torch.pow(data - Variable(mean_broadcast), exponent) return torch.cat([data, diffs], 1) d_sampler = get_distribution_sampler(data_mean, data_stddev) gi_sampler = get_generator_input_sampler() G = Generator(input_size=g_input_size, hidden_size=g_hidden_size, output_size=g_output_size) D = Discriminator(input_size=d_input_func(d_input_size), hidden_size=d_hidden_size, output_size=d_output_size) criterion = nn.BCELoss() # Binary cross entropy: http://pytorch.org/docs/nn.html#bceloss d_optimizer = optim.Adam(D.parameters(), lr=d_learning_rate, betas=optim_betas) g_optimizer = optim.Adam(G.parameters(), lr=g_learning_rate, betas=optim_betas) for epoch in range(num_epochs): for d_index in range(d_steps): # 1. Train D on real+fake D.zero_grad() # 1A: Train D on real d_real_data = Variable(d_sampler(d_input_size)) d_real_decision = D(preprocess(d_real_data)) d_real_error = criterion(d_real_decision, Variable(torch.ones(1))) # ones = true d_real_error.backward() # compute/store gradients, but don't change params # 1B: Train D on fake d_gen_input = Variable(gi_sampler(minibatch_size, g_input_size)) d_fake_data = G(d_gen_input).detach() # detach to avoid training G on these labels d_fake_decision = D(preprocess(d_fake_data.t())) d_fake_error = criterion(d_fake_decision, Variable(torch.zeros(1))) # zeros = fake d_fake_error.backward() d_optimizer.step() # Only optimizes D's parameters; changes based on stored gradients from backward() for g_index in range(g_steps): # 2. Train G on D's response (but DO NOT train D on these labels) G.zero_grad() gen_input = Variable(gi_sampler(minibatch_size, g_input_size)) g_fake_data = G(gen_input) dg_fake_decision = D(preprocess(g_fake_data.t())) g_error = criterion(dg_fake_decision, Variable(torch.ones(1))) # we want to fool, so pretend it's all genuine g_error.backward() g_optimizer.step() # Only optimizes G's parameters if epoch % print_interval == 0: print("%s: D: %s/%s G: %s (Real: %s, Fake: %s) " % (epoch, extract(d_real_error)[0], extract(d_fake_error)[0], extract(g_error)[0], stats(extract(d_real_data)), stats(extract(d_fake_data))))
In this part of the code you are training G to fool D, so G generates fake data and asks D whether it thinks it's real (true labels), D's gradients are then propogated all the way to G (this is possible as D's input was G's output) so that it will learn to better fool D in the next iteration. The inputs of G are not trainable and G only tries to transform them into real data (data similar to what d_sampler generates)
https://stackoverflow.com/questions/47499404/
Best way in Pytorch to upsample a Tensor and transform it to rgb?
For a nice output in Tensorboard I want to show a batch of input images, corresponding target masks and output masks in a grid. Input images have different size then the masks. Furthermore the images are obviously RGB. From a batch of e.g. 32 or 64 I only want to show the first 4 images. After some fiddling around I came up with the following example code. Good thing: It works. But I am really not sure if I missed something in Pytorch. It just looks much longer then I expected. Especially the upsampling and transformation to RGB seems wild. But the other transformations I found would not work for a whole batch. import torch from torch.autograd import Variable import torch.nn.functional as FN import torchvision.utils as vutils from tensorboardX import SummaryWriter import time batch = 32 i_size = 192 o_size = 112 nr_imgs = 4 # Tensorboard init writer = SummaryWriter('runs/' + time.strftime('%Y%m%d_%H%M%S')) input_image=Variable(torch.rand(batch,3,i_size,i_size)) target_mask=Variable(torch.rand(batch,o_size,o_size)) output_mask=Variable(torch.rand(batch,o_size,o_size)) # upsample target_mask, add dim to have gray2rgb tm = FN.upsample(target_mask[:nr_imgs,None], size=[i_size, i_size], mode='bilinear') tm = torch.cat( (tm,tm,tm), dim=1) # grayscale plane to rgb # upsample target_mask, add dim to have gray2rgb om = FN.upsample(output_mask[:nr_imgs,None], size=[i_size, i_size], mode='bilinear') om = torch.cat( (om,om,om), dim=1) # grayscale plane to rgb # add up all images and make grid imgs = torch.cat( ( input_image[:nr_imgs].data, tm.data, om.data ) ) x = vutils.make_grid(imgs, nrow=nr_imgs, normalize=True, scale_each=True) # Tensorboard img output writer.add_image('Image', x, 0) EDIT: Found this on Pytorchs Issues list. Its about Batch support for Transform. Seems there are no plans to add batch transforms in the future. So my current code might be the best solution for the time being, anyway?
Maybe you can just convert your Tensors to the numpy array (.data.cpu().numpy() ) and use opencv to do upsampling? OpenCV implementation should be quite fast.
https://stackoverflow.com/questions/47521393/
How to find and understand the autograd source code in PyTorch
I have a good understanding of the autograd algorithm, and I think I should learn about the source code in PyTorch. However, when I see the project on GitHub, I am confused by the structure, cuz so many files include autograd. So which part is the most important core code of autograd?
Try to understand the autograd variable is probably the first thing, what you can do. From my understanding is autograd only a naming for the modules, which containing classes with enhancement of gradients and backward functions. Be aware a lot of the algorithm, e.g. back-prop through the graph, is hidden in compiled code. If you look into the __init__.py, you can get a glimpse about all important functions (backward & grad)
https://stackoverflow.com/questions/47525820/
How can I give a name to each module in ModuleList?
I have the following component in my model: feedfnn = [] for task_name, num_class in self.tasks: if self.config.nonlinear_fc: ffnn = nn.Sequential(OrderedDict([ ('dropout1', nn.Dropout(self.config.dropout_fc)), ('dense1', nn.Linear(self.config.nhid * self.num_directions * 8, self.config.fc_dim)), ('tanh', nn.Tanh()), ('dropout2', nn.Dropout(self.config.dropout_fc)), ('dense2', nn.Linear(self.config.fc_dim, self.config.fc_dim)), ('tanh', nn.Tanh()), ('dropout3', nn.Dropout(self.config.dropout_fc)), ('dense3', nn.Linear(self.config.fc_dim, num_class)) ])) else: ffnn = nn.Sequential(OrderedDict([ ('dropout1', nn.Dropout(self.config.dropout_fc)), ('dense1', nn.Linear(self.config.nhid * self.num_directions * 8, self.config.fc_dim)), ('dropout2', nn.Dropout(self.config.dropout_fc)), ('dense2', nn.Linear(self.config.fc_dim, self.config.fc_dim)), ('dropout3', nn.Dropout(self.config.dropout_fc)), ('dense3', nn.Linear(self.config.fc_dim, num_class)) ])) feedfnn.append(ffnn) self.ffnn = nn.ModuleList(feedfnn) When I print my model, I get the description of the above component as: (ffnn): ModuleList ( (0): Sequential ( (dropout1): Dropout (p = 0) (dense1): Linear (4096 -> 512) (dropout2): Dropout (p = 0) (dense2): Linear (512 -> 512) (dropout3): Dropout (p = 0) (dense3): Linear (512 -> 2) ) (1): Sequential ( (dropout1): Dropout (p = 0) (dense1): Linear (4096 -> 512) (dropout2): Dropout (p = 0) (dense2): Linear (512 -> 512) (dropout3): Dropout (p = 0) (dense3): Linear (512 -> 3) ) (2): Sequential ( (dropout1): Dropout (p = 0) (dense1): Linear (4096 -> 512) (dropout2): Dropout (p = 0) (dense2): Linear (512 -> 512) (dropout3): Dropout (p = 0) (dense3): Linear (512 -> 3) ) ) Can I put a specific name like (task1): Sequential, (task2): Sequential instead of (0): Sequential, (1): Sequential?
That's straightforward. Simply start with an empty ModuleListand then use add_module for it. For example, import torch.nn as nn from collections import OrderedDict final_module_list = nn.ModuleList() a_sequential_module_with_names = nn.Sequential(OrderedDict([ ('dropout1', nn.Dropout(0.1)), ('dense1', nn.Linear(10, 10)), ('tanh', nn.Tanh()), ('dropout2', nn.Dropout(0.1)), ('dense2', nn.Linear(10, 10)), ('tanh', nn.Tanh()), ('dropout3', nn.Dropout(0.1)), ('dense3', nn.Linear(10, 10))])) final_module_list.add_module('Stage 1', a_sequential_module_with_names) final_module_list.add_module('Stage 2', a_sequential_module_with_names) etc.
https://stackoverflow.com/questions/47544009/
When should I use nn.ModuleList and when should I use nn.Sequential?
I am new to Pytorch and one thing that I don't quite understand is the usage of nn.ModuleList and nn.Sequential. Can I know when I should use one over the other? Thanks.
nn.ModuleList does not have a forward method, but nn.Sequential does have one. So you can wrap several modules in nn.Sequential and run it on the input. nn.ModuleList is just a Python list (though it's useful since the parameters can be discovered and trained via an optimizer). While nn.Sequential is a module that sequentially runs the component on the input.
https://stackoverflow.com/questions/47544051/
Calculating Distance in Parameter Space for PyTorch Network
I'm new to PyTorch. I want to keep track of the distance in parameter-space my model travels through its optimization. This is the code I'm using. class ParameterDiffer(object): def __init__(self, network): network_params = [] for p in network.parameters(): network_params.append(p.data.numpy()) self.network_params = network_params def get_difference(self, network): total_diff = 0.0 for i, p in enumerate(network.parameters()): p_np = p.data.numpy() diff = self.network_params[i] - p_np # print(diff) scalar_diff = np.sum(diff ** 2) total_diff += scalar_diff return total_diff Will this work? I keep track of total_diff through time, and am logging it, but it seems to be zero ALWAYS. Even though the model's performance is improving, which confuses me greatly.
The cause This is because the way PyTorch treat conversion between numpy array and torch Tensor. If the underlying data type between numpy array and torch Tensor are the same, they will share the memory. Change the value of one will also change the value of the other. I will show a concrete example here, x = Variable(torch.rand(2, 2)) y = x.data.numpy() x Out[39]: Variable containing: 0.8442 0.9968 0.7366 0.4701 [torch.FloatTensor of size 2x2] y Out[40]: array([[ 0.84422851, 0.996831 ], [ 0.73656738, 0.47010136]], dtype=float32) Then if you change x in-place and see the value in x and y, you will find they are still the same. x += 2 x Out[42]: Variable containing: 2.8442 2.9968 2.7366 2.4701 [torch.FloatTensor of size 2x2] y Out[43]: array([[ 2.84422851, 2.99683094], [ 2.7365675 , 2.47010136]], dtype=float32) So during your model update, the parameter in your model and in the class ParameterDiffer will always be the same. That is why you are seeing zeros. How to work around this? If the numpy array and torch Tensor's underlying data type are not compatible, it will force a copy of original data in torch Tensor, which will make the numpy array and torch Tensor have separate memory. A simple way is just to convert numpy array to type np.float64. Instead of network_params.append(p.data.numpy()) You can use network_params.append(p.data.numpy().astype(np.float64)) Important references http://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html#numpy-bridge https://github.com/pytorch/pytorch/issues/2246
https://stackoverflow.com/questions/47544151/
Pytorch: Can’t load images using ImageFolder
I’m trying to load images using “ImageFolder”. data_dir = './train_dog' # directory structure is train_dog/image dset = datasets.ImageFolder(data_dir, transform) train_loader = torch.utils.data.DataLoader(dset, batch_size=128, shuffle=True) However, it seems not working. So I checked the stored data as below print dset[0][0] Then it shows only 3 tensors(size 64x64). [torch.FloatTensor of size 3x64x64] There are more than 10,000 images in the folder. How come it can’t store all data?
You should try this: print len(dset) which represents the size of the dataset, aka the number of image files. dset[0] means the (shuffled) first index of the dataset, where dset[0][0] contains the input image tensor and dset[0][1] contains the corresponding label or target.
https://stackoverflow.com/questions/47553103/
When will the computation graph be freed if I only do forward for some samples?
I have a use case where I do forward for each sample in a batch and only accumulate loss for some of the samples based on some condition on the model output of the sample. Here is an illustrating code, for batch_idx, (data, target) in enumerate(train_loader): optimizer.zero_grad() total_loss = 0 loss_count_local = 0 for i in range(len(target)): im = Variable(data[i].unsqueeze(0).cuda()) y = Variable(torch.FloatTensor([target[i]]).cuda()) out = model(im) # if out satisfy some condtion, we will calculate loss # for this sample, else proceed to next sample if some_condition(out): loss = criterion(out, y) else: continue total_loss += loss loss_count_local += 1 if loss_count_local == 32 or i == (len(target)-1): total_loss /= loss_count_local total_loss.backward() total_loss = 0 loss_count_local = 0 optimizer.step() My question is, as I do forward for all samples but only do backward for some of the samples. When will the graph for those samples which do not contribute to the loss be freed? Will these graphs be freed only after the for loop has ended or immediately after I do forward for the next sample? I am a little confused here. Also for those samples that do contribute to the total_loss, their graph will be freed immediately after we do total_loss.backward(). Is that right?
Let's start with a general discussion of how PyTorch frees memory: First, we should emphasize that PyTorch uses an implicitly declared graph that is stored in Python object attributes. (Remember, it's Python, so everything is an object). More specifically, torch.autograd.Variables have a .grad_fn attribute. This attribute's type defines what kind of computation node we have (e.g. an addition), and the input to that node. This is important because Pytorch frees memory simply by using the standard python garbage collector (if fairly aggressively). In this context, this means that the (implicitly declared) computation graphs will be kept alive as long as there are references to the objects holding them in the current scope! This means that if you e.g. do some kind of batching on samples s_1 ... s_k, compute the loss for each and add the loss at the end, that cumulative loss will hold references to each individual loss, which in turn holds references to each of the computation nodes that computed it. So your question applied to your code is more about how Python (or, more specifically its garbage collector) handles references than about Pytorch does. Since you accumulate the loss in one object (total_loss), you keep pointers alive, and thereby do not free the memory until you re-initialize that object in the outer loop. Applied to your example, this means that the computation graph you create in the forward pass (at out = model(im)) is only referenced by the out object and any future computations thereof. So if you compute the loss and sum it, you will keep references to out alive, and thereby to the computation graph. If you do not use it, however, the garbage collector should recursively collect out, and its computation graph.
https://stackoverflow.com/questions/47587122/
How to cast a 1-d IntTensor to int in Pytorch
How do I convert a 1-D IntTensor to an integer? This: IntTensor.int() Gives an error: KeyError: Variable containing: 423 [torch.IntTensor of size 1]
You can use: print(dictionary[IntTensor.data[0]]) The key you're using is an object of type autograd.Variable. .data gives the tensor and the index 0 can be used to access the element.
https://stackoverflow.com/questions/47588682/
torch.nn has no attribute named upsample
Following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-perform-neural-style-transfer-with-python-3-and-pytorch#step-2-%E2%80%94-running-your-first-style-transfer-experiment When I run the example in Jupyter notebook, I get the following: So, I've tried troubleshooting, which eventually got me to running it as per the github example (https://github.com/zhanghang1989/PyTorch-Multi-Style-Transfer) says to via command line: python main.py eval --content-image images/content/venice-boat.jpg --style-image images/21styles/candy.jpg --model models/21styles.model --content-size 1024 --cuda=0 However, this gives the following error: Traceback (most recent call last): File "main.py", line 287, in <module> main() File "main.py", line 44, in main evaluate(args) File "main.py", line 242, in evaluate stylemodel = Net(ngf=args.ngf) File "/root/styletransfer/PyTorch-Style-Transfer/experiments/net.py", line 284, in init model += [upblock(ngf*expansion, 32, 2, normlayer), File "/root/styletransfer/PyTorch-Style-Transfer/experiments/net.py", line 127, in init kernelsize=1, stride=1, upsample=stride) File "/root/styletransfer/PyTorch-Style-Transfer/experiments/net.py", line 167, in init self.upsamplelayer = torch.nn.Upsample(scalefactor=upsample) AttributeError: module 'torch.nn' has no attribute 'Upsample' I can't figure out how to get past this?
I think the reason maybe that you have an older version of PyTorch on your system. On my system, the pytorch version is 0.2.0, torch.nn has a module called Upsample. You can uninstall your current version of pytorch and reinstall it.
https://stackoverflow.com/questions/47635918/
Reshaping 2 numpy dimensions into one with zipping?
I tried searching for this question but I couldn't find anything relevant. The quickest way to describe the problem is with a simple example: lets say I have a 2D numpy arrayl like this: [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23]] So it has the shape [3,6] I want to reshape it into a 1D array that looks like this: [0, 10 ,20 ,1 ,11 ,21 ,2 ,12 ,22 ,3 ,13 ,23 ] Unlike the array we get with reshape: [ 0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23] Now, to the actual problem I have... I actually have a 3D array and I want to reshape it into 2D array, and I want to do so with the method described above. And another example would be: import numpy a = numpy.array([[[0,1,2],[10,11,12],[20,21,22]], [[100,101,102],[110,111,112],[120,121,122]], [[200,201,202],[210,211,212],[220,221,222]]]) a.shape a.reshape(3,9) OUTPUT: array([[ 0, 1, 2, 10, 11, 12, 20, 21, 22], [100, 101, 102, 110, 111, 112, 120, 121, 122], [200, 201, 202, 210, 211, 212, 220, 221, 222]]) And again, I want my output to look like this instead: [[ 0, 10, 20, 1, 11, 21, 2, 12, 22], [100, 110, 120, 101, 111, ..................], [...........................................]] EDIT: just for the sake of people who google this problem, I add some search terms that some people might search for: Interweave dimensions numpy array Zip dimensions numpy array Numpy reshape ordered dimensions Tensor reshape dimensions timesteps
We need to swap the last two axes with np.swapaxes or np.transpose and then reshape. For 2D input case, it would be - a.swapaxes(-2,-1).ravel() For 3D input case, only the reshape part changes - a.swapaxes(-2,-1).reshape(a.shape[0],-1) Generic way : To make it generic that would cover all n-dim array cases - a.swapaxes(-2,-1).reshape(a.shape[:-2] + (-1,)).squeeze() Sample runs 2D case : In [186]: a Out[186]: array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23]]) In [187]: a.swapaxes(-2,-1).reshape(a.shape[:-2] + (-1,)).squeeze() Out[187]: array([ 0, 10, 20, 1, 11, 21, 2, 12, 22, 3, 13, 23]) 3D case : In [189]: a Out[189]: array([[[ 0, 1, 2], [ 10, 11, 12], [ 20, 21, 22]], [[100, 101, 102], [110, 111, 112], [120, 121, 122]], [[200, 201, 202], [210, 211, 212], [220, 221, 222]]]) In [190]: a.swapaxes(-2,-1).reshape(a.shape[:-2] + (-1,)).squeeze() Out[190]: array([[ 0, 10, 20, 1, 11, 21, 2, 12, 22], [100, 110, 120, 101, 111, 121, 102, 112, 122], [200, 210, 220, 201, 211, 221, 202, 212, 222]]) Runtime test - In [14]: a = np.random.rand(3,3,3) # @mahdi n75's soln In [15]: %timeit np.reshape(a,(3,9), order='F') 1000000 loops, best of 3: 1.22 µs per loop In [16]: %timeit a.swapaxes(-2,-1).reshape(a.shape[0],-1) 1000000 loops, best of 3: 1.01 µs per loop In [20]: a = np.random.rand(30,30,30) # @mahdi n75's soln In [21]: %timeit np.reshape(a,(30,900), order='F') 10000 loops, best of 3: 28.4 µs per loop In [22]: %timeit a.swapaxes(-2,-1).reshape(a.shape[0],-1) 10000 loops, best of 3: 18.9 µs per loop In [17]: a = np.random.rand(300,300,300) # @mahdi n75's soln In [18]: %timeit np.reshape(a,(300,90000), order='F') 1 loop, best of 3: 333 ms per loop In [19]: %timeit a.swapaxes(-2,-1).reshape(a.shape[0],-1) 10 loops, best of 3: 52.4 ms per loop
https://stackoverflow.com/questions/47642014/
Automatically set cuda variables in pytorch
I'm trying to automatically set Variables to use cuda if a flag use_gpu is activated. Usually I would do: import torch from torch import autograd use_gpu = torch.cuda.is_available() foo = torch.randn(5) if use_gpu: fooV = autograd.Variable(foo.cuda()) else: fooV = autograd.Variable(foo) However, to do things faster when I have to initialise variables in different parts of the code I wanted to do something like this: import torch from torch import autograd use_gpu = torch.cuda.is_available() class Variable(autograd.Variable): def __init__(self, data, *args, **kwargs): if use_gpu: data = data.cuda() super(Variable, self).__init__(data, *args, **kwargs) foo = torch.randn(5) fooV = Variable(foo) Unfortunately, this doesn't seem to be working and fooV doesn't contain a cuda Tensor when the use_gpu is True.
An alternative is to use type method on CPU Tensor to convert it to GPU Tensor, if use_cuda: dtype = torch.cuda.FloatTensor else: dtype = torch.FloatTensor x = torch.rand(2,2).type(dtype) Also, you can find a discussion here.
https://stackoverflow.com/questions/47645271/
tf.concat operation in PyTorch
torch.stack is not what I am searching. I am looking for the Tensorflow's concat operation for Pytorch. I have searched the doc http://pytorch.org/docs/0.3.0/
I belive torch.cat is what you are looking for. http://pytorch.org/docs/master/torch.html#torch.cat
https://stackoverflow.com/questions/47645428/
Create a nnModule that's just the identity
I'm trying to debug a pretty complex interaction between different nnModules. It would be very helpful for me to be able to replace one of them with just an identity network for debugging purposes. For example: net_a = NetworkA() net_b = NetworkB() net_c = NetworkC() input = Autograd.Variable(torch.rand(10,2)) out = net_a(input) out = net_b(out) out = net_c(out) I would like to be able to just change the second line to net_b = IdentityNet(), instead of having to go through and reconnect all my As to Cs. But, when I make a completely empty nnModule, the optimizer throws ValueError: optimizer got an empty parameter list. Is there any workaround this? A minimum non-working example: import torch.optim as optim class IdentityModule(nnModule): def forward(self, inputs): return inputs identity = IdentityModule() opt = optim.Adam(identity, lr=0.001) out = identity(any_tensor) error = torch.mean(out) error.backward() opt.step()
The problem you encounter here is a logical one. Look at what it means when you do: error.backward() opt.step() .backward() will recursively compute the gradients from your output to any input you pass into the network. In terms of the computation graph, there are two noteworthy kinds of inputs: the input you pass in, and the nn.Parameters that model the network's behavior. When you then do opt.step(), PyTorch will look for any input that it can update to change the output of the network, namely the nn.Parameters(). However, your Pseudo-code does not have a single nn.Parameter!, since the identity module does not contain one. So when you call these functions, the opt.step() has no targets, explaining the error message. This does not extend to the case you describe earlier. If you chain a module with no parameters into a larger chain with some that do have parameters, there are parameters to train in the computation graph. You need to make sure, though, that the optimizer indeed gets all of these parameters passed upon initialization. A simple trick is to print these: net_a = SomeNetwork() net_b = IdentityNetwork() # has no parameters net_c = SomeNetwork() print(list(net_a.parameters())) # will contain whatever parameters in net_a print(list(net_b.parameters())) # will be [] print(list(net_c.parameters())) # will contain whatever parameters in net_c # to train all of them, you can do one of two things: # 1. create new module. This works, since `.parameters()` collects params recursively from all submodules. class NewNet(nn.Module): def __init__(self): nn.Module.__init__(self) self.net_a = net_a self.net_b = identity self.net_c = net_c def forward(self, input): return self.net_c(self.net_b(self.net_a(input))) all_parameters = list(NewNet().parameters()) print(all_parameters) # will contain a list of all parameters of net_a and net_c # 2. simply merge the lists all_parameters = list(net_a.parameters()) + list(net_b.parameters()) + list(net_c.parameters()) print(all_parameters) # will contain a list of all parameters of net_a and net_c opt = optim.SGD(all_parameters)
https://stackoverflow.com/questions/47646130/
Error when upgrading PyTorch to 0.3.0
I tried to update PyTorch to the recently released 0.3.0, conda install pytorch=0.3.0 torchvision -c pytorch But I'm getting the following error: NoPackagesFoundError: Dependency missing in current linux-64 channels: - pytorch 0.3.0* -> mkl >=2018
You can also update the condo itself and then try again: conda update conda conda update pytorch -c pytorch It will use the updated channels and download the latest mil version.
https://stackoverflow.com/questions/47734702/