id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st81668 | Yeah. This is a relu example, but you can extend this to your own problem. The returned value in backward are the derivatives of the input of the forward, which is the output of the second to the last layer in your case. Your loss is implemented in the forward, or constructed by using the output of the forward. You just need to write your last layer’s derivative manually in the backward. |
st81669 | thanks for clarifying. I am still not completely there.
so let’s say I have the following:
‘’’
class SDTWLoss(torch.autograd.Function):
@staticmethod
def forward( ctx, y_pred, y):
_dtw = SoftDTW(y_pred, y ,device)
dtw_value, dtw_grad, dtw_E_mat= _dtw.compute() # calculate loss value for y_prediction and y_actual
G = jacobian_product_with_expected_sdtw_grad(y_pred, y, dtw_grad,device) # calculate derivative of loss w.r.t. y_pred (last layer of my graph)
ctx.save_for_backward(G) #save derviative of Loss w.r.t y for backward
dtw_loss = torch.mean(dtw_value)
return dtw_loss
@staticmethod
def backward( ctx, grad_output ):
G = ctx.saved_tensors
grad_input = grad_output.clone() # is this the derivative of the layer before the last layer w.r.t model's parameters???
# if so, I should multiply G by grad_input here, right?
grad_input = G*grad_input
return grad_input
‘’’
Does this code make sense? |
st81670 | unfortunately it’s not working yet!
if grad_output is the gradient w.r.t y_predicted, I am calculating it manually (matrix G). what should I multiply it to , to get the gradient w.r.t. model’s params? |
st81671 | You need to do return grad_input, None in your backward as you do not need grads for true y. |
st81672 | Hello.
I was wondering if there were any helpful implementations of a 3d convolution which maintains size for irregular dimensions (ie not square). |
st81673 | Hi,
You mean irregular dimensions of the kernel? If so, yes you can set a per-dimension padding that will match the kernel size in that dimension. |
st81674 | Hi,
I am working on learning an image filter, but while the training process, after some iterations, the loss and all learned parameters became nan values.
Here is the main part of my code:
class net(nn.Module):
def __init__(self):
super(net, self).__init__()
self.encoder = models.resnet18(pretrained=True)
self.fc1 = nn.Linear(1000, 256)
self.fc2 = nn.Linear(256, 128)
self.tanh_params = nn.Linear(128, 1)
self.relu = nn.ReLU()
def forward(self, input):
input = self.encoder(input)
input = self.relu(self.fc2(self.relu(self.fc1(input))))
tanh_params = torch.exp(self.tanh_params(input))
image = torch.tanh(tanh_params * (input - torch.mean(input))
image = image * input
return image
The code seems well but the result is unsatisified, are there something wrong or missed in this code block, or maybe this error is caused by my datasets?
Thank you to whom reading this problem and want to give me a hand. |
st81675 | Hi,
No tanh cannot return nans as it’s gradient is well defined everywhere.
If this happens after some iterations, you should make sure your loss is well behaved and is not just diverging to very very large values until it gets nan. |
st81676 | Hi,
Thank for your reply, and is there possible that if tanh_params is large and the (input - torch.mean(input) block is very close to zero, then it will return a very large gradient and finally cause gradient explosion to make the situation I came across?
Is this comment stated a good way to check and debug my problem, [How to check for vanishing/exploding gradients 26] |
st81677 | Hi,
If I’m not mistaken, the gradient for tanh is never large right? It goes from 0 to 1?
I would recommend to print some values first to make sure that they become nan become they are too big. |
st81678 | Hi, anyone who cares.
I was aware of the functionality of torch.cuda.empty_cache() that calling this function can release the GPU memory which is no longer bound to a python variable but still in the memory pool. However, when I place the model in any GPU other than GPU 0 and call torch.cuda.empty_cache(), besides releasing memory on the specified GPU, about 700MB memory of GPU 0 will be occupied. It confused me so much and I can’t figure out why. Does anyone know about the internal machenism of this function and can explain why the strage memory comes out?
FYI, the approach of placing model to a certain GPU was specifying device index in pytorch code, rather than setting environment variable ‘CUDA_VISIBLE_DEVICES’ outside. |
st81679 | Hi,
If this is a one time thing, then this is most likely because it initializes the cuda context on GPU 0.
We discourage the use of this function unless you do have a very good reason to release that memory. Could you explain your usecase for needing to clear the cache and not use CUDA_VISIBLE_DEVICES ? |
st81680 | Hi,
Thanks for your quick reply and explaination! I agree with you that the extra memory occupation is due to the cuda context being initialized on GPU 0. However, I was wondering if there was a solution that allowed me to specify which GPU to initialize the cuda context.
The usecase of torch.cuda.empty_cache() is that I need to call a subprocess to achieve an exhaustive test after 10 epoch training. Releasing GPU cached memory allows this subprocess to utilize them and avoid OOM.
Using environment variables is very convenient. As for CUDA_VISIBLE_DEVICES, I’m sure that CUDA_VISIBLE_DEVICES can save me from such a circumstance for now. However, it will modify the environment variable, and I may need other processes to perform some deeplearning tasks on other GPUs with potentially different framework, like TensorFlow. As a result, I’d like to find a way than can constrain the GPU utility locally, trying not to mess up with the environment variables. |
st81681 | Hi,
This sounds like a completely valid use case for empty_cache() !
For the env variable, you can set it temporarily for a single command by doing:
CUDA_VISIBLE_DEVICES=2 python your_command.py
This way, only this python command will have the env variable defined. |
st81682 | I am trying to introduce new singleton dimension to a Normal distribution. I know I can access loc, scale and change them to get the desired distribution. I could use expand() to introduce new dimension as first dimensions. But what do I do if I want to introduce new dimension else where?
example:
Given Normal of size [10,10,10], I want a distribution with shape [10,10,1,10] |
st81683 | The simplest way to do this is at the creation of the distribution, call .unsqueeze(2) on the loc and the scale argument tensors.
If you don’t want to do this, you can always create another distribution from the first one:
dist2 = torch.distributions.Normal(loc=dist1.loc.unsqueeze(2), scale=dist1.scale.unsqueeze(2))
I guess you are looking for a .unsqueeze() method for distributions, that would work like .expand(), but it does not exist. You could submit a PR or an issue on github but I don’t know if such a method would be very useful. |
st81684 | I designed a model for object detection and trained on one gpu, the loss is decreasing and got a good result.
But, when I was trying to train the same network on multi-gpus, the loss is not decreasing. And more strange thing is that, the loss curve is exactly the same not matter the lr is 0.05 or 0.0005.
The dataset and training pipeline are used for other models and working good on multi-gpus.
Anybody got an idea, what the potential reason could be?
If you need more details, just write on the comment. |
st81685 | Hi @Shangyin_Gao,
What’s the single-GPU LR? Did you also try to scale it such as LR = LR * num_gpus? |
st81686 | Hi,
I have a simple network that I’m trying to learn to segment a 3d volume. And my network is returning some strange behaviour. I mean after some iterations the error drops to a very low value but the loss stays around maximum:
Iteration: 93 - idx: 92 of 297 - Training Loss: 0.9229209423065186 - Training Error: 0.96309
Iteration: 94 - idx: 93 of 297 - Training Loss: 1.0 - Training Error: 1.0
Iteration: 95 - idx: 94 of 297 - Training Loss: 1.0 - Training Error: 1.0
Iteration: 96 - idx: 95 of 297 - Training Loss: 0.9052178859710693 - Training Error: 0.95456
Iteration: 97 - idx: 96 of 297 - Training Loss: 0.9063018560409546 - Training Error: 0.95752
Iteration: 98 - idx: 97 of 297 - Training Loss: 0.9971625804901123 - Training Error: 0.9988
Iteration: 99 - idx: 98 of 297 - Training Loss: 0.9963698983192444 - Training Error: 0.99843
Iteration: 100 - idx: 99 of 297 - Training Loss: 1.0 - Training Error: 1.0
Iteration: 101 - idx: 100 of 297 - Training Loss: 0.9743770360946655 - Training Error: 0.98899
Iteration: 102 - idx: 101 of 297 - Training Loss: 0.9997477531433105 - Training Error: 0.99989
Iteration: 103 - idx: 102 of 297 - Training Loss: 0.8088855743408203 - Training Error: 0.90434
Iteration: 104 - idx: 103 of 297 - Training Loss: 0.8306054472923279 - Training Error: 0.91758
Iteration: 105 - idx: 104 of 297 - Training Loss: 0.8507647514343262 - Training Error: 0.92999
Iteration: 106 - idx: 105 of 297 - Training Loss: 0.8689086437225342 - Training Error: 0.93817
Iteration: 107 - idx: 106 of 297 - Training Loss: 0.8423064351081848 - Training Error: 0.92586
Iteration: 108 - idx: 107 of 297 - Training Loss: 0.9808754920959473 - Training Error: 0.99174
Iteration: 109 - idx: 108 of 297 - Training Loss: 0.9371287822723389 - Training Error: 0.97213
Iteration: 110 - idx: 109 of 297 - Training Loss: 0.9500914812088013 - Training Error: 0.9782
Iteration: 111 - idx: 110 of 297 - Training Loss: 0.866399884223938 - Training Error: 0.93801
Iteration: 112 - idx: 111 of 297 - Training Loss: 0.9967585802078247 - Training Error: 0.99864
Iteration: 113 - idx: 112 of 297 - Training Loss: 0.9402463436126709 - Training Error: 0.97344
Iteration: 114 - idx: 113 of 297 - Training Loss: 0.9903985261917114 - Training Error: 0.99581
Iteration: 115 - idx: 114 of 297 - Training Loss: 0.9773250222206116 - Training Error: 0.98987
Iteration: 116 - idx: 115 of 297 - Training Loss: 0.9529093503952026 - Training Error: 0.97944
Iteration: 117 - idx: 116 of 297 - Training Loss: 0.8779460787773132 - Training Error: 0.94363
Iteration: 118 - idx: 117 of 297 - Training Loss: 0.968449056148529 - Training Error: 0.98645
Iteration: 119 - idx: 118 of 297 - Training Loss: 1.0 - Training Error: 1.0
Iteration: 120 - idx: 119 of 297 - Training Loss: 0.8482145071029663 - Training Error: 0.92954
Iteration: 121 - idx: 120 of 297 - Training Loss: 0.9723891019821167 - Training Error: 0.24093
Iteration: 122 - idx: 121 of 297 - Training Loss: 1.0 - Training Error: 0.31912
Iteration: 123 - idx: 122 of 297 - Training Loss: 1.0 - Training Error: 0.29264
Iteration: 124 - idx: 123 of 297 - Training Loss: 0.8992700576782227 - Training Error: 0.20317
Iteration: 125 - idx: 124 of 297 - Training Loss: 0.8656968474388123 - Training Error: 0.19998
Iteration: 126 - idx: 125 of 297 - Training Loss: 1.0 - Training Error: 0.27035
Iteration: 127 - idx: 126 of 297 - Training Loss: 0.9026780128479004 - Training Error: 0.20375
Iteration: 128 - idx: 127 of 297 - Training Loss: 0.9268592596054077 - Training Error: 0.23639
Iteration: 129 - idx: 128 of 297 - Training Loss: 0.8402963876724243 - Training Error: 0.15921
Iteration: 130 - idx: 129 of 297 - Training Loss: 1.0 - Training Error: 0.23356
Iteration: 131 - idx: 130 of 297 - Training Loss: 1.0 - Training Error: 0.29319
Iteration: 132 - idx: 131 of 297 - Training Loss: 0.9110627770423889 - Training Error: 0.21088
Iteration: 133 - idx: 132 of 297 - Training Loss: 0.9204986095428467 - Training Error: 0.2349
Iteration: 134 - idx: 133 of 297 - Training Loss: 0.8369404077529907 - Training Error: 0.20368
Iteration: 135 - idx: 134 of 297 - Training Loss: 0.8765052556991577 - Training Error: 0.20096
Iteration: 136 - idx: 135 of 297 - Training Loss: 0.9297358989715576 - Training Error: 0.24956
Iteration: 137 - idx: 136 of 297 - Training Loss: 1.0 - Training Error: 0.25418
Iteration: 138 - idx: 137 of 297 - Training Loss: 0.8197125792503357 - Training Error: 0.14655
Iteration: 139 - idx: 138 of 297 - Training Loss: 0.8560500144958496 - Training Error: 0.1742
Iteration: 140 - idx: 139 of 297 - Training Loss: 0.911932110786438 - Training Error: 0.19162
Iteration: 141 - idx: 140 of 297 - Training Loss: 0.8006452918052673 - Training Error: 0.15542
Iteration: 142 - idx: 141 of 297 - Training Loss: 1.0 - Training Error: 0.31364
Iteration: 143 - idx: 142 of 297 - Training Loss: 1.0 - Training Error: 0.29259
Iteration: 144 - idx: 143 of 297 - Training Loss: 1.0 - Training Error: 0.29525
Iteration: 145 - idx: 144 of 297 - Training Loss: 0.8789593577384949 - Training Error: 0.22947
Iteration: 146 - idx: 145 of 297 - Training Loss: 0.8523666858673096 - Training Error: 0.22481
Iteration: 147 - idx: 146 of 297 - Training Loss: 0.8480030298233032 - Training Error: 0.19208
Iteration: 148 - idx: 147 of 297 - Training Loss: 0.966659426689148 - Training Error: 0.30955
Iteration: 149 - idx: 148 of 297 - Training Loss: 0.9490553736686707 - Training Error: 0.32177
Iteration: 150 - idx: 149 of 297 - Training Loss: 0.991357147693634 - Training Error: 0.25028
Iteration: 151 - idx: 150 of 297 - Training Loss: 0.9695178270339966 - Training Error: 0.32728
Iteration: 152 - idx: 151 of 297 - Training Loss: 0.991864800453186 - Training Error: 0.32936
Iteration: 153 - idx: 152 of 297 - Training Loss: 0.93214350938797 - Training Error: 0.26553
Iteration: 154 - idx: 153 of 297 - Training Loss: 1.0 - Training Error: 0.35379
Iteration: 155 - idx: 154 of 297 - Training Loss: 0.9247879981994629 - Training Error: 0.2841
Iteration: 156 - idx: 155 of 297 - Training Loss: 1.0 - Training Error: 0.26329
Iteration: 157 - idx: 156 of 297 - Training Loss: 0.9641293287277222 - Training Error: 0.3922
Iteration: 158 - idx: 157 of 297 - Training Loss: 0.8773941993713379 - Training Error: 0.29334
Iteration: 159 - idx: 158 of 297 - Training Loss: 0.8569602966308594 - Training Error: 0.23416
Iteration: 160 - idx: 159 of 297 - Training Loss: 0.8664135932922363 - Training Error: 0.2346
Iteration: 161 - idx: 160 of 297 - Training Loss: 0.9659935235977173 - Training Error: 0.30228
Iteration: 162 - idx: 161 of 297 - Training Loss: 0.9180066585540771 - Training Error: 0.22153
Iteration: 163 - idx: 162 of 297 - Training Loss: 1.0 - Training Error: 0.28928
Iteration: 164 - idx: 163 of 297 - Training Loss: 0.8440924882888794 - Training Error: 0.18165
Iteration: 165 - idx: 164 of 297 - Training Loss: 0.9442515969276428 - Training Error: 0.21878
Iteration: 166 - idx: 165 of 297 - Training Loss: 1.0 - Training Error: 0.24745
Iteration: 167 - idx: 166 of 297 - Training Loss: 0.9008297324180603 - Training Error: 0.22211
Iteration: 168 - idx: 167 of 297 - Training Loss: 1.0 - Training Error: 0.26047
Iteration: 169 - idx: 168 of 297 - Training Loss: 1.0 - Training Error: 0.24333
I have a binary segmentation case and am using DiceLoss().
I manually checked the result, and when the error was high the output was noting, a black image volume. but as the error decreased the network is trying to predict the shape, I mean I am getting some output (not correct but its localized around the actual ground truth label) but why is the loss so high…
Does this mean the network is not learning? If so, what can I do to fix it?
Thank you |
st81687 | While searching for a solution I cam upon this thread: https://github.com/pytorch/pytorch/issues/3358 2, suggesting to add the below code under loss.backwards():
loss.backward()
for param in net.parameters():
print(param.grad.data.sum())
unless I understood it wrong, this is to check if the computed gradients are returning any non-zero values. If they are non-zero then the learning rate is too small.
But the time when I get non-zero gradients is when the network is showing that its learning, but at zeros values I get a loss of 1.0.
tensor(-0.0001, device='cuda:0')
tensor(3.8132e-09, device='cuda:0')
tensor(1.5014e-06, device='cuda:0')
tensor(-0.0006, device='cuda:0')
tensor(1.4931e-09, device='cuda:0')
tensor(2.0285e-06, device='cuda:0')
tensor(-0.0003, device='cuda:0')
tensor(3.4502e-10, device='cuda:0')
tensor(1.4271e-06, device='cuda:0')
tensor(-0.0005, device='cuda:0')
tensor(-0.0000, device='cuda:0')
tensor(1.6241e-06, device='cuda:0')
tensor(-0.0003, device='cuda:0')
tensor(-0.0000, device='cuda:0')
tensor(1.2744e-06, device='cuda:0')
tensor(-0.0003, device='cuda:0')
tensor(-0.0000, device='cuda:0')
tensor(1.5523e-06, device='cuda:0')
tensor(-0.0006, device='cuda:0')
tensor(-0.0000, device='cuda:0')
tensor(2.0451e-06, device='cuda:0')
tensor(-0.0009, device='cuda:0')
tensor(-0.0000, device='cuda:0')
tensor(2.3836e-06, device='cuda:0')
tensor(-0.0011, device='cuda:0')
tensor(-0.0000, device='cuda:0')
tensor(2.6307e-06, device='cuda:0')
tensor(-0.0038, device='cuda:0')
tensor(6.4067e-10, device='cuda:0')
tensor(6.6819e-06, device='cuda:0')
tensor(-0.0074, device='cuda:0')
tensor(-0.0000, device='cuda:0')
tensor(2.7682e-06, device='cuda:0')
tensor(0.0008, device='cuda:0')
tensor(-0.0001, device='cuda:0')
tensor(-0.0000, device='cuda:0')
tensor(-0.0044, device='cuda:0')
tensor(-0.0001, device='cuda:0')
tensor(-0.0052, device='cuda:0')
tensor(-0.0007, device='cuda:0')
tensor(-0.0053, device='cuda:0')
tensor(-0.0004, device='cuda:0')
tensor(-0.0008, device='cuda:0')
tensor(-0.0021, device='cuda:0')
Iteration: 7 - idx: 6 of 297 - Training Loss: 0.83579021692276 - Training Error: 0.90537
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
tensor(0., device='cuda:0')
Iteration: 8 - idx: 7 of 297 - Training Loss: 1.0 - Training Error: 1.0
Sorry for the very beginner question but the github thread suggests that zero gradient values are preferred, but the time I get high loss is when my gradients are zero.
I also tried lowering my learning rate from 1e-2 to 1e-3 but that did not improve or fix anything.
What am I doing wrong?
Thank you |
st81688 | If someone comes by this via Google search, I wanted to update why I was getting this loss behaviour. The reason was that I was applying nn.Sigmoid() at the model output and in the DiceLoss() as well. Removing the sigmoid operation from the model output fixed the weird loss behaviour.
ptrblk explained this more here: Why my loss function's value doesn't going down? 12 which helped me fix this. |
st81689 | Hi,
similar topic to this question 19: do optimizers work transparently in multiprocess runs or do I need to average the gradients of each process manually?
The imagenet example 6 in the pytorch/examples repo does not do explicit gradient averaging between processes, but the example on distributed 21 training in pytorch’s tutorials does.
Thanks a lot!
Enrico |
st81690 | Solved by pietern in post #4
If you use vanilla multiprocessing you’ll have to do this yourself. If you use it in combination with torch.nn.parallel.DistributedDataParallel then gradient synchronization and averaging is done for you. Also see the documentation on torch.distributed for more information. |
st81691 | I have a similar question here 13. I simultaneously opened a query in pytorch/fairseq#779 10 to which the response was that there is built in averaging.
How about trying some black box experiments to figure out? |
st81692 | If you use vanilla multiprocessing you’ll have to do this yourself. If you use it in combination with torch.nn.parallel.DistributedDataParallel 14 then gradient synchronization and averaging is done for you. Also see the documentation on torch.distributed 15 for more information. |
st81693 | @pietern can you show me in the source where the average is done? for the life of me i’ve been all over the codebase and i can’t find it.
i’m looking here
github.com
pytorch/pytorch/blob/master/torch/autograd/__init__.py#L44 3
raise RuntimeError("grad can be implicitly created only for scalar outputs")
new_grads.append(torch.ones_like(out))
else:
new_grads.append(None)
else:
raise TypeError("gradients can be either Tensors or None, but got " +
type(grad).__name__)
return tuple(new_grads)
def backward(tensors, grad_tensors=None, retain_graph=None, create_graph=False, grad_variables=None):
r"""Computes the sum of gradients of given tensors w.r.t. graph leaves.
The graph is differentiated using the chain rule. If any of ``tensors``
are non-scalar (i.e. their data has more than one element) and require
gradient, then the Jacobian-vector product would be computed, in this
case the function additionally requires specifying ``grad_tensors``.
It should be a sequence of matching length, that contains the "vector"
in the Jacobian-vector product, usually the gradient of the differentiated
function w.r.t. corresponding tensors (``None`` is an acceptable value for
all tensors that don't need gradient tensors).
and
github.com
pytorch/pytorch/blob/master/torch/csrc/autograd/python_engine.cpp#L90
// backwards threads hold a lock, we'll probably deadlock in the engine
// destructor.
if (_reinitialize_engine) {
engine.~PythonEngine();
new (&engine) torch::autograd::python::PythonEngine();
_reinitialize_engine = false;
}
}
// Implementation of torch._C._EngineBase.run_backward
PyObject *THPEngine_run_backward(THPEngine *self, PyObject *args, PyObject *kwargs)
{
HANDLE_TH_ERRORS
_maybe_reinitialize_engine_after_fork();
PyObject *tensors = nullptr;
PyObject *grad_tensors = nullptr;
unsigned char keep_graph = 0;
unsigned char create_graph = 0;
PyObject *inputs = nullptr;
unsigned char allow_unreachable = 0;
const char *accepted_kwargs[] = { |
st81694 | @makslevental It’s done not in the autograd code but in the DDP reducer code:
github.com
pytorch/pytorch/blob/8a026d4f74b71944ac2860c315996165a40f5626/torch/csrc/distributed/c10d/reducer.cpp#L321-L322 10
// Prescale bucket contents to turn the global sum into the global average.
replica.contents.div_(process_group_->getSize()); |
st81695 | When I was training my model on single GPU(cuda:0), it just worked with batch_size==4. However, I keep the batch_size == 4 and train my model on 4 GPUs, it raise warning : RuntimeWarning: RNN module weights are not part of single contiguous chunk of memory. This means they need to be compacted at every call, possibly greatly increasing memory usage. To compact weights again call flatten_parameters().
and error:RuntimeError: CUDA out of memory. Tried to allocate 98.38 MiB (GPU 1; 15.89 GiB total capacity; 14.56 GiB already allocated; 33.25 MiB free; 150.76 MiB cached
Hope somebody helps me. It’s confusing。 |
st81696 | Traceback:
File "/home/user/miniconda/envs/py36/lib/python3.6/site-packages/torch/nn/modules/module.py", line 489, in __call__
result = self.forward(*input, **kwargs)
File "/home/user/miniconda/envs/py36/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py", line 142, in forward
replicas = self.replicate(self.module, self.device_ids[:len(inputs)])
File "/home/user/miniconda/envs/py36/lib/python3.6/site-packages/torch/nn/parallel/data_parallel.py", line 147, in replicate
return replicate(module, device_ids)
File "/home/user/miniconda/envs/py36/lib/python3.6/site-packages/torch/nn/parallel/replicate.py", line 13, in replicate
param_copies = Broadcast.apply(devices, *params)
File "/home/user/miniconda/envs/py36/lib/python3.6/site-packages/torch/nn/parallel/_functions.py", line 21, in forward
outputs = comm.broadcast_coalesced(inputs, ctx.target_gpus)
File "/home/user/miniconda/envs/py36/lib/python3.6/site-packages/torch/cuda/comm.py", line 40, in broadcast_coalesced
return torch._C._broadcast_coalesced(tensors, devices, buffer_size)
RuntimeError: CUDA out of memory. Tried to allocate 11.38 MiB (GPU 3; 15.89 GiB total capacity; 13.87 GiB already allocated; 7.25 MiB free; 408.58 MiB cached) (malloc at /opt/conda/conda-bld/pytorch_1544174967633/work/aten/src/THC/THCCachingAllocator.cpp:231)
frame #0: c10::Error::Error(c10::SourceLocation, std::string const&) + 0x45 (0x7f59fa323cc5 in /home/user/miniconda/envs/py36/lib/python3.6/site-packages/torch/lib/libc10.so) |
st81697 | I’m wondering if I need to do anything special when training with BatchNorm in pytorch. From my understanding the gamma and beta parameters are updated with gradients as would normally be done by an optimizer. However, the mean and variance of the batches are updated slowly using momentum.
So do we need to specify to the optimizer when the mean and variance parameters are updated, or does pytorch automatically take care of this?
Is there a way to access the mean and variance of the BN layer so that I can make sure it was changing while I trained the model.
If needed here is my model and training procedure:
def bn_drop_lin(n_in:int, n_out:int, bn:bool=True, p:float=0.):
"Sequence of batchnorm (if `bn`), dropout (with `p`) and linear (`n_in`,`n_out`) layers followed by `actn`."
layers = [nn.BatchNorm1d(n_in)] if bn else []
if p != 0: layers.append(nn.Dropout(p))
layers.append(nn.Linear(n_in, n_out))
return nn.Sequential(*layers)
class Model(nn.Module):
def __init__(self, i, o, h=()):
super().__init__()
nodes = (i,) + h + (o,)
self.layers = nn.ModuleList([bn_drop_lin(i,o, p=0.5)
for i, o in zip(nodes[:-1], nodes[1:])])
def forward(self, x):
x = x.view(x.shape[0], -1)
for layer in self.layers[:-1]:
x = F.relu(layer(x))
return self.layers[-1](x)
Training:
for i, data in enumerate(trainloader):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
This is a x-post from https://stackoverflow.com/questions/57865112/training-with-batchnorm-in-pytorch 2 |
st81698 | Solved by ptrblck in post #2
No, since the running estimates are buffers and do not require gradients, you don’t have to pass them to the optimizer.
You can access them via my_bn_layer.running_mean and my_bn_layer.running_var. |
st81699 | No, since the running estimates are buffers and do not require gradients, you don’t have to pass them to the optimizer.
You can access them via my_bn_layer.running_mean and my_bn_layer.running_var. |
st81700 | Hi, I’m trying to debug the results I’m getting inside a LSTM layer, I mean inside the cells and the intermediate h_i and c_i, someone knows if it’s even possible? or has any trick to check it?
Just to give context I’m trying to write a network using lstm cells in “low level” , so I need reference to debug.
Thanks! |
st81701 | Hi,
I’m not getting split when I use torch.utils.data.random_split. Here’s my code:
class DeviceLoader(Dataset):
def __init__(self, root_dir, train=True, transform=None):
self.file_path = root_dir
self.train = train
self.transform = transform
self.file_names = ['%s/%s'%(root,file) for root,_,files in os.walk(root_dir) for file in files]
self.len = len(self.file_names)
self.labels = {'BP_Raw_Images':0, 'DT_Raw_Images':1, 'GL_Raw_Images':2, 'PO_Raw_Images':3, 'WS_Raw_Images':4}
def __len__(self):
return(len(self.file_names))
def __getitem__(self, idx):
file_name = self.file_names[idx]
device = file_name.split('/')[5]
img = self.pil_loader(file_name)
if(self.transform):
img = self.transform(img)
cat = self.labels[device]
if(self.train):
return(img, cat)
else:
return(img, file_name)
full_data = DeviceLoader(root_dir=’/kaggle/input/devices/dataset/’, transform=transforms, train=True)
train_size = int(0.7*len(full_data))
val_size = len(full_data) - train_size
train_data, val_data = torch.utils.data.random_split(full_data,[train_size,val_size])
I get correct numbers for train_size and val_size, but when I do random_split, both train_data and val_data get full_data. There is no split happening.
Please help me fix this issue.
@ptrblck |
st81702 | Solved by Nikronic in post #2
Hi,
It looks weird, because I just ran the code using random TensorDataset and it is ok when you can get the length of your dataset, trainset, and valset correctly as you have achieved this too.
import torch
from torch.utils.data.dataset import TensorDataset, random_split
init_dataset = TensorDat… |
st81703 | Hi,
It looks weird, because I just ran the code using random TensorDataset and it is ok when you can get the length of your dataset, trainset, and valset correctly as you have achieved this too.
import torch
from torch.utils.data.dataset import TensorDataset, random_split
init_dataset = TensorDataset(
torch.randn(100, 3, 5, 5),
)
train_size = int(0.7*len(init_dataset))
val_size = len(init_dataset) - train_size
train_data, val_data = torch.utils.data.random_split(init_dataset,[train_size,val_size])
What is the length of your dataset? I would like to do some experiments with your defined class. |
st81704 | I copied your code and ran, it works fine. Could you show the version of your environment packages?
Here is a script you can use: https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py 3
Just run the code using python collect_env.py and paste output here. |
st81705 | I’m sorry. I was checking train_data.dataset.len instead of len(train_data). Split is happening correctly. No issues. |
st81706 | Hi !, I just started training my model with PyTorch. However, I met a problem when I trained my model with GPU. The error message is shown below.
RuntimeError: Tensor for argument #2 ‘weight’ is on CPU, but expected it to be on GPU (while checking arguments for cudnn_batch_norm)
And this is my train.py
import torch
import torch.nn as nn
import torch.optim as optim
from make_data import train_dataloader, test_dataloader
from make_net import net, Net
from torch.optim.lr_scheduler import ReduceLROnPlateau
import time
import os
# os.environ["CUDA_VISIBLE_DEVICES"] ="1"
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
criterion = nn.MSELoss()
opt_Adam = optim.Adam(net.parameters(), lr=0.1, betas=(0.9, 0.99))
scheduler = ReduceLROnPlateau(opt_Adam, mode='min')
def train_model(model, criterion, optimizer, scheduler, num_epochs=30):
since = time.time()
train_loader =train_dataloader
net = model()
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs")
net = nn.DataParallel(net)
net.to(device)
criterion = criterion
optimizer = optimizer
scheduler = scheduler
for epoch in range(num_epochs):
running_loss = 0.0
print("Epoch {}/{}".format(epoch, num_epochs-1))
print("-" * 10)
for i, sample in enumerate(train_loader, 0):
image, pressure = sample['image'], sample['pressure']
image = image.float()
image = image.to(device)
pressure = pressure.float()
pressure = pressure.to(device)
optimizer.zero_grad()
output = net(pressure)
loss = criterion(output, image)
loss.backward()
optimizer.step()
running_loss += loss.item()
if (i+1) % 100 == 0:
print("%d, %5d, loss: %.3f" % (epoch, i, running_loss/100))
running_loss = 0.0
# scheduler.step()
train_model(model=Net, criterion=criterion, optimizer=opt_Adam, scheduler=scheduler)
I don’t know how to fix this error.
I would appreciate it if you could give me some valuable advice. |
st81707 | I’m not sure, where you are initializing the net instance, as the code shouldn’t run in the first place.
(opt_Adam is using net.parameters() outside of train_model, which will fail, since net is initialized inside train_model)
This minimal example will run:
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def train_model(model, criterion, num_epochs=30):
net.to(device)
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr=0.1, betas=(0.9, 0.99))
for epoch in range(num_epochs):
running_loss = 0.0
print("Epoch {}/{}".format(epoch, num_epochs-1))
print("-" * 10)
for i in range(1):
image = torch.randn(1, 1)
image = image.to(device)
pressure = torch.randn(1, 1)
pressure = pressure.to(device)
optimizer.zero_grad()
output = net(pressure)
loss = criterion(output, image)
loss.backward()
optimizer.step()
running_loss += loss.item()
if (i+1) % 100 == 0:
print("%d, %5d, loss: %.3f" % (epoch, i, running_loss/100))
running_loss = 0.0
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(1, 1)
def forward(self, x):
x = self.fc1(x)
return x
net = Net()
train_model(model=net, criterion=nn.MSELoss()) |
st81708 | Many thanks for your prompt reply!
However, after I modified the code for model training, the same error persisted.
The error message is shown below…
Traceback (most recent call last):
File "make_train.py", line 44, in <module>
output = net(pressure)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 493, in __call__
result = self.forward(*input, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/parallel/data_parallel.py", line 152, in forward
outputs = self.parallel_apply(replicas, inputs, kwargs)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/parallel/data_parallel.py", line 162, in parallel_apply
return parallel_apply(replicas, inputs, kwargs, self.device_ids[:len(replicas)])
File "/usr/local/lib/python3.6/dist-packages/torch/nn/parallel/parallel_apply.py", line 83, in parallel_apply
raise output
File "/usr/local/lib/python3.6/dist-packages/torch/nn/parallel/parallel_apply.py", line 59, in _worker
output = module(*input, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 493, in __call__
result = self.forward(*input, **kwargs)
File "/home/data/lyf/pytorch/make_net.py", line 92, in forward
x = F.elu(nn.BatchNorm2d(num_features=self.f_dim*8)(x))
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 493, in __call__
result = self.forward(*input, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/batchnorm.py", line 83, in forward
exponential_average_factor, self.eps)
File "/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py", line 1697, in batch_norm
training, momentum, eps, torch.backends.cudnn.enabled
RuntimeError: Tensor for argument #2 'weight' is on CPU, but expected it to be on GPU (while checking arguments for cudnn_batch_norm)
Please allow me to show you the code for the network definition.
import torch
import torch.nn as nn
import torch.nn.functional as F
from make_ops import conv_out_size_same
from make_data import batch_size
s_h, s_w = 403, 640
# 403,640
s_h2, s_w2 = conv_out_size_same(s_h, 2), conv_out_size_same(s_w, 2)
# 202, 320
s_h4, s_w4 = conv_out_size_same(s_h2, 2), conv_out_size_same(s_w2, 2)
# 101, 160
s_h8, s_w8 = conv_out_size_same(s_h4, 2), conv_out_size_same(s_w4, 2)
# 51, 80
s_h16, s_w16 = conv_out_size_same(s_h8, 2), conv_out_size_same(s_w8, 2)
# 25, 40
s_h32, s_w32 = conv_out_size_same(s_h16, 2), conv_out_size_same(s_w16, 2)
# 12, 20
s_h64, s_w64 = conv_out_size_same(s_h32, 2), conv_out_size_same(s_w32, 2)
# 6, 10
s_h128, s_w128 = conv_out_size_same(s_h64, 2), conv_out_size_same(s_w64, 2)
# 3,5
s_h256, s_w256 = conv_out_size_same(s_h128, 2), conv_out_size_same(s_w128, 2)
# 2, 3
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.CONV1_DEPTH = 2
self.CONV2_DEPTH = 4
self.CONV3_DEPTH = 8
self.CONV4_DEPTH = 16
self.CONV5_DEPTH = 32
self.CONV6_DEPTH = 64
self.CONV7_DEPTH = 128
self.CONV8_DEPTH = 256
self.f_dim = 32
self.channel_dim = 1
self.FC_NODE = 512
self.IMG_HEIGHT = 403
self.IMG_WIDTH = 640
self.batch_size = batch_size
self.fc1 = nn.Linear(in_features=10, out_features=self.f_dim*8)
self.fc2 = nn.Linear(in_features=self.f_dim*8, out_features=self.f_dim*8*s_w256*s_h256)
self.deconv1 = nn.ConvTranspose2d(in_channels=self.f_dim*8, out_channels=self.f_dim*4,
kernel_size=2, stride=2)
self.deconv2 = nn.ConvTranspose2d(in_channels=self.f_dim*4, out_channels=self.f_dim*2,
kernel_size=2, stride=2)
self.deconv3 = nn.ConvTranspose2d(in_channels=self.f_dim*2, out_channels=self.f_dim,
kernel_size=2, stride=2)
self.deconv4 = nn.ConvTranspose2d(in_channels=self.f_dim, out_channels=self.f_dim//2,
kernel_size=2, stride=2)
self.deconv5 = nn.ConvTranspose2d(in_channels=self.f_dim//2, out_channels=self.f_dim//4,
kernel_size=2, stride=2)
self.deconv6 = nn.ConvTranspose2d(in_channels=self.f_dim//4, out_channels=self.f_dim//8,
kernel_size=2, stride=2)
self.deconv7 = nn.ConvTranspose2d(in_channels=self.f_dim//8, out_channels=self.f_dim//16,
kernel_size=2, stride=2)
self.deconv8 = nn.ConvTranspose2d(in_channels=self.f_dim//16, out_channels=self.channel_dim,
kernel_size=2, stride=2)
self.conv1 = nn.Conv2d(in_channels=self.channel_dim, out_channels=self.CONV1_DEPTH,
kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(in_channels=self.CONV1_DEPTH, out_channels=self.CONV2_DEPTH,
kernel_size=2, stride=2)
self.conv3 = nn.Conv2d(in_channels=self.CONV2_DEPTH, out_channels=self.CONV3_DEPTH,
kernel_size=2, stride=2)
self.conv4 = nn.Conv2d(in_channels=self.CONV3_DEPTH, out_channels=self.CONV4_DEPTH,
kernel_size=2, stride=2)
self.conv5 = nn.Conv2d(in_channels=self.CONV4_DEPTH, out_channels=self.CONV5_DEPTH,
kernel_size=2, stride=2)
self.conv6 = nn.Conv2d(in_channels=self.CONV5_DEPTH, out_channels=self.CONV6_DEPTH,
kernel_size=2, stride=2)
self.conv7 = nn.Conv2d(in_channels=self.CONV6_DEPTH, out_channels=self.CONV7_DEPTH,
kernel_size=2, stride=2)
self.conv8 = nn.Conv2d(in_channels=self.CONV7_DEPTH, out_channels=self.CONV8_DEPTH,
kernel_size=2, stride=2)
self.avg_pool = nn.AvgPool2d(kernel_size=2, stride=1)
def forward(self, input_tensor):
x = self.fc1(input_tensor)
x = self.fc2(x)
x = x.view(-1, self.f_dim*8, s_h256, s_w256)
x = F.elu(nn.BatchNorm2d(num_features=self.f_dim*8)(x))
x = F.elu(nn.BatchNorm2d(num_features=self.f_dim*4)(self.deconv1(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.f_dim*2)(self.deconv2(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.f_dim)(self.deconv3(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.f_dim//2)(self.deconv4(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.f_dim//4)(self.deconv5(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.f_dim//8)(self.deconv6(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.f_dim//16)(self.deconv7(x)))
x = F.tanh(nn.BatchNorm2d(num_features=self.channel_dim)(self.deconv8(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.CONV1_DEPTH)(self.conv1(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.CONV2_DEPTH)(self.conv2(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.CONV3_DEPTH)(self.conv3(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.CONV4_DEPTH)(self.conv4(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.CONV5_DEPTH)(self.conv5(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.CONV6_DEPTH)(self.conv6(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.CONV7_DEPTH)(self.conv7(x)))
x = F.elu(nn.BatchNorm2d(num_features=self.CONV8_DEPTH)(self.conv8(x)))
x = self.avg_pool(x)
x = x.view(-1, self.num_flat_features(x))
x = F.elu(nn.Linear(in_features=x.size()[-1], out_features=self.FC_NODE)(x))
x = nn.Linear(in_features=self.FC_NODE, out_features=self.IMG_HEIGHT*self.IMG_WIDTH)(x)
x = x.view(-1, self.IMG_HEIGHT, self.IMG_WIDTH)
return x
def num_flat_features(self, x):
size = x.size()[1:]
num_features = 1
for s in size:
num_features *= s
return num_features
The error message tells me Error in checking BatchNorm used in Cudnn.
The code for my modified model training is shown below.
import torch
import torch.nn as nn
import torch.optim as optim
from make_data import train_dataloader, test_dataloader
from make_net import Net
num_epochs = 30
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
train_loader = train_dataloader
criterion = nn.MSELoss()
net = Net()
optimizer = optim.Adam(net.parameters(), lr=0.1, betas=(0.9, 0.99))
if torch.cuda.is_available():
print("Let's use", torch.cuda.device_count(), "GPUs")
net = nn.DataParallel(net)
net.to(device)
for epoch in range(num_epochs):
running_loss = 0.0
print("Epoch {}/{}".format(epoch, num_epochs-1))
print("-" * 10)
for i, sample in enumerate(train_loader, 0):
image, pressure = sample['image'], sample['pressure']
image = image.float()
image = image.to(device)
pressure = pressure.float()
pressure = pressure.to(device)
optimizer.zero_grad()
output = net(pressure)
loss = criterion(output, image)
loss.backward()
optimizer.step()
running_loss += loss.item()
if (i+1) % 100 == 0:
print("%d, %5d, loss: %.3f" % (epoch, i, running_loss/100))
running_loss = 0.0
Many thanks for your prompt reply!
Thank you very much!!! |
st81709 | Thanks for the code.
You are creating some layers inside the forward method on the fly.
These layers will be reinitialized in each forward pass, so they won’t be trained, and also won’t get pushed to the GPU, since they are unknown to the model when you call model.to(device).
The standard way would be to create these layers in the __init__ method (as your other layers) and just apply them on the activation in forward.
If you really want to use randomly initialized layers in the forward pass, you could use your code and push these newly created layers manually using the device attribute of another already registered parameter. |
st81710 | Thank you very much for your prompt reply and valuable comments.
I will modify my code according to your opinion.
Thank you again |
st81711 | When I was training my model using multi-gpus, I set the batch_size=8, and used two gpus. This setting cannot make the best of my machine(4 GPUs and each with memory of 12G), however, if I set the batch_size bigger or use more GPUs, it would raise exception(GPU out of memory). It seems like that, the first GPU takes more assignment, so when I set the batch_size bigger or used more GPUs, the first GPU was out of memory. How can I fix it?
图像 1.png714×396 79.1 KB
The image show my GPU’s state. I used GPU 2 and 3. |
st81712 | This is commonly observed in multi-gpu setups, because some kind of aggregation has to be performed on one selected GPU (in the default case, cuda:0). See this answer 8, which explains the problem in a bit more details, and check the answer just after it for a possible solution (i.e. split the loss on multiple GPUs as well, not just the network). |
st81713 | Let say I have a 3 dimensional tensor.
a = torch.arange(8).reshape(2, 2, 2)
>>> a
tensor(
[[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
I want to compute the minimum over the dimension 1 and 2, to get
tensor([0, 4])
However, torch.min() does not support multiple dimensions. In contrast, torch.sum() does support? Is there any particular reason for that?
So for this specific case, currently the most efficient way to take minimum over multiple dimensions is to first reshape the tesnor
a.reshape(2, 2 * 2)
and then take the minimum over the second axis? |
st81714 | Hi @Kevin96,
You should do:
a.view(-1,2*2).min(axis=1)
where view guarantees 7 no memory copy, and almost no overhead. |
st81715 | HI kaiwen,
not very memory-efficient but “easy”?
def mul_min(x, axis, keepdim=False):
axis = reversed(sorted(axis))
min_x = x
for i in axis:
min_x, _ = min_x.min(i, keepdim)
return min_x |
st81716 | Hi,
Suppose there is an occasion where I use python multi-thread to do inference with two models. That is thread 1 use model 1 to infer picture 1, and thread 2 use model 2 to infer picture 2. Suppose python gil switches among the two threads every 2ms, and the inference time is 200ms. Will the whole time of running the two models concurrently be 400ms or less than that ? Will the inference on one thread be interrupted and turned into waiting mode when another thread is active, or will it not be affected? |
st81717 | Hi,
We do release the GIL as soon as we get out of python code. So for pytorch ops, it’s more or less all of them.
The backward, unless you implement custom Functions, will run completely out of the GIL. |
st81718 | While training the model as below, I got this error: Given normalized_shape=[13], expected input with shape [*, 13], but got input of size[477].
Can anybody advise how to overcome this error?
device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
model.to(device)
criterion.to(device)
model.train()
epochs = 1000
print_every = 50 # epochs
# threshold = 0.5 # prediction value greater than this is interpreted as a prediction of 1
for e in range(epochs):
running_train_loss = 0
running_train_accuracy = 0
running_train_recall = 0
running_train_precision = 0
running_train_f1 = 0
for features, labels in trainloader:
features = features.to(device)
labels = labels.to(device)
output = model(features)
loss = criterion(output, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
current_loss = loss.item()
current_accuracy = torch.mean((output.argmax(dim=1) == labels).type(torch.FloatTensor)).item()
current_recall = torch.mean((output.argmax(dim=1) == labels)[labels == 1].type(torch.FloatTensor)).item()
current_precision = torch.mean((output.argmax(dim=1) == labels)[output.argmax(dim=1) == 1].type(torch.FloatTensor)).item() if (output.argmax(dim=1) == 1).sum() != 0 else 0
current_f1 = 2 * current_recall * current_precision / (current_recall + current_precision) if current_recall > 0 and current_precision > 0 else 0
running_train_loss += current_loss * features.shape[0]
running_train_accuracy += current_accuracy * features.shape[0]
running_train_recall += current_recall * features.shape[0]
running_train_precision += current_precision * features.shape[0]
running_train_f1 += current_f1 * features.shape[0]
running_train_loss /= len(trainloader.sampler)
running_train_accuracy /= len(trainloader.sampler)
running_train_recall /= len(trainloader.sampler)
running_train_precision /= len(trainloader.sampler)
running_train_f1 /= len(trainloader.sampler)
model.eval()
running_validation_loss = 0
running_validation_accuracy = 0
running_validation_recall = 0
running_validation_precision = 0
running_validation_f1 = 0
with torch.no_grad():
for features, labels in validationloader:
features = features.to(device)
labels = labels.to(device)
output = model(features)
loss = criterion(output, labels)
current_loss = loss.item()
current_accuracy = torch.mean((output.argmax(dim=1) == labels).type(torch.FloatTensor)).item()
current_recall = torch.mean((output.argmax(dim=1) == labels)[labels == 1].type(torch.FloatTensor)).item()
current_precision = torch.mean((output.argmax(dim=1) == labels)[output.argmax(dim=1) == 1].type(torch.FloatTensor)).item() if (output.argmax(dim=1) == 1).sum() != 0 else 0
current_f1 = 2 * current_recall * current_precision / (current_recall + current_precision) if current_recall > 0 and current_precision > 0 else 0
running_validation_loss += current_loss * features.shape[0]
running_validation_accuracy += current_accuracy * features.shape[0]
running_validation_recall += current_recall * features.shape[0]
running_validation_precision += current_precision * features.shape[0]
running_validation_f1 += current_f1 * features.shape[0]
running_validation_loss /= len(testloader.sampler)
running_validation_accuracy /= len(testloader.sampler)
running_validation_recall /= len(testloader.sampler)
running_validation_precision /= len(testloader.sampler)
running_validation_f1 /= len(testloader.sampler)
model.train()
train_logs['losses'].append(running_train_loss)
train_logs['accuracies'].append(running_train_accuracy)
train_logs['recalls'].append(running_train_recall)
train_logs['precisions'].append(running_train_precision)
train_logs['f1_scores'].append(running_train_precision)
validation_logs['losses'].append(running_validation_loss)
validation_logs['accuracies'].append(running_validation_accuracy)
validation_logs['recalls'].append(running_validation_recall)
validation_logs['precisions'].append(running_validation_precision)
validation_logs['f1_scores'].append(running_validation_precision)
if e == 0 or (e + 1) % print_every == 0:
print(f"Epoch : {epoch}")
print(f"Training Loss : {running_train_loss}")
print(f"Training Accuracy : {round(running_train_accuracy * 100, 2)}%")
print(f"Training Recall : {round(running_train_recall * 100, 2)}%")
print(f"Training Precision : {round(running_train_precision * 100, 2)}%")
print(f"Training F1 Score : {round(running_train_f1, 4)}")
print(f"Validation Loss : {running_validation_loss}")
print(f"Validation Accuracy : {round(running_validation_accuracy * 100, 2)}%")
print(f"Validation Recall : {round(running_validation_recall * 100, 2)}%")
print(f"Validation Precision : {round(running_validation_precision * 100, 2)}%")
print(f"Validation F1 Score : {round(running_validation_f1, 4)}")
print()
epoch += 1 |
st81719 | Hello everyone,
I am quite new with Skorch, and I am in the process of applying K-fold cross-validation using data Loaders from a directory of images.
After creating the train and validation loaders, I user the fit(X,y) method from NeuralNet class, with X = current_train_loader, and y = current_train_target. As soon as the fit(X,y) executes, the following error occurs:
image.png987×278 12.7 KB
Whereas, I fill in the input and target exactly as mentioned. Is there anything wrong with my procedure? Following is what my training phase looks like: |
st81720 | This also happened to me when I initialized the criterion. For example,
criterion = torch.nn.BCELoss()
I solve this problem by:
criterion = torch.nn.BCELoss |
st81721 | Hi,
I am trying to understand how the dataloader works, and I come in to a question: can pytorch prefetch the training samples during training, so that the model do not need to wait for the data before one round of training?
If pytorch has this function, how could I switch on or switch off it? |
st81722 | If you are using multiple workers (num_workers>=1), the next batches will be prefetched once the code enters the DataLoader loop. |
st81723 | Hi my Colab session crashes everytime i run the code below.
Please help.
class Model(nn.Module):
def __init__(self, size, K):
super(Model, self).__init__()
# define the layers
# Input channels = 3, output channels = 20, filter size = (5,5)
# padding=0 (valid mode), padding=4 (full mode), padding=2 (same mode)
self.conv1 = nn.Conv2d(3, 20, kernel_size=5, stride=1, padding=2)
self.conv2 = nn.Conv2d(20, 50, kernel_size=5, stride=1, padding=2)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
self.linear1 = nn.Linear(3200, size)
self.linear2 = nn.Linear(size, K)
self.dropout = nn.Dropout(0.25)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 3200) ## reshaping
x = self.dropout(x)
x = F.relu(self.linear1(x))
x = self.dropout(x)
x = self.linear2(x)
return x
class CNN():
def __init__(self, size):
self.size = size
def fit(self, Xtrain, Ytrain, Xtest, Ytest, training_epochs=10, batch_sz=500):
N = Xtrain.shape[0]
K = len(set(Ytrain))
# convert the data arrays into torch tensors
Xtrain = torch.from_numpy(Xtrain).float()
Ytrain = torch.from_numpy(Ytrain).long()
Xtest = torch.from_numpy(Xtest).float()
Ytest = torch.from_numpy(Ytest).long()
model = Model(self.size, K)
loss = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
def train(model, loss, optimizer, inputs, labels):
inputs = Variable(inputs, requires_grad=False)
labels = Variable(labels, requires_grad=False)
optimizer.zero_grad()
# get output from the model, given the inputs
logits = model(inputs)
# get loss for the predicted output
cost = loss(logits, labels)
# get gradients w.r.t to parameters
cost.backward()
# update parameters
optimizer.step()
return cost.item()
def test(model, loss, inputs, labels):
inputs = Variable(inputs, requires_grad=False)
labels = Variable(labels, requires_grad=False)
logits = model(inputs)
cost = loss(logits, labels)
return cost.item()
def predict(model, inputs):
inputs = Variable(inputs, requires_grad=False)
logits = model(inputs)
return logits.data.numpy().argmax(axis=1)
n_batches = N // batch_sz
train_costs = []
test_costs = []
train_accuracies = []
test_accuracies = []
for epoch in range(training_epochs):
for j in range(n_batches):
Xbatch = Xtrain[j*batch_sz:(j*batch_sz + batch_sz)]
Ybatch = Ytrain[j*batch_sz:(j*batch_sz + batch_sz)]
train_c=train(model, loss, optimizer, Xbatch, Ybatch)
if j % 20 == 0:
train_costs.append(train_c)
test_c=test(model, loss, Xtest, Ytest)
test_costs.append(test_c)
p_train = predict(model, Xtrain)
p_test = predict(model, Xtest)
acc_train = np.mean(p_train == Ytrain.numpy())
train_accuracies.append(acc_train)
acc_test = np.mean(p_test == Ytest.numpy())
test_accuracies.append(acc_test)
print("Epoch", (epoch+1), "Training Cost", "%.2f" % train_c, "Test cost", "%.2f" % test_c, "Training Acc", "%.2f" % acc_train, "Test Acc", "%.2f" % acc_test)
plt.plot(train_costs, label='Training Cost')
plt.plot(test_costs, label='Test Cost')
plt.legend()
plt.show()
plt.plot(train_accuracies, label='Training accuracy')
plt.plot(test_accuracies, label='Test accuracy')
plt.legend()
plt.show()
def main():
from google.colab import drive
drive.mount('/content/gdrive', force_remount = True)
train = scipy.io.loadmat('/content/gdrive/My Drive/Colab Notebooks/Convolutional Neural Networks/train_32x32.mat')
test = scipy.io.loadmat('/content/gdrive/My Drive/Colab Notebooks/Convolutional Neural Networks/test_32x32.mat')
Xtrain = train['X']
Ytrain = train['y']
#print(Xtrain.shape) (32, 32, 3, 73257)
#print(Ytrain.shape) (73257, 1)
Ytrain = Ytrain.flatten() - 1
Xtest = test['X']
Ytest = test['y']
#print(Xtest.shape) (32, 32, 3, 26032)
#print(Ytest.shape) (26032, 1)
Ytest = Ytest.flatten() - 1
Xtrain = (Xtrain.transpose(3,2,0,1) / 255).astype(np.float32)
Xtest = (Xtest.transpose(3,2,0,1) / 255).astype(np.float32)
model = CNN(500)
model.fit(Xtrain, Ytrain, Xtest, Ytest)
if __name__ == '__main__':
main() |
st81724 | You are most likely running out of memory, since you are trying to pass the whole training data to your model.
To reduce the memory footprint, use mini batches, which won’t use that much memory. |
st81725 | I was seeing how the means and standard deviations of the weights of a CNN change as the model progresses and observed that the standard deviations of the later layers is initilzed much less that the first by default:
Screen Shot 2019-09-09 at 5.18.02 PM.png1214×526 110 KB
Left is the means and right is the stds
This was for a small 4 layer network, even when I made a larger network I observed the same, that the later layers were intilizied to have much lower variance:
Screen Shot 2019-09-09 at 5.20.40 PM.png1920×624 116 KB
Usually the standard deviation of the second layer is half that of the first layer
As you can see the stds systematically decrease. Can someone explain why this is done? I know we want our ouputs to have mean 0 and std 1 but how is this helping that?
Code:
Create any CNN in pytorch and then run
model=Conv()
def stats(x): return x.mean(),x.std()
for i,e in enumerate(model.children()):
print(i,e)
print('-----Layer Mean and std',stats(e.weight))
Update
Even with I manually initilise the layers I get the same behavior!
model=Conv()
for l in model.children():
try:
init.kaiming_normal_(l.weight)
l.bias.data.zero_()
except:
pass
def stats(x): return x.mean(),x.std()
for i,e in enumerate(model.children()):
print(i,e)
print('-----Layer Mean and std',stats(e.weight))
Screen Shot 2019-09-09 at 7.11.05 PM.png1874×592 99.1 KB
This is pretty unsettling! pytorch is keeping track of the layer index. Why is this happening? |
st81726 | I’m start to use Pytorch and trying to implement ResNet for my problem, which is not related to images or NLP. The implementation of ResNet in Pytorch has convolutional layers which I don’t need and don’t want to include at the beginning. Are you guys aware of existing implementation of ResNet in Pytorch in a MLP type of setting? Or what I really need to do is reimplement the ResNet in Pytorch?
Thank you. |
st81727 | If you are removing the conv layers in the ResNet implementation, I guess you would like to create a fully connected model with some skip connections?
If so, you could have a look at the current implementation of BasicBlock 73 and BottleNeck 22 and try to adapt these modules to your code. |
st81728 | Thank you. That’s actually what I’m doing currently. I try read and modify the code in github: pytorch/vision/blob/master/torchvision/models/resnet.py. |
st81729 | I noticed that when similar questions are asked the commonly given advice is to use SubsetRandomSampler or random.split. Isn’t it wrong, though?
I always thought that, during validation, the validation set should be the same through all the different runs, since, changing it every time wouldn’t allow getting a good estimate of the error given the hyperparameters.
I guess the solution is as simple as setting a manual seed before calling random.split and then setting it back to its initial value. I just wonder if my idea of how validation works is correct. |
st81730 | I would say it depends a bit on your use case.
If you are running some quick experiments, setting the seed and splitting the datasets randomly might be sufficient to reproduce your results.
However, if you really need the same splits for each run, you could sample the split indices once, store them locally, and use them in a Subset to get the same training, validation (and test) sets. |
st81731 | Hello,
I am re-implementing the supervised learning experiments from Model-Agnostic Meta Learning (MAML) 110 in PyTorch.
The goal is to learn features that are “most fine-tune-able.” This is achieved by taking gradient step(s) in the direction that maximizes performance on the validation set given a step(s) on the training set. This requires second derivatives with respect to the parameters. See Algorithm 1 in the paper.
Where I am stuck is that I need to do:
(1) inner loop: a forward pass on the training example, take gradients with respect to the parameters (2) meta loop: do a forward pass with the updated parameters on a validation example, then take another gradient wrt the original parameters and backprop through the first gradient (thus the second derivative).
From the Improved WGAN implementation, I see that I can take the gradient and retain the graph, allowing me to then take another gradient. But I don’t see how I can do the second forward pass without updating the parameters via opt.step(). Do I need to have two graphs, one where I cache the old parameters for the meta-update, and one where I allow the parameters to update in the inner loop?
Thanks for your help!
EDIT: I understand now that I need to add variables to the graph for each gradient of each variable. Then in the meta-update, the gradient of these gradients can be taken with a backward pass over the augmented graph. |
st81732 | Were you able to successfully implement it? If yes, can you explain how you did it?
I have a related question here |
st81733 | Yes I have an implementation, but I’ve been unable to replicate the Omniglot experiments from the paper. Let me clean up the code and I will make it public soon. |
st81734 | Here is a link to the MAML code: https://github.com/katerakelly/pytorch-maml 1.0k
I was able to replicate the Omniglot experiments with it. |
st81735 | is there a easy way to train networks within the maml framework without having to code up the functional form ? as this would make training of deeper networks easier |
st81736 | Can you post your implemention? I am also curious about the “module” style implemention about maml. |
st81737 | Hi,
I have a symmetric matrix X which is constructed using the outputs of network for each batch. I then find the eigenvalues and eigenvectors of X using
e, V = torch.symeig(X, True)
While this works initially, I get the error below after some time. I think this may be due to the outputs of the network. Pls, is there any approach I can use to avoid this error?
Intel MKL ERROR: Parameter 4 was incorrect on entry to SLASCL.
Intel MKL ERROR: Parameter 4 was incorrect on entry to SLASCL.
info: 99
, submat: 0
info: 901
symeig_cuda: the algorithm failed to converge; 901 off-diagonal elements of an intermediate tridiagonal form did not converge to zero. |
st81738 | The error always troubles me.I have refered to the official website for installing torch and torchvision by the package called pip .When I import torch,everything goes well;but when I import torchvision,the error always occurs。the screenshot shows below
Screenshot from 2019-09-02 08-43-09.png803×500 91.4 KB
The intresting thing is that everything is ok when I use tensorflow.
The detail below is about TF2.0
‘’’
2019-09-02 08:39:51.517620: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcudart.so.10.0
2019-09-02 08:39:51.608876: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcublas.so.10.0
2019-09-02 08:39:51.636179: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcufft.so.10.0
2019-09-02 08:39:51.644710: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcurand.so.10.0
2019-09-02 08:39:51.705207: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcusolver.so.10.0
2019-09-02 08:39:51.742977: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcusparse.so.10.0
2019-09-02 08:39:51.861754: I tensorflow/stream_executor/platform/default/dso_loader.cc:42] Successfully opened dynamic library libcudnn.so.7
‘’’
I hope who can help me to fix it.Thanks.
ps:
OS:ubuntu18.04
cuda:10.0
torch 1.2.0
torchvision 0.3 |
st81739 | Which binaries did you install (with which CUDA versions) or did you build from source?
Could you make sure to uninstall all older torchvision and PyTorch versions and reinstall them afterwards?
It might also be a good idea to create a new virtual environment. |
st81740 | ptrblck:
you insta
Thanks for your answer! I have fixed it by uninstalling the current version(torchvision 0.4) and reinstalling the older torchvision(0.3). Now,everything goes well. |
st81741 | Good to hear it’s working with the older version. Did you install torchvision 0.3 using the conda or pip binaries? If so, could you try to install the latest version using the same approach? |
st81742 | My current state is under windoes, use libtorch and use network programming-socket.
But, I find that <WINSOCK2.H> conflicts with <torch/script.h>.
I am helpless now, who has good advice?
Thanks! |
st81743 | Hi,
I just encountered an error, when I perform a bool slices operation like:
average = torch.mean(tensor[tensor[:] != 0]),
the system returns me an error: Function ‘AddmmBackward’ returned nan values in its 2th output.
I realized that this equation may not be a differentiable function, so I was wondering if there is a differentiable way can let me get the same result as the equation stated above.
Thanks. |
st81744 | Solved by albanD in post #2
Hi,
This operation is fine. Note that you don’t need the [:].
This error occurs when you run in AnomalyMode? You should check which forward function it correspond to and print the output value to make sure they are in acceptable ranges. |
st81745 | Hi,
This operation is fine. Note that you don’t need the [:].
This error occurs when you run in AnomalyMode? You should check which forward function it correspond to and print the output value to make sure they are in acceptable ranges. |
st81746 | Hey,
Thanks for your suggestions and this operation really worked after I fixed a little error somewhere else. |
st81747 | I have this class.
class Net(torch.nn.Module):
def init(self, D_in, H, D_out):
super(Net, self).init()
self.fc1 = nn.Linear(D_in, H)
self.fc2 = nn.Linear(H, H)
self.fc3 = nn.Linear(H,H)
self.fc4 = nn.Linear(H, D_out)
self.active_1 = torch.nn.Tanh()
self.active_2 = torch.nn.Tanh()
self.active_3 = torch.nn.Tanh()
self.fc11 = nn.Linear(D_in, H)
self.fc22 = nn.Linear(H, H)
self.fc33 = nn.Linear(H, H)
self.fc_tot = nn.Linear(D_out, D_out)
##################################
def forward(self, x):
"""
In the forward function we accept a Tensor of input data and we must return
a Tensor of output data. We can use Modules defined in the constructor as
well as arbitrary operators on Tensors.
"""
y = self.active_1(self.fc1(x))
y = self.active_2(self.fc2(y))
y = self.active_3(self.fc3(y))
y = self.fc4(y)
y = y*y########################
y = self.fc_tot(y)
return y
As you see I have not to use these three functions( self.fc11 = nn.Linear(D_in, H),self.fc22 = nn.Linear(H, H),self.fc33 = nn.Linear(H, H)) in forward part, but when I delete from the class, the result gets completely change? why? |
st81748 | yes, and the result is good but I do not know, how can I explain it.
the only parameter that, get change in class is the " _cdata". |
st81749 | I installed pip install tb-nightly
I’m trying to visualize the code
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter(log_dir='./logs')
x = range(100)
for i in x:
writer.add_scalar('y=2x', i * 2, i)
writer.close()
The documentation says the command tensorboard --logdir=logs
But getting an error tensorboard --logdir=logs ^ SyntaxError: can't assign to operator
How it works? |
st81750 | It might be related to this thread 10. Are you running the command inside a bash terminal? |
st81751 | GitHub
blue-season/pywarm 4
A cleaner way to build neural networks for PyTorch. - blue-season/pywarm |
st81752 | PyWarm 7 is a high-level neural network construction API for PyTorch.
Using PyWarm, you can put all network data flow logic in the forward() method of your model, without the need to define children modules in the __init__() method then call it again in the forward(). This result in a much more readable model definition in fewer lines of code. Check the GitHub repository for code examples and more details! |
st81753 | PyWarm just hit v0.2!
Featuring the warm functional interface to Transformer, and a new example for MobileNet. |
st81754 | See an example of the transformer model 8 (Attention is all you need) in less than 50 lines of code. |
st81755 | I recently came across switchable normalization in Andrew Ng’s ‘The Batch.’ Is this a layer that can be plugged into an existing model for normalization purposes? If so, is there a pytorch implementation of it? |
st81756 | A version here: https://github.com/switchablenorms/Switchable-Normalization/blob/master/devkit/ops/switchable_norm.py 180 |
st81757 | How can I judge the model is train or validation in the ‘forward’ function?
In fact, I have construct a network, and write the ‘forward’ function. I want to judge whether this forward process happened in the training process or in the validation process. |
st81758 | Hi @linyu,
You can know by checking the value of the nn.Module attribute self.training in forward (set to True in net.train() and to False in net.eval()) . |
st81759 | I’m trying to use a convolutional auto-encoder to reconstruct some vectors (not images).
In order to assess whether it’s working I’d like to plot the cosine similarity between the input data and the reconstructed vector. What I’m doing right now is this:
model.eval()
with torch.no_grad():
for data in loader_val: # Validation dataset
# CAE
data, noise = data # Use data w/ noise as input model
data = data.unsqueeze(1).float()
noise = noise.unsqueeze(1).float()
out = model(noise)
loss = criterion(out, data)
# Cosine similarity
cos = CosineSimilarity()
cosine_sims.append(cos(data, out))
I wanted to visually see how it changes after each epoch and so I used the following commands to plot it:
plt.plot([np.mean(np.abs(el.numpy())) for el in cosine_sims])
The problem is that the values start at 0.9 and they just fluctuate (not decreasing or increasing). Is there something wrong in the way I use CosineSimilarity? |
st81760 | The Euclidean distance does not necessarily correlate with the angle (cosine similarity).
Imagine a point cloud near the origin of a coordinate system. While the MSELoss could be low, the cosine similarity might be high between certain points.
Would it be possible to use the CosineSimilarity as the criterion to train the model? |
st81761 | I’ve being thinking about this for a while now. I guess it’s possible but I don’t think I understand how to actually use it. The CosineSimilarity returns a number for each pair of vectors, and not a real loss. Should I take the mean or should I add it to MSELoss? Thanks. |
st81762 | Can a loss function be like:-
Total_loss = MSEloss()+CosineSimilarity()
I think this will be better measure.
Build your custom CosineSimilarityLoss if possible. |
st81763 | I guess, the sign for cosine similarity shall be - (minus). Also, if the vectors are L2 normalized, MSELoss ~ -CosineSimilarity. |
st81764 | But I cannot simply add (or subtract) the cosine similarity to the loss function, since the former is not just a real number. Do you recommend taking the mean? |
st81765 | Hi everyone. I’m trying to load a pre-trained model and see its accuracy for a small apple diseases dataset:
import torch
import torchvision
import torchvision.transforms as transforms
from torchvision import datasets, models
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
testset = torchvision.datasets.ImageFolder('data/', transform=transforms)
testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=True, num_workers=2)
"""testset = torchvision.datasets.CIFAR10(root='./data', train=False,
download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=2)"""
classes = ('Folha Desfolha Precoce', 'Folha Glifosato', 'Folha Magnésio', 'Folha Potássio',
'Folha Sadia Gala', 'Fruto Alternaria', 'Fruto Bitter Pit', 'Fruto Bitter Pit', 'Fruto Colletotrichum',
'Fruto Penicillium')
device = torch.device('cpu')
net = torch.load('applesnet/main.pt', map_location=device)
net.eval()
The problem is when I try to run the code below to measure the accuracy, I get the error
message “TypeError: ‘module’ object is not callable”:
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the test images: %d %%' % (
100 * correct / total))
TypeError Traceback (most recent call last)
<ipython-input-10-bc22d0ffcea3> in <module>
3 with torch.no_grad():
4
----> 5 for data in testloader:
6 images, labels = data
7 outputs = net(images)
~/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py in __next__(self)
635 self.reorder_dict[idx] = batch
636 continue
--> 637 return self._process_next_batch(batch)
638
639 next = __next__ # Python 2 compatibility
~/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py in _process_next_batch(self, batch)
656 self._put_indices()
657 if isinstance(batch, ExceptionWrapper):
--> 658 raise batch.exc_type(batch.exc_msg)
659 return batch
660
TypeError: Traceback (most recent call last):
File "/home/gustavo/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 138, in _worker_loop
samples = collate_fn([dataset[i] for i in batch_indices])
File "/home/gustavo/anaconda3/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 138, in <listcomp>
samples = collate_fn([dataset[i] for i in batch_indices])
File "/home/gustavo/anaconda3/lib/python3.7/site-packages/torchvision/datasets/folder.py", line 103, in __getitem__
sample = self.transform(sample)
TypeError: 'module' object is not callable
The most strange thing is, when I use the CIFAR-10 dataset instead of this particular dataset, I don’t get this error message. |
st81766 | Solved by Nikronic in post #2
Hi,
You have typo here, it must be transform not transforms. I mean s is the problem.
Based on your definition in below line
transform is composed object and transforms is the PyTorch package itself.
In the CIFAR10 example, you are using transform!
Good luck |
st81767 | Hi,
You have typo here, it must be transform not transforms. I mean s is the problem.
Gustavo_Adolfo_Schwa:
testset = torchvision.datasets.ImageFolder(‘data/’, transform=transforms)
Based on your definition in below line
Gustavo_Adolfo_Schwa:
transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
transform is composed object and transforms is the PyTorch package itself.
In the CIFAR10 example, you are using transform!
Gustavo_Adolfo_Schwa:
“”"testset = torchvision.datasets.CIFAR10(root=’./data’, train=False, download=True, transform=transform)
Good luck |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.