instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
PyTorch and Convolutional Neural Networks
I have a image input 340px*340px and I want to classify it to 2 classes. I want to create convolution neural network (PyTorch framework). I have a problem with input and output of layer. class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 3 channels (RGB), kernel=5, but i don't understand why 6. self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) #why 16? self.conv2 = nn.Conv2d(6, 16, 5) #why 107584 = 328*328 self.fc1 = nn.Linear(107584, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 2) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) # i dont understand this line x = x.view(x.size(0), -1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x Is it network is correct?
# 3 channels (RGB), kernel=5, but i don't understand why 6. The second parameter of Conv2d is out_channels. In a convolutional layer you can arbitrarily define a number of out channels. So it's set to 6 because someone set it to 6. # why 16? Same as above. #why 107584 = 328*328 and \ # i dont understand this line Tensor.view() returns a new tensor with the same data as the self tensor but of a different size. x = x.view(x.size(0), -1): -1 means "infer from other dimensions" so, you are forcing the Tensor to be [1, 15*164*164] => [1, 403440]. 403440 is also the correct value for self.fc1 = nn.Linear(107584, 120), instead of 107584.
https://stackoverflow.com/questions/49029705/
LSTM with Attention
I am trying to add attention mechanism to stacked LSTMs implementation https://github.com/salesforce/awd-lstm-lm All examples online use encoder-decoder architecture, which I do not want to use (do I have to for the attention mechanism?). Basically, I have used https://webcache.googleusercontent.com/search?q=cache:81Q7u36DRPIJ:https://github.com/zhedongzheng/finch/blob/master/nlp-models/pytorch/rnn_attn_text_clf.py+&cd=2&hl=en&ct=clnk&gl=uk def __init__(self, rnn_type, ntoken, ninp, nhid, nlayers, dropout=0.5, dropouth=0.5, dropouti=0.5, dropoute=0.1, wdrop=0, tie_weights=False): super(RNNModel, self).__init__() self.encoder = nn.Embedding(ntoken, ninp) self.rnns = [torch.nn.LSTM(ninp if l == 0 else nhid, nhid if l != nlayers - 1 else (ninp if tie_weights else nhid), 1, dropout=0) for l in range(nlayers)] for rnn in self.rnns: rnn.linear = WeightDrop(rnn.linear, ['weight'], dropout=wdrop) self.rnns = torch.nn.ModuleList(self.rnns) self.attn_fc = torch.nn.Linear(ninp, 1) self.decoder = nn.Linear(nhid, ntoken) self.init_weights() def attention(self, rnn_out, state): state = torch.transpose(state, 1,2) weights = torch.bmm(rnn_out, state)# torch.bmm(rnn_out, state) weights = torch.nn.functional.softmax(weights)#.squeeze(2)).unsqueeze(2) rnn_out_t = torch.transpose(rnn_out, 1, 2) bmmed = torch.bmm(rnn_out_t, weights) bmmed = bmmed.squeeze(2) return bmmed def forward(self, input, hidden, return_h=False, decoder=False, encoder_outputs=None): emb = embedded_dropout(self.encoder, input, dropout=self.dropoute if self.training else 0) emb = self.lockdrop(emb, self.dropouti) new_hidden = [] raw_outputs = [] outputs = [] for l, rnn in enumerate(self.rnns): temp = [] for item in emb: item = item.unsqueeze(0) raw_output, new_h = rnn(item, hidden[l]) raw_output = self.attention(raw_output, new_h[0]) temp.append(raw_output) raw_output = torch.stack(temp) raw_output = raw_output.squeeze(1) new_hidden.append(new_h) raw_outputs.append(raw_output) if l != self.nlayers - 1: raw_output = self.lockdrop(raw_output, self.dropouth) outputs.append(raw_output) hidden = new_hidden output = self.lockdrop(raw_output, self.dropout) outputs.append(output) outputs = torch.stack(outputs).squeeze(0) outputs = torch.transpose(outputs, 2,1) output = output.transpose(2,1) output = output.contiguous() decoded = self.decoder(output.view(output.size(0)*output.size(1), output.size(2))) result = decoded.view(output.size(0), output.size(1), decoded.size(1)) if return_h: return result, hidden, raw_outputs, outputs return result, hidden This model is training, but my loss is quite high as compared to the model without the attention model.
I understood your question but it is a bit tough to follow your code and find the reason why the loss is not decreasing. Also, it is not clear why you want to compare the last hidden state of the RNN with all the hidden states at every time step. Please note, a particular trick/mechanism is useful if you use it in the correct way. The way you are trying to use attention mechanism, I am not sure if it is the correct way. So, don't expect that since you are using attention trick in your model, you will get good results!! You should think, why attention mechanism will bring advantage to your desired task? You didn't clearly mention what is that task you are targetting? Since you have pointed to a repo which contains code on language modeling, I am guessing the task is: given a sequence of tokens, predict the next token. One possible problem I can see in your code is: in the for item in emb: loop, you will always use the embedddings as input to each LSTM layer, so having a stacked LSTM doesn't make sense to me. Now, let me first answer your question and then show step-by-step how can you build your desired NN architecture. Do I need to use encoder-decoder architecture to use attention mechanism? The encoder-decoder architecture is better known as sequence-to-sequence to learning and it is widely used in many generation task, for example, machine translation. The answer to your question is no, you are not required to use any specific neural network architecture to use attention mechanism. The structure you presented in the figure is little ambiguous but should be easy to implement. Since your implementation is not clear to me, I am trying to guide you to a better way of implementing it. For the following discussion, I am assuming we are dealing with text inputs. Let's say, we have an input of shape 16 x 10 where 16 is batch_size and 10 is seq_len. We can assume we have 16 sentences in a mini-batch and each sentence length is 10. batch_size, vocab_size = 16, 100 mat = np.random.randint(vocab_size, size=(batch_size, 10)) input_var = Variable(torch.from_numpy(mat)) Here, 100 can be considered as the vocabulary size. It is important to note that throughout the example I am providing, I am assuming batch_size as the first dimension in all respective tensors/variables. Now, let's embed the input variable. embedding = nn.Embedding(100, 50) embed = embedding(input_var) After embedding, we got a variable of shape 16 x 10 x 50 where 50 is the embedding size. Now, let's define a 2-layer unidirectional LSTM with 100 hidden units at each layer. rnns = nn.ModuleList() nlayers, input_size, hidden_size = 2, 50, 100 for i in range(nlayers): input_size = input_size if i == 0 else hidden_size rnns.append(nn.LSTM(input_size, hidden_size, 1, batch_first=True)) Then, we can feed our input to this 2-layer LSTM to get the output. sent_variable = embed outputs, hid = [], [] for i in range(nlayers): if i != 0: sent_variable = F.dropout(sent_variable, p=0.3, training=True) output, hidden = rnns[i](sent_variable) outputs.append(output) hid.append(hidden[0].squeeze(0)) sent_variable = output rnn_out = torch.cat(outputs, 2) hid = torch.cat(hid, 1) Now, you can simply use the hid to predict the next word. I would suggest you do that. Here, shape of hid is batch_size x (num_layers*hidden_size). But since you want to use attention to compute soft alignment score between last hidden states with each hidden states produced by LSTM layers, let's do this. sent_variable = embed hid, con = [], [] for i in range(nlayers): if i != 0: sent_variable = F.dropout(sent_variable, p=0.3, training=True) output, hidden = rnns[i](sent_variable) sent_variable = output hidden = hidden[0].squeeze(0) # batch_size x hidden_size hid.append(hidden) weights = torch.bmm(output[:, 0:-1, :], hidden.unsqueeze(2)).squeeze(2) soft_weights = F.softmax(weights, 1) # batch_size x seq_len context = torch.bmm(output[:, 0:-1, :].transpose(1, 2), soft_weights.unsqueeze(2)).squeeze(2) con.append(context) hid, con = torch.cat(hid, 1), torch.cat(con, 1) combined = torch.cat((hid, con), 1) Here, we compute soft alignment score between the last state with all the states of each time step. Then we compute a context vector which is just a linear combination of all the hidden states. We combine them to form a single representation. Please note, I have removed the last hidden states from output: output[:, 0:-1, :] since you are comparing with last hidden state itself. The final combined representation stores the last hidden states and context vectors produced at each layer. You can directly use this representation to predict the next word. Predicting the next word is straight-forward and as you are using a simple linear layer is just fine. Edit: We can do the following to predict the next word. decoder = nn.Linear(nlayers * hidden_size * 2, vocab_size) dec_out = decoder(combined) Here, the shape of dec_out is batch_size x vocab_size. Now, we can compute negative log-likelihood loss which will be used to backpropagate later. Before computing the negative log-likelihood loss, we need to apply log_softmax to the output of the decoder. dec_out = F.log_softmax(dec_out, 1) target = np.random.randint(vocab_size, size=(batch_size)) target = Variable(torch.from_numpy(target)) And, we also defined the target which is required to compute the loss. See NLLLoss for details. So, now we can compute the loss as follows. criterion = nn.NLLLoss() loss = criterion(dec_out, target) print(loss) The printed loss value is: Variable containing: 4.6278 [torch.FloatTensor of size 1] Hope the entire explanation helps you!!
https://stackoverflow.com/questions/49086221/
optim.lr_scheduler.ReduceLROnPlateau gives error value cannot be converted to type float without overflow: inf
I am using pytorch with this install command: pip3 install http://download.pytorch.org/whl/cu80/torch-0.3.1-cp35-cp35m-linux_x86_64.whl. I have a model that trains without issues, but when I add a learning rate scheduler, I get an error My scheduler: # In init self.optimizer = optim.Adam(self.model.parameters(), lr=0.01) self.scheduler = optim.lr_scheduler.ReduceLROnPlateau( self.optimizer, 'min', factor=0.1, patience=5, verbose=True ) # after each epoch self.scheduler.step(loss) The error: ... my_project/.env/lib/python3.5/site-packages/torch/optim/lr_scheduler.py in <lambda>(a, best) 330 if mode == 'min' and threshold_mode == 'rel': 331 rel_epsilon = 1. - threshold --> 332 self.is_better = lambda a, best: a < best * rel_epsilon 333 self.mode_worse = float('Inf') 334 elif mode == 'min' and threshold_mode == 'abs': RuntimeError: value cannot be converted to type float without overflow: inf Doc: http://pytorch.org/docs/master/optim.html#torch.optim.lr_scheduler.ReduceLROnPlateau Related thread: https://discuss.pytorch.org/t/value-cannot-be-converted-to-type-double-without-overflow-inf/11752/7
I'm using gpu tensors, eg: Variable(torch.from_numpy(X).type(torch.FloatTensor).cuda(), requires_grad=False) If I cast it to the cpu like that, the error goes away # after each epoch self.scheduler.step(loss.cpu().data.numpy()) Still, I would like a cleaner solution.
https://stackoverflow.com/questions/49097669/
Differentiate gradients
Is there a way to differentiate gradients in PyTorch? For example, I can do this in TensorFlow: from pylab import * import tensorflow as tf tf.reset_default_graph() sess = tf.InteractiveSession() def gradient_descent( loss_fnc, w, max_its, lr): '''a gradient descent "RNN" ''' for k in range(max_its): w = w - lr * tf.gradients( loss_fnc(w), w )[0] return w lr = tf.Variable( 0.0, dtype=tf.float32) w = tf.Variable( tf.zeros(10), dtype=tf.float32) reg = tf.Variable( 1.0, dtype=tf.float32 ) def loss_fnc(w): return tf.reduce_sum((tf.ones(10) - w)**2) + reg * tf.reduce_sum( w**2 ) w_n = gradient_descent( loss_fnc, w, 10, lr ) sess.run( tf.initialize_all_variables()) # differentiate through the gradient_descent RNN with respnect to the initial weight print(tf.gradients( w_n, w)) # differentiate through the gradient_descent RNN with respnect to the learning rate print(tf.gradients( w_n, lr)) and the output is [<tf.Tensor 'gradients_10/AddN_9:0' shape=(10,) dtype=float32>] [<tf.Tensor 'gradients_11/AddN_9:0' shape=() dtype=float32>] How would I do something similar in PyTorch?
You just need to use the function torch.autograd.grad it does exactly the same as tf.gradients. So in pytorch this would be: from torch.autograd import Variable, grad import torch def gradient_descent( loss_fnc, w, max_its, lr): '''a gradient descent "RNN" ''' for k in range(max_its): w = w - lr * grad( loss_fnc(w), w ) return w lr = Variable(torch.zeros(1), , requires_grad=True) w = Variable( torch.zeros(10), requires_grad=True) reg = Variable( torch.ones(1) , requires_grad=True) def loss_fnc(w): return torch.sum((Variable(torch.ones(10)) - w)**2) + reg * torch.sum( w**2 ) w_n = gradient_descent( loss_fnc, w, 10, lr ) # differentiate through the gradient_descent RNN with respnect to the initial weight print(grad( w_n, w)) # differentiate through the gradient_descent RNN with respnect to the learning rate print(grad( w_n, lr))
https://stackoverflow.com/questions/49149699/
Can I assign the coordinate that convolutional filter works on?
I do not want the conv kernel to slide every pixel in the image, I only need to to do conv operation on the pixels I assigned. For example, on a 224 x 224 image, normally the conv operation will slide all 224 x 224 = 50176 pixels. However, if I only want it to do conv on (15,67), (34, 90), (143,201)...., how can I do it? BTW, I want these operations all run on GPU. Thanks a lot!
If you have the kernel K (of shape H_k x W_k x C_in x C_out) and the image I (of shape MB x H x W x C_in) and you have a position where you want to apply the kernel h, w then you don't need to use a convolution, you can just apply the kernel directly with a broadcasting matrix multiplication: Out = torch.matmul(I[:, h:h+H_k, w:w+W_k, None, :], K.unsqueeze(0))[:, :, :, 0, :]
https://stackoverflow.com/questions/49169437/
Using a pytorch model for inference
I am using the fastai library (fast.ai) to train an image classifier. The model created by fastai is actually a pytorch model. type(model) <class 'torch.nn.modules.container.Sequential'> Now, I want to use this model from pytorch for inference. Here is my code so far: torch.save(model,"./torch_model_v1") the_model = torch.load("./torch_model_v1") the_model.eval() # shows the entire network architecture Based on the example shown here: http://pytorch.org/tutorials/beginner/data_loading_tutorial.html#sphx-glr-beginner-data-loading-tutorial-py, I understand that I need to write my own data loading class which will override some of the functions in the Dataset class. But what is not clear to me is the transformations that I need to apply at test time? In particular, how do I normalize the images at test time? Another question: is my approach of saving and loading the model in pytorch fine? I read in the tutorial here: http://pytorch.org/docs/master/notes/serialization.html that the approach that I have used is not recommended. The reason is not clear though.
Just to clarify: the_model.eval() not only prints the architecture, but sets the model to evaluation mode. In particular, how do I normalize the images at test time? It depends on the model you have. For instance, for torchvision modules, you have to normalize the inputs this way. Regarding on how to save / load models, torch.save/torch.load "saves/loads an object to a disk file." So, if you save the_model, it will save the entire model object, including its architecture definition and some other internal aspects. If you save the_model.state_dict(), it will save a dictionary containing the model state (i.e. parameters and buffers) only. Saving the model can break the code in various ways, so the preferred method is to save and load only the model state. However, I'm not sure if fast.ai "model file" is actually a full model or the state of a model. You have to check this so you can correctly load it.
https://stackoverflow.com/questions/49221374/
Pytorch pretrained model (VGG-19) same image gives slightly different class score in the final FC layer
I am using pretrained vgg-19 from torch.vision module I have the pre-processing of image data like below: normalize = transforms.Normalize( mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] ) preprocess = transforms.Compose([ transforms.Scale(224), transforms.ToTensor(), normalize ]) The problem is if I pass an image like a tennis ball through the network and save all the 1000 class score from the final FC layer and pass the same image again after some time, the final FC layer i.e the class score is slightly changed. Although the image category detected by the network is correct. (its a tennis ball) Is it normal to have the slightly different class score for the same image? I mean, does this suppose to happen? Or for the correctly implemented pre-trained model, the network should give you the exact same class score every time for the same image.
Possible reasons why the class score could be different: You are using GPUs: The GPU evaluation is slightly stochastic, so if you are using GPUs in your feedforward evaluation, it could give slightly different scores. You are using the model in training mode model.train() and didn't activate the evaluation mode using model.eval() and your model contains some stochastic parts like dropout or adding noise to input. Then those stochastic parts will still be active.
https://stackoverflow.com/questions/49224709/
Titan XP vs Quadro P400 GPU in Pytorch
I gave the the two GPUs on my machine a try and I expected the Titan-XP to be faster than the Quadro-P400. However, both gave almost the same execution time. I need to know if PyTorch will dynamically choose one GPU over another, or, I myself will have to specify which one PyTorch will use, during run-time. Here is the code snippet used in the test: import torch import time def do_something(gpu_device): torch.cuda.set_device(gpu_device) # torch.cuda.set_device(device_num) print("current GPU device ", torch.cuda.current_device()) strt = time.time() a = torch.randn(100000000).cuda() xx = time.time() - strt print("execution time, to create 1E8 random numbers, is ", xx) # print(a) # print(a + 2) no_of_GPUs= torch.cuda.device_count() print("how many GPUs are there:", no_of_GPUs) for i in range(0, no_of_GPUs): print(i, "th GPU is", torch.cuda.get_device_name(i)) do_something(i) Sample output: how many GPUs are there: 2 0 th GPU is TITAN Xp COLLECTORS EDITION current GPU device 0 execution time, to create 1E8 random numbers, is 5.527713775634766 1 th GPU is Quadro P400 current GPU device 1 execution time, to create 1E8 random numbers, is 5.511776685714722
Despite what you might believe, the lack of performance difference which you see is because the random number generation is being run on your host CPU not the GPU. If I modify your do_something routine like this: def do_something(gpu_device, ongpu=False, N=100000000): torch.cuda.set_device(gpu_device) print("current GPU device ", torch.cuda.current_device()) strt = time.time() if ongpu: a = torch.cuda.FloatTensor(N).normal_() else: a = torch.randn(N).cuda() print("execution time, to create 1E8 random no, is ", time.time() - strt) return a and run it two ways, I get very different execution times: In [4]: do_something(0) current GPU device 0 execution time, to create 1E8 random no, is 7.736972808837891 Out[4]: -9.3955e-01 -1.9721e-01 -1.1502e+00 ...... -1.2428e+00 3.1547e-01 -2.1870e+00 [torch.cuda.FloatTensor of size 100000000 (GPU 0)] In [5]: do_something(0,True) current GPU device 0 execution time, to create 1E8 random no, is 0.001735687255859375 Out[5]: 4.1403e+06 5.7016e+06 1.2710e+07 ...... 8.9790e+06 1.3779e+07 8.0731e+06 [torch.cuda.FloatTensor of size 100000000 (GPU 0)] i.e. your version takes 7 seconds and mine takes 1.7ms. I think it is obvious which one ran on the GPU....
https://stackoverflow.com/questions/49235599/
Pytorch register_hook to Keras implementation
Im trying to implement the following project into Tensorflow/Keras. https://github.com/jacobgil/pytorch-pruning Im having a hard time understanding what register_hook does? It can be found in finetune.py, row 66. x.register_hook(self.compute_rank) I've searched for clear explanations regarding this function and tried to find Keras-equivalents, without any luck. Do you have answers to these questions?
First things first, here's the documentation: http://pytorch.org/docs/master/autograd.html#torch.autograd.Variable.register_hook This allows you to register a method to a Variable that is called whenever the Variable's .grad is updated, i.e. in a backward pass, and takes the grad as input. The method can return a Variable that would replace the original .grad or None if you just want to read the gradients to do something else. If you update the gradients this way, the nodes further down in the compute graph see the new updated gradient in the backward pass and will have their respective gradients calculated with the updated value. I'm not a Tensorflow expert, but the RegisterGradient decorators (documentation) seem to be able to do the same, for an example see this answer.
https://stackoverflow.com/questions/49276111/
Tensor sizes CrossEntropyLoss
In the snippet: criterion = nn.CrossEntropyLoss() raw_loss = criterion(output.view(-1, ntokens), targets) output size is torch.Size([5, 5, 8967]), targets size is torch.Size([25]), and ntokens is 8967 After modifying the code, my output size is torch.Size([5, 8967]) and targets size is torch.Size([25]) which rises dimensionality issues when computing the loss. Is it sensible to increase the size of my Linear activation that produces the output by 5, so that I can resize the output later to be of the size torch.Size([5, 5, 8967])? The problem with increasing the size of the tensor is that ntokens can become quite large and I can easily run out of memory because of that. Is there an alternative approach?
You should do something like this: ntokens = 8000 output = Variable(torch.randn(5, 5, ntokens)) targets = Variable(torch.from_numpy(np.random.randint(0, ntokens, size=25))) criterion = nn.CrossEntropyLoss() loss = criterion(output.view(-1, ntokens), targets) print(loss) This prints: Variable containing: 9.4613 [torch.FloatTensor of size 1] Here, I am assuming output contains predictions of next word for 5 sentences (minibatch size is 5) and each sentence is of length 5 (sequence length is 5). 8000 is the vocabulary size, so your model is predicting a probability distribution over the entire vocabulary. Now, you can compute the loss of predicting each word as your target shape is 25 as required. Please note, CrossEntropyLoss expects input to contain scores for each class. So, input has to be a 2D Tensor of size (minibatch, C) and the target has to be a class index (0 to C-1) for each value of a 1D tensor of size minibatch.
https://stackoverflow.com/questions/49280731/
Implementing WNGrad in Pytorch?
I'm trying to implement the WNGrad (technically WN-Adam, algorithm 4 in the paper) optimizier (WNGrad) in pytorch. I've never implemented an optimizer in pytorch before so I don't know if I've done it correctly (I started from the adam implementation). The optimizer does not make much progress and falls down like I would expect (bj values can only monotonically increase, which happens quickly so no progress is made) but I'm guessing I have a bug. Standard optimizers (Adam, SGD) work fine on the same model I'm trying to optimize. Does this implementation look correct? from torch.optim import Optimizer class WNAdam(Optimizer): """Implements WNAdam algorithm. It has been proposed in `WNGrad: Learn the Learning Rate in Gradient Descent`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 0.1) beta1 (float, optional): exponential smoothing coefficient for gradient. When beta=0 this implements WNGrad. .. _WNGrad\: Learn the Learning Rate in Gradient Descent: https://arxiv.org/abs/1803.02865 """ def __init__(self, params, lr=0.1, beta1=0.9): if not 0.0 <= beta1 < 1.0: raise ValueError("Invalid beta1 parameter: {}".format(beta1)) defaults = dict(lr=lr, beta1=beta1) super().__init__(params, defaults) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data state = self.state[p] # State initialization if len(state) == 0: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Learning rate adjustment state['bj'] = 1.0 exp_avg = state['exp_avg'] beta1 = group['beta1'] state['step'] += 1 state['bj'] += (group['lr']**2)/(state['bj'])*grad.pow(2).sum() # update exponential moving average exp_avg.mul_(beta1).add_(1 - beta1, grad) bias_correction = 1 - beta1 ** state['step'] p.data.sub_(group['lr'] / state['bj'] / bias_correction, exp_avg) return loss
The paper's author has an open sourced implementation on GitHub.
https://stackoverflow.com/questions/49282523/
Binary One Hot Encoding For Dimension Reduction
Introduction: I've been studying machine learning this last couple of months, more specifically neural networks. I found out that categorical data, such as cities, could be transformed to integer data, but shouldn't because there's no linearity. What I mean by this is: there is no reason why New York should be 1 or 100. A better solution to this is one hot encoding. However, it greatly increases the dimensionality of the problem (Picture a network input with the number of cities as input nodes). Example: New York = [1, 0, 0] Buenos Aires = [0, 1, 0] Tokio = [0, 0, 1] You need N inputs, N being the number of cities. Possible Solution: I don't really know if this already exists or if it could work, I haven't tested it yet. That being said, in the example above, I'm using decimal inputs. Could you use binary inputs, in order to reduce the dimensionality of the problem? Example using binary inputs New York = [0, 1] Buenos Aires = [1, 0] Tokio = [1, 1] In this way, you only need ≈ log(N) (base 2) number of inputs which greatly increases, specially if there are a great number of features. For example: if you have 1000 categorical data inputs, it would only result in 10 inputs for a neural network. Thank you in advance. Remember I'm only learning.
I do not think that you can translate One Hot Encoding (OHE) to binary inputs. The meaning of One Hot Encoding is that you have as many features as you have cities. No two cities share value for any feature, as they are distinct. After you translation to binary inputs, various cities randomly share values for the same feature. E.g. both Buenos Aires and Tokio would have 1 as the first feature. The neural network would think that they really have this feature in common. Yet it is not the case, depending on your ordering, New York could easily share value of the first feature with Tokio: Buenos Aires = [0, 1] Tokio = [1, 0] New York = [1, 1] Now, Tokio and New York seem more similar to each other.
https://stackoverflow.com/questions/49300526/
I need some explanations about GAN codes
Here is github codes for epoch in range(num_epoch): for i, (img, _) in enumerate(dataloader): num_img = img.size(0) # =================train discriminator img = img.view(num_img, -1) real_img = Variable(img).cuda() real_label = Variable(torch.ones(num_img)).cuda() fake_label = Variable(torch.zeros(num_img)).cuda() I don`t understand whats the torch.ones and torch.zeros in training codes. Can anyone explain about this?
As you probably know: In GAN, generator tries to fool the discriminator by convincing that a fake example is a true example. Discriminator trained to distinguish true examples and fake examples. On the other hand, the generator is trained to generate (fake) examples that look very close to the real examples. Analysis of the code/example (in the link) you shared. Generator: is a simple feed-forward neural network. The generator generates 28 * 28 images from random (noisy) distribution. The goal of the generator is to generate images that look like real images. Discriminator: is a simple feed-forward neural network. The discriminator provides a sigmoid ([0, 1]) score given an image. The goal of the discriminator is to give low score (~0) to fake images and high score (~1) to real images. In essence, the discriminator wants to distinguish real images from fake ones. How does the code work? First, the discriminator is provided examples of real images and a loss is computed based on discriminator's predicted score. # compute loss of real_img real_out = D(real_img) d_loss_real = criterion(real_out, real_label) real_scores = real_out # closer to 1 means better Then the discriminator is provided the fake images generated by the generator. A loss is computed based on discriminator's score on fake examples. # compute loss of fake_img z = Variable(torch.randn(num_img, z_dimension)).cuda() fake_img = G(z) fake_out = D(fake_img) d_loss_fake = criterion(fake_out, fake_label) fake_scores = fake_out # closer to 0 means better Essentially, the generator and discriminator are competing against each other to become expert in achieving their goal. We can think in this way: if we have a perfect generator, then it will create fake example exactly look like real ones and the discriminator will fail to distinguish them and vice versa. The code you provided above is just creating labels using torch.zeros() and torch.ones(). You can simply consider it as binary labels for real and fake images.
https://stackoverflow.com/questions/49312367/
Loading huge text files for neural machine translation with Pytorch
In PyTorch, I have written a dataset loading class for loading 2 text files as source and targets, for neural machine translation purpose. Each file has 93577946 lines, and each of them allocates 8GB memory on Hard Disc. The class is as the following: class LoadUniModal(Dataset): sources = [] targets = [] maxlen = 0 lengths = [] def __init__(self, src, trg, src_vocab, trg_vocab): self.src_vocab = src_vocab self.trg_vocab = trg_vocab with codecs.open(src, encoding="utf-8") as f: for line in f: tokens = line.replace("\n", "").split() self.maxlen = max(self.maxlen, len(tokens)) self.sources.append(tokens) with codecs.open(trg, encoding="utf-8") as f: for line in f: tokens = line.replace("\n", "").split() self.maxlen = max(self.maxlen, len(tokens)) self.targets.append(tokens) self.lengths.append(len(tokens)+2) # Overrride to give PyTorch access to any image on the dataset def __getitem__(self, index): # Source sentence processing tokens = self.sources[index] ntokens = [self.src_vocab['<START>']] for a in range(self.maxlen): if a <= (len(tokens) - 1): if tokens[a] in self.src_vocab.keys(): ntokens.append(self.src_vocab[tokens[a]]) else: ntokens.append(self.src_vocab['<UNK>']) elif a == len(tokens): ntokens.append(self.src_vocab['<END>']) elif a > len(tokens): ntokens.append(self.src_vocab['<PAD>']) source = torch.from_numpy(np.asarray(ntokens)).long() # Target sentence processing tokens = self.targets[index] ntokens = [self.trg_vocab['<START>']] for a in range(self.maxlen): if a <= (len(tokens) - 1): if tokens[a] in self.trg_vocab.keys(): ntokens.append(self.trg_vocab[tokens[a]]) else: ntokens.append(self.trg_vocab['<UNK>']) elif a == len(tokens): ntokens.append(self.trg_vocab['<END>']) elif a > len(tokens): ntokens.append(self.trg_vocab['<PAD>']) target = torch.from_numpy(np.asarray(ntokens)).long() length = self.lengths[index] return [0], source, target, length def __len__(self): return len(self.sources) I use the class in order to load dataset as follows: def load_text_train_data(train_dir, src_vocab, trg_vocab, lang_pair, batch_size): tpl = ast.literal_eval(lang_pair) slang = tpl[1] tlang = tpl[2] strain_file = os.path.join(train_dir, "train"+slang) ttrain_file = os.path.join(train_dir, "train"+tlang) data_iter = LoadUniModal(strain_file, ttrain_file, src_vocab, trg_vocab) data_iter = DataLoader(data_iter, batch_size=batch_size) return data_iter When I am trying to load the data, I get memory error. How would it be possible to load the data without memory problem? Thanks,
This shouldn't give you an error unless you load the entire data in memory at once. One suggestion I want to give you is: don't pad all sentences to a maximum length. In machine translation data, in general, sentence lengths vary a lot. Also, you can try smaller mini-batches of size x (ex., 32, 64) which your memory can afford. Only pad the elements of the current mini-batch and move to cuda tensor and then pass it to your model. Hopefully, it will solve your problem.
https://stackoverflow.com/questions/49338649/
How to deploy pytorch in docker image?
I want to deploy pytorch on a docker image. Is there a way that I can do that? I faced so much problems installing pytorch, their official installation links does not seem to be working; neither pip/conda works. Does anyone have any alternative solution in installing pytorch?
You can find pytorch images on Dockerhub. If those images are not sufficient, you can check their Dockerfiles to see how you can build you own custom image.
https://stackoverflow.com/questions/49357332/
In pytorch, the meaning of y.backward([0.1, 1.0, 0.0001])
In pytorch what is the meaning of y.backward([0.1, 1.0, 0.0001])? I understand that y.backward() means doing backpropagation. But what is the meaning of [0.1, 1.0, 0.0001] in y.backward([0.1, 1.0, 0.0001])?
The expression y.backward([0.1, 1.0, 0.0001]) is actually wrong. It should be y.backward(torch.Tensor([0.1, 1.0, 0.0001])), where torch.Tensor([0.1, 1.0, 0.0001]) are the Variables of which the derivative will be computed. Example: x = Variable(torch.ones(2, 2), requires_grad=True) y = (x + 2).mean() y.backward(torch.Tensor([1.0])) print(x.grad) Here, y = (x + 2)/4 and so, dy/dx_i = 0.25 since x_i = 1.0. Also note, y.backward(torch.Tensor([1.0])) and y.backward() are equivalent. If you do: y.backward(torch.Tensor([0.1])) print(x.grad) it prints: Variable containing: 1.00000e-02 * 2.5000 2.5000 2.5000 2.5000 [torch.FloatTensor of size 2x2] It is simply 0.1 * 0.25 = 0.025. So, now if you compute: y.backward(torch.Tensor([0.1, 0.01])) print(x.grad) Then it prints: Variable containing: 1.00000e-02 * 2.5000 0.2500 2.5000 0.2500 [torch.FloatTensor of size 2x2] Where, dy/dx_11 = dy/d_x21 = 0.025 and dy/dx_12 = dy/d_x22 = 0.0025. See the function prototype of backward(). You may consider looking into this example.
https://stackoverflow.com/questions/49441425/
CTC loss goes down and stops
I’m trying to train a captcha recognition model. Model details are resnet pretrained CNN layers + Bidirectional LSTM + Fully Connected. It reached 90% sequence accuracy on captcha generated by python library captcha. The problem is that these generated captcha seems to have similary location of each character. When I randomly add spaces between characters, the model does not work any more. So I wonder is LSTM learning segmentation during learning? Then I try to use CTC loss. At first, loss goes down pretty quick. But it stays at about 16 without significant drop later. I tried different layers of LSTM, different number of units. 2 Layers of LSTM reach lower loss, but still not converging. 3 layers are just like 2 layers. The loss curve: #encoding:utf8 import os import sys import torch import warpctc_pytorch import traceback import torchvision from torch import nn, autograd, FloatTensor, optim from torch.nn import functional as F from torch.utils.data import DataLoader from torch.optim.lr_scheduler import MultiStepLR from tensorboard import SummaryWriter from pprint import pprint from net.utils import decoder from logging import getLogger, StreamHandler logger = getLogger(__name__) handler = StreamHandler(sys.stdout) logger.addHandler(handler) from dataset_util.utils import id_to_character from dataset_util.transform import rescale, normalizer from config.config import MAX_CAPTCHA_LENGTH, TENSORBOARD_LOG_PATH, MODEL_PATH class CNN_RNN(nn.Module): def __init__(self, lstm_bidirectional=True, use_ctc=True, *args, **kwargs): super(CNN_RNN, self).__init__(*args, **kwargs) model_conv = torchvision.models.resnet18(pretrained=True) for param in model_conv.parameters(): param.requires_grad = False modules = list(model_conv.children())[:-1] # delete the last fc layer. for param in modules[8].parameters(): param.requires_grad = True self.resnet = nn.Sequential(*modules) # CNN with fixed parameters from resnet as feature extractor self.lstm_input_size = 512 * 2 * 2 self.lstm_hidden_state_size = 512 self.lstm_num_layers = 2 self.chracter_space_length = 64 self._lstm_bidirectional = lstm_bidirectional self._use_ctc = use_ctc if use_ctc: self._max_captcha_length = int(MAX_CAPTCHA_LENGTH * 2) else: self._max_captcha_length = MAX_CAPTCHA_LENGTH if lstm_bidirectional: self.lstm_hidden_state_size = self.lstm_hidden_state_size * 2 # so that hidden size for one direction in bidirection lstm is the same as vanilla lstm self.lstm = self.lstm = nn.LSTM(self.lstm_input_size, self.lstm_hidden_state_size // 2, dropout=0.5, bidirectional=True, num_layers=self.lstm_num_layers) else: self.lstm = nn.LSTM(self.lstm_input_size, self.lstm_hidden_state_size, dropout=0.5, bidirectional=False, num_layers=self.lstm_num_layers) # dropout doen't work for one layer lstm self.ouput_to_tag = nn.Linear(self.lstm_hidden_state_size, self.chracter_space_length) self.tensorboard_writer = SummaryWriter(TENSORBOARD_LOG_PATH) # self.dropout_lstm = nn.Dropout() def init_hidden_status(self, batch_size): if self._lstm_bidirectional: self.hidden = (autograd.Variable(torch.zeros((self.lstm_num_layers * 2, batch_size, self.lstm_hidden_state_size // 2))), autograd.Variable(torch.zeros((self.lstm_num_layers * 2, batch_size, self.lstm_hidden_state_size // 2)))) # number of layers, batch size, hidden dimention else: self.hidden = (autograd.Variable(torch.zeros((self.lstm_num_layers, batch_size, self.lstm_hidden_state_size))), autograd.Variable(torch.zeros((self.lstm_num_layers, batch_size, self.lstm_hidden_state_size)))) # number of layers, batch size, hidden dimention def forward(self, image): ''' :param image: # batch_size, CHANNEL, HEIGHT, WIDTH :return: ''' features = self.resnet(image) # [batch_size, 512, 2, 2] batch_size = image.shape[0] features = [features.view(batch_size, -1) for i in range(self._max_captcha_length)] features = torch.stack(features) self.init_hidden_status(batch_size) output, hidden = self.lstm(features, self.hidden) # output = self.dropout_lstm(output) tag_space = self.ouput_to_tag(output.view(-1, output.size(2))) # [MAX_CAPTCHA_LENGTH * BATCH_SIZE, CHARACTER_SPACE_LENGTH] tag_space = tag_space.view(self._max_captcha_length, batch_size, -1) if not self._use_ctc: tag_score = F.log_softmax(tag_space, dim=2) # [MAX_CAPTCHA_LENGTH, BATCH_SIZE, CHARACTER_SPACE_LENGTH] else: tag_score = tag_space return tag_score def train_net(self, data_loader, eval_data_loader=None, learning_rate=0.008, epoch_num=400): try: if self._use_ctc: loss_function = warpctc_pytorch.warp_ctc.CTCLoss() else: loss_function = nn.NLLLoss() # optimizer = optim.SGD(filter(lambda p: p.requires_grad, self.parameters()), momentum=0.9, lr=learning_rate) # optimizer = MultiStepLR(optimizer, milestones=[10,15], gamma=0.5) # optimizer = optim.Adadelta(filter(lambda p: p.requires_grad, self.parameters())) optimizer = optim.Adam(filter(lambda p: p.requires_grad, self.parameters())) self.tensorboard_writer.add_scalar("learning_rate", learning_rate) tensorbard_global_step=0 if os.path.exists(os.path.join(TENSORBOARD_LOG_PATH, "resume_step")): with open(os.path.join(TENSORBOARD_LOG_PATH, "resume_step"), "r") as file_handler: tensorbard_global_step = int(file_handler.read()) + 1 for epoch_index, epoch in enumerate(range(epoch_num)): for index, sample in enumerate(data_loader): optimizer.zero_grad() input_image = autograd.Variable(sample["image"]) # batch_size, 3, 255, 255 tag_score = self.forward(input_image) if self._use_ctc: tag_score, target, tag_score_sizes, target_sizes = self._loss_preprocess_ctc(tag_score, sample) loss = loss_function(tag_score, target, tag_score_sizes, target_sizes) loss = loss / tag_score.size(1) else: target = sample["padded_label_idx"] tag_score, target = self._loss_preprocess(tag_score, target) loss = loss_function(tag_score, target) print("Training loss: {}".format(float(loss))) self.tensorboard_writer.add_scalar("training_loss", float(loss), tensorbard_global_step) loss.backward() optimizer.step() if index % 250 == 0: print(u"Processing batch: {} of {}, epoch: {}".format(index, len(data_loader), epoch_index)) self.evaluate(eval_data_loader, loss_function, tensorbard_global_step) tensorbard_global_step += 1 self.save_model(MODEL_PATH + "_epoch_{}".format(epoch_index)) except KeyboardInterrupt: print("Exit for KeyboardInterrupt, save model") self.save_model(MODEL_PATH) with open(os.path.join(TENSORBOARD_LOG_PATH, "resume_step"), "w") as file_handler: file_handler.write(str(tensorbard_global_step)) except Exception as excp: logger.error(str(excp)) logger.error(traceback.format_exc()) def predict(self, image): # TODO ctc version ''' :param image: [batch_size, channel, height, width] :return: ''' tag_score = self.forward(image) # TODO ctc # if self._use_ctc: # tag_score = F.softmax(tag_score, dim=-1) # decoder.decode(tag_score) confidence_log_probability, indexes = tag_score.max(2) predicted_labels = [] for batch_index in range(indexes.size(1)): label = "" for character_index in range(self._max_captcha_length): if int(indexes[character_index, batch_index]) != 1: label += id_to_character[int(indexes[character_index, batch_index])] predicted_labels.append(label) return predicted_labels, tag_score def predict_pil_image(self, pil_image): try: self.eval() processed_image = normalizer(rescale({"image": pil_image}))["image"].view(1, 3, 255, 255) result, tag_score = self.predict(processed_image) self.train() except Exception as excp: logger.error(str(excp)) logger.error(traceback.format_exc()) return [""], None return result, tag_score def evaluate(self, eval_dataloader, loss_function, step=0): total = 0 sequence_correct = 0 character_correct = 0 character_total = 0 loss_total = 0 batch_size = eval_data_loader.batch_size true_predicted = {} self.eval() for sample in eval_dataloader: total += batch_size input_images = sample["image"] predicted_labels, tag_score = self.predict(input_images) for predicted, true_label in zip(predicted_labels, sample["label"]): if predicted == true_label: # dataloader is making label a list, use batch_size=1 sequence_correct += 1 for index, true_character in enumerate(true_label): character_total += 1 if index < len(predicted) and predicted[index] == true_character: character_correct += 1 true_predicted[true_label] = predicted if self._use_ctc: tag_score, target, tag_score_sizes, target_sizes = self._loss_preprocess_ctc(tag_score, sample) loss_total += float(loss_function(tag_score, target, tag_score_sizes, target_sizes) / batch_size) else: tag_score, target = self._loss_preprocess(tag_score, sample["padded_label_idx"]) loss_total += float(loss_function(tag_score, target)) # averaged over batch index print("True captcha to predicted captcha: ") pprint(true_predicted) self.tensorboard_writer.add_text("eval_ture_to_predicted", str(true_predicted), global_step=step) accuracy = float(sequence_correct) / total avg_loss = float(loss_total) / (total / batch_size) character_accuracy = float(character_correct) / character_total self.tensorboard_writer.add_scalar("eval_sequence_accuracy", accuracy, global_step=step) self.tensorboard_writer.add_scalar("eval_character_accuracy", character_accuracy, global_step=step) self.tensorboard_writer.add_scalar("eval_loss", avg_loss, global_step=step) self.zero_grad() self.train() def _loss_preprocess(self, tag_score, target): ''' :param tag_score: value return by self.forward :param target: sample["padded_label_idx"] :return: (processed_tag_score, processed_target) ready for NLLoss function ''' target = target.transpose(0, 1) target = target.contiguous() target = target.view(target.size(0) * target.size(1)) tag_score = tag_score.view(-1, self.chracter_space_length) return tag_score, target def _loss_preprocess_ctc(self, tag_score, sample): target_2d = [ [int(ele) for ele in sample["padded_label_idx"][row, :] if int(ele) != 0 and int(ele) != 1] for row in range(sample["padded_label_idx"].size(0))] target = [] for ele in target_2d: target.extend(ele) target = autograd.Variable(torch.IntTensor(target)) # tag_score = F.softmax(F.sigmoid(tag_score), dim=-1) tag_score_sizes = autograd.Variable(torch.IntTensor([self._max_captcha_length] * tag_score.size(1))) target_sizes = autograd.Variable(sample["captcha_length"].int()) return tag_score, target, tag_score_sizes, target_sizes # def visualize_graph(self, dataset): # '''Since pytorch use dynamic graph, an input is required to visualize graph in tensorboard''' # # warning: Do not run this, the graph is too large to visualize... # sample = dataset[0] # input_image = autograd.Variable(sample["image"].view(1, 3, 255, 255)) # tag_score = self.forward(input_image) # self.tensorboard_writer.add_graph(self, tag_score) def save_model(self, model_path): self.tensorboard_writer.close() self.tensorboard_writer = None # can't be pickled torch.save(self, model_path) self.tensorboard_writer = SummaryWriter(TENSORBOARD_LOG_PATH) @classmethod def load_model(cls, model_path=MODEL_PATH, *args, **kwargs): net = cls(*args, **kwargs) if os.path.exists(model_path): model = torch.load(model_path) if model: model.tensorboard_writer = SummaryWriter(TENSORBOARD_LOG_PATH) net = model return net def __del__(self): if self.tensorboard_writer: self.tensorboard_writer.close() if __name__ == "__main__": from dataset_util.dataset import dataset, eval_dataset data_loader = DataLoader(dataset, batch_size=2, shuffle=True) eval_data_loader = DataLoader(eval_dataset, batch_size=2, shuffle=True) net = CNN_RNN.load_model() net.train_net(data_loader, eval_data_loader=eval_data_loader) # net.predict(dataset[0]["image"].view(1, 3, 255, 255)) # predict_pil_image test code # from config.config import IMAGE_PATHS # import glob # from PIL import Image # # image_paths = glob.glob(os.path.join(IMAGE_PATHS.get("EVAL"), "*.png")) # for image_path in image_paths: # pil_image = Image.open(image_path) # predicted, score = net.predict_pil_image(pil_image) # print("True value: {}, predicted: {}".format(os.path.split(image_path)[1], predicted)) print("Done") The above codes are main part. If you need other components that makes it running, leave a comment. Got stuck here for quite long. Any advice for training crnn + ctc is appreciated.
I've been training with ctc loss and encountered the same problem. I know this is a rather late answer but hopefully it'll help someone else who's researching on this. After trial and error and a lot of research there are a few things that's worth knowing when it comes to training with ctc (if your model is set up correctly): The quickest way for the model to lower cost is to predict only blanks. This is noted in a few papers and blogs: see http://www.tbluche.com/ctc_and_blank.html The model learns to predict only blanks first, then it starts picking up on the error signal in regards to the correct underlying labels. This is also explained in the above link. In practice, I noticed that my model starts to learn the real underlying labels/targets after a couple hundred epochs and the loss starts decreasing dramatically again. Similar to what is shown for the toy example here: https://thomasmesnard.github.io/files/CTC_Poster_Mesnard_Auvolat.pdf These parameters have a great impact on whether your model converges or not - learning rate, batch size and epoch number.
https://stackoverflow.com/questions/49483394/
Difference between 'ctx' and 'self' in python?
While using the deep learning library PyTorch I came across definitions like this. Does ctx have the same behavior as self? class LinearFunction(Function): @staticmethod def forward(ctx, input, weight, bias=None): ctx.save_for_backward(input, weight, bias) output = input.mm(weight.t()) if bias is not None: output += bias.unsqueeze(0).expand_as(output) return output @staticmethod def backward(ctx, grad_output): input, weight, bias = ctx.saved_variables grad_input = grad_weight = grad_bias = None if ctx.needs_input_grad[0]: grad_input = grad_output.mm(weight) if ctx.needs_input_grad[1]: grad_weight = grad_output.t().mm(input) if bias is not None and ctx.needs_input_grad[2]: grad_bias = grad_output.sum(0).squeeze(0) return grad_input, grad_weight, grad_bias
A static method (@staticmethod) is called using the class type directly, not an instance of this class: LinearFunction.backward(x, y) Since you have no instance, it does not make sense to use self in a static method. Here, ctx is just a regular argument that you'll have to pass when calling your methods.
https://stackoverflow.com/questions/49516188/
cffi error when compiling faster rcnn pytorch
I'm trying to compile faster_rcnn_pytorch using the instructions given here: https://github.com/longcw/faster_rcnn_pytorch I get this error: (p27) [$USER@compute-1-5 faster_rcnn]$ ./make.sh Traceback (most recent call last): File "setup.py", line 59, in <module> CUDA = locate_cuda() File "setup.py", line 45, in locate_cuda raise EnvironmentError('The nvcc binary could not be ' EnvironmentError: The nvcc binary could not be located in your $PATH. Either add it to your path, or set $CUDAHOME Compiling roi pooling kernels by nvcc... ./make.sh: line 10: nvcc: command not found /home/$USER/play/hw2/gitdir/hw2-release/code/faster_rcnn/roi_pooling generating /tmp/tmpP8mucv/_roi_pooling.c setting the current directory to '/tmp/tmpP8mucv' running build_ext building '_roi_pooling' extension creating home creating home/$USER creating home/$USER/play creating home/$USER/play/hw2 creating home/$USER/play/hw2/gitdir creating home/$USER/play/hw2/gitdir/hw2-release creating home/$USER/play/hw2/gitdir/hw2-release/code creating home/$USER/play/hw2/gitdir/hw2-release/code/faster_rcnn creating home/$USER/play/hw2/gitdir/hw2-release/code/faster_rcnn/roi_pooling creating home/$USER/play/hw2/gitdir/hw2-release/code/faster_rcnn/roi_pooling/src gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/torch/utils/ffi/../../lib/include -I/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/torch/utils/ffi/../../lib/include/TH -I/data2/$USER/anaconda2/envs/p27/include/python2.7 -c _roi_pooling.c -o ./_roi_pooling.o gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/torch/utils/ffi/../../lib/include -I/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/torch/utils/ffi/../../lib/include/TH -I/data2/$USER/anaconda2/envs/p27/include/python2.7 -c /home/$USER/play/hw2/gitdir/hw2-release/code/faster_rcnn/roi_pooling/src/roi_pooling.c -o ./home/$USER/play/hw2/gitdir/hw2-release/code/faster_rcnn/roi_pooling/src/roi_pooling.o gcc -pthread -shared -L/data2/$USER/anaconda2/envs/p27/lib -Wl,-rpath=/data2/$USER/anaconda2/envs/p27/lib,--no-as-needed ./_roi_pooling.o ./home/$USER/play/hw2/gitdir/hw2-release/code/faster_rcnn/roi_pooling/src/roi_pooling.o /home/$USER/play/hw2/gitdir/hw2-release/code/faster_rcnn/roi_pooling/src/cuda/roi_pooling.cu.o -L/data2/$USER/anaconda2/envs/p27/lib -lpython2.7 -o ./_roi_pooling.so gcc: error: /home/$USER/play/hw2/gitdir/hw2-release/code/faster_rcnn/roi_pooling/src/cuda/roi_pooling.cu.o: No such file or directory Traceback (most recent call last): File "build.py", line 34, in <module> ffi.build() File "/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/torch/utils/ffi/__init__.py", line 167, in build _build_extension(ffi, cffi_wrapper_name, target_dir, verbose) File "/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/torch/utils/ffi/__init__.py", line 103, in _build_extension ffi.compile(tmpdir=tmpdir, verbose=verbose, target=libname) File "/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/cffi/api.py", line 697, in compile compiler_verbose=verbose, debug=debug, **kwds) File "/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/cffi/recompiler.py", line 1520, in recompile compiler_verbose, debug) File "/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/cffi/ffiplatform.py", line 22, in compile outputfilename = _build(tmpdir, ext, compiler_verbose, debug) File "/data2/$USER/anaconda2/envs/p27/lib/python2.7/site-packages/cffi/ffiplatform.py", line 58, in _build raise VerificationError('%s: %s' % (e.__class__.__name__, e)) cffi.error.VerificationError: LinkError: command 'gcc' failed with exit status 1 As far as I can tell, there are 2 problems: nvcc is not found cffi error Regarding nvcc, I'm not sure how to add it to my path. It looks like I have both CUDA 8 and CUDA 9 so maybe I need to add it to only CUDA 9? (p27) [$USER@compute-1-5 faster_rcnn]$ which nvcc /usr/bin/which: no nvcc in (/data2/$USER/anaconda2/envs/p27/bin:/data2/$USER/anaconda2/bin:/opt/afni:/data2/$USER/anaconda2/bin:/opt/afni:/data2/$USER/anaconda2/bin:/opt/fsl/bin:/opt/openmpi/bin:/usr/lib64/qt-3.3/bin:/opt/afni:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/ganglia/bin:/opt/ganglia/sbin:/usr/java/latest/bin:/opt/maui/bin:/opt/torque/bin:/opt/torque/sbin:/opt/pdsh/bin:/opt/rocks/bin:/opt/rocks/sbina:/home/$USER/bin:/opt/maui/bin:/opt/torque/bin:/opt/torque/sbina:/opt/maui/bin:/opt/torque/bin:/opt/torque/sbina) (p27) [$USER@compute-1-5 faster_rcnn]$ find /opt -name nvcc /opt/cuda-8.0/bin/nvcc /opt/freesurfer/lib/cuda/bin/nvcc (p27) [$USER@compute-1-5 faster_rcnn]$ echo $LD_LIBRARY_PATH /home/$USER/lib/cuDNN/v7/cuda/lib64:/home/$USER/cuda-9.0/lib64:/home/$USER/cuda-9.0/extras/CUPTI/lib64:/home/$USER/lib/cuDNN/v7/cuda/lib64:/home/$USER/cuda-9.0/lib64:/home/$USER/cuda-9.0/extras/CUPTI/lib64:/opt/fsl/lib:/opt/openmpi/lib:/home/$USER/cuda/lib64:/home/$USER/cuda/lib64 Regarding cffi error, I have installed both gcc and cffi using conda but I'm not sure why it still complains. (p27) [$USER@compute-1-5 faster_rcnn]$ conda list | grep cffi cffi 1.11.5 py27h9745a5d_0 anaconda (p27) [$USER@compute-1-5 faster_rcnn]$ conda list | grep gcc gcc 4.8.5 7 anaconda libgcc-ng 7.2.0 hdf63c60_3 anaconda Thank you for helping!!
So looks like the problem was because I had 2 CUDA installations. For some reason, when I added CUDA 8.0 to the path, it did not work but when I added CUDA 9.0 to the path, it worked. I added this to my bashrc: export PATH=/home/$USER/cuda-9.0/bin:"$PATH" To check whether nvcc is correctly added to the path, I ran this command as shown here : cat $(which nvcc).profile
https://stackoverflow.com/questions/49520443/
PyTorch - modifications of autograd variables
In my PyTorch program, I have a matrix which is continuously updated over runtime. I wonder how to perform this update. I tried using something like this: matrix[0, index] = hidden[0] Both matrix and hidden are autograd Variables. When using the example above I'm getting the following error message: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation I wonder how to get around this and perform the update without using in-place operations. Probably slicing the matrix and creating a new matrix with torch.cat would work, but this doesn't seem to be a very nice solution. Is there a better way doing this? Thanks in advance!
Maybe posting a piece of code could help, but have you tried using a dataset ? You could sequentially run through data efficiently with it. http://pytorch.org/docs/master/data.html#torch.utils.data.TensorDataset
https://stackoverflow.com/questions/49528348/
Loss doesn't decrease in training the pytorch RNN
Here is the RNN network I designed for a sentiment. class rnn(nn.Module): def __init__(self, input_size, hidden_size, output_size): super().__init__() self.hidden_size = hidden_size self.i2h = nn.Linear(input_size, hidden_size) self.h2o = nn.Linear(hidden_size, output_size) self.h2h = nn.Linear(hidden_size , hidden_size) self.relu = nn.Tanh() self.sigmoid = nn.LogSigmoid() def forward(self, input, hidden): hidden_new = self.relu(self.i2h(input)+self.h2h(hidden)) output = self.h2o(hidden) output = self.sigmoid(output) return output, hidden_new def init_hidden(self): return Variable(torch.zeros(1, self.hidden_size)) Then, I create and train the network as : RNN = rnn(50, 50, 1) learning_rate = 0.0005 criteria = nn.MSELoss() optimizer = optim.Adam(RNN.parameters(), lr=learning_rate) hidden = RNN.init_hidden() epochs = 2 for epoch in range(epochs): for i in range(len(train['Phrase'])): input = convert_to_vectors(train['Phrase'][i]) for j in range(len(input)): temp_input = Variable(torch.FloatTensor(input[j])) output, hidden = RNN(temp_input, hidden) temp_output = torch.FloatTensor([np.float64(train['Sentiment'][i])/4]) loss = criteria( output, Variable(temp_output)) loss.backward(retain_graph = True) if (i%20 == 0): print('Current loss is ', loss) The problem is that the loss of the network isn't decreasing. It increases, then decreases and so on. It isn't stable at all. I tried using a smaller learning rate but it doesn't seem to help. Why is this happening and how can I rectify this?
You just need to call optimizer.step() after you do loss.backward(). Which, by the way, illustrates a common misconception: Backpropagation is not a learning algorithm, it's just a cool way of computing the gradient of the loss w.r.t. your parameters. You then use some variant of Gradient Descent (eg. plain SGD, AdaGrad, etc., in your case Adam) to update the weights given the gradients.
https://stackoverflow.com/questions/49601263/
PyTorch: purpose of addmm function
What is the purpose of the following PyTorch function (doc): torch.addmm(beta=1, mat, alpha=1, mat1, mat2, out=None) More specifically, is there any reason to prefer this function instead of just using beta * mat + alpha * (mat1 @ mat2)
The addmm function is an optimized version of the equation beta*mat + alpha*(mat1 @ mat2). I ran some tests and timed their execution. If beta=1, alpha=1, then the execution of both the statements (addmm and manual) is approximately the same (addmm is just a little faster), regardless of the matrices size. If beta and alpha are not 1, then addmm is two times faster than the manual execution for smaller matrices (with total elements in order of 105). But, if matrices are large (in order of 106), the speedup seems negligible (39ms v/s 41ms)
https://stackoverflow.com/questions/49609226/
Import error when importing torch
I didn't make any change but it suddenly doesn't work. >>> import torch Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/cheng/anaconda/envs/py36/lib/python3.6/site-packages/torch/__init__.py", line 56, in <module> from torch._C import * ImportError: numpy.core.multiarray failed to import I tried pip install numpy -I but it didn't work. My OS is Mac OS X, and I tried to install by both pip and conda. Reinstall the env didn't work as well. pytorch version 0.3.1 numpy version 1.14.2 Solution: Do not name your file tokenize.py!
Solution according to OP: A file named tokenize.py in the current directory caused this issue.
https://stackoverflow.com/questions/49624501/
how to serve pytorch or sklearn models using tensorflow serving
I have found tutorials and posts which only says to serve tensorflow models using tensor serving. In model.conf file, there is a parameter model_platform in which tensorflow or any other platform can be mentioned. But how, do we export other platform models in tensorflow way so that it can be loaded by tensorflow serving.
I'm not sure if you can. The tensorflow platform is designed to be flexible, but if you really want to use it, you'd probably need to implement a C++ library to load your saved model (in protobuf) and give a serveable to tensorflow serving platform. Here's a similar question. I haven't seen such an implementation, and the efforts I've seen usually go towards two other directions: Pure python code serving a model over HTTP or GRPC for instance. Such as what's being developed in Pipeline.AI Dump the model in PMML format, and serve it with a java code.
https://stackoverflow.com/questions/49624799/
Pytorch super(class, self).__init__() vs super().__init__()
So far out of all the paper and its corresponding code I see people use super(class, self).__init__() instead of super().__init__() within their def __init__ function regardless of which python version people are using. Why? I thought they are the same thing but different syntax for different version of python. Am I paranoid or is there an actual reason to use the old format in pytorch? Edited: It's for backward compatibility and nothing else.
I asked on the official form and it seems to be just for backward compatibility and nothing else.
https://stackoverflow.com/questions/49634682/
How is the output h_n of an RNN (nn.LSTM, nn.GRU, etc.) in PyTorch structured?
The docs say h_n of shape (num_layers * num_directions, batch, hidden_size): tensor containing the hidden state for t = seq_len Now, the batch and hidden_size dimensions are pretty much self-explanatory. The first dimension remains a mystery, though. I assume, that the hidden states of all "last cells" of all layers are included in this output. But then what is the index of, for example, the hidden state of the "last cell" in the "uppermost layer"? h_n[-1]? h_n[0]? Is the output affected by the batch_first option?
The implementation of LSTM and GRU in pytorch automatically includes the possibility of stacked layers of LSTMs and GRUs. You give this with the keyword argument nn.LSTM(num_layers=num_layers). num_layers is the number of stacked LSTMs (or GRUs) that you have. The default value is 1, which gives you the basic LSTM. num_directions is either 1 or 2. It is 1 for normal LSTMs and GRUs, and it is 2 for bidirectional RNNs. So in your case, you probably have a simple LSTM or GRU so the value of num_layers * num_directions would then be one. h_n[0] is the hidden state of the bottom-most layer (the one which takes in the input), and h_n[-1] of the top-most layer (the one which outputs the output of the network). batch_first puts the batch dimension before the time dimension (the default being the time dimension before the batch dimension), because the hidden state doesn't have a time dimension, batch_first has no effect on the hidden state shape.
https://stackoverflow.com/questions/49674079/
How to combine multiple h5 files?
Limited by the device, I could only produce several h5 files (the format of each file are same with shape of [idx, 1, 224, 224]) for huge dataset (>100GB) and now I'm confused about the solution to combine these files into a single one for further training on PyTorch. enter image description here
In h5py, groups and files support copy(), which can be used to move groups (including the root group) and their contents between files. See the docs here (scroll down a bit to find copy()): http://docs.h5py.org/en/latest/high/group.html The HDF5 distribution also includes a command-line tool called h5copy that can be used to move things around, and the C API has an H5Ocopy() function.
https://stackoverflow.com/questions/49707601/
cuda runtime error (48): no kernel image is available for execution on the device
I'm new to pytorch. I took the code from this repository https://github.com/ruotianluo/ImageCaptioning.pytorch and wanted to make captions to the images. Installed "CUDA" and when I run the script to create the annotations produces this: $ CUDA_LAUNCH_BLOCKING = 1 python eval.py --model model.pth - -infos_path infos.pkl --image_folder blah --num_images 1 /home/azat/anaconda2/lib/python2.7/site-packages/h5py/init.py:36: FutureWarning: Conversion of the second argument of issubdtype from float tonp.floating is deprecated. In the future, it will be treated as np.float64 == np.dtype (float) .type. from ._conv import register_converters as _register_converters /home/azat/anaconda2/lib/python2.7/site-packages/torch/cuda/init.py:97: UserWarning: Found GPU0 GeForce 820M which is of cuda capability 2.1. PyTorch no longer supports this GPU because it is too old. warnings.warn (old_gpu_warn% (d, name, major, capability 1)) DataLoaderRaw loading images from folder: blah 0 listing all images in directory blah DataLoaderRaw found 8 images THCudaCheck FAIL file = / pytorch / torch / lib / THC / generic / THCTensorMathPairwise.cu line = 40 error = 48: no kernel image is available for execution on the device Traceback (most recent last call last): File "eval.py", line 122, in vars (opt)) File "/ home / azat / Programing / Python / techno_atom_neuro / Others Implementation / ImageCaptioning.pytorch-master / eval_utils.py", line 82, in eval_split data = loader.get_batch (split) File "/ home / azat / Programing / Python / techno_atom_neuro / Others Implementation / ImageCaptioning.pytorch-master / dataloaderraw.py", line 112, in get_batch img = Variable (preprocess (img), volatile = True) File "/home/azat/anaconda2/lib/python2.7/site-packages/torchvision/transforms/transforms.py", line 42, in call img = t (img) File "/home/azat/anaconda2/lib/python2.7/site-packages/torchvision/transforms/transforms.py", line 118, in call return F.normalize (tensor, self.mean, self.std) File "/home/azat/anaconda2/lib/python2.7/site-packages/torchvision/transforms/functional.py", line 161, in normalize t.sub_ (m) .div_ (s) RuntimeError: cuda runtime error (48): no kernel image is available for execution on the device at /pytorch/torch/lib/THC/generic/THCTensorMathPairwise.cu:40 So, I want to find out what this error is, hardware or software. And how can I solve this problem. Thanks. PyTorch OS: Ubuntu 16.04 PyTorch version: 0.3.1 pip Python version: Python 2.7.14 :: Anaconda custom (64-bit) CUDA/cuDNN version: 9.1 GPU models and configuration: $ nvidia-smi Wed Apr 11 21:34:08 2018 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 390.48 Driver Version: 390.48 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce 820M Off | 00000000:08:00.0 N/A | N/A | | N/A 54C P0 N/A / N/A | 114MiB / 1985MiB | N/A Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GPU PID Type Process name Usage | |=============================================================================| | 0 Not Supported | +-----------------------------------------------------------------------------+
The answer is buried in that huge error message you got: UserWarning: Found GPU0 GeForce 820M which is of cuda capability 2.1. PyTorch no longer supports this GPU because it is too old.
https://stackoverflow.com/questions/49785199/
Google Colaboratory local runtime using local GPU
I'm using Colaboratory and Pytorch to run a GAN that uses an unusual dataset, which is currently stored locally on my machine. To access these files I connected to a local runtime (as per https://research.google.com/colaboratory/local-runtimes.html). However, Colaboratory now uses my own GPU when running now, which it did not do on previous runs. I know this because current runs run much much slower, as they are using my GTX 1060 6GB instead of Colab's Tesla K80. I checked this using torch.cuda.get_device_name(0) Which returns "GeForce GTX 1060 6G" when I am connected locally. This is the case even with Edit -> Notebook Settings -> Hardware Accelerator -> "GPU" selected. However, when I am not connected locally, and instead use the (default) "Connect to hosted runtime" option, torch.cuda.get_device_name(0) does return "Tesla K80". I've had trouble uploading my dataset to Drive, as it is a large image dataset, and would like to carry on using the local runtime. How do I use both the local runtime and Colab's amazing Tesla K80? Any help would be much appreciated.
Colab is using your GPU because you connected it to a local runtime. That's what connecting it to your own runtime means. It means that you're using your machine instead of handling the process on Google's servers. If you want to still use Google's servers and processing capabilities, I'd suggest looking into connecting your Google Drive to the Colaboratory runtime.
https://stackoverflow.com/questions/49856659/
Could not import pytorch in windows
I am trying to install torch in windows to use with python. I have install torch and lua somehow. Then I tried using: conda install -c peterjc123 pytorch from this answer here. It seems to have succeeded and asks for a new package to be installed: The following NEW packages will be INSTALLED: pytorch: 0.3.1-py36_cuda80_cudnn6he774522_2 peterjc123 I don't have a GPU but thought it might use CPU (I am not sure about that but I proceeded anyway). The problem is that after the installation I cannot import it: import PyTorch ModuleNotFoundError: No module named 'pytorch' The code I tried was from here. Does this seem normal? I would expect an error regarding functionality or something not about importing the module. P.S. My initial intention is to run this code which uses torch. I am not sure how torch and pytorch are connected but I was hoping to make it work.
Use import torch to import the complete pyTorch library.
https://stackoverflow.com/questions/49893932/
How to install pytorch in Anaconda with conda or pip?
I am trying to install pytorch in Anaconda to work with Python 3.5 in Windows. Following the instructions in pytorch.org I introduced the following code in Anaconda: pip3 install torch torchvision But the following error came in: Command "python setup.py egg_info" failed with error code 1 in C:\Users\sluis\AppData\Local\Temp\pip-install-qmrvz7b9\torch\ By searching on the web I found out that it may be because of setuptools being out of date but I checked and have it updated. I also tried: conda install -c peterjc123 pytorch cuda80 But the following error arise: The following specifications were found to be in conflict: - pytorch Use "conda info <package>" to see the dependencies for each package. I also tried to load the pytorch's tar.bz2 file which I download in the following website: anaconda.org/peterjc123/pytorch/files And then just do: $ conda install filename.tar.bz2 But I got the following error: Error: HTTPError: 404 Client Error: None for url: file:///C|/Users/sluis/pytorch-0.3.1-py36_cuda80_cudnn6he774522_2.tar.bz2: file:///C|/Users/sluis/pytorch-0.3.1-py36_cuda80_cudnn6he774522_2.tar.bz2 I am quite new to this programming world so I don't really know how to dig more on the errors. Anyone knows how to get pytorch installed? Edit: As suggested in the comments I tried: conda install pytorch torchivsion -c pytorch And I got the following error: Error: Packages missing in current win-64 channels: - pytorch - torchvision I did: anaconda search -t conda torchvision And tried to install dericlk/torchvision using the following command: conda install -c derickl torchvision But I am getting the same error: Error: Package missing in current win-64 channels: - torchvision I couldn't find any torchvisionpackages for win-64. conda list is giving me the following: # packages in environment at C:\Users\aaaa\AppData\Local\Continuum\Anaconda3\envs\torchenv2: # mkl-include 2018.0.2 1 anaconda certifi 2016.2.28 py35_0 cffi 1.10.0 py35_0 cmake 3.6.3 vc14_0 [vc14] openmp 2018.0.0 intel_8 intel mkl 2017.0.3 0 numpy 1.13.1 py35_0 pip 10.0.0 <pip> pip 9.0.1 py35_1 pycparser 2.18 py35_0 python 3.5.4 0 pyyaml 3.12 py35_0 setuptools 36.4.0 py35_1 typing 3.6.2 py35_0 vc 14 0 vs2015_runtime 14.0.25420 0 wheel 0.29.0 py35_0 wincertstore 0.2 py35_0 zlib 1.2.11 vc14_0 [vc14] =======
The following worked for me. First install MKL: conda install -c anaconda mkl After this, install pytorch and torchvision: conda install -c pytorch pytorch torchvision
https://stackoverflow.com/questions/49918479/
How does one implement adversarial examples in pytorch?
I wanted to reproduce: from the paper https://arxiv.org/pdf/1312.6199.pdf. I was wondering, how does one actually implement this in pytorch? My main confusion is that for loss_f I am using a torch.nn.CrossEntropy() criterion for example. Do i just need to change the code that I already have from: loss = criterion(outputs+r, labels) loss.backward() to: loss = criterion(outputs+r, labels) loss = loss + c * r.norm(2) loss.backward() or something along those lines (of course include r in the optimizer!). I know its not quite right cuz I did not explicitly show how I implemented x+r or the hypercube constraint but those are parts that I still need to figure out. I think for the moment I want to focus first without the hypercube constraint. If we assume I am ok with going out of that is the above correct? I just want to know if: loss = loss + c * r.norm(2) works as it should. Now if we do include the hypercube constraint how does my solution change? Is that were the "penalty function method" come into place? https://discuss.pytorch.org/t/how-does-one-implement-adversarial-examples-in-pytorch/15668
This is how i did it. Hope that helps you. #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 18 12:39:16 2016 @author: manojacharya """ import torch import torch.nn as nn from torch.autograd import Variable from torchvision import models,transforms import numpy as np from scipy.misc import imread, imresize import os import matplotlib.pyplot as plt import torch.nn.functional as F import json normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transform = transforms.Compose( [transforms.ToTensor(), normalize]) def imshow(inp, title=None): """Imshow for Tensor.""" plt.figure() inp = inp.data[0] inp = inp.numpy().transpose((1, 2, 0)) mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) inp = std * inp + mean plt.imshow(inp) plt.axis('off') if title is not None: plt.title(title) with open('imagenet.json') as f: imagenet_labels = json.load(f) # In[model]: model = models.vgg16(pretrained=True) for param in model.parameters(): param.requires_grad = False def predict(img): pred_raw = model(img) pred = F.softmax(pred_raw) _,indices = torch.topk(pred,k=1) for ind in indices.data.numpy().ravel(): print ("%.2f%% , class: %s , %s" %(100*pred.data[0][ind],str(ind),imagenet_labels[ind])) # In[image ]: peppers = imread("dog.jpg") img = imresize(peppers,(224,224)) imgtensor = transform(img) imgvar = Variable(imgtensor.unsqueeze(0),requires_grad=False) imgvard = Variable(imgtensor.unsqueeze(0),requires_grad=True) optimizer = torch.optim.Adam([imgvard], lr = 0.1) loss_fn = nn.CrossEntropyLoss() label = torch.LongTensor(1) #classify the object as this label label[0] = 80 label = Variable(label) eps = 2/255.0 #%% Nepochs = 50 print ("Starting ...........",predict(imgvar)) for epoch in range(Nepochs): optimizer.zero_grad() pred_raw = model(imgvard) loss = loss_fn(pred_raw,label) diff = imgvard.data - imgvar.data imgvard.data = torch.clamp(torch.abs(diff),max=eps) + imgvar.data loss.backward() optimizer.step() print('epoch: {}/{}, loss: {}'.format( epoch + 1,Nepochs, loss.data[0])) predict(imgvard) print('Finished Training') #%% imshow(imgvard) #%% plt.figure() diffimg = diff[0].numpy() diffimg = diffimg.transpose((1,2,0)) plt.imshow(diffimg)
https://stackoverflow.com/questions/49951492/
RNN Implementation
I am going to implement RNN using Pytorch . But , before that , I am having some difficulties in understanding the character level one-hot encoding which is asked in the question . Please find below the question Choose the text you want your neural network to learn, but keep in mind that your data set must be quite large in order to learn the structure! RNNs have been trained on highly diverse texts (novels, song lyrics, Linux Kernel, etc.) with success, so you can get creative. As one easy option, Gutenberg Books is a source of free books where you may download full novels in a .txt format. We will use a character-level representation for this model. To do this, you may use extended ASCII with 256 characters. As you read your chosen training set, you will read in the characters one at a time into a one-hot-encoding, that is, each character will map to a vector of ones and zeros, where the one indicates which of the characters is present: char → [0, 0, · · · , 1, · · · , 0, 0] Your RNN will read in these length-256 binary vectors as input. So , For example , I have read a novel in python. Total unique characters is 97. and total characters is somewhere around 300,000 . So , will my input be 97 x 256 one hot encoded matrix ? or will it be 300,000 x 256 one hot encoded matrix ?
One hot assumes each of your vector should be different in one place. So if you have 97 unique character then i think you should use a 1-hot vector of size ( 97 + 1 = 98). The extra vector maps all the unknown character to that vector. But you can also use a 256 length vector. So you input will be: B x N x V ( B = batch size, N = no of characters , V = one hot vector size). But if you are using libraries they usually ask the index of characters in vocabulary and they handle index to one hot conversion. Hope that helps.
https://stackoverflow.com/questions/49954852/
PyTorch - RuntimeError: Assertion 'cur_target >= 0 && cur_target < n_classes' failed
I'm trying to make a neural network with PyTorch to predict student's final exam grades. I've done it like this - # Hyper Parameters input_size = 2 hidden_size = 50 num_classes =21 num_epochs = 500 batch_size = 5 learning_rate = 0.1 # define a customise torch dataset class DataFrameDataset(torch.utils.data.Dataset): def __init__(self, df): self.data_tensor = torch.Tensor(df.as_matrix()) # a function to get items by index def __getitem__(self, index): obj = self.data_tensor[index] input = self.data_tensor[index][0:-1] target = self.data_tensor[index][-1] - 1 return input, target # a function to count samples def __len__(self): n, _ = self.data_tensor.shape return n # load all data data_i = pd.read_csv('dataset/student-mat.csv', header=None,delimiter=";") data = data_i.iloc[:,30:33] # normalise input data for column in data: # the last column is target if column != data.shape[1] - 1: data[column] = data.loc[:, [column]].apply(lambda x: (x - x.mean()) / x.std()) # randomly split data into training set (80%) and testing set (20%) msk = np.random.rand(len(data)) &lt; 0.8 train_data = data[msk] test_data = data[~msk] # define train dataset and a data loader train_dataset = DataFrameDataset(df=train_data) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True) # Neural Network class Net(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(Net, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.sigmoid = nn.Sigmoid() self.fc2 = nn.Linear(hidden_size, num_classes) def forward(self, x): out = self.fc1(x) out = self.sigmoid(out) out = self.fc2(out) return out net = Net(input_size, hidden_size, num_classes) # Loss and Optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Rprop(net.parameters(), lr=learning_rate) # store all losses for visualisation all_losses = [] # train the model by batch for epoch in range(num_epochs): for step, (batch_x, batch_y) in enumerate(train_loader): # convert torch tensor to Variable X = Variable(batch_x) Y = Variable(batch_y.long()) # Forward + Backward + Optimize optimizer.zero_grad() # zero the gradient buffer outputs = net(X) loss = criterion(outputs, Y) all_losses.append(loss.data[0]) loss.backward() optimizer.step() if epoch % 50 == 0: _, predicted = torch.max(outputs, 1) # calculate and print accuracy total = predicted.size(0) correct = predicted.data.numpy() == Y.data.numpy() print('Epoch [%d/%d], Step [%d/%d], Loss: %.4f, Accuracy: %.2f %%' % (epoch + 1, num_epochs, step + 1, len(train_data) // batch_size + 1, loss.data[0], 100 * sum(correct)/total)) I'm getting an error at line loss = criterion(outputs, Y) which says - RuntimeError: Assertion 'cur_target &gt;= 0 &amp;&amp; cur_target &lt; n_classes' failed. at /pytorch/torch/lib/THNN/generic/ClassNLLCriterion.c:62 I'm not able to figure out what I'm doing wrong as I'm pretty new to this and I've already checked the other posts here but, they don't seem to help. The data dataframe looks like - 30 31 32 0 5 6 6 1 5 5 6 2 7 8 10 3 15 14 15 4 6 10 10 5 15 15 15 Can anyone tell me what I am doing wrong and how can I correct it. Any help is appreciated! Thanks! :)
I had the same error in my program and i just realized that the problem was in the number of output nodes in my network In my program the number of output nodes of my model was not equal to the number of labels of the data the number of output was 1 and the number of target labels was 10. then i changed the number of output to 10, there was no error
https://stackoverflow.com/questions/49971958/
How does one create a data set in pytorch and save it into a file to later be used?
I want to extract data from cifar10 in a specific order according to some criterion f(Image,label) (for the sake of an example lets say f(Image,label) simply computes the sum of all the pixels in Image). Then it I want to generate 1 file for the train set and 1 file for the test set that I can later load in a dataloader to use for training a neural net. How do I do this? My current idea was simply to loop through the data with data loader with shuffle off and remember the indices of the images and the score and then sort the indices according to the score and then loop through everything again and create some giant numpy array and save it. After I save it I’d use torch.utils.data.TensorDataset(X_train, X_test) to wrap with TensorDataset and feed to DataLoader. I think it might work for a small data set like cifar10 at the very least, right? Another very important thing for me is that I also want to only train on the first K images (especially since I already sorted them the first K have a special meaning which I want to keep) so respecting but training only with a fraction will be important. https://discuss.pytorch.org/t/how-does-one-create-a-data-set-in-pytorch-and-save-it-into-a-file-to-later-be-used/16742
the simplest way to save this is to just read to an array and then do numpy.save('file',data,allow_pickle =False) to load it you then to data = numpy.load('file') remember to set the batch size to 1 and torch.to_numpy() everything once you do this its fairly simple to just rebuild your data loader and reload data loader with your dataset use numpy.load('file', mmap_mode='r') if you need to get at the data without loading it all to ram (helps with those pesky 600gb datasets) for those asking why numpy.save() whole datasets? : sometimes your data needs post processing, batching, reshaping, and this takes a lot of CPU time. You don't want to be using that cpu time re-crunching your data before you send it to your model. the next step up is to start using databases and servers, it does this, but better with more SQL! in terms of using slices of data its just a mater of reloading your dataset with dataset(data[k:],label[k:]) instead of dataset(data,label)
https://stackoverflow.com/questions/49987614/
How can I build an RNN without using nn.RNN
I need to build an RNN (without using nn.RNN) with following specifications : It should have set of weights [ It is a chanracter RNN. It should have 1 hidden layer Wxh (from input layer to hidden layer ) Whh (from the recurrent connection in the hidden layer) W ho (from hidden layer to output layer) I need to use Tanh for hidden layer I need to use softmax for output layer. I have implemented the code . I am using CrossEntropyLoss() as loss function . Which is giving me error as RuntimeError Traceback (most recent call last) &lt;ipython-input-33-94b42540bc4f&gt; in &lt;module&gt;() 25 print("target ",target_tensor[timestep]) 26 ---&gt; 27 loss += criterion(output,target_tensor[timestep].view(1,n_vocab)) 28 29 loss.backward() /opt/anaconda/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 323 for hook in self._forward_pre_hooks.values(): 324 hook(self, input) --&gt; 325 result = self.forward(*input, **kwargs) 326 for hook in self._forward_hooks.values(): 327 hook_result = hook(self, input, result) /opt/anaconda/lib/python3.6/site-packages/torch/nn/modules/loss.py in forward(self, input, target) 145 _assert_no_grad(target) 146 return F.nll_loss(input, target, self.weight, self.size_average, --&gt; 147 self.ignore_index, self.reduce) 148 149 /opt/anaconda/lib/python3.6/site-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce) 1047 weight = Variable(weight) 1048 if dim == 2: -&gt; 1049 return torch._C._nn.nll_loss(input, target, weight, size_average, ignore_index, reduce) 1050 elif dim == 4: 1051 return torch._C._nn.nll_loss2d(input, target, weight, size_average, ignore_index, reduce) RuntimeError: multi-target not supported at /opt/conda/conda-bld/pytorch_1513368888240/work/torch/lib/THNN/generic/ClassNLLCriterion.c:22 ​ Here is my code for model : class CharRNN(torch.nn.Module): def __init__(self,input_size,hidden_size,output_size, n_layers = 1): super(CharRNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.n_layers = 1 self.x2h_i = torch.nn.Linear(input_size + hidden_size, hidden_size) self.x2h_f = torch.nn.Linear(input_size + hidden_size, hidden_size) self.x2h_o = torch.nn.Linear(input_size + hidden_size, hidden_size) self.x2h_q = torch.nn.Linear(input_size + hidden_size, hidden_size) self.h2o = torch.nn.Linear(hidden_size, output_size) self.sigmoid = torch.nn.Sigmoid() self.softmax = torch.nn.Softmax() self.tanh = torch.nn.Tanh() def forward(self, input, h_t, c_t): combined_input = torch.cat((input,h_t),1) i_t = self.sigmoid(self.x2h_i(combined_input)) f_t = self.sigmoid(self.x2h_f(combined_input)) o_t = self.sigmoid(self.x2h_o(combined_input)) q_t = self.tanh(self.x2h_q(combined_input)) c_t_next = f_t*c_t + i_t*q_t h_t_next = o_t*self.tanh(c_t_next) output = self.softmax(h_t_next) return output, h_t, c_t def initHidden(self): return torch.autograd.Variable(torch.zeros(1, self.hidden_size)) def weights_init(self,model): classname = model.__class__.__name__ if classname.find('Linear') != -1: model.weight.data.normal_(0.0, 0.02) model.bias.data.fill_(0) ` and this is the code for training the model : ` input_tensor = torch.autograd.Variable(torch.zeros(seq_length,n_vocab)) target_tensor = torch.autograd.Variable(torch.zeros(seq_length,n_vocab)) model = CharRNN(input_size = n_vocab, hidden_size = hidden_size, output_size = output_size) model.apply(model.weights_init) criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr = learning_rate) for i in range(n_epochs): print("Iteration", i) start_idx = np.random.randint(0, n_chars-seq_length-1) train_data = raw_text[start_idx:start_idx + seq_length + 1] input_tensor = torch.autograd.Variable(seq2tensor(train_data[:-1],n_vocab), requires_grad = True) target_tensor= torch.autograd.Variable(seq2tensor(train_data[1:],n_vocab), requires_grad = False).long() loss = 0 h_t = torch.autograd.Variable(torch.zeros(1,hidden_size)) c_t = torch.autograd.Variable(torch.zeros(1,hidden_size)) for timestep in range(seq_length): output, h_t, c_t = model(input_tensor[timestep].view(1,n_vocab), h_t, c_t) loss += criterion(output,target_tensor[timestep].view(1,n_vocab)) loss.backward() optimizer.step() optimizer.zero_grad() x_t = input_tensor[0].view(1,n_vocab) h_t = torch.autograd.Variable(torch.zeros(1,hidden_size)) c_t = torch.autograd.Variable(torch.zeros(1,hidden_size)) gen_seq = [] for timestep in range(100): output, h_t, c_t = model(x_t, h_t, c_t) ix = np.random.choice(range(n_vocab), p=output.data.numpy().ravel()) x_t = torch.autograd.Variable(torch.zeros(1,n_vocab)) x_t[0,ix] = 1 gen_seq.append(idx2char[ix]) txt = ''.join(gen_seq) print ('----------------------') print (txt) print ('----------------------') Can you please help me ? Thanks in advance.
The problem is with your target tensor. It is of shape 1, n_classes, a 2D tensor, but CrossEntropyLoss expects a 1D tensor. Or stated in other terms, you are providing a one-hot encoded target tensor, but the loss function is expecting class number from 0 to n_classes-1. Change your loss calculation to - one_hot_target = target_tensor[timestep].view(1,n_vocab) _, class_target = torch.max(one_hot_target, dim=1) loss += criterion(output, class_target)
https://stackoverflow.com/questions/49987673/
Converting Pytorch model .pth into onnx model
I have one pre-trained model into format of .pth extension. I want to convert that into Tensorflow protobuf. But I am not finding any way to do that. I have seen onnx can convert models from pytorch into onnx and then from onnx to Tensorflow. But with that approach I got following error in the first stage of conversion. from torch.autograd import Variable import torch.onnx import torchvision import torch dummy_input = Variable(torch.randn(1, 3, 256, 256)) model = torch.load('./my_model.pth') torch.onnx.export(model, dummy_input, "moment-in-time.onnx")` It gives error like this. File "t.py", line 9, in &lt;module&gt; torch.onnx.export(model, dummy_input, "moment-in-time.onnx") File "/usr/local/lib/python3.5/dist-packages/torch/onnx/__init__.py", line 75, in export _export(model, args, f, export_params, verbose, training) File "/usr/local/lib/python3.5/dist-packages/torch/onnx/__init__.py", line 108, in _export orig_state_dict_keys = model.state_dict().keys() AttributeError: 'dict' object has no attribute 'state_dict' What is possible solution ?
try changing your code to this from torch.autograd import Variable import torch.onnx import torchvision import torch dummy_input = Variable(torch.randn(1, 3, 256, 256)) state_dict = torch.load('./my_model.pth') model.load_state_dict(state_dict) torch.onnx.export(model, dummy_input, "moment-in-time.onnx")
https://stackoverflow.com/questions/50007085/
Does batch_first affect hidden tensors in Pytorch LSTMs?
Does batch_first affect hidden tensors in Pytorch LSTMs? That is if batch_first parameter is true, Will the hidden state be (numlayer*direction,num_batch,encoding_dim) or (num_batch,numlayer*direction,encoding_dim) I've tested both, both give no error.
I was thinking about the same question some time ago. Like laydog outlined, in the documentation it says batch_first – If True, then the input and output tensors are provided as (batch, seq, feature) As I understand the question we are talking about the hidden / cell state tuple, not the actual inputs and outputs. For me it seems pretty obvious that this does not affect the hidden state as they mention: (batch, seq, feature) This clearly refers to inputs and outputs, not the state tuple which consists of two tuples with shape: (num_layers * num_directions, batch, hidden_size) So I'm pretty certain the hidden and cell states are not affected by this, it also would not make sense to me changing the order hidden state tuple. Hope this helps.
https://stackoverflow.com/questions/50012347/
PyTorch - How to set Activation Rules of neurons to increase efficiency of Neural Network?
I'm trying to make a Back Propagation Neural Network with PyTorch. I can successfully execute and test its accuracy, but it doesn't work very efficiently. Now, I'm supposed to increase its efficiency by setting different activation rules for neurons, so that those neurons that don't contribute to the final output get excluded (pruned) from the computations, thereby increasing the time and accuracy. My code looks like this (extracted snippets) - # Hyper Parameters input_size = 20 hidden_size = 50 num_classes =130 num_epochs = 500 batch_size = 5 learning_rate = 0.1 # normalise input data for column in data: # the last column is target if column != data.shape[1] - 1: data[column] = data.loc[:, [column]].apply(lambda x: (x - x.mean()) / x.std()) # randomly split data into training set (80%) and testing set (20%) msk = np.random.rand(len(data)) &lt; 0.8 train_data = data[msk] test_data = data[~msk] # define train dataset and a data loader train_dataset = DataFrameDataset(df=train_data) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True) # Neural Network class Net(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(Net, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.sigmoid = nn.Sigmoid() self.fc2 = nn.Linear(hidden_size, num_classes) def forward(self, x): out = self.fc1(x) out = self.sigmoid(out) out = self.fc2(out) return out net = Net(input_size, hidden_size, num_classes) # train the model by batch for epoch in range(num_epochs): for step, (batch_x, batch_y) in enumerate(train_loader): # convert torch tensor to Variable X = Variable(batch_x) Y = Variable(batch_y.long()) # Forward + Backward + Optimize optimizer.zero_grad() # zero the gradient buffer outputs = net(X) loss = criterion(outputs, Y) all_losses.append(loss.data[0]) loss.backward() optimizer.step() if epoch % 50 == 0: _, predicted = torch.max(outputs, 1) # calculate and print accuracy total = predicted.size(0) correct = predicted.data.numpy() == Y.data.numpy() print('Epoch [%d/%d], Step [%d/%d], Loss: %.4f, Accuracy: %.2f %%' % (epoch + 1, num_epochs, step + 1, len(train_data) // batch_size + 1, loss.data[0], 100 * sum(correct)/total)) Can someone tell me how to do that in PyTorch as I'm very new to PyTorch.
I'm not sure if that question is supposed to be on stackoverflow, but I will give you a hint anyway. You are working with a sigmoid activation function at the moment, the gradient of which vanishes if the input value is too large to small. A commonly used approach is to use the ReLU activation function (stands for rectified linear unit). ReLU(x) is the identity for the positive domain and 0 for the negative domain, in Python that would be written as follows: def ReLU(x): if(x &gt; 0): return x else: return 0 It should be readily available in PyTorch
https://stackoverflow.com/questions/50014365/
PyTorch print output to 2dp
Is there a way to print the output of a CNN model evaluation to 2dp given that the output is a multi element FloatTensor? eg. prediction = torch.exp(model(image2)) print(prediction) Out: Variable containing: 2.84e-01 1.68e-07 7.16e-01 [torch.FloatTensor of size 1x3] It would be better if I could output the value as: Variable containing: 0.28 0.00 0.72 [torch.FloatTensor of size 1x3] I've tried: print("%.2f" % prediction) and using: torch.set_printoptions(precision=2) But neither give the desired effect. I had a look on the documentation page: http://pytorch.org/docs/master/torch.html#creation-ops ...under 'torch.set_printoptions' but I can't see how any of the arguments might help in this situation. Many thanks in advance!
This has now been implemented. Use torch.set_printoptions(sci_mode=False) https://pytorch.org/docs/stable/torch.html#torch.set_printoptions
https://stackoverflow.com/questions/50043438/
pytorch cnn stride error
I am now using pytorch 0.4.0 in windows to build a CNN and here is my code: class net(nn.Module): def __init__(self): super(net, self).__init__() self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=(1,3),stride=1 ) self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=(1,3), stride=1) self.dense1 = nn.Linear(32 * 28 * 24, 60) self.out = nn.Linear(60,3) def forward(self, input): x = F.relu(self.conv1(input)) x = F.relu(self.conv2(x)) x = x.view(x.size(0), -1) # flatten(batch,32*7*7) x = self.dense1(x) output = self.out(x) return output but I get the error that File "D:\Anaconda\lib\site-packages\torch\nn\modules\conv.py", line 301, in forward self.padding, self.dilation, self.groups) RuntimeError: expected stride to be a single integer value or a list of 1 values to match the convolution dimensions, but got stride=[1, 1] I think it shows that I made some mistakes in the code above, but I don't know how to fix it, can any one help me out? Thanks in advance!
Fine, maybe I know what's happening cause I've faced same runtime error just 4 or 5 hours ago. Here is my solution in my case(I defined the dataset by myself): The image I feed into the net is 1 channel, same as your code(self.conv1 = nn.Conv2d(in_channels=1,...)). And the attribute of the image which would bring runtime error is as followed: error_img The image I fixed is as followed: fixed_img Can you feel the difference? The input image's channel should be 1, so the img.shape()should be tuple! Use img.reshape(1,100,100)to fix it and the net's forward function would proceed. I hope it can help you.
https://stackoverflow.com/questions/50073358/
Is it possible to view the code of a torch pretrained network
If you're thinking such a noob while reading the title - yes I am. I've googled but didn't find a single guide that allowed me to view how a pre-trained torch neural network is designed/coded. I have already downloaded the pre-trained network (file format .t7) and I have torch installed. Can anyone help me view how it is coded (what size filters used, parameters used etc.)? May be it's not on google because it's not possible? Will be happy to answer any additional questions you have or if anything isn't clear. Thank You.
I think it is not possible to get the underlying code. But you can get a summary of the model which includes the layers and the main parameters just by using print. model = SumModel(vocab_size=vocab_size, hiddem_dim=hidden_dim, batch_size=batch_size) # saving model torch.save(model, 'test_model.save') # print summary of original print(' - original model summary:') print(model) print() # load saved model loaded_model = torch.load('test_model.save') # print summary of loaded model print(' - loaded model summary:') print(loaded_model) This will output a summary which looks like this. - original model summary: SumModel( (word_embedding): Embedding(530734, 128) (encoder): LSTM(128, 128, batch_first=True) (decoder): LSTM(128, 128, batch_first=True) (output_layer): Linear(in_features=128, out_features=530734, bias=True) ) - loaded model summary: SumModel( (word_embedding): Embedding(530734, 128) (encoder): LSTM(128, 128, batch_first=True) (decoder): LSTM(128, 128, batch_first=True) (output_layer): Linear(in_features=128, out_features=530734, bias=True) ) Tested with Pytorch 0.4.0 As you can see both outputs for the original and the loaded model are consistent. I hope this helps.
https://stackoverflow.com/questions/50073402/
Pytorch vs. Keras: Pytorch model overfits heavily
For several days now, I'm trying to replicate my keras training results with pytorch. Whatever I do, the pytorch model will overfit far earlier and stronger to the validation set then in keras. For pytorch I use the same XCeption Code from https://github.com/Cadene/pretrained-models.pytorch. The dataloading, the augmentation, the validation, the training schedule etc. are equivalent. Am I missing something obvious? There must be a general problem somewhere. I tried thousands of different module constellations, but nothing seems to come even close to the keras training. Can somebody help? Keras model: val accuracy > 90% # base model base_model = applications.Xception(weights='imagenet', include_top=False, input_shape=(img_width, img_height, 3)) # top model x = base_model.output x = GlobalMaxPooling2D()(x) x = Dense(512, activation='relu')(x) x = Dropout(0.5)(x) predictions = Dense(4, activation='softmax')(x) # this is the model we will train model = Model(inputs=base_model.input, outputs=predictions) # Compile model from keras import optimizers adam = optimizers.Adam(lr=0.0001) model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) # LROnPlateau etc. with equivalent settings as pytorch Pytorch model: val accuracy ~81% from xception import xception import torch.nn.functional as F # modified from https://github.com/Cadene/pretrained-models.pytorch class XCeption(nn.Module): def __init__(self, num_classes): super(XCeption, self).__init__() original_model = xception(pretrained="imagenet") self.features=nn.Sequential(*list(original_model.children())[:-1]) self.last_linear = nn.Sequential( nn.Linear(original_model.last_linear.in_features, 512), nn.ReLU(), nn.Dropout(p=0.5), nn.Linear(512, num_classes) ) def logits(self, features): x = F.relu(features) x = F.adaptive_max_pool2d(x, (1, 1)) x = x.view(x.size(0), -1) x = self.last_linear(x) return x def forward(self, input): x = self.features(input) x = self.logits(x) return x device = torch.device("cuda") model=XCeption(len(class_names)) if torch.cuda.device_count() &gt; 1: print("Let's use", torch.cuda.device_count(), "GPUs!") # dim = 0 [30, xxx] -&gt; [10, ...], [10, ...], [10, ...] on 3 GPUs model = nn.DataParallel(model) model.to(device) criterion = nn.CrossEntropyLoss(size_average=False) optimizer = optim.Adam(model.parameters(), lr=0.0001) scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.2, patience=5, cooldown=5) Thank you very much! Update: Settings: criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=lr) scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, 'min', factor=0.2, patience=5, cooldown=5) model = train_model(model, train_loader, val_loader, criterion, optimizer, scheduler, batch_size, trainmult=8, valmult=10, num_epochs=200, epochs_top=0) Cleaned training function: def train_model(model, train_loader, val_loader, criterion, optimizer, scheduler, batch_size, trainmult=1, valmult=1, num_epochs=None, epochs_top=0): for epoch in range(num_epochs): for phase in ['train', 'val']: running_loss = 0.0 running_acc = 0 total = 0 # Iterate over data. if phase=="train": model.train(True) # Set model to training mode for i in range(trainmult): for data in train_loader: # get the inputs inputs, labels = data inputs, labels = inputs.to(torch.device("cuda")), labels.to(torch.device("cuda")) # zero the parameter gradients optimizer.zero_grad() # forward outputs = model(inputs) # notinception _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) # backward + optimize only if in training phase loss.backward() optimizer.step() # statistics total += labels.size(0) running_loss += loss.item()*labels.size(0) running_acc += torch.sum(preds == labels) train_loss=(running_loss/total) train_acc=(running_acc.double()/total) else: model.train(False) # Set model to evaluate mode with torch.no_grad(): for i in range(valmult): for data in val_loader: # get the inputs inputs, labels = data inputs, labels = inputs.to(torch.device("cuda")), labels.to(torch.device("cuda")) # zero the parameter gradients optimizer.zero_grad() # forward outputs = model(inputs) _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels.data) # statistics total += labels.size(0) running_loss += loss.item()*labels.size(0) running_acc += torch.sum(preds == labels) val_loss=(running_loss/total) val_acc=(running_acc.double()/total) scheduler.step(val_loss) return model
it may be because type of weight initialization you are using otherwise this should not happen try with same initializer in both the models
https://stackoverflow.com/questions/50079735/
Pytorch LongTensor of large integer gives float float value
x = torch.LongTensor([108500]) print (x) gives 1.0850e+05 [torch.LongTensor of size 1] Why is it so? Can't we have LongTensor of large integer? How can I convert the value of x to be integer so that I can get the embedding of x.
As you can see in the documentation, torch.LongTensor uses the data type '64-bit integer (signed)'. So what you are seeing in your output is actually an integer, it's only the exponential notation.
https://stackoverflow.com/questions/50090714/
Pytorch AttributeError: module 'torch' has no attribute 'set_grad_enabled'
AttributeError: module 'torch' has no attribute 'set_grad_enabled' Traceback (most recent call last): File "/home/thaqafi/PycharmProjects/transfer_learning/tutorial_transfer.py", line 280, in model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, num_epochs=25) File "/home/thaqafi/PycharmProjects/transfer_learning/tutorial_transfer.py", line 179, in train_model with torch.set_grad_enabled(True): AttributeError: module 'torch' has no attribute 'set_grad_enabled' using source code form Pytorch webiste. http://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
As far as I know this feature was not available before version 0.4.0, so probably you are using a version lower than 0.4.0 (e.g. 0.3.1.). Try updating PyTorch to version 0.4.0. if possible.
https://stackoverflow.com/questions/50097653/
DataLoader not randomly sampling in PyTorch
My DataLoader is returning me the same image with each epoch. My model is only looking at the same single image (indexed '0') each time (batch size is 1...although nothing changes with different batch sizes, anyways). Here's my dataset, stripped down to the important bits: class MyDataset(Dataset): def __init__(self, path, loader=pil_loader): self.path = path self.images = os.listdir(path) def __getitem__(self, index): image = self.images[index] . . . And here's the DataSet: train_ds = MyDataset('/data') And here's my sampler: train_sampler = RandomSampler(train_ds) And here's my DataLoader: train_dl = DataLoader(train_ds, batch_size=1, sampler=train_sampler) I'm not sure why it is returning me the same image each time, during training. Do I have RandomSampler incompletely set up? Or maybe I wrote the __getitem__ incorrectly? I can't figure it out.
Aha. Well, if anyone ends up here with the same issue, I figured out what it is and maybe this will help. My definition of __len__ was wrong. I guess the random sampler depends on how you've set up the length method. Mine was temporarily mocked up as def __len__(self): return len(0) instead of something real, like: def __len__(self): return len(self.images)
https://stackoverflow.com/questions/50124712/
If we combine one trainable parameters with a non-trainable parameter, is the original trainable param trainable?
I have two nets and I combine their parameters in some fancy way using only pytorch operations. I store the result in a third net which has its parameters set to non-trainable. Then I proceed and pass data through this new net. The new net is just a placeholder for: placeholder_net.W = Op( not_trainable_net.W, trainable_net.W ) Then I pass data: output = placeholder_net(input) I am concerned that since the parameters of the placeholder net are set to non-trainable that it won’t actually train the variable that it should train. Will this happen? Or what is the result when you combine a trainable param with and non-trainable param (and then set that where the param is not trainable)? Current solution: del net3.conv0.weight net3.conv0.weight = net.conv0.weight + net2.conv0.weight import torch from torch import nn import torch.optim as optim import torchvision import torchvision.transforms as transforms from collections import OrderedDict import copy def dont_train(net): ''' set training parameters to false. ''' for param in net.parameters(): param.requires_grad = False return net def get_cifar10(): transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) 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) classes = ('plane', 'car', 'bird', 'cat','deer', 'dog', 'frog', 'horse', 'ship', 'truck') return trainloader,classes def combine_nets(net_train, net_no_train, net_place_holder): ''' Combine nets in a way train net is trainable ''' params_train = net_train.named_parameters() dict_params_place_holder = dict(net_place_holder.named_parameters()) dict_params_no_train = dict(net_no_train.named_parameters()) for name, param_train in params_train: if name in dict_params_place_holder: layer_name, param_name = name.split('.') param_no_train = dict_params_no_train[name] ## get place holder layer layer_place_holder = getattr(net_place_holder, layer_name) delattr(layer_place_holder, param_name) ## get new param W_new = param_train + param_no_train # notice addition is just chosen for the sake of an example ## store param in placehoder net setattr(layer_place_holder, param_name, W_new) return net_place_holder def combining_nets_lead_to_error(): ''' Intention is to only train the net with trainable params. Placeholder rnet is a dummy net, it doesn't actually do anything except hold the combination of params and its the net that does the forward pass on the data. ''' device = torch.device("cuda" if torch.cuda.is_available() else "cpu") ''' create three musketeers ''' net_train = nn.Sequential(OrderedDict([ ('conv1', nn.Conv2d(1,20,5)), ('relu1', nn.ReLU()), ('conv2', nn.Conv2d(20,64,5)), ('relu2', nn.ReLU()) ])).to(device) net_no_train = copy.deepcopy(net_train).to(device) net_place_holder = copy.deepcopy(net_train).to(device) ''' prepare train, hyperparams ''' trainloader,classes = get_cifar10() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net_train.parameters(), lr=0.001, momentum=0.9) ''' train ''' net_train.train() net_no_train.eval() net_place_holder.eval() for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, (inputs, labels) in enumerate(trainloader, 0): optimizer.zero_grad() # zero the parameter gradients inputs, labels = inputs.to(device), labels.to(device) # combine nets net_place_holder = combine_nets(net_train,net_no_train,net_place_holder) # outputs = net_place_holder(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.item() 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 ''' DONE ''' print('Done \a') if __name__ == '__main__': combining_nets_lead_to_error()
First, do not use eval() mode for any network. Set requires_grad flag to false to make the parameters non-trainable for only the second network and train the placeholder network. If this doesn't work, you can try the following approach which I prefer. Instead of using multiple networks, you can use a single network and use a non-trainable layer as a parallel connection after every trainable layer before non-linearity. For example look at this image: Set requires_grad flag to false to make the parameters non-trainable. Do not use eval() and train the network. Combining outputs of the layers before non-linearity is important. Initialize the parameters of the parallel layer and choose the post-operation such that it gives the same result as when you combine the parameters.
https://stackoverflow.com/questions/50144597/
Any example of torch 0.4.0 nn.LayerNorm example for nn.LSTMCell?
In pytorch 0.4.0 release, there is a nn.LayerNorm module. I want to implement this layer to my LSTM network, though I cannot find any implementation example on LSTM network yet. And the pytorch Contributor implies that this nn.LayerNorm is only applicable through nn.LSTMCells. It will be a great help if I can get any git repo or some code that implements nn.LayerNorm on nn.LSTMcell or any torch LSTM network. Thanks in advance
I am also looking for a solution. Here is an example from https://github.com/pytorch/pytorch/issues/11335 Thanks to @jinserk class LayerNormLSTMCell(nn.LSTMCell): def __init__(self, input_size, hidden_size, bias=True): super().__init__(input_size, hidden_size, bias) self.ln_ih = nn.LayerNorm(4 * hidden_size) self.ln_hh = nn.LayerNorm(4 * hidden_size) self.ln_ho = nn.LayerNorm(hidden_size) def forward(self, input, hidden=None): self.check_forward_input(input) if hidden is None: hx = input.new_zeros(input.size(0), self.hidden_size, requires_grad=False) cx = input.new_zeros(input.size(0), self.hidden_size, requires_grad=False) else: hx, cx = hidden self.check_forward_hidden(input, hx, '[0]') self.check_forward_hidden(input, cx, '[1]') gates = self.ln_ih(F.linear(input, self.weight_ih, self.bias_ih)) \ + self.ln_hh(F.linear(hx, self.weight_hh, self.bias_hh)) i, f, o = gates[:, :(3 * self.hidden_size)].sigmoid().chunk(3, 1) g = gates[:, (3 * self.hidden_size):].tanh() cy = (f * cx) + (i * g) hy = o * self.ln_ho(cy).tanh() return hy, cy class LayerNormLSTM(nn.Module): def __init__(self, input_size, hidden_size, num_layers=1, bias=True, bidirectional=False): super().__init__() self.input_size = input_size self.hidden_size = hidden_size self.num_layers = num_layers self.bidirectional = bidirectional num_directions = 2 if bidirectional else 1 self.hidden0 = nn.ModuleList([ LayerNormLSTMCell(input_size=(input_size if layer == 0 else hidden_size * num_directions), hidden_size=hidden_size, bias=bias) for layer in range(num_layers) ]) if self.bidirectional: self.hidden1 = nn.ModuleList([ LayerNormLSTMCell(input_size=(input_size if layer == 0 else hidden_size * num_directions), hidden_size=hidden_size, bias=bias) for layer in range(num_layers) ]) def forward(self, input, hidden=None): seq_len, batch_size, hidden_size = input.size() # supports TxNxH only num_directions = 2 if self.bidirectional else 1 if hidden is None: hx = input.new_zeros(self.num_layers * num_directions, batch_size, self.hidden_size, requires_grad=False) cx = input.new_zeros(self.num_layers * num_directions, batch_size, self.hidden_size, requires_grad=False) else: hx, cx = hidden ht = [[None, ] * (self.num_layers * num_directions)] * seq_len ct = [[None, ] * (self.num_layers * num_directions)] * seq_len if self.bidirectional: xs = input for l, (layer0, layer1) in enumerate(zip(self.hidden0, self.hidden1)): l0, l1 = 2 * l, 2 * l + 1 h0, c0, h1, c1 = hx[l0], cx[l0], hx[l1], cx[l1] for t, (x0, x1) in enumerate(zip(xs, reversed(xs))): ht[t][l0], ct[t][l0] = layer0(x0, (h0, c0)) h0, c0 = ht[t][l0], ct[t][l0] t = seq_len - 1 - t ht[t][l1], ct[t][l1] = layer1(x1, (h1, c1)) h1, c1 = ht[t][l1], ct[t][l1] xs = [torch.cat((h[l0], h[l1]), dim=1) for h in ht] y = torch.stack(xs) hy = torch.stack(ht[-1]) cy = torch.stack(ct[-1]) else: h, c = hx, cx for t, x in enumerate(input): for l, layer in enumerate(self.hidden0): ht[t][l], ct[t][l] = layer(x, (h[l], c[l])) x = ht[t][l] h, c = ht[t], ct[t] y = torch.stack([h[-1] for h in ht]) hy = torch.stack(ht[-1]) cy = torch.stack(ct[-1]) return y, (hy, cy)
https://stackoverflow.com/questions/50147001/
How to add a L2 regularization term in my loss function
I’m going to compare the difference between with and without regularization, so I want to custom two loss functions. My loss function with L2 norm: ###NET class CNN(nn.Module): def __init__(self): super(CNN,self).__init__() self.layer1 = nn.Sequential( nn.Conv2d(3, 16, kernel_size = 5, padding=2), nn.ReLU(), nn.MaxPool2d(2)) self.layer2 = nn.Sequential( nn.Conv2d(16, 32, kernel_size = 5, padding=2), nn.ReLU(), nn.MaxPool2d(2)) self.layer3 = nn.Sequential( nn.Conv2d(32, 32, kernel_size = 5, padding=2), nn.ReLU(), nn.MaxPool2d(4)) self.fc = nn.Linear(32*32*32,11) def forward(self, x): out = self.layer1(x) out = self.layer2(out) out = self.layer3(out) out = out.view(out.size(0), -1) out = self.fc(out) return out net = CNN() ###OPTIMIZER criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr = LR, momentum = MOMENTUM) 1.How can I add a L2 norm in my loss function? 2.If I want to write the loss function by myself (without using optim.SGD) and do the grad-decent by autograd, how can I do? Thanks for your help!
You can explicitly compute the norm of the weights yourself, and add it to the loss. reg = 0 for param in CNN.parameters(): reg += 0.5 * (param ** 2).sum() # you can replace it with abs().sum() to get L1 regularization loss = criterion(CNN(x), y) + reg_lambda * reg # make the regularization part of the loss loss.backward() # continue as usuall See this thread for more info.
https://stackoverflow.com/questions/50149376/
Anaconda / Pytorch - Getting error when trying to get Pytorch working
I've tried the installing Pytorch with Anaconda on a Windows 10 system but have gotten a variety of errors back with each attempt. I downloaded a windows compatible tar file of the package from https://anaconda.org/peterjc123/pytorch/files and was apparently able to get the the package installed using conda install filename.tar.bz2. By apparently, I mean that the Pytorch shows up in the list of packages available in the environment I set up for using Pytorch. But when I go to load the package I get this error: &gt;&gt;&gt; import torch Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\conner\Anaconda3\envs\pytorch\lib\site-packages\torch\__init__.py", line 76, in &lt;module&gt; from torch._C import * ImportError: DLL load failed: The specified module could not be found. I also tried updating Anaconda with conda update --all which raised a relevant warning: (pytorch) C:\Users\User 1\Downloads&gt;conda update --all Fetching package metadata ............. Solving package specifications: Warning: ['Dependency missing in current win-64 channels: \n - pytorch -&gt; mkl &gt;=2018'], skipping Fetching package metadata ............. Solving package specifications: Warning: ['Dependency missing in current win-64 channels: \n - pytorch -&gt; mkl &gt;=2018'], skipping NoPackagesFoundError: Dependency missing in current win-64 channels: - pytorch -&gt; mkl &gt;=2018 The mkl package also shows up in the list of packages connected to the pytorch environment. I interpret the error to mean that there isn't a recent enough version of mkl. Would that be correct? Any other insights or advice? I really need to get pytorch installed.
I recommend you create a new conda enviroment and try to reinstall PyTorch in this way: To install PyTorch via Anaconda, and do not have a CUDA-capable[LINK] system or do not require CUDA, use the following conda command. conda install pytorch-cpu torchvision-cpu -c pytorch To install PyTorch via Anaconda, and you are using CUDA 9.0, use the following conda command: conda install pytorch torchvision -c pytorch CUDA 8.x conda install pytorch torchvision cuda80 -c pytorch CUDA 10.0 conda install pytorch torchvision cuda100 -c pytorch #Inno
https://stackoverflow.com/questions/50195080/
No module named 'torch' or 'torch.C'
Would appreciate an explanation like I'm 5 simply because I have checked all relevant answers and none have helped. I have installed Python. I have installed Pycharm. I have installed Anaconda. I have installed Microsoft Visual Studio. I have not installed the CUDA toolkit. In Anaconda, I used the commands mentioned on Pytorch.org (06/05/18) conda install pytorch -c pytorch pip3 install torchvision Both have downloaded and installed properly, and I can find them in my Users/Anaconda3/pkgs folder, which I have added to the Python path. Trying to enter import torch in the Python console proved unfruitful - always giving me the same error, No module named 'torch' I have also tried using the Project Interpreter to download the Pytorch package. It worked for numpy (sanity check, I suppose) but told me to go to Pytorch.org when I tried to install the "pytorch" or "torch" packages. When trying to use the console in PyCharm, pip3 install codes (thinking maybe I need to save the packages into my current project, rather than in the Anaconda folder) return me an error message saying torch-0.4.0-cp35-cp35m-win_amd64.whl is not a supported wheel on this platform. The same message shows no matter if I try downloading the CUDA version or not, or if I choose to use the 3.5 or 3.6 Python link (I have Python 3.7) Currently the closest I have gotten to a solution, is manually copying the "torch" and "torch-0.4.0-py3.6.egg-info" folders into my current Project's lib folder. However, when I do that and then run "import torch" I received the following error: Traceback (most recent call last): File "", line 1, in File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pydev_pydev_bundle\pydev_import_hook.py", line 19, in do_import module = self._system_import(name, *args, **kwargs) File "C:\Users\Michael\PycharmProjects\Pytorch_2\venv\lib\site-packages\torch__init__.py", line 78, in from torch._C import * File "C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pydev_pydev_bundle\pydev_import_hook.py", line 19, in do_import module = self._system_import(name, *args, **kwargs) ModuleNotFoundError: No module named 'torch._C'
pip uninstall torch then pip install torch worked for me.
https://stackoverflow.com/questions/50203945/
PyTorch: Add validation error in training
I am using PyTorch to train a cnn model. Here is my Network architecture: import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 5) self.pool = nn.MaxPool2d(2,2) self.conv1_bn = nn.BatchNorm2d(32) self.conv2 = nn.Conv2d(32, 64, 5) self.conv2_drop = nn.Dropout2d() self.conv2_bn = nn.BatchNorm2d(64) self.fc1 = torch.nn.Linear(53*53*64, 256) self.fc2 = nn.Linear(256, 136) def forward(self, x): x = F.relu(self.conv1_bn(self.pool(self.conv1(x)))) x = F.relu(self.conv2_bn(self.pool(self.conv2_drop(self.conv2(x))))) x = x.view(-1, 53*53*64) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) return x Then I train the model like below: # prepare the net for training net.train() for epoch in range(n_epochs): # loop over the dataset multiple times running_loss = 0.0 # train on batches of data, assumes you already have train_loader for batch_i, data in enumerate(train_loader): # get the input images and their corresponding labels images = data['image'] key_pts = data['keypoints'] # flatten pts key_pts = key_pts.view(key_pts.size(0), -1) # wrap them in a torch Variable images, key_pts = Variable(images), Variable(key_pts) # convert variables to floats for regression loss key_pts = key_pts.type(torch.FloatTensor) images = images.type(torch.FloatTensor) # forward pass to get outputs output_pts = net(images) # calculate the loss between predicted and target keypoints loss = criterion(output_pts, key_pts) # zero the parameter (weight) gradients optimizer.zero_grad() # backward pass to calculate the weight gradients loss.backward() # update the weights optimizer.step() # print loss statistics running_loss += loss.data[0] I am wondering if it is possible to add the validation error in the training? I mean something like this (validation split) in Keras: myModel.fit(trainX, trainY, epochs=50, batch_size=1, verbose=2, validation_split = 0.1)
Here is an example how to split your dataset for training and validation, then switch between the two phases every epoch: import numpy as np import torch from torchvision import datasets from torch.autograd import Variable from torch.utils.data.sampler import SubsetRandomSampler # Examples: my_dataset = datasets.MNIST(root="/home/benjamin/datasets/mnist", train=True, download=True) validation_split = 0.1 dataset_len = len(my_dataset) indices = list(range(dataset_len)) # Randomly splitting indices: val_len = int(np.floor(validation_split * dataset_len)) validation_idx = np.random.choice(indices, size=val_len, replace=False) train_idx = list(set(indices) - set(validation_idx)) # Contiguous split # train_idx, validation_idx = indices[split:], indices[:split] ## Defining the samplers for each phase based on the random indices: train_sampler = SubsetRandomSampler(train_idx) validation_sampler = SubsetRandomSampler(validation_idx) train_loader = torch.utils.data.DataLoader(my_dataset, sampler=train_sampler) validation_loader = torch.utils.data.DataLoader(my_dataset, sampler=validation_sampler) data_loaders = {"train": train_loader, "val": validation_loader} data_lengths = {"train": len(train_idx), "val": val_len} # Training with Validation (your code + code from Pytorch tutorial: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html) n_epochs = 40 net = ... for epoch in range(n_epochs): print('Epoch {}/{}'.format(epoch, n_epochs - 1)) print('-' * 10) # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': optimizer = scheduler(optimizer, epoch) net.train(True) # Set model to training mode else: net.train(False) # Set model to evaluate mode running_loss = 0.0 # Iterate over data. for data in data_loaders[phase]: # get the input images and their corresponding labels images = data['image'] key_pts = data['keypoints'] # flatten pts key_pts = key_pts.view(key_pts.size(0), -1) # wrap them in a torch Variable images, key_pts = Variable(images), Variable(key_pts) # convert variables to floats for regression loss key_pts = key_pts.type(torch.FloatTensor) images = images.type(torch.FloatTensor) # forward pass to get outputs output_pts = net(images) # calculate the loss between predicted and target keypoints loss = criterion(output_pts, key_pts) # zero the parameter (weight) gradients optimizer.zero_grad() # backward + optimize only if in training phase if phase == 'train': loss.backward() # update the weights optimizer.step() # print loss statistics running_loss += loss.data[0] epoch_loss = running_loss / data_lengths[phase] print('{} Loss: {:.4f}'.format(phase, epoch_loss))
https://stackoverflow.com/questions/50207001/
Pytorch on Windows gives ImportError
I installed Pytorch for PYthon 3.6 using pip as instructed on https://pytorch.org/. Pytorch is installed succesfully, but when I run code, I get this: File "C:\Users\\PycharmProjects\chatbot-light\pytorch\rnn_attention\seq2seq_translation_tutorial.py", line 93, in &lt;module&gt; import torch File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\__init__.py", line 78, in &lt;module&gt; from torch._C import * ImportError: DLL load failed: The specified module could not be found
Pytorch devs recommend installing Pytorch using Anaconda. Since Anaconda deals with all the dependencies you shouldn't have any DLL-related problems after installing Pytorch with it.
https://stackoverflow.com/questions/50264129/
RNN with many-to-one setup - which output to use
I going through a series of machine learning examples that use RNNs for document classification (many-to-one). In most tutorials, the RNN output of the last time step is used, i.e., fed into one or more dense layers to map it to the number of classes (e.g., [1], [2]). However, I also came across some examples where, instead of the last output, the average of the outputs over all time steps is used (mean pooling?, e.g., [3]). The dimensions of this averaged output are of course the same as for the last output. So computationally, both approaches just work the same. My questions is now, what is the intuition between the two different approaches. Due to recursive nature, the last output also reflects the output of the previous time steps. So why the idea of averaging the RNN outputs over all time steps. When to use what?
Pooling over time is a specific technique that is used to extract the features from the input sequence. From this question: The reason to do this, instead of "down-sampling" the sentence like in a CNN, is that in NLP the sentences naturally have different length in a corpus. This makes the feature maps different for different sentences, but we'd like to reduce the tensor to a fixed size to apply softmax or regression head in the end. As stated in the paper, it allows to capture the most important feature, one with the highest value for each feature map. It's important to note here that max-over-time (or average-over-time) is usually an intermediate layer. In particular, there can be several of them in a row or in parallel (with different window size). The end result produced by the network can still be either many-to-one or many-to-many (at least in theory). However, in most of the cases, there is a single output from the RNN. If the output must be a sequence, this output is usually fed into another RNN. So it all boils down to how exactly this single value is learned: take the last cell output or aggregate across the whole sequence or apply attention mechanism, etc.
https://stackoverflow.com/questions/50270283/
Pytorch: Softmax on each row of a 2d Tensor
I need my neural net to output N distributions over A actions. each distribution should go through softmax. The sum of each row should then obviously be 1 and the sum of the whole layer should be N. Is there such functionality in PyTorch?
Use the softmax and specify the row as the dimension to operate on import torch.nn.Functional as F x = ...# your N x A input x_distribution = F.softmax(x, dim = 1)
https://stackoverflow.com/questions/50303872/
PyTorch : error message "torch has no [...] member"
Good evening, I have just installed PyTorch 0.4.0 and I'm trying to carry out the first tutorial "What is PyTorch?" I have written a Tutorial.py file which I try to execute with Visual Studio Code Here is the code : from __future__ import print_function import torch print (torch.__version__) x = x = torch.rand(5, 3) print(x) Unfortunately, when I try to debug it, i have an error message : "torch has no rand member" This is true with any member function of torch I may try Can anybody help me please?
In case you haven't got a solution to your problem or someone else encounters it. The error is raised because of Pylint (Python static code analysis tool) not recognizing rand as the member function. You can either configure Pylint to ignore this problem or you can whitelist torch (better solution) to remove lint errors by adding following to your .pylintrc file. [TYPECHECK] # List of members which are set dynamically and missed by Pylint inference # system, and so shouldn't trigger E1101 when accessed. generated-members=numpy.*, torch.* In Visual Studio Code, you could also add the following to the user settings: "python.linting.pylintArgs": [ "--generated-members=numpy.* ,torch.*" ] The issue is discussed here on PyTorch GitHub page.
https://stackoverflow.com/questions/50319943/
Higher order gradients in pytorch
I have implemented the following Jacobian function in pytorch. Unless I have made a mistake, it computes the Jacobian of any tensor w.r.t. any dimensional inputs: import torch import torch.autograd as ag def nd_range(stop, dims = None): if dims == None: dims = len(stop) if not dims: yield () return for outer in nd_range(stop, dims - 1): for inner in range(stop[dims - 1]): yield outer + (inner,) def full_jacobian(f, wrt): f_shape = list(f.size()) wrt_shape = list(wrt.size()) fs = [] f_range = nd_range(f_shape) wrt_range = nd_range(wrt_shape) for f_ind in f_range: grad = ag.grad(f[tuple(f_ind)], wrt, retain_graph=True, create_graph=True)[0] for i in range(len(f_shape)): grad = grad.unsqueeze(0) fs.append(grad) fj = torch.cat(fs, dim=0) fj = fj.view(f_shape + wrt_shape) return fj On top of this, I have tried to implement a recursive function to calculate nth order derivatives: def nth_derivative(f, wrt, n): if n == 1: return full_jacobian(f, wrt) else: deriv = nth_derivative(f, wrt, n-1) return full_jacobian(deriv, wrt) I ran a simple test: op = torch.ger(s, s) deep_deriv = nth_derivative(op, s, 5) Unfortunately, this succeeds in getting me the Hessian...but no higher order derivatives. I'm aware many higher order derivatives should be 0, but I'd prefer if pytorch can analytically compute that. One fix has been to change the gradient calculation to: try: grad = ag.grad(f[tuple(f_ind)], wrt, retain_graph=True, create_graph=True)[0] except: grad = torch.zeros_like(wrt) Is this the accepted correct way to handle this? Or is there a better option? Or do I have the reason for my issue completely wrong to begin with?
You can just iterate calling the grad function: import torch from torch.autograd import grad def nth_derivative(f, wrt, n): for i in range(n): grads = grad(f, wrt, create_graph=True)[0] f = grads.sum() return grads x = torch.arange(4, requires_grad=True).reshape(2, 2) loss = (x ** 4).sum() print(nth_derivative(f=loss, wrt=x, n=3)) outputs tensor([[ 0., 24.], [ 48., 72.]])
https://stackoverflow.com/questions/50322833/
CUDNN_STATUS_INTERNAL_ERROR when using both Pytorch and TensorFlow
I'm running a program to process some data, and I inference both a TensorFlow model and a Pytorch model. When inferencing either of the models everything works fine. However, when I add the pytorch input my program crashes with this error: 2018-05-14 12:55:05.525251: E tensorflow/stream_executor/cuda/cuda_dnn.cc:385] could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR 2018-05-14 12:55:05.525280: F tensorflow/core/kernels/conv_ops.cc:717] Check failed: stream-&gt;parent()-&gt;GetConvolveAlgorithms( conv_parameters.ShouldIncludeWinogradNonfusedAlgo&lt;T&gt;(), &amp;algorithms) Note that this already happens before I do anything with Pytorch. No models are loaded, nothing is put on GPU, no devices are checked. Does anyone know what might be going wrong, how to fix it, and if there are some parameters I can change? Something I already tried is disabling the PyTorch backend using this code: import torch.backends.cudnn as cudnn cudnn.enabled = False But unfortunately this does not help...
You'll find in the NVIDIA Forums some references of cuBLAS not playing well with several Python processes interacting with it at the same time. This is referenced in this 1 year old issue for Tensorflow, but it should be the same for any multiple-PyTorch client applications interfacing with GPU through CUDA - and cuBLAS, to be more specific. cuBLAS handles weren't being properly initialized, somehow due to a mixture of issues related to on-disk caching and RAM utilization being too large. The solution was both to delete the on-disk cache for cuBLAS, sudo rm -rf ~/.nv and restrict the amount of memory usage for nets.
https://stackoverflow.com/questions/50328876/
Pytorch autograd fails with "RuntimeError: differentiated input is unreachable" after collecting inputs
Pytorch version 0.3.1 EDIT: I am rewriting this question to be simpler, as I've narrowed down the bug. I have some variables: x = ag.Variable(torch.ones(1, 1), requires_grad = True) y = ag.Variable(torch.ones(1, 1), requires_grad = True) z = ag.Variable(torch.ones(1, 1), requires_grad = True) I then create a variable representing their concatenation: w = torch.cat([x, y, z]) f = x + y + z Then I try to take derivatives: ag.grad(f, x, retain_graph=True, create_graph=True) This is fine and returns 1, as expected. Same for y and z. However, ag.grad(f, w, retain_graph=True, create_graph=True) Returns an error: RuntimeError: differentiated input is unreachable Of course that makes sense - w is not explicitly used in the declaration of f. However, I’d like a behavior where one line of code can generate something like [1; 1; 1] as output. Let’s say I wanted to conveniently batch my variables together, and then take the gradient of the whole shebang at once, rather than processing variables independently (which can make bookkeeping a nightmare). Is there any way to get the outcome I desire?
Does something like this work or you want to keep f = x + y + z? w = torch.cat([x, y, z]) f = w[0] + w[1] + w[2] print (ag.grad(f, w, retain_graph=True, create_graph=True)) # output (tensor([[ 1.],[ 1.],[ 1.]]),)
https://stackoverflow.com/questions/50361177/
Why does my SRGAN (using PyTorch) result look similar to SRResNet results?
SRGAN was implemented using PyTorch. Generator pre-train was conducted in 100 times and the SRGAN train was conducted in 200 times. The code is a combination of the existing github codes. For the content loss, MSELoss () in PyTorch was used and BCELoss () in PyTorch was used for adversarial loss. When I ran code, LossD converges to 0, and LossG oscillates around a certain value. So I stopped training because I thought it was not training anymore. If the training is 1e5 as in the paper, will the result change? Or is it a matter of loss function? Below is the SRGAN training code. print('Adversarial training') for epoch in range(NUM_EPOCHS): train_bar = tqdm(train_loader) running_results = {'batch_sizes': 0, 'd_loss': 0, 'g_loss': 0, 'd_score': 0, 'g_score': 0} # train_bar = tqdm(train_loader) for data, target in train_bar: batch_size = data.size(0) running_results['batch_sizes'] += batch_size target_real = Variable(torch.ones(batch_size, 1)) target_fake = Variable(torch.zeros(batch_size, 1)) if torch.cuda.is_available(): target_real = target_real.cuda() target_fake = target_fake.cuda() real_img = Variable(target) z = Variable(data) # Generate real and fake inputs if torch.cuda.is_available(): inputsD_real = real_img.cuda() inputsD_fake = netG(z.cuda()) else: inputsD_real = real_img inputsD_fake = netG(z) ######### Train discriminator ######### netD.zero_grad() # With real data outputs = netD(inputsD_real) D_real = outputs.data.mean() lossD_real = adversarial_criterion(outputs, target_real) # With fake data outputs = netD(inputsD_fake.detach()) # Don't need to compute gradients wrt weights of netG (for efficiency) D_fake = outputs.data.mean() lossD_fake = adversarial_criterion(outputs, target_fake) lossD_total = lossD_real + lossD_fake lossD_total.backward() # Update discriminator weights optimizerD.step() ######### Train generator ######### netG.zero_grad() real_features = Variable(feature_extractor(inputsD_real).data) fake_features = feature_extractor(inputsD_fake) lossG_vgg19 = content_criterion(fake_features, real_features) lossG_adversarial = adversarial_criterion(netD(inputsD_fake).detach(), target_real) lossG_mse = content_criterion(inputsD_fake, inputsD_real) lossG_total = lossG_mse + 2e-6 * lossG_vgg19 + 0.001 * lossG_adversarial lossG_total.backward() # Update generator weights optimizerG.step()
If you use the classic GAN model for alternate training, this situation is inevitable, try to change the training method
https://stackoverflow.com/questions/50364968/
PyTorch: DecoderRNN: RuntimeError: input must have 3 dimensions, got 2
I am building a DecoderRNN using PyTorch (This is an image-caption decoder): class DecoderRNN(nn.Module): def __init__(self, embed_size, hidden_size, vocab_size): super(DecoderRNN, self).__init__() self.hidden_size = hidden_size self.gru = nn.GRU(embed_size, hidden_size, hidden_size) self.softmax = nn.LogSoftmax(dim=1) def forward(self, features, captions): print (features.shape) print (captions.shape) output, hidden = self.gru(features, captions) output = self.softmax(self.out(output[0])) return output, hidden The data have the following shapes: torch.Size([10, 200]) &lt;- features.shape (10 for batch size) torch.Size([10, 12]) &lt;- captions.shape (10 for batch size) Then I got the following errors. Any ideas what I missed here? Thanks! --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-2-76e05ba08b1d&gt; in &lt;module&gt;() 44 # Pass the inputs through the CNN-RNN model. 45 features = encoder(images) ---&gt; 46 outputs = decoder(features, captions) 47 48 # Calculate the batch loss. /opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 323 for hook in self._forward_pre_hooks.values(): 324 hook(self, input) --&gt; 325 result = self.forward(*input, **kwargs) 326 for hook in self._forward_hooks.values(): 327 hook_result = hook(self, input, result) /home/workspace/model.py in forward(self, features, captions) 37 print (captions.shape) 38 # features = features.unsqueeze(1) ---&gt; 39 output, hidden = self.gru(features, captions) 40 output = self.softmax(self.out(output[0])) 41 return output, hidden /opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs) 323 for hook in self._forward_pre_hooks.values(): 324 hook(self, input) --&gt; 325 result = self.forward(*input, **kwargs) 326 for hook in self._forward_hooks.values(): 327 hook_result = hook(self, input, result) /opt/conda/lib/python3.6/site-packages/torch/nn/modules/rnn.py in forward(self, input, hx) 167 flat_weight=flat_weight 168 ) --&gt; 169 output, hidden = func(input, self.all_weights, hx) 170 if is_packed: 171 output = PackedSequence(output, batch_sizes) /opt/conda/lib/python3.6/site-packages/torch/nn/_functions/rnn.py in forward(input, *fargs, **fkwargs) 383 return hack_onnx_rnn((input,) + fargs, output, args, kwargs) 384 else: --&gt; 385 return func(input, *fargs, **fkwargs) 386 387 return forward /opt/conda/lib/python3.6/site-packages/torch/autograd/function.py in _do_forward(self, *input) 326 self._nested_input = input 327 flat_input = tuple(_iter_variables(input)) --&gt; 328 flat_output = super(NestedIOFunction, self)._do_forward(*flat_input) 329 nested_output = self._nested_output 330 nested_variables = _unflatten(flat_output, self._nested_output) /opt/conda/lib/python3.6/site-packages/torch/autograd/function.py in forward(self, *args) 348 def forward(self, *args): 349 nested_tensors = _map_variable_tensor(self._nested_input) --&gt; 350 result = self.forward_extended(*nested_tensors) 351 del self._nested_input 352 self._nested_output = result /opt/conda/lib/python3.6/site-packages/torch/nn/_functions/rnn.py in forward_extended(self, input, weight, hx) 292 hy = tuple(h.new() for h in hx) 293 --&gt; 294 cudnn.rnn.forward(self, input, hx, weight, output, hy) 295 296 self.save_for_backward(input, hx, weight, output) /opt/conda/lib/python3.6/site-packages/torch/backends/cudnn/rnn.py in forward(fn, input, hx, weight, output, hy) 206 if (not is_input_packed and input.dim() != 3) or (is_input_packed and input.dim() != 2): 207 raise RuntimeError( --&gt; 208 'input must have 3 dimensions, got {}'.format(input.dim())) 209 if fn.input_size != input.size(-1): 210 raise RuntimeError('input.size(-1) must be equal to input_size. Expected {}, got {}'.format( RuntimeError: input must have 3 dimensions, got 2
Your GRU input needs to be 3-dimensional: input of shape (seq_len, batch, input_size): tensor containing the features of the input sequence. Further you need to provide the hidden state (last encoder hidden state in this case) as second parameter: self.gru(input, h_0) Where input is your actual input and h_0 the hidden state which needs to be 3-dimensional as well: h_0 of shape (num_layers * num_directions, batch, hidden_size): tensor containing the initial hidden state for each element in the batch. Defaults to zero if not provided. https://pytorch.org/docs/master/nn.html#torch.nn.GRU
https://stackoverflow.com/questions/50399055/
How to build an autograd-compatible Pytorch module that resizes tensors like images?
I was wondering if I can build an image resize module in Pytorch that takes a torch.tensor of 3*H*W as the input and return a tensor as the resized image. I know it is possible to convert tensor to PIL Image and use torchvision, but I also hope to back propagate gradients from the resized image to the original image, and the following example will return such error (in PyTorch 0.4.0 on Windows 10): import numpy as np from torchvision import transforms t2i = transforms.ToPILImage() i2t = transforms.ToTensor() trans = transforms.Compose( t2i, transforms.Resize(size=200), i2t] ) test = np.random.normal(size=[3, 300, 300]) test = torch.tensor(test, requires_grad=True) resized = trans(test) resized.backward() print(test.grad) Traceback (most recent call last): File "D:/Projects/Python/PyTorch/test.py", line 41, in &lt;module&gt; main() File "D:/Projects/Python/PyTorch/test.py", line 33, in main resized = trans(test) File "D:\Anaconda3\envs\pytorch\lib\site-packages\torchvision\transforms\transforms.py", line 42, in __call__ img = t(img) File "D:\Anaconda3\envs\pytorch\lib\site-packages\torchvision\transforms\transforms.py", line 103, in __call__ return F.to_pil_image(pic, self.mode) File "D:\Anaconda3\envs\pytorch\lib\site-packages\torchvision\transforms\functional.py", line 102, in to_pil_image npimg = np.transpose(pic.numpy(), (1, 2, 0)) RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead. It seems like I cannot "imresize" a tensor without detaching it from autograd first, but detaching it prevents me from computing gradients. Is there a way to build a torch function/module that does the same thing as torchvision.transforms.Resize that is autograd compatiable? Any help is much appreciated!
torch.nn.functional.upsample works for me, ypa!
https://stackoverflow.com/questions/50408673/
How do I load up an image and convert it to a proper tensor for PyTorch?
I'm trying to custom load some image files (JPG files) with some labels and feed them into a convolutional neural network (CNN) in PyTorch following the example here. However, there still seem to be no decent end-to-end tutorials. The problem that I am seeing is the following. RuntimeError: thnn_conv2d_forward is not implemented for type torch.ByteTensor My Dataset looks like the following. class ImageData(Dataset): def __init__(self, width=256, height=256, transform=None): self.width = width self.height = height self.transform = transform y, x = get_images() #y is a list of labels, x is a list of file paths self.y = y self.x = x def __getitem__(self, index): img = Image.open(self.x[index]) # use pillow to open a file img = img.resize((self.width, self.height)) # resize the file to 256x256 img = img.convert('RGB') #convert image to RGB channel if self.transform is not None: img = self.transform(img) img = np.asarray(img).transpose(-1, 0, 1) # we have to change the dimensions from width x height x channel (WHC) to channel x width x height (CWH) img = torch.from_numpy(np.asarray(img)) # create the image tensor label = torch.from_numpy(np.asarray(self.y[index]).reshape([1, 1])) # create the label tensor return img, label def __len__(self): return len(self.x) The CNN is taken from here and is modified to handle NCWH (batch x channel x width x height) as follows. class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 256, 256) 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 The learning loop is also taken from the same tutorial and looks like the following. for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(dataloader, 0): # get the inputs inputs, labels = data # 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.item() 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 print('Finished Training') However, the RuntimeError mentioned above is thrown. Any ideas on what I am doing wrong? Additionally, I know that without transposing the image data, it is in the shape of WHC, but the NN model requires it as CWH. The problem is this, if we change from WHC to CWH, then we can no longer simply plot the images if we iterate over the DataLoader. data = ImageData() dataloader = DataLoader(data, batch_size=10, shuffle=True, num_workers=1) imgs, labels = next(iter(dataloader)) plt.imshow(imgs.numpy()[0,:,:,:]) plt.show() Attempting to do will throw the following error. TypeError: Invalid dimensions for image data To me, that Pillow gives you WHC and you can use that to plot, but the PyTorch CNN wants CWH to process, is a nuisance. Any idea on how to consistently or easily not do so many transforms but be able to plot and feed the data into the CNN? Or is this mismatch of WHC vs CWH just something we have to live with? Without transposing the image, when feeding it to the CNN, the following error is thrown. RuntimeError: Given groups=1, weight[256, 3, 256, 256], so expected input[10, 256, 256, 3] to have 3 channels, but got 256 channels instead.
conv2d operates on float tensors. It's common and good practice to normalize input images before passing them into the neural network. I would add the line img = img/255 immediately before you convert it to a Torch tensor in __getitem__, then it will be converted to a float tensor rather than a byte tensor and thus will be compatible with the conv2d method.
https://stackoverflow.com/questions/50420168/
How to Train Word Embedding With Pytorch
I am trying learn and practice how to train the embedding of Vocabulary set using pytorch. https://pytorch.org/tutorials/beginner/nlp/word_embeddings_tutorial.html loss = loss_function(log_probs, torch.tensor([word_to_ix[target]], dtype=torch.long)) At the above tutorial example, the loss was calculated between log_probs which is 4 x 10 tensor (4 for context words number and 10 is embedding_dimension) and the word index of target which is integer ranged from 0 to 49. I can't understand why the code doesn't compare between its context embedding with its target embedding but just compare with its class index, which is a mere integer holding no information.. I think one must go back to the embedding parameter then call it, and compare it with its context I guess. Is it just because it's only for the tutorial or I am misinterpreting some point? Thanks for your help in advance.
The embedding is a by-product of training your model. The model itself is trained with supervised learning to predict the next word give the context words. This is usually done (also in that tutorial) in the form of a one-hot encoder. The log_probs are the output of the model that are probabilities in logarithmic form which is then compared to one-hot encoder target. Higher probabilities for the correct target word corresponds to lower loss and inversely, lower probabilities for correct target words will cause larger loss signals to propagate through the network and change the weights. That is why the log_probs are compared against the target.
https://stackoverflow.com/questions/50435310/
Importing PyTorch in PyCharm using Anaconda
I just installed PyCharm and Anaconda. I installed PyTorch to Anaconda and i can even use "import torch" in Anaconda. I've created a new Project in PyCharm with the Anaconda Interpreter but i still can't use PyTorch in PyCharm.
I had this problem also. Program that imported torch worked fine at anaconda prompt running in my pytorch env, but when i ran pycharm from the windows shortcut and EVEN set my environment to use pytorch env, it would complain torch could not be imported. When i ran pycharm from the prompt as shown, it worked.
https://stackoverflow.com/questions/50440391/
‘DataParallel’ object has no attribute ‘init_hidden’
What I want to do is using DataParallel in my custom RNN class. It seems like I initialized hidden_0 in a wrong way... class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size, n_layers=1): super(RNN, self).__init__() self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.n_layers = n_layers self.encoder = nn.Embedding(input_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size, n_layers,batch_first = True) self.decoder = nn.Linear(hidden_size, output_size) self.init_hidden(batch_size) def forward(self, input): input = self.encoder(input) output, self.hidden = self.gru(input,self.hidden) output = self.decoder(output.contiguous().view(-1,self.hidden_size)) output = output.contiguous().view(batch_size,num_steps,N_CHARACTERS) #print (output.size())10,50,67 return output def init_hidden(self,batch_size): self.hidden = Variable(T.zeros(self.n_layers, batch_size, self.hidden_size).cuda()) And I call the network in this way: decoder = T.nn.DataParallel(RNN(N_CHARACTERS, HIDDEN_SIZE, N_CHARACTERS), dim=1).cuda() Then start training: for epoch in range(EPOCH_): hidden = decoder.init_hidden() But I get the error and I have no ideal how to fix it… 'DataParallel' object has no attribute 'init_hidden' Thanks for your help!
When using DataParallel your original module will be in attribute module of the parallel module: for epoch in range(EPOCH_): hidden = decoder.module.init_hidden()
https://stackoverflow.com/questions/50442000/
RuntimeError: addmm(): argument 'mat1' (position 1) must be Variable, not torch.FloatTensor
I am running this extremely simple PyTorch example NN from the documentation as is, with nothing at all changed. I get this error: Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "/opt/conda/envs/fastai/lib/python3.6/site-packages/torch/nn/modules/module.py", line 357, in __call__ result = self.forward(*input, **kwargs) File "/opt/conda/envs/fastai/lib/python3.6/site-packages/torch/nn/modules/container.py", line 67, in forward input = module(input) File "/opt/conda/envs/fastai/lib/python3.6/site-packages/torch/nn/modules/module.py", line 357, in __call__ result = self.forward(*input, **kwargs) File "/opt/conda/envs/fastai/lib/python3.6/site-packages/torch/nn/modules/linear.py", line 55, in forward return F.linear(input, self.weight, self.bias) File "/opt/conda/envs/fastai/lib/python3.6/site-packages/torch/nn/functional.py", line 835, in linear return torch.addmm(bias, input, weight.t()) RuntimeError: addmm(): argument 'mat1' (position 1) must be Variable, not torch.FloatTensor Apparently during the matrix multiplication, there is some data type error. Why would the matrices I'm trying to multiply need to be Variable anyway? I can do x = Variable(torch.randn(N, D_in)) y = Variable(torch.randn(N, D_out)) but get AttributeError: 'Variable' object has no attribute 'item' so that didn't help. I am running PyTorch version 0.3.1.post2.
I had the same issue, so I will just add the update commands in case you don't want to search them: Optional: conda list | grep pytorch conda upgrade conda The following update didn't update anything, although they should and I think its the right way to update (you may try it first) conda update pytorch torchvision What did help was to specify the version explicitly: conda install pytorch=0.4.0 -c pytorch
https://stackoverflow.com/questions/50475094/
Issue while reshaping a torch tensor from [10,200,1] to [2000,1,1]
I am having a problem when trying to reshape a torch tensor Yp of dimensions [10,200,1] to [2000,1,1]. The tensor is obtained from a numpy array y of dimension [2000,1]. I am doing the following: Yp = reshape(Yp, (-1,1,1)) I try to subtract the result to a torch tensor version of y by doing: Yp[0:2000,0] - torch.from_numpy(y[0:2000,0]) I expect the result to be an array of zeros, but that is not the case. Calling different orders when reshaping (order = 'F' or 'C') does not solve the problem, and strangely outputs the same result when doing the subtraction. I only manage to get an array of zeros by calling on the tensor Yp the ravel method with order = 'F'. What am I doing wrong? I would like to solve this using reshape!
I concur with @linamnt's comment (though the actual resulting shape is [2000, 1, 2000]). Here is a small demonstration: import torch import numpy as np # Your inputs according to question: y = np.random.rand(2000, 1) y = torch.from_numpy(y[0:2000,0]) Yp = torch.reshape(y, (10,200,1)) # Your reshaping according to question: Yp = torch.reshape(Yp, (-1,1,1)) # (note: Tensor.view() may suit your need more if you don't want to copy values) # Your subtraction: y_diff = Yp - y print(y_diff.shape) # &gt; torch.Size([2000, 1, 2000]) # As explained by @linamnt, unwanted broadcasting is done # since the dims of your tensors don't match # If you give both your tensors the same shape, e.g. [2000, 1, 1] (or [2000]): y_diff = Yp - y.view(-1, 1, 1) print(y_diff.shape) # &gt; torch.Size([2000, 1, 1]) # Checking the result tensor contains only 0 (by calculing its abs. sum): print(y_diff.abs().sum()) # &gt; 0
https://stackoverflow.com/questions/50532286/
Pytorch - Incorrect dimensions when using LSTM network
I'm getting started with pytorch and used a few transformation to build the following model using one of the tutorials as a reference: model = torch.nn.Sequential( torch.nn.Linear(D_in, H), torch.nn.ReLU(), torch.nn.Linear(H, D_out), ) I want to use an LSTM network, so I tried to do the following: model = torch.nn.Sequential( torch.nn.LSTM(D_in, H), torch.nn.Linear(H, D_out) ) which gives me this error: RuntimeError: input must have 3 dimensions, got 2 Why am I seeing this error? I anticipate there's something fundamentally wrong in my understanding of how transformations (networks?) can be chained in pytorch... EDIT After following @esBee's suggestion, I found that following runs correctly. This is because an LSTM expects the input to be of the folowing dimension: input of shape (seq_len, batch, input_size): tensor containing the features of the input sequence. The input can also be a packed variable length sequence local_x = local_x.unsqueeze(0) y_pred, (hn, cn) = layerA(local_x) y_pred = y_pred.squeeze(0) y_pred = layerB(y_pred) However, the fact that my original training/test dataset is only of sequence length 1 makes me feel like I'm doing something incorrectly. What is the purpose of this parameter in the context of neural networks?
The thing you have to pay attention to here, is that, as opposed to linear layers such as torch.nn.Linear, there's more than 1 output for recurring layers such as torch.nn.LSTM. While torch.nn.Linear returns simply the y in y = Ax + b, torch.nn.LSTMs return output, (h_n, c_n) (explained in more detail in the docs) to let you choose which output you want to process. So what happens in your example is you are feeding all these several types of output into the layer after your LSTM layer (leading to the error you are seeing). You should instead choose a specific part of the output of your LSTM and feed only that into the next layer. Sadly I don't know how to choose the output of an LSTM within a Sequential (suggestions welcome), but you can rewrite model = torch.nn.Sequential( torch.nn.LSTM(D_in, H), torch.nn.Linear(H, D_out) ) model(x) as layerA = torch.nn.LSTM(D_in, H) layerB = torch.nn.Linear(H, D_out) x = layerA(x) x = layerB(x) and then correct it by choosing the output features (h_n) of the last layer of your LSTM by writing layerA = torch.nn.LSTM(D_in, H) layerB = torch.nn.Linear(H, D_out) x = layerA(x)[0] x = layerB(x)
https://stackoverflow.com/questions/50557039/
How do I calculate the confusion matrix in PyTorch efficiently?
I have a tensor that contains my predictions and a tensor that contains the actual labels for my binary classification problem. How can I calculate the confusion matrix efficiently?
After my first version using a for-loop has proven inefficient, this is the fastest solution I came up with so far, for two equal-dimensional tensors prediction and truth: def confusion(prediction, truth): confusion_vector = prediction / truth true_positives = torch.sum(confusion_vector == 1).item() false_positives = torch.sum(confusion_vector == float('inf')).item() true_negatives = torch.sum(torch.isnan(confusion_vector)).item() false_negatives = torch.sum(confusion_vector == 0).item() return true_positives, false_positives, true_negatives, false_negatives Commented version and test-case at https://gist.github.com/the-bass/cae9f3976866776dea17a5049013258d
https://stackoverflow.com/questions/50601134/
from torch._C import * ImportError: DLL load failed: The specified module could not be found
I am trying to import torch in my windows machine using python 3.5. (CPU only)(pip) I have followed the steps given in the official website. When I try to import torch it gives me the error: from torch._C import * ImportError: DLL load failed: The specified module could not be found. I have looked up from torch._C import * (ImportError: DLL load failed: The specified module could not be found. and ModuleNotFoundError: No module named 'torch._C' and followed their instructions, still the error persists. The total traceback: Traceback (most recent call last): File "D:\CFPS.py", line 1, in &lt;module&gt; import torch File "C:\Program Files (x86)\Python35\lib\site-packages\torch\__init__.py", line 78, in &lt;module&gt; from torch._C import * ImportError: DLL load failed: The specified module could not be found. [Finished in 0.6s] Is there a way to get past through this?
I've been encountering the same problem. Pytorch seems to require openmp, however this is not part of the PIP distribution. If you install Pytorch through Anaconda, the Anaconda install includes openmp, so this problem goes away. To resolve this problem with pip, you can pip install intel-openmp but you still have to copy the openmp binaries from Python\Library\bin over to Python\Lib\site-packages\torch\lib Here's a link to the pytorch issue pytorch issue
https://stackoverflow.com/questions/50612899/
LBFGS never converges in large dimensions in pytorch
I am playing with Rule 110 of Wolfram cellular automata. Given line of zeroes and ones, you can calculate next line with these rules: Starting with 00000000....1 in the end you get this sequence: Just of curiosity I decided to approximate these rules with a polynomial, so that cells could be not only 0 and 1, but also gray color in between: def triangle(x,y,z,v0): v=(y + y * y + y * y * y - 3. * (1. + x) * y * z + z * (1. + z + z * z)) / 3. return (v-v0)*(v-v0) so if x,y,z and v0 matches any of these rules from the table, it will return 0, and positive nonzero value otherwise. Next I've added all possible groups of 4 neighbors into single sum, which will be zero for integer solutions: def eval(): s = 0. for i in range(W - 1): for j in range(1, W + 1): xx = x[i, (j - 1) % W] yy = x[i, j % W] zz = x[i, (j + 1) % W] r = x[i + 1, j % W] s += triangle(xx, yy, zz, r) for j in range(W - 1): s += x[0, j] * x[0, j] s += (1 - x[0, W - 1]) * (1 - x[0, W - 1]) return torch.sqrt(s) Also in the bottom of this function I add ordinary conditions for first line, so that all elements are 0 except last one, which is 1. Finally I've decided to minimize this sum of squares on W*W matrix with pytorch: x = Variable(torch.DoubleTensor(W,W).zero_(), requires_grad=True) opt = torch.optim.LBFGS([x],lr=.1) for i in range(15500): def closure(): opt.zero_grad() s=eval() s.backward() return s opt.step(closure) Here is full code, you can try it yourself. The problem is that for 10*10 it converges to correct solution in ~20 steps: But if I take 15*15 board, it never finishes convergence: The graph on the right shows how sum of squares is changing with each next iteration and you can see that it never reaches zero. My question is why this happens and how can I fix this. Tried different pytorch optimisers, but all of them perform worse then LBFGS. Tried different learning rates. Any ideas why this happen and how I can reach final point during optimisation? UPD: improved convergence graph, log of SOS: UPD2: I also tried doing same in C++ with dlib, and I don't have any convergency issues there, it goes much deeper in much less time: I am using this code for optimisation in C++: find_min_using_approximate_derivatives(bfgs_search_strategy(), objective_delta_stop_strategy(1e-87), s, x, -1)
What's you're trying to do here is non convex optimisation and this is a notoriously difficult problem. Once you think about it, it make sense because just about any practical mathematical problem can be formulated as an optimisation problem. 1. Prelude So, before giving you hints as to where to find a solution to your particular problem, I want to illustrate why certain optimisation problems are easy to solve. I'm going to start by discussing convex problems. These are easy to solve even in the constrained case, and the reason for this is that when you compute the gradient you actually get a lot of information of where the minimum cannot be (the Taylor expansion of a convex function, f, is always an underestimate of f), additionally there is only one minimum and no sadle points. If you're interested in learning more about convex optimisation I recommend seeing Stephen Boyd's class in convex optimisation on YouTube Now then if non convex optimization is so difficult, how come we are able to solve it in deep learning? The answer is simply that the non convex function we are minimising in deep learning it's quite nice as demonstrated by Henaff et al. It is therefore important that machine learning practitioners realise that the operation procedures used in deep learning will most likely not yield a good minimum, if they converge to a minimum in the first place, on other non-convex problems. 2. Answer to your question Now then to answer your problem, You're not you probably not gonna find and fast solution as nonconvex optimisation is NP complete. But fear not, SciPy has a few global optimisation algorithms to choose from. Here is a link to another stack overflow thread with a good answer to your question. 3. Moral of the story Finally, I want to remind you that convergence guarantees are important, forgetting it has led to an oil rig collapsing. PS. Please forgive typos, I'm usong my phone for this Update: As to why BFGS works with dlib, there might be two reasons, firstly, BFGS is better at using curvature information than L-BFGS, and secondly it uses a line search to find an optimal step size. I'd recommend checking if PyTorch allow line searches and if not, setting an decreasing step size (or just a really low one).
https://stackoverflow.com/questions/50621786/
How can I enable pytorch GPU support in Google Colab?
How can I enable pytorch to work on GPU? I've installed pytorch successfully in google colab notebook: Tensorflow reports GPU to be in place: But torch.device function fails somehow: How can I fix this?
I hit the same issue. Try installing Torch like this: # http://pytorch.org/ from os import path from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag()) accelerator = 'cu80' #'cu80' if path.exists('/opt/bin/nvidia-smi') else 'cpu' print('Platform:', platform, 'Accelerator:', accelerator) !pip install --upgrade --force-reinstall -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.0-{platform}-linux_x86_64.whl torchvision import torch print('Torch', torch.__version__, 'CUDA', torch.version.cuda) print('Device:', torch.device('cuda:0')) The output should be: Platform: cp36-cp36m Accelerator: cu80 Torch 0.4.0 CUDA 8.0.61 Device: cuda:0 Some snippets floating around use torch-0.3.0.post4-{platform}-linux_x86_64.whl, which will lead to the same error, because device is a Torch 4 feature. If you have already installed the wrong version, you may need to do !pip uninstall torch. Also be sure to enable GPU under Edit > Notebook settings > Hardware accelerator.
https://stackoverflow.com/questions/50624863/
PyTorch - "Attribute Error: module 'torch' has no attribute 'float'
I'm trying to implement the Spatial Transformer Network from here and I am running into this issue: class STNLayer(torch.nn.Module): def __init__(self, input_size): super(STNLayer, self).__init__() self.input_size = input_size self.localization = nn.Sequential( nn.Conv2d(self.input_size, 8, kernel_size = 7), nn.MaxPool2d(2, stride = 2), nn.ReLU(True), nn.Conv2d(8, 10, kernel_size = 5), nn.MaxPool2d(2, stride = 2), nn.ReLU(True) ) self.fc_loc = nn.Sequential( nn.Linear(10 * 12 * 12, 32), nn.ReLU(True), #nn.BatchNorm1d(32), nn.Linear(32, 3*2) ) # Initialize weights to identity transformation self.fc_loc[2].weight.data.zero_() self.fc_loc[2].bias.data = torch.cuda.FloatTensor([1,0,0,0,1,0]) The line self.fc_loc[2].bias.data = torch.cuda.FloatTensor([1,0,0,0,1,0]) is giving the error: *** AttributeError: module 'torch' has no attribute 'float' How do I fix this?
About the AttributeError AttributeError: module 'torch' has no attribute 'float' This AttributeError implies that somewhere in the code must be something like torch.float. In your code example I cannot find anything like it. However, the link you referenced for the code contains the following line: self.fc_loc[2].bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float)) PyTorch data types like torch.float came with PyTorch 0.4.0, so when you use something like torch.float in earlier versions like 0.3.1 you will see this error, because torch then actually has no attribute float. If you have a line like in the example you've linked, it makes perfectly sense to get an error like this. For the code you've posted it makes no sense. As you did not include a full error traceback I can only conjecture what the problem is. So probably you either have somewhere used torch.float in your code or you have imported some code with torch.float. So what can you do to fix it? Easiest way would be just updating PyTorch to 0.4.0 or higher. If you don't want to update or if you are not able to do so for some reason. You just need to find the line (or lines) where torch.float is used and change it. So probably something like this: torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float) and change it to: torch.FloatTensor([1,0,0,0,1,0]) Similarly to the line you posted in your question. I hope this helps! Short Add-on for Jupyter Notebook: This is just a side node, because your code and error message do not match: When importing code to Jupyter Notebook it is safest to restart the kernel after doing changes to the imported code. Otherwise already loaded modules are omitted during import and changes are not applied. So if there was an error in the old code this error might still occur and the traceback then points to the line you have just corrected. So for example when changing in the imported code: torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float) to torch.FloatTensor([1,0,0,0,1,0]) it might still complain about torch.float even if the line then doesn't contain a torch.floatanymore (it even shows the new code in the traceback). This is kind of confusing because the traceback then shows an error which doesn't make sense for the given line. In such a case restarting the kernel helps.
https://stackoverflow.com/questions/50652579/
Anchor boxes and offsets in SSD object detection
How do you calculate anchor box offsets for object detection in SSD? As far as I understood anchor boxes are the boxes in 8x8 feature map, 4x4 feature map, or any other feature map in the output layer. So what are the offsets? Is it the distance between the centre of the bounding box and the centre of a particular box in say a 4x4 feature map? If I am using a 4x4 feature map as my output, then my output should be of the dimension: (4x4, n_classes + 4) where 4 is for my anchor box co-ordinates. This 4 co-ordinates can be something like: (xmin, xmax, ymin, ymax) This will correspond to the top-left and bottom-right corners of the bounding box. So why do we need offsets and if so how do we calculate them? Any help would be really appreciated!
We need offsets because thats what we calculate when we default anchor boxes, In case of ssd for every feature map cell they will have predefined number of anchor boxes of different scale ratios on very feature map cell,I think in the paper this number is 6. Now because this is a detection problem ,we will also have ground truth bounding boxes,Here roughly, we compare the IOU of the anchor box to the GT box and if it is greater than a threshold say 0.5 we predict the box offsets to that anchor box.
https://stackoverflow.com/questions/50663135/
Column/row slicing a torch sparse tensor
I have a pytorch sparse tensor that I need sliced row/column wise using this slice [idx][:,idx] where idx is a list of indexes, using the mentioned slice yields my desired result on an ordinary float tensor. Is it possible applying the same slicing on a sparse tensor? Example here: #constructing sparse matrix i = np.array([[0,1,2,2],[0,1,2,1]]) v = np.ones(4) i = torch.from_numpy(i.astype("int64")) v = torch.from_numpy(v.astype("float32")) test1 = torch.sparse.FloatTensor(i, v) #constructing float tensor test2 = np.array([[1,0,0],[0,1,0],[0,1,1]]) test2 = autograd.Variable(torch.cuda.FloatTensor(test2), requires_grad=False) #slicing idx = [1,2] print(test2[idx][:,idx]) output: Variable containing: 1 0 1 1 [torch.cuda.FloatTensor of size 2x2 (GPU 0)] I am holding a 250.000 x 250.000 adjacency matrix, where I need to slice n rows and n columns, using the random idx, by simply sampling n random idx's. Since the dataset is so large it is not realistic to convert to a more convenient datatype. can I achieve the same slicing result on test1? Is it even possible? If not, are there any work-arounds? Right now I am running my model with the following "hack" of a solution: idx = sorted(random.sample(range(0, np.shape(test1)[0]), 9000)) test1 = test1AsCsr[idx][:,idx].todense().astype("int32") test1 = autograd.Variable(torch.cuda.FloatTensor(test1), requires_grad=False) Where test1AsCsr is my test1 converted to a numpy CSR matrix. This solution works, it is however very slow, and makes my GPU utilization very low, since it needs to read/write from CPU memory, constantly. Edit: Its fine with a non-sparse tensor as result
Possible answer for 2-dimentional sparse indices Find an answer below, playing with several pytorch methods (torch.eq(), torch.unique(), torch.sort(), etc.) in order to output a compact, sliced tensor of shape (len(idx), len(idx)). I tested several edge cases (unordered idx, v with 0s, i with multiple same index pairs, etc.), though I may have forgot some. Performance should also be checked. import torch import numpy as np def in1D(x, labels): """ Sub-optimal equivalent to numpy.in1D(). Hopefully this feature will be properly covered soon c.f. https://github.com/pytorch/pytorch/issues/3025 Snippet by Aron Barreira Bordin Args: x (Tensor): Tensor to search values in labels (Tensor/list): 1D array of values to search for Returns: Tensor: Boolean tensor y of same shape as x, with y[ind] = True if x[ind] in labels Example: &gt;&gt;&gt; in1D(torch.FloatTensor([1, 2, 0, 3]), [2, 3]) FloatTensor([False, True, False, True]) """ mapping = torch.zeros(x.size()).byte() for label in labels: mapping = mapping | x.eq(label) return mapping def compact1D(x): """ "Compact" values 1D uint tensor, so that all values are in [0, max(unique(x))]. Args: x (Tensor): uint Tensor Returns: Tensor: uint Tensor of same shape as x Example: &gt;&gt;&gt; densify1D(torch.ByteTensor([5, 8, 7, 3, 8, 42])) ByteTensor([1, 3, 2, 0, 3, 4]) """ x_sorted, x_sorted_ind = torch.sort(x, descending=True) x_sorted_unique, x_sorted_unique_ind = torch.unique(x_sorted, return_inverse=True) x[x_sorted_ind] = x_sorted_unique_ind return x # Input sparse tensor: i = torch.from_numpy(np.array([[0,1,4,3,2,1],[0,1,3,1,4,1]]).astype("int64")) v = torch.from_numpy(np.arange(1, 7).astype("float32")) test1 = torch.sparse.FloatTensor(i, v) print(test1.to_dense()) # tensor([[ 1., 0., 0., 0., 0.], # [ 0., 8., 0., 0., 0.], # [ 0., 0., 0., 0., 5.], # [ 0., 4., 0., 0., 0.], # [ 0., 0., 0., 3., 0.]]) # note: test1[1, 1] = v[i[1,:]] + v[i[6,:]] = 2 + 6 = 8 # since both i[1,:] and i[6,:] are [1,1] # Input slicing indices: idx = [4,1,3] # Getting the elements in `i` which correspond to `idx`: v_idx = in1D(i, idx).byte() v_idx = v_idx.sum(dim=0).squeeze() == i.size(0) # or `v_idx.all(dim=1)` for pytorch 0.5+ v_idx = v_idx.nonzero().squeeze() # Slicing `v` and `i` accordingly: v_sliced = v[v_idx] i_sliced = i.index_select(dim=1, index=v_idx) # Building sparse result tensor: i_sliced[0] = compact1D(i_sliced[0]) i_sliced[1] = compact1D(i_sliced[1]) # To make sure to have a square dense representation: size_sliced = torch.Size([len(idx), len(idx)]) res = torch.sparse.FloatTensor(i_sliced, v_sliced, size_sliced) print(res) # torch.sparse.FloatTensor of size (3,3) with indices: # tensor([[ 0, 2, 1, 0], # [ 0, 1, 0, 0]]) # and values: # tensor([ 2., 3., 4., 6.]) print(res.to_dense()) # tensor([[ 8., 0., 0.], # [ 4., 0., 0.], # [ 0., 3., 0.]]) Previous answer for 1-dimentional sparse indices Here is a (probably sub-optimal and not covering all edge cases) solution, following the intuitions shared in a related open issue (hopefully this feature will be properly covered soon): # Constructing a sparse tensor a bit more complicated for the sake of demo: i = torch.LongTensor([[0, 1, 5, 2]]) v = torch.FloatTensor([[1, 3, 0], [5, 7, 0], [9, 9, 9], [1,2,3]]) test1 = torch.sparse.FloatTensor(i, v) # note: if you directly have sparse `test1`, you can get `i` and `v`: # i, v = test1._indices(), test1._values() # Getting the slicing indices: idx = [1,2] # Preparing to slice `v` according to `idx`. # For that, we gather the list of indices `v_idx` such that i[v_idx[k]] == idx[k]: i_squeeze = i.squeeze() v_idx = [(i_squeeze == j).nonzero() for j in idx] # &lt;- doesn't seem optimal... v_idx = torch.cat(v_idx, dim=1) # Slicing `v` accordingly: v_sliced = v[v_idx.squeeze()][:,idx] # Now defining your resulting sparse tensor. # I'm not sure what kind of indexing you want, so here are 2 possibilities: # 1) "Dense" indixing: test1x = torch.sparse.FloatTensor(torch.arange(v_idx.size(1)).long().unsqueeze(0), v_sliced) print(test1x) # torch.sparse.FloatTensor of size (3,2) with indices: # # 0 1 # [torch.LongTensor of size (1,2)] # and values: # # 7 0 # 2 3 # [torch.FloatTensor of size (2,2)] # 2) "Sparse" indixing using the original `idx`: test1x = torch.sparse.FloatTensor(autograd.Variable(torch.LongTensor(idx)).unsqueeze(0), v_sliced) # note: this indexing would fail if elements of `idx` were not in `i`. print(test1x) # torch.sparse.FloatTensor of size (3,2) with indices: # # 1 2 # [torch.LongTensor of size (1,2)] # and values: # # 7 0 # 2 3 # [torch.FloatTensor of size (2,2)]
https://stackoverflow.com/questions/50666440/
Embedding in pytorch
Does Embedding make similar words closer to each other? And do I just need to give to it all the sentences? Or it is just a lookup table and I need to code the model?
nn.Embedding holds a Tensor of dimension (vocab_size, vector_size), i.e. of the size of the vocabulary x the dimension of each vector embedding, and a method that does the lookup. When you create an embedding layer, the Tensor is initialised randomly. It is only when you train it when this similarity between similar words should appear. Unless you have overwritten the values of the embedding with a previously trained model, like GloVe or Word2Vec, but that's another story. So, once you have the embedding layer defined, and the vocabulary defined and encoded (i.e. assign a unique number to each word in the vocabulary) you can use the instance of the nn.Embedding class to get the corresponding embedding. For example: import torch from torch import nn embedding = nn.Embedding(1000,128) embedding(torch.LongTensor([3,4])) will return the embedding vectors corresponding to the word 3 and 4 in your vocabulary. As no model has been trained, they will be random.
https://stackoverflow.com/questions/50747947/
dimension out of range (expected to be in range of [-2, 1], but got 2)
Why does the following error popup? What should be in this range and why? What does -2 dimension mean? RuntimeError: dimension out of range (expected to be in range of [-2, 1], but got 2) This code will produce the error import torch torch.bmm(torch.randn(1000, 784) , torch.randn(784, 10))
torch.mm: Performs a matrix multiplication of the matrices mat1 and mat2. If mat1 is a (n×m) tensor, mat2 is a (m×p) tensor, out will be a (n×p) tensor. torch.bmm: Performs a batch matrix-matrix product of matrices stored in batch1 and batch2. batch1 and batch2 must be 3-D tensors each containing the same number of matrices. If batch1 is a (b×n×m) tensor, batch2 is a (b×m×p) tensor, out will be a (b×n×p) tensor. The following code snippet works. import torch x = torch.mm(torch.randn(100, 78) , torch.randn(78, 10)) bsize = 16 x = torch.bmm(torch.randn(bsize, 100, 78) , torch.randn(bsize, 78, 10))
https://stackoverflow.com/questions/50776744/
Dot Product of Tensors with Different Shapes in PyTorch
p=torch.randn(2,3) q=torch.randn(3,4,5) I want to perform dot product, to obtain a result of shape (2,4,5). How can this be done with PyTorch?
Two solutions for multi-dimensional matrix multiplications: Use Tensor.reshape() to get 2-D tensors and use torch.mm(); Use directly torch.einsum(). Demonstration: import torch p=torch.randn(2,3) q=torch.randn(3,4,5) # Solution 1: Reshaping to use 2-dimensional torch.mm() res1 = torch.mm(p, q.resize(3, 4 * 5)).resize_(2, 4, 5) print(res1.shape) # torch.Size([2, 4, 5]) # Solution 2: Using explicit torch.einsum() res2 = torch.einsum("ab,bcd-&gt;acd", (p, q)) print(res2.shape) # torch.Size([2, 4, 5]) # Checking if results are equal: print((res1 == res2).all()) # tensor(1, dtype=torch.uint8)
https://stackoverflow.com/questions/50791316/
Python loop faster than Pandas
The below code will show that using python loop is faster than using Pandas. My understanding before I tested it was different. So I'm wondering am I using pandas wrongly for this operation? The below code shows that Pandas solution is about 7 times slower: Pandas time 0.0008931159973144531 Loop time 0.0001239776611328125 Code: import pandas as pd import numpy as np import time import torch batch_size = 5 classes = 4 raw_target = torch.from_numpy(np.array([1, 0, 3, 2, 0])) rows = np.array(range(batch_size)) t0 = time.time() zeros = pd.DataFrame(0, index=range(batch_size), columns=range(classes)) zeros.iloc[[rows, raw_target.numpy()]] = 1 t1 = time.time() print("Pandas time ", t1-t0) t0 = time.time() target = raw_target.numpy() zeros = np.zeros((batch_size, classes), dtype=np.float64) for zero, target in zip(zeros, target): zero[target] = 1 t1 = time.time() print("Loop time ", t1-t0) The code uses PyTorch because the actual code where the problem exists uses PyTorch. What could be better/optimal solution to this example? The resulting matrix is: [[0. 1. 0. 0.] [1. 0. 0. 0.] [0. 0. 0. 1.] [0. 0. 1. 0.] [1. 0. 0. 0.]]
Depending on your use-case, having everything running through PyTorch could be advantageous (e.g. to keep all computations on the GPU). The PyTorch-only solution would follow the numpy syntax (i.e. zeros[rows, raw_target] = 1.): import numpy as np import torch batch_size = 5 classes = 4 raw_target = torch.from_numpy(np.array([1, 0, 3, 2, 0])) rows = torch.range(0, batch_size-1, dtype=torch.int64) x = torch.zeros((batch_size, classes), dtype=torch.float64) x[rows, raw_target] = 1. print(x.detach()) # tensor([[ 0., 1., 0., 0.], # [ 1., 0., 0., 0.], # [ 0., 0., 0., 1.], # [ 0., 0., 1., 0.], # [ 1., 0., 0., 0.]], dtype=torch.float64)
https://stackoverflow.com/questions/50794502/
Minimization and maximization at the same time in PyTorch
I would like to know how to take gradient steps for the following mathematical operation in PyTorch (A, B and C are PyTorch modules whose parameters do not overlap) This is somewhat different than the cost function of a Generative Adversarial Network (GAN), so I cannot use examples for GANs off the shelf, and I got stuck while trying to adapt them for the above cost. One approach I thought of is to construct two optimizers. Optimizer opt1 has the parameters for the modules A and B, and optimizer opt2 has the parameters of module C. One can then: take a step for minimizing the cost function for C run the network again with the same input to get the costs (and intermediate outputs) again take a step with respect to A and B. I am sure they must be a better way to do this with PyTorch (maybe using some detach operations), possibly without running the network again. Any help is appreciated.
Yes it is possible without going through the network two times, which is both wasting resources and wrong mathematically, since the weights have changed and so the lost, so you are introducing a delay doing this, which may be interesting but not what you are trying to achieve. First, create two optimizers just as you said. Compute the loss, and then call backward. At this point, the gradient for the parameters A,B,C have been filled, so now you can just have to call the step method for the optimizer minimizing the loss, but not for the one maximizing it. For the later, you need to reverse the sign of the gradient of the leaf parameter tensor C. def d(y, x): return torch.pow(y.abs(), x + 1) A = torch.nn.Linear(1,2) B = torch.nn.Linear(2,3) C = torch.nn.Linear(2,3) optimizer1 = torch.optim.Adam((*A.parameters(), *B.parameters())) optimizer2 = torch.optim.Adam(C.parameters()) x = torch.rand((10, 1)) loss = (d(B(A(x)), x) - d(C(A(x)), x)).sum() optimizer1.zero_grad() optimizer2.zero_grad() loss.backward() for p in C.parameters(): if p.grad is not None: # In general, C is a NN, with requires_grad=False for some layers p.grad.data.mul_(-1) # Update of grad.data not tracked in computation graph optimizer1.step() optimizer2.step() NB: I have not checked mathematically if the result is correct but I assume it is.
https://stackoverflow.com/questions/50809367/
How do I add LSTM, GRU or other recurrent layers to a Sequential in PyTorch
I like using torch.nn.Sequential as in self.conv_layer = torch.nn.Sequential( torch.nn.Conv1d(196, 196, kernel_size=15, stride=4), torch.nn.Dropout() ) But when I want to add a recurrent layer such as torch.nn.GRU it won't work because the output of recurrent layers in PyTorch is a tuple and you need to choose which part of the output you want to further process. So is there any way to get self.rec_layer = nn.Sequential( torch.nn.GRU(input_size=2, hidden_size=256), torch.nn.Linear(in_features=256, out_features=1) ) to work? For this example, let's say I want to feed torch.nn.GRU(input_size=2, hidden_size=20)(x)[1][-1] (the last hidden state of the last layer) into the following Linear layer.
I made a module called SelectItem to pick out an element from a tuple or list class SelectItem(nn.Module): def __init__(self, item_index): super(SelectItem, self).__init__() self._name = 'selectitem' self.item_index = item_index def forward(self, inputs): return inputs[self.item_index] SelectItem can be used in Sequential to pick out the hidden state: net = nn.Sequential( nn.GRU(dim_in, dim_out, batch_first=True), SelectItem(1) )
https://stackoverflow.com/questions/50817916/
PyTorch: copy_if failed to synchronize: device-side assert triggered
Getting the following error: RuntimeError: copy_if failed to synchronize: device-side assert triggered when trying to execute: if torch.nonzero(gt_class_ids &gt; n_classes).size()[0] &gt; 0: where gt_class_ids is Torch.cuda.LongTensor of size [128] and n_classes = 81. Running on cuda 9.x
The following code works for me. n_classes = 81 gt_class_ids = torch.from_numpy(numpy.random.randint(1, 100, size=128)).long() if torch.nonzero(gt_class_ids &gt; n_classes).size(0) &gt; 0: print('okay') One suggestion: run the code without using cuda and then you will be able to see the real error message. Sometimes when we run code using cuda, it gives error message having device-side assert triggered which hides the real error message.
https://stackoverflow.com/questions/50852294/
I want to customise the last layer of VGG 19 architecture for a classification. which will be more useful keras or pytorch?
I want to customise the last layer of VGG 19 architecture for a classification problem. which will be more useful keras or pytorch?
It heavily depends on what you want to do with it. While Keras offers different backends, such as TensorFlow or Theano (which in turn can offer you a little more flexibility), and transfers better to production systems, PyTorch is definitely also easy to implement. Additionally, it offers great scaling on (multi-)GPU systems, since it is trivial to outsource your computations in a PyTorch model. I do not know how easy that is in Keras (never done it, so I genuinely cannot judge). If you just want to play around with one of the frameworks, it usually boils down to personal preference. I personally prefer PyTorch, due to its more "python-esque" approach to things, but I know many people that prefer Keras because of its clear and simple layout and documentation. Providing a little more information, or your context, can also potentially increase the quality of the answers you receive.
https://stackoverflow.com/questions/50868516/
PyTorch 0.4 LSTM: Why does each epoch get slower?
I have a toy model of a PyTorch 0.4 LSTM on a GPU. The overall idea of the toy problem is that I define a single 3-vector as an input, and define a rotation matrix R. The ground truth targets are then a sequence of vectors: At T0, the input vector; at T1 the input vector rotated by R; at T2 the input rotated by R twice, etc. (The input is padded the output length with zero-inputs after T1) The loss is the average L2 difference between ground truth and outputs. The rotation matrix, construction of the input/output data, and loss functions are probably not of interest, and not shown here. Never mind that the results are pretty terrible: Why does this become successively slower with each passing epoch?! I've shown on-GPU information below, but this happens on the CPU as well (only with larger times.) The time to execute ten epochs of this silly little thing grows rapidly. It's quite noticeable just watching the numbers scroll by. epoch: 0, loss: 0.1753, time previous: 33:28.616360 time now: 33:28.622033 time delta: 0:00:00.005673 epoch: 10, loss: 0.2568, time previous: 33:28.622033 time now: 33:28.830665 time delta: 0:00:00.208632 epoch: 20, loss: 0.2092, time previous: 33:28.830665 time now: 33:29.324966 time delta: 0:00:00.494301 epoch: 30, loss: 0.2663, time previous: 33:29.324966 time now: 33:30.109241 time delta: 0:00:00.784275 epoch: 40, loss: 0.1965, time previous: 33:30.109241 time now: 33:31.184024 time delta: 0:00:01.074783 epoch: 50, loss: 0.2232, time previous: 33:31.184024 time now: 33:32.556106 time delta: 0:00:01.372082 epoch: 60, loss: 0.1258, time previous: 33:32.556106 time now: 33:34.215477 time delta: 0:00:01.659371 epoch: 70, loss: 0.2237, time previous: 33:34.215477 time now: 33:36.173928 time delta: 0:00:01.958451 epoch: 80, loss: 0.1076, time previous: 33:36.173928 time now: 33:38.436041 time delta: 0:00:02.262113 epoch: 90, loss: 0.1194, time previous: 33:38.436041 time now: 33:40.978748 time delta: 0:00:02.542707 epoch: 100, loss: 0.2099, time previous: 33:40.978748 time now: 33:43.844310 time delta: 0:00:02.865562 The model: class Sequence(torch.nn.Module): def __init__ (self): super(Sequence, self).__init__() self.lstm1 = nn.LSTM(3,30) self.lstm2 = nn.LSTM(30,300) self.lstm3 = nn.LSTM(300,30) self.lstm4 = nn.LSTM(30,3) self.hidden1 = self.init_hidden(dim=30) self.hidden2 = self.init_hidden(dim=300) self.hidden3 = self.init_hidden(dim=30) self.hidden4 = self.init_hidden(dim=3) self.dense = torch.nn.Linear(30, 3) self.relu = nn.LeakyReLU() def init_hidden(self, dim): return (torch.zeros(1, 1, dim).to(device) ,torch.zeros(1, 1, dim).to(device) ) def forward(self, inputs): out1, self.hidden1 = self.lstm1(inputs, self.hidden1) out2, self.hidden2 = self.lstm2(out1, self.hidden2) out3, self.hidden3 = self.lstm3(out2, self.hidden3) #out4, self.hidden4 = self.lstm4(out3, self.hidden4) # This is intended to act as a dense layer on the output of the LSTM out4 = self.relu(self.dense(out3)) return out4 The training loop: sequence = Sequence().to(device) criterion = L2_Loss() optimizer = torch.optim.Adam(sequence.parameters()) _, _, _, R = getRotation(np.pi/27, np.pi/26, np.pi/25) losses = [] date1 = datetime.datetime.now() for epoch in range(1001): # Define input as a Variable-- each row of 3 is a vector, a distinct input # Define target directly from input by applicatin of rotation vector # Define predictions by running input through model inputs = getInput(25) targets = getOutput(inputs, R) inputs = torch.cat(inputs).view(len(inputs), 1, -1).to(device) targets = torch.cat(targets).view(len(targets), 1, -1).to(device) target_preds = sequence(inputs) target_preds = target_preds.view(len(target_preds), 1, -1) loss = criterion(targets, target_preds).to(device) losses.append(loss.data[0]) if (epoch % 10 == 0): date2 = datetime.datetime.now() print("epoch: %3d, \tloss: %6.4f, \ttime previous: %s\ttime now: %s\ttime delta: %s" % (epoch, loss.data[0], date1.strftime("%M:%S.%f"), date2.strftime("%M:%S.%f"), date2 - date1)) date1 = date2 # Zero out the grads, run the loss backward, and optimize on the grads optimizer.zero_grad() loss.backward(retain_graph=True) optimizer.step()
Short answer: Because we did not detach the hidden layers, and therefore the system kept backpropagating farther and father back through time, taking up more memory and requiring more time. Long answer: This answer is meant to work without teacher forcing. "Teacher forcing" is when all inputs at all time-steps are "ground truth" input values. In contrast, without teacher forcing, the input of each time step is the output from the previous time step, no matter how early in the training regime (and therefore, how wildly erratic) that data might be. This is a bit of a manual operation in PyTorch, requiring us to keep track of not only the output, but the hidden state of the network at each step, so we can provide it to the next. Detachment has to happen, not at every time step, but at the beginning of each sequence. A method that seems to work is to define a "detach" method as part of the Sequence model (which will manually detach all the hidden layers), and call it explicitly after the optimizer.step(). This prevents the gradual accumulation of the hidden states, prevents the gradual slowdown, and still seems to train the network. I cannot truly vouch for it because I have only employed it on a toy model, not a real problem. Note 1: There are probably better ways to factor the initialization of the network and use that instead of a manual detach, as well. Note2: The loss.backward(retain_graph=True) statement retains the graph because error messages suggested it. Once the detach is enacted, that warning disappears. I leave this answer un-accepted in the hopes that someone knowledgeable will add their expertise.
https://stackoverflow.com/questions/50899548/
System hangs after first epoch training in pytorch
So, I was trying to train on ResNet model in PyTorch using the ImageNet example in the GitHub repository. Here's what my train method looks like (it is almost similar to that in example) def train(train_loader, model, criterion, optimizer, epoch): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() top1 = AverageMeter() top5 = AverageMeter() args = get_args() # switch to train mode model.train() end = time.time() for i, (input, target) in enumerate(train_loader): print(i) # data loading time data_time.update(time.time() - end) if cuda: target = target.cuda(async = True) input_var = torch.autograd.Variable(input).cuda() else: input_var = torch.autograd.Variable(input) target_var = torch.autograd.Variable(target) # compute output output = model(input_var) loss = criterion(output, target_var) # measure accuracy and record loss prec1, prec5 = accuracy(output.data, target, topk=(1, 5)) losses.update(loss.item(), input.size(0)) top1.update(prec1.item(), input.size(0)) # top5.update(prec5.item(), input.size(0)) # compute gradient and do optimizer step optimizer.zero_grad() loss.backward() optimizer.step() #measure elapsed time batch_time.update(time.time() - end) end = time.time() # print to console and write logs to tensorboard if i % args.print_freq == 0: print('Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t' 'Prec@1 {top1.val:.3f} ({top1.avg:.3f})\t'.format( epoch, i, len(train_loader), batch_time=batch_time, data_time=data_time, loss=losses, top1=top1, top5=top5)) niter = epoch * len(train_loader) + i # writer.add_scalar('Train/Loss', losses.val, niter) # writer.add_scalar('Train/Prec@1', top1.val, niter) # writer.add_scalar('Train/Prec@5', top5.val, niter) System Information: GPU: Nvidia Titan XP Memory: 32 Gb PyTorch: 0.4.0 When I run this code, training starts with epoch 0 Epoch: [0][0/108] Time 5.644 (5.644) Data 1.929 (1.929) Loss 6.9052 (6.9052) Prec@1 0.000 (0.000) And then the remote server automatically disconnects. It happened five times. And this is the data loader: #Load the Data --&gt; TRAIN traindir = 'train' normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) train_dataset = datasets.ImageFolder(traindir, transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize, ])) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=args.batch_size, shuffle=True, num_workers=args.num_workers, pin_memory=cuda ) # Load the data --&gt; Validation valdir = 'valid' valid_loader = torch.utils.data.DataLoader( datasets.ImageFolder(valdir, transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize, ])), batch_size=args.batch_size, shuffle=False, num_workers=args.num_workers, pin_memory=cuda ) if args.evaluate: validate(valid_loader, model, criterion, epoch=0) return # Start for epoch in range(args.start_epoch, args.epochs): adjust_learning_rate(optimizer, epoch) # train for epoch train(train_loader, model, criterion, optimizer, epoch) # evaluate on valid prec1 = validate(valid_loader, model, criterion, epoch) # remember best prec1 and save checkpoint is_best = prec1 &gt; best_prec1 best_prec1 = max(prec1, best_prec1) save_checkpoint({ 'epoch': epoch + 1, 'arch': args.arch, 'state_dict': model.state_dict(), 'best_prec1': best_prec1, 'optimizer': optimizer.state_dict() }, is_best) With this params for the loader: args.num_workers = 4 args.batch_size = 32 pin_memory = torch.cuda.is_available() Is there something wrong in my approach?
seems a bug in pytorch's dataloader. try args.num_workers = 0
https://stackoverflow.com/questions/50911880/
Need help understand this implementation of ConvLSTM code in pytorch
I am having issue understand the following implementation of ConvLSTM. I don't really understand what input_size + hidden_size is? Also the 4 * hidden_size value for output? model = ConvLSTMCell(c, d) tells us that c and d are input_size and hidden_size which are 3 and 5 respectively. I assume c is channel and d stands for output dimension? Also, why are we multiplying hidden_size by 4 for output? Is 4 the default 4 gates of the LSTM cell? Can some one more experience explain to me what is going on within the convolution? Thank you. self.Gates = nn.Conv2d(input_size + hidden_size, 4 * hidden_size, KERNEL_SIZE, padding=PADDING) import torch from torch import nn import torch.nn.functional as f from torch.autograd import Variable # Define some constants KERNEL_SIZE = 3 PADDING = KERNEL_SIZE // 2 class ConvLSTMCell(nn.Module): """ Generate a convolutional LSTM cell """ def __init__(self, input_size, hidden_size): super().__init__() self.input_size = input_size self.hidden_size = hidden_size self.Gates = nn.Conv2d(input_size + hidden_size, 4 * hidden_size, KERNEL_SIZE, padding=PADDING) def forward(self, input_, prev_state): # get batch and spatial sizes batch_size = input_.data.size()[0] spatial_size = input_.data.size()[2:] # generate empty prev_state, if None is provided if prev_state is None: state_size = [batch_size, self.hidden_size] + list(spatial_size) prev_state = ( Variable(torch.zeros(state_size)), Variable(torch.zeros(state_size)) ) prev_hidden, prev_cell = prev_state # data size is [batch, channel, height, width] stacked_inputs = torch.cat((input_, prev_hidden), 1) gates = self.Gates(stacked_inputs) # chunk across channel dimension in_gate, remember_gate, out_gate, cell_gate = gates.chunk(4, 1) # apply sigmoid non linearity in_gate = f.sigmoid(in_gate) remember_gate = f.sigmoid(remember_gate) out_gate = f.sigmoid(out_gate) # apply tanh non linearity cell_gate = f.tanh(cell_gate) # compute current cell and hidden state cell = (remember_gate * prev_cell) + (in_gate * cell_gate) hidden = out_gate * f.tanh(cell) return hidden, cell def _main(): """ Run some basic tests on the API """ # define batch_size, channels, height, width b, c, h, w = 1, 3, 4, 8 d = 5 # hidden state size lr = 1e-1 # learning rate T = 6 # sequence length max_epoch = 20 # number of epochs # set manual seed torch.manual_seed(0) print('Instantiate model') model = ConvLSTMCell(c, d) print(repr(model)) print('Create input and target Variables') x = Variable(torch.rand(T, b, c, h, w)) y = Variable(torch.randn(T, b, d, h, w)) print('Create a MSE criterion') loss_fn = nn.MSELoss() print('Run for', max_epoch, 'iterations') for epoch in range(0, max_epoch): state = None loss = 0 for t in range(0, T): state = model(x[t], state) loss += loss_fn(state[0], y[t]) print(' &gt; Epoch {:2d} loss: {:.3f}'.format((epoch+1), loss.data[0])) # zero grad parameters model.zero_grad() # compute new grad parameters through time! loss.backward() # learning_rate step against the gradient for p in model.parameters(): p.data.sub_(p.grad.data * lr) print('Input size:', list(x.data.size())) print('Target size:', list(y.data.size())) print('Last hidden state size:', list(state[0].size())) if __name__ == '__main__': _main() __author__ = "Alfredo Canziani" __credits__ = ["Alfredo Canziani"] __maintainer__ = "Alfredo Canziani" __email__ = "[email protected]" __status__ = "Prototype" # "Prototype", "Development", or "Production" __date__ = "Jan 17"
Yes, you are right, the output is timed by 4 because there are 4 gates
https://stackoverflow.com/questions/50914300/
How to convert numpy array into LongTensor type Variable in PyTorch?
I am trying to convert numpy array into PyTorch LongTensor type Variable as follows: import numpy as np import torch as th y = np.array([1., 1., 1.1478225, 1.1478225, 0.8521775, 0.8521775, 0.4434675]) yth = Variable(th.from_numpy(y)).type(torch.LongTensor) However the result I am getting is a rounded off version: tensor([ 1, 1, 1, 1, 0, 0, 0]) How can I keep the precision of numpy array while getting LongTensor variable? Expected result should be: tensor([1., 1., 1.1478225, 1.1478225, 0.8521775, 0.8521775, 0.4434675])
LongTensor represents tensors with values of type long / int64 (c.f. table in doc). Your float values are thus converted (i.e. rounded) to integers. To keep float values, use FloatTensor (float32) or DoubleTensor (float64) instead.
https://stackoverflow.com/questions/50928148/
Cannot load torchvision despite it being installed
I have installed pytorch and torchvision using: conda install pytorch-cpu -c pytorch pip install torchvision when I try to run the following in spyder: import torch import torchvision import torchvision.transforms as transforms I get: Traceback (most recent call last): File "&lt;ipython-input-2-0bf25e9dac67&gt;", line 2, in &lt;module&gt; import torchvision File "C:\Users\lkoefoed\AppData\Local\Continuum\anaconda3\lib\site-package\torchvision\__init__.py", line 2, in &lt;module&gt; from torchvision import datasets File "C:\Users\lkoefoed\AppData\Local\Continuum\anaconda3\lib\site-packages\torchvision\datasets\__init__.py", line 1, in &lt;module&gt; from .lsun import LSUN, LSUNClass File "C:\Users\lkoefoed\AppData\Local\Continuum\anaconda3\lib\site-packages\torchvision\datasets\lsun.py", line 2, in &lt;module&gt; from PIL import Image File "C:\Users\lkoefoed\AppData\Local\Continuum\anaconda3\lib\site-packages\PIL\Image.py", line 56, in &lt;module&gt; from . import _imaging as core ImportError: DLL load failed: The specified module could not be found.
Fixed by running: conda install pytorch-cpu -c pytorch pip install torchvision Deleting the PIL and pillow folders in site-packages, then running: pip install pillow
https://stackoverflow.com/questions/50960830/
PyToch Skorch passing 3 dimensional input
Im trying to fit a model in PyTorch while using skorch. My problem is, that my model uses an LSTM layer, which expects 3d input and I don't know how to pass the input correctly. When passing a 2d-array to fit() I get an error from PyTorch for the expected 3d input. If passing a 3d-array, I get the error from the fit() method for inconsistent lengths (which both make perfectly sense to me). Example code below: import numpy as np import torch from torch import nn import skorch class lstmNet(nn.Module): def __init__(self, input_size, hidden_size, num_layers): super(lstmNet, self).__init__() self.rnn = nn.LSTM( input_size, hidden_size, num_layers ) self.lin = nn.Linear( in_features=hidden_size, out_features=1 ) def forward(self, x): print(x.size()) out, hn = self.rnn(x) out = self.lin(out) return out input_feat = 5 hidden_size = 10 lstmLayers = 2 seq = 20 batch = 30 features = 5 net = skorch.NeuralNet( module=lstmNet( input_size=input_feat, hidden_size=hidden_size, num_layers=lstmLayers ), criterion=torch.nn.MSELoss, optimizer=torch.optim.SGD, lr=0.1, max_epochs=10 ) #inputArr2d = np.random.rand(seq * batch, features) inputArr3d = np.random.rand(seq, batch, features) print('input:\n {}\nshape: {}'.format(inputArr3d, inputArr3d.shape)) targetArr = np.random.rand((seq * batch)) #print('target:\n {}\nshape: {}'.format(targetArr, targetArr.shape)) net.fit(X=inputArr3d, y=targetArr) This is the error when calling net.fit(X=inputArr2d, y=targetArr): Traceback (most recent call last): File "C:\Spielplatz\Python\examples\playground.py", line 64, in &lt;module&gt; net.fit(X=inputArr2d, y=targetArr) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 686, in fit self.partial_fit(X, y, **fit_params) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 646, in partial_fit self.fit_loop(X, y, **fit_params) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 584, in fit_loop step = self.train_step(Xi, yi, **fit_params) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 507, in train_step y_pred = self.infer(Xi, **fit_params) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 810, in infer return self.module_(x, **fit_params) File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 491, in __call__ result = self.forward(*input, **kwargs) File "C:\Spielplatz\Python\examples\playground.py", line 33, in forward out, hn = self.rnn(x) File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 491, in __call__ result = self.forward(*input, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\rnn.py", line 178, in forward self.check_forward_args(input, hx, batch_sizes) File "C:\ProgramData\Anaconda3\lib\site-packages\torch\nn\modules\rnn.py", line 126, in check_forward_args expected_input_dim, input.dim())) RuntimeError: input must have 3 dimensions, got 2 And this is the error when calling net.fit(X=inputArr3d, y=targetArr): Traceback (most recent call last): File "C:\Spielplatz\Python\examples\playground.py", line 64, in &lt;module&gt; net.fit(X=inputArr3d, y=targetArr) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 686, in fit self.partial_fit(X, y, **fit_params) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 646, in partial_fit self.fit_loop(X, y, **fit_params) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 573, in fit_loop X, y, **fit_params) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 1004, in get_split_datasets dataset = self.get_dataset(X, y) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\net.py", line 961, in get_dataset return dataset(X, y, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\skorch\dataset.py", line 104, in __init__ raise ValueError("X and y have inconsistent lengths.") ValueError: X and y have inconsistent lengths.
Passing a 2D-array is, as you said yourself, not going to work since you don't have a time dimension then, so the error message is correct in this case (LSTM expects 3 dimensions). The confiusing part is the error message when passing a 3D array. What is happening is that you are formatting your data as (sequence, batch, feature), i.e. "batch second". There is an alternative format called "batch first" where the data is formatted as (batch, sequence, feature) which is the default in sklearn (and consequently in skorch). If you re-format your data this way and configure your LSTM to use this format (pass batch_first=True) the error should go away: self.rnn = nn.LSTM( input_size, hidden_size, num_layers, batch_first=True, ) # ... inputArr3d = np.random.rand(batch, seq, features) Note that your module also needs to convert the return value of the RNN into something that the following layers can process (i.e. flatten the time dimension) or otherwise the linear layer will not know what to do with the extra time dimension.
https://stackoverflow.com/questions/50968788/
Optimizer got an empty parameter list in pytorch
I try to use convolutional network structures in a VAE experiment, the code is something like: Class CNN(nn.Module):... hparams1=[...] hparams2=[...] Model1=CNN(hyparams1) Model2=CNN(hyparams2) def VAE(x): encoder=Model1(x) z=reparameterize(encoder) #reparameterize is defined decoder=Model2(z) return decoder if args.cuda: Model1.cuda() Model2.cuda() parameters = chain(Model1.parameters(), Model2.parameters()) optimizer = optim.Adam(parameters, lr=1e-3) Error:Optimizer got an empty parameter list. The same problem occurs when I defind VAE as a class: class VAE(nn.Module): def encoder(x,model): return model(x) def reparameterize(): def decoder(z,model): return model(z) def forward(x,Model1,Model2) output=encoder(x,Model1) z=reparameterize(output) return decoder(z,Model2) model=VAE() optimizer = optim.Adam(model.parameters(), lr=1e-3) Error:Optimizer got an empty parameter list. I guess maybe the problem is that I fail to initialize the parameters in a class VAE, but I don't know how to deal with it. Thank you very much!
In the first case, you can use: parameters = list(Model1.parameters())+ list(Model2.parameters()) optimizer = optim.Adam(parameters, lr=1e-3) In the second case, you didn't create the object, so basically you can try this: model = VAE() optimizer = optim.Adam(model.parameters(), lr=1e-3) By the way, you can start from modifying the VAE example provided by Pytorch. EDIT Perhaps you miss the initial function or initialize the model in a wrong way. See the init function here. Hope it helps.
https://stackoverflow.com/questions/50981904/
Pytorch, Unable to get repr for
I'm implementing some RL in PyTorch and had to write my own mse_loss function (which I found on Stackoverflow ;) ). The loss function is: def mse_loss(input_, target_): return torch.sum( (input_ - target_) * (input_ - target_)) / input_.data.nelement() Now, in my training loop, the first input is something like: tensor([-1.7610e+10]), tensor([-6.5097e+10]) With this input I'll get the error: Unable to get repr for &lt;class 'torch.Tensor'&gt; Computing a = (input_ - target_) works fine, while b = a * a respectively b = torch.pow(a, 2) will fail with the error metioned above. Does anyone know a fix for this? Thanks a lot! Update: I just tried using torch.nn.functional.mse_loss which will result in the same error..
I had the same error,when I use the below code criterion = torch.nn.CrossEntropyLoss().cuda() output=output.cuda() target=target.cuda() loss=criterion(output, target) but I finally found my wrong:output is like tensor([[0.5746,0.4254]]) and target is like tensor([2]),the number 2 is out of indice of output when I not use GPU,this error message is: RuntimeError: Assertion `cur_target &gt;= 0 &amp;&amp; cur_target &lt; n_classes' failed. at /opt/conda/conda-bld/pytorch-nightly_1547458468907/work/aten/src/THNN/generic/ClassNLLCriterion.c:93
https://stackoverflow.com/questions/51009687/
Pytorch loss inf nan
I'm trying to do simple linear regression with 1 feature. It's a simple 'predict salary given years experience' problem. The NN trains on years experience (X) and a salary (Y). For some reason the loss is exploding and ultimately returns inf or nan This is the code I have: import torch import torch.nn as nn import pandas as pd import numpy as np dataset = pd.read_csv('./salaries.csv') x_temp = dataset.iloc[:, :-1].values y_temp = dataset.iloc[:, 1:].values X_train = torch.FloatTensor(x_temp) Y_train = torch.FloatTensor(y_temp) class Model(torch.nn.Module): def __init__(self): super().__init__() self.linear = torch.nn.Linear(1,1) def forward(self, x): y_pred = self.linear(x) return y_pred model = Model() loss_func = torch.nn.MSELoss(size_average=False) optim = torch.optim.SGD(model.parameters(), lr=0.01) #training for epoch in range(200): #calculate y_pred y_pred = model(X_train) #calculate loss loss = loss_func(y_pred, Y_train) print(epoch, &quot;{:.2f}&quot;.format(loss.data)) #backward pass + update weights optim.zero_grad() loss.backward() optim.step() test_exp = torch.FloatTensor([[8.0]]) print(&quot;8 years experience --&gt; &quot;, model(test_exp).data[0][0].item()) As I mentioned, once it starts training the loss gets super big and ends up showing inf after like the 10th epoch. I suspect it may have something to do with how i'm loading the data? This is what is in salaries.csv file: Years Salary 1.1 39343 1.3 46205 1.5 37731 2 43525 2.2 39891 2.9 56642 3 60150 3.2 54445 3.2 64445 3.7 57189 3.9 63218 4 55794 4 56957 4.1 57081 4.5 61111 4.9 67938 5.1 66029 5.3 83088 Thank you for your help
Once the loss becomes inf after a certain pass, your model gets corrupted after backpropagating. This probably happens because the values in "Salary" column are too big. try normalizing the salaries. Alternatively, you could try to initialize the parameters by hand (rather than letting it be initialized randomly), letting the bias term be the average of salaries, and the slope of the line be 0 (for instance). That way the initial model would be close enough to the optimal solution, so that the loss does not blow up.
https://stackoverflow.com/questions/51033066/
Pytorch inceptionV3 transfer learning gives error - max() received an invalid combination of arguments
The program for transfer learning inception_v3 in pytorch that i am using is here : https://drive.google.com/file/d/1zn4z7nOp_wJne0En6zq4WJfwHVVftERT/view?usp=sharing I am getting the following error upon running the program : Epoch 0/24 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-20-cc88ea5f8bd3&gt; in &lt;module&gt;() 1 model_ft = train_model(model_ft, criterion, optimizer_ft, exp_lr_scheduler, ----&gt; 2 num_epochs=25) &lt;ipython-input-17-812cf3c4576a&gt; in train_model(model, criterion, optimizer, scheduler, num_epochs) 33 outputs = model(inputs) 34 print(outputs) ---&gt; 35 _, preds = torch.max(outputs, 1) 36 loss = criterion(outputs, labels) 37 TypeError: max() received an invalid combination of arguments - got (tuple, int), but expected one of: * (Tensor input) * (Tensor input, Tensor other, Tensor out) * (Tensor input, int dim, bool keepdim, tuple of Tensors out) How can this be fixed ? Thank you
in this case, I have changed the code as below and its worked for me, Tutorial https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html model_ft = models.inception_v3(pretrained=True) model_ft.aux_logits=False
https://stackoverflow.com/questions/51045839/
Different behavior with torch.mean(data, 0) and torch.mean(data) for vector
I was surprised to find different behavior with torch.mean(data, 0) and torch.mean(data), where "data" — is 1D-tensor (vector, not a matrix or something else): from torchvision import datasets import torch path = './MNIST_data' data = datasets.MNIST(path, train=True, download=True).train_data.view(-1).float() print(torch.mean(data)) print(torch.mean(data, 0)) Results after execution: tensor(33.3184) tensor(33.4961) Could anyone suppose what is going on? I assumed that the results should be the same.
An Example should help you clear your doubt. Lets say we have data = torch.Tensor([[1,2,3,4],[1,2,3,4]]) Now When you perform torch.mean(data),It will sum all the elements in the data tensor and divide that by the number of elements in that tensor,Giving you a result of 2.5 As for your operation of torch.mean(data, 0) This will perform mean along the horizontal direction,which means it will take the first element of row one which is 1 and take the first element of row 2 which is 2,sum them up and divide by 2.It helps to visualize the data array this way [1, 2, 3, 4] [1, 2, 3, 4] The final result will be tensor of [1, 2, 3, 4] if you know how we ended up getting this tensor, You've understood the difference. Hope that clears it, Let me know if you have questions
https://stackoverflow.com/questions/51078039/
RuntimeError: Expected object of type torch.FloatTensor but found type torch.cuda.DoubleTensor for argument #2 'weight'
I have been trying to retrain a model but unfortunately the last 2 days I keep getting the same error. Could you please help a little bit with this one? Initial work: %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import numpy as np import time import torch from torch import nn from torch import optim import torch.nn.functional as F from torch.autograd import Variable from torchvision import datasets, transforms import torchvision.models as models from collections import OrderedDict Datasets: data_dir = 'flowers' train_dir = data_dir + '/train' data_dir = 'flowers' train_transforms = transforms.Compose([transforms.Resize(224), transforms.RandomResizedCrop(224), transforms.RandomRotation(45), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) train_data = datasets.ImageFolder(train_dir, transform=train_transforms) trainloader = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=True) import json with open('cat_to_name.json', 'r') as f: cat_to_name = json.load(f) Tried to use a pretrained model and train only the classifier: # Load a pretrained model model = models.vgg16(pretrained=True) # Keep the parameters the same for param in model.parameters(): param.requires_grad = False # and final output 102, since tht we have 102 flowers. classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(25088, 4096)), ('relu', nn.ReLU()), ('fc3', nn.Linear(4096, 102)), ('output', nn.LogSoftmax(dim=1)) ])) # Replace model's old classifier with the new classifier model.classifier = classifier # Calculate the loss criterion = nn.NLLLoss() optimizer = optim.Adam(model.classifier.parameters(), lr=0.001) model.to('cuda') epochs = 1 print_every = 40 steps = 0 for e in range(epochs): running_loss = 0 model.train() # model = model.double() for images, labels in iter(trainloader): steps += 1 images.resize_(32, 3, 224, 224) inputs = Variable(images.to('cuda')) targets = Variable(labels.to('cuda')) optimizer.zero_grad() # Forward and backward passes output = model.forward(images) loss = criterion(output, labels) loss.backward() optimizer.step() #running_loss += loss.data[0] running_loss += loss.item() if steps % print_every == 0: print("Epoch: {}/{}... ".format(e+1, epochs), "Loss: {:.4f}".format(running_loss/print_every)) Error message: RuntimeError: Expected object of type torch.FloatTensor but found type torch.cuda.DoubleTensor for argument #2 weight
you should have passed inputs to the feed forward network but you have passed images to the network # Forward and backward passes output = model.forward(inputs)
https://stackoverflow.com/questions/51081004/
pytorch: zero_grad vs zero_grad() - role of parenthesis?
I'm trying to train a pytorch model as follows: start = time.time() for epoch in range(100): t_loss = 0 for i in range(100): optimizer.zero_grad scores = my_model(sent_dict_list[i]) scores = scores.permute(0, 2, 1) loss = loss_function(scores, torch.tensor(targ_list[i]).cuda()) t_loss += loss.item() loss.backward() optimizer.step() print("t_loss = ", t_loss) I find that when I call "optimizer.zero_grad" my loss decreases at the end of every epoch whereas when I call "optimizer.zero_grad()" with the parenthesis it stays almost exactly the same. I don't know what difference this makes and was hoping someone could explain it to me.
I assume you're new to python, the '()' means simple a function call. Consider this example: &gt;&gt;&gt; def foo(): print("function") &gt;&gt;&gt; foo &lt;function __main__.foo&gt; &gt;&gt;&gt; foo() function Remember functions are objects in python, you can even store them like this: &gt;&gt;&gt; [foo, foo, foo] Returning to your question, you have to call the function otherwise it won't work.
https://stackoverflow.com/questions/51082508/
How to compute Pairwise L1 Distance matrix on very large images in neighborhood only?
I am working on Deep learning approach for my project. And I need to calculate Distance Matrix on 4D Tensor which will be of size N x 128 x 64 x 64 (Batch Size x Channels x Height x Width). The distance matrix for this type of tensor will of size N x 128 x 4096 x 4096 and it will be impossible to fit this type of tensor in GPU, even on CPU it will require lot of memory. So, I would like to calculate the distance matrix only in some neighborhood pixels (say within radius of 5) and consider this rectangular matrix for further processing in neural network. With this approach my distance matrix will be of size N x 128 x 4096 x 61. It will take less memory in comparison to full distance matrix. Precisely, I am trying to implement the Convolution Random Walk Networks for Semantic Segmentation. This network needs to calculate the Pairwise L1 Distance for features. Architecture Just to add this type of Distance Matrix is usually calculated for image segmentation via spectral clustering. For Example X = [[a,b],[c,d]] L1_dist = [ [0, |a-b|, |a-c|, 0], [|a-b|, 0, 0, |b-d|], [|a-c|, 0, 0, |c-d| ], [0, |b-d|, |c-d|, 0 ] ] Final_L1_dist = [ [0, |a-b|, |a-c|], // "a" is near to b and c. Including self element i.e. a [|a-b|, 0, |b-d|], // "b" is near to a and d. [|a-c|, 0, |c-d| ], // "c" is near to a and d. [|b-d|, |c-d|, 0 ] // "d" is near to b and c. ] I would appreciate, if some one can help me to find an efficient way to compute such a matrix. Thanks
As far as I understand, the goal is to apply minus operation to each pixel and its surrounding neighbors. This sounds like convolution to me. Consider the following convolution process (assume padding='SAME'): The 3x3 kernel calculates, for each pixel, the difference between the center pixel and its left one. For other neighbors, consider the following kernels: Thus the goal can be achieved via the following: Repeat each kernel for num_channels times using tf.tile; Apply each kernel channel-wisely using tf.nn.depthwise_conv2d; Do tf.abs to get the distance; Reshape each distance tensor to NxCx(HW)x1 and stack them properly. For efficient for loop, you may consider using tf.map_fn.
https://stackoverflow.com/questions/51091496/
How to train Actor-Critic (A2C) reinforcement learning
I am currently been able to train a system using Q-Learning. I will to move it to Actor_Critic (A2C) method. Please don't ask me why for this move, I have to. I am currently borrowing the implementation from https://github.com/higgsfield/RL-Adventure-2/blob/master/1.actor-critic.ipynb The thing is, I am keep getting a success rate of approx ~ 50% (which is basically random behavior). My game is a long episode (50 steps). Should I print out the reward, the value, or what? How should I debug this? Here are some log: simulation episode 2: Success, turn_count =20 loss = tensor(1763.7875) simulation episode 3: Fail, turn_count= 42 loss = tensor(44.6923) simulation episode 4: Fail, turn_count= 42 loss = tensor(173.5872) simulation episode 5: Fail, turn_count= 42 loss = tensor(4034.0889) simulation episode 6: Fail, turn_count= 42 loss = tensor(132.7567) loss = simulation episode 7: Success, turn_count =22 loss = tensor(2099.5344) As a general trend, I have observed that for Success episodes, the loss tends to be huge, where as for Fail episode, the loss function output tends to be small.
I think you're making a mistake, if you really want to know how to implement Actor Critic algorithm you need first to master 2 things : - Implementing value based RL algorithms (such as DQN). - Implementing policy based RL algorithms (such as Policy Gradients). You can't directly jump on actor critic models, in fact you can but you will understand nothing if you're not able to understand actor (policy based) and critic (value based) separately. It's like if you wanted to paint the Joconde before beginning by learning how to paint. My advice, take the time to learn these 2 elements before implementing an AC agent. I made a free course with tensorflow and completes implementations here https://simoninithomas.github.io/Deep_reinforcement_learning_Course/ But again, implement architectures by yourself, copy an architecture is useless if you don't really understand it.
https://stackoverflow.com/questions/51095025/
Add / substract between matrix and vector in pytorch
I want to do + / - / * between matrix and vector in pytorch. How can I do with good performance? I tried to use expand, but it's really slow (I am using big matrix with small vector). a = torch.rand(2,3) print(a) 0.7420 0.2990 0.3896 0.0715 0.6719 0.0602 [torch.FloatTensor of size 2x3] b = torch.rand(2) print(b) 0.3773 0.6757 [torch.FloatTensor of size 2] a.add(b) Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3066, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-17-a1cb1b03d031&gt;", line 1, in &lt;module&gt; a.add(b) RuntimeError: inconsistent tensor size, expected r_ [2 x 3], t [2 x 3] and src [2] to have the same number of elements, but got 6, 6 and 2 elements respectively at c:\miniconda2\conda-bld\pytorch-cpu_1519449358620\work\torch\lib\th\generic/THTensorMath.c:1021 Expected result: 0.7420-0.3773 0.2990-0.3773 0.3896-0.3773 0.0715-0.6757 0.6719-0.6757 0.0602-0.6757
To make use of broadcasting, you need to promote the dimension of the tensor b to two dimensions since the tensor a is 2D. In [43]: a Out[43]: tensor([[ 0.9455, 0.2088, 0.1070], [ 0.0823, 0.6509, 0.1171]]) In [44]: b Out[44]: tensor([ 0.4321, 0.8250]) # subtraction In [46]: a - b[:, None] Out[46]: tensor([[ 0.5134, -0.2234, -0.3252], [-0.7427, -0.1741, -0.7079]]) # alternative way to do subtraction In [47]: a.sub(b[:, None]) Out[47]: tensor([[ 0.5134, -0.2234, -0.3252], [-0.7427, -0.1741, -0.7079]]) # yet another approach In [48]: torch.sub(a, b[:, None]) Out[48]: tensor([[ 0.5134, -0.2234, -0.3252], [-0.7427, -0.1741, -0.7079]]) The other operations (+, *) can be done analogously. In terms of performance, there seems to be no advantage of using one approach over the others. Just use any one of the three approaches. In [49]: a = torch.rand(2000, 3000) In [50]: b = torch.rand(2000) In [51]: %timeit torch.sub(a, b[:, None]) 2.4 ms ± 8.31 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [52]: %timeit a.sub(b[:, None]) 2.4 ms ± 6.94 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [53]: %timeit a - b[:, None] 2.4 ms ± 12 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
https://stackoverflow.com/questions/51097719/