user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
blackbirdbarber | After it runs can hook remove itself from inside? | ptrblck | You could try to access the handle from inside the hook:
def hook(grad):
print(grad)
handle.remove()
model = nn.Linear(1, 1)
handle = model.weight.register_hook(hook)
model(torch.randn(1, 1)).backward()
model(torch.randn(1, 1)).backward()
This code will print the gradient only once a… |
berat | Hi,torch.utils.data.dataset.random_split returns aSubsetobject which has notransformsattribute. How can I split aDatasetobject and return anotherDatasetobject with the sametransformsattribute?Thanks | ptrblck | Here is a small example:
class MyDataset(Dataset):
def __init__(self, subset, transform=None):
self.subset = subset
self.transform = transform
def __getitem__(self, index):
x, y = self.subset[index]
if self.transform:
x = self.transform(x… |
jerrychang | Hello everyone, I’m training my custom data recently, but the loss only update at the first time, and I really don’t know where the problem ishere is the codefor epoch in range(cfg['epoch']):
for phase in ['train', 'valid']:
if phase == 'train':
net.train()
else:
net.eval()
running_loss, running_acc... | ptrblck | Thanks for the code!
Could you remove the last softmax call from your model?
nn.CrossEntropyLoss expects logits as the model’s output, since internally F.log_softmax and nn.NLLLoss will be used.
Your model should thus just return self.fc3(x) without and non-linearity. |
ChrisKonishi | I’m trying to implement GradCAM for inception_v3, but after my modifications, it’s taking a long time, much more than what I get without the changes. Am I doing something wrong? | ptrblck | Thanks for the information.
self.feat_conv won’t contain the same forward pass as the original model, as all functional calls from the forward method will be lost.
E.g.this pooling operationwill not be applied (neither the following), if you just wrap the child modules in an nn.Sequential block. … |
Abdelrahman_Mohamed | class Datasetload(Dataset):
def __init__(self, file_path, transform=None):
self.data = pd.read_csv(file_path)
self.transform = transform
def __len__(self):
return len(self.data)
def __getitem__(self, index):
image = self.data.iloc[index, 1:].values.astype(n... | ptrblck | The trailing comma might create transform as a tuple.
Could you remove it and try your code again? |
hagsmand | I get this error size mismatch, m1: [50 x 52480], m2: [256 x 2] and try to fix it by change linear dim to [52480 x 2] it can train but always get 0 lossHere is my code.class LSTMtagger(nn.Module):
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, num_layers):
super(LSTMtagger, self).__... | ptrblck | Your current code throws an error, if I pass an input of shape [50, 256] to it in the self.lstm layer.
For the batch_first=True argument, the input should be [batch_size, seq, feature], so just passing embeds without the view gets rid of this error.
If you would like to use the output features of … |
isalirezag | Have a silly question:import torch
a = torch.rand(2,2)
b= torch.rand(2,2)whata @ bdo? | ptrblck | It’s a matrix multiplication. If I’m not mistaken it was introduced in Python3. |
Ran_Ran | This is the error message I get. In the first line, I output the shapes ofpredictedandtarget. From my understanding, the error arises from those shapes not being the same but here they clearly are.torch.Size([6890, 3]) torch.Size([6890, 3])
Traceback (most recent call last):
File "train.py", line 251, in <module>
... | ptrblck | You are passing the target as a numpy array, which works differently for size() (it returns the number of elements as an int, thus raising this error).
Remove the numpy() call and the code should work fine. |
Shisho_Sama | Hello everyone.Is it possible to run two modules in parallel in Pytorch?Currently all I have seen so far, has been in a sequential manner but can I for example do sth like this :input
p1 | p2
|********|***********
| |
| |
|********|***********
|
|
... | ptrblck | If you are running the code on a GPU and call p1 and p2 after each other, these calls will be queued onto the device and executed asynchronously. Depending on the workload of p1, p2 might start while p1 is still executing.
If you have multiple GPUs in your system (and don’t use data parallel), you … |
conjuring | I have a basic doubt regarding the syntax of the code while passing the input to the Linear model. Following is the code that I got from documentation.m = nn.Linear(20, 30) //Line1input = torch.randn(128, 20)//Line2output = m(input) //Line3Now my doubt is:in Line1, m ... | ptrblck | If you call the model directly, the internal__call__method will be called, which will register hooks etc. and call forward itself.
You should therefore not call forward manually, but let the module do it. |
John1231983 | I have a tensorflow function. I want to convert it to pytorch. However, I got a big error between tensorflow and pytorch result. Could you please check my code and let me know what is the problem?tensorflow result 0.23463342
Pytorch result 0.035501156The colab is atHereThis is my target tensorflow codeeps = 1e-5
ndims... | ptrblck | Skimming through your code it looks like the padding in your PyTorch approach might be wrong.
If I’m not mistaken you are using a 3D ([9x9x9]) conv kernel. To get the same volumetric output as your input, you should use padding=4 for stride=1. |
rasoolfa | Hi,Is the following right way to share a layer between two different networks? or it is better to have a separate module for a shared layer?import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class A(nn.Module):
def __init__(self):
super(A, self).__init__()
... | ptrblck | Yes, this should work.
Here is a small (simplified) example:
class A(nn.Module):
def __init__(self):
super(A, self).__init__()
self.fc = nn.Linear(3, 1)
def forward(self, x):
x = self.fc(x)
return x
class B(nn.Module):
def __init__(self, shared_re):
… |
Ranahanocka | I have successfully installed NVIDIA driver & cudatoolkit via conda. However, I am not able to use cuda in pytorch (even though it installed successfully).Previously, I was using Pytorch with CUDA 8.0, and wanted to upgrade. I removed / purge all CUDA through:sudo apt-get --purge remove cuda
sudo apt-get autoremove
dpk... | ptrblck | Thanks for the information.
Based on the codes, it looks like 384.81 is still installed (at least nvidia-settings) and still contains config files. I would recommend to purge all drivers, and reinstall the latest (or desired) one. |
alekhka | Hi,I have been using PyTorch for a while now and one of the things I find attractive is that I can “bypass” few layers by not forward passing through it all. My understanding was that by not including them in the forward pass they would automatically be dropped off from the network and wouldn’t be backpropped through. ... | ptrblck | Basically you are right. The “missing” operations won’t be tracked by Autograd and thus the backward pass won’t be performed on them either.
However, these layers are still registered as parameters to the model, so they will show up in the print statement as well as in model.parameters().
Since t… |
cijerezg | I define my custom loss as follows:def custom loss(target,output,mask):
output = torch.neg(output)
loss = torch.add(target,output)
loss = torch.pow(loss,2)
loss = torch.mul(loss,mask)
loss = torch.mean(loss)I’ve seen many people use a class. But I also read a function would be fine. Would that loss ... | ptrblck | Yes, your approach should work just fine.
The advantage of using a class is that it can hold internal attributes you would have to pass otherwise to your functional approach.
E.g. using nn.CrossEntropyLoss, you could define the weight or reduction argument while creating an instance of this class.… |
Nisheeth_Jaiswal | def img_convert(tensor):image = tensor.clone().detach().numpy()image = image.transpose(1, 2, 0)print(image.shape)image = image*np.array(0.5,) + np.array(0.5,)image = image.clip(0, 1)return imagedataiter = iter(training_loader)images, labels = dataiter.next()fig = plt.figure(figsize=(25, 4))for idx in np.arange(20):ax =... | ptrblck | I would add something like:
if image.shape[2] == 1:
image = image[:, :, 0]
return image
into your img_convert method. |
lorenzo_fabbri | I’m using a customDatasetwhere the path to the images is created from a Pandas DataFrame. Out of curiosity I added aprint(idx)to the__getitem__function and I noticed that it’s called twice (it prints two different indices) if I use 1 worker. If I use multiple workers, it’s called even more times. The batch size is 1, t... | ptrblck | Each worker will create a batch and call into your Dataset's __getitem__.
For num_workers=0, the main thread will be used to create the batch. For num_workers=1 you will use another additional process to fetch the next batch. |
fbrah | Hi,I am working on someone’s code in torch 0.3.I want to count number of padding so I wrote:ys = valid_decoder_inputs[1:,:].view(-1) #true target
not_padding = ys.ne(PAD_IDX)
no_not_padding = not_padding.sum().item()However torch 0.3 doesn’t support item(). Can you help of how to write this lin... | ptrblck | You could replace it with x.sum().data[0].
The probably better approach would be to port the code to the latest PyTorch version, as you might encounter already solved bugs etc. |
samuelagbede | I have a CNN and a LSTM that I want to connect together to form some sort of ConvLSTM. The first layer in the CNN has a batchnorm2d layer which is then connected to a convolutional layer.class ConvNet(nn.Module):
def __init__(self, num_classes=20,flatten_size=2*5, inputs=3, recurrent=False):
super(ConvNet, ... | ptrblck | After setting n_inputs=2560, the code runs fine on the CPU and the GPU and I get an output of shape [16, 4, 2560].
Could you check, if you are passing a ByteTensor as your input to the model?
Make sure it’s a FloatTensor (or call .float() on it before passing to the model). |
debowin | Hello,I’m curious if its possible to do something likenp.random.choice([a, b], p=[p_a, p_b])using PyTorch whereaandbare 1-d tensors of length L andp_aandp_bare probabilities used to sample elements from either tensoraorbinto the resultant 1-d tensor.I thinktorch.multinomial([p_a, p_b], L)might be useful here - it retur... | ptrblck | I’m not sure to completely understand the use case, but this code snippet should work, if you would like to sample either the element from a or b based on the probabilities:
L = 10
a = torch.arange(L)
b = torch.arange(L, 2*L)
p_a = 0.2
probs = torch.empty(1, L).uniform_()
idx = (probs >= p_a).to(t… |
Philipp_Friebertshau | How can I replace the forward method of a predefined torchvision model with my customized forward function?I tried the following:method_replace1382×1080 103 KB | ptrblck | You could derive a custom class using the resnet class as its parent:
import torchvision.models as models
from torchvision.models.resnet import ResNet, BasicBlock
class MyResNet18(ResNet):
def __init__(self):
super(MyResNet18, self).__init__(BasicBlock, [2, 2, 2, 2])
def f… |
kirk86 | Hi there,I was wondering if someone could shed some light on the following questions:Why is ReduceLROnPlateau the only object withoutget_lr()method among all schedulers?How to retrieve the learning rate in this case? Previously without scheduler I would dooptimizer.param_groups[0]['lr']but now after using the scheduler... | ptrblck | The scheduler might track multiple param_groups as describedhere.
It should still work as shown in this example:
model = nn.Linear(10, 2)
optimizer = optim.Adam(model.parameters(), lr=1e-3)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(
optimizer, patience=10, verbose=True)
for i in… |
dashesy | What is the benefit of usingregister_buffercompared to declaring a normal tensor in__init__?class MyModule(nn.Module):
def __init__(self, child):
self.child = torch.as_tensor(child).int()
# vs
self.register_buffer('child', torch.from_numpy(np.array(child, dtype=np.int32)))The buffer is seria... | ptrblck | Since buffers are serialized, they can also be restored using model.load_state_dict. Otherwise you would end up with a newly initialized buffer.
That’s possible, but not convenient, e.g. if you are using nn.DataParallel, as each model will be replicated on the specified devices. Hard-coding a d… |
ElleryL | Hey; I construct a very simple classification model to classify mixture of gaussian.In this case, bivariate Gaussian. The data close to mode one has label 0 and data close to mode two has label 1.Here is how I generate train samplesfrom torch.distributions.multivariate_normal import MultivariateNormal
m1 = Multivariate... | ptrblck | I tried a few approaches using different weight init methods etc., but the main issue seems to be the loss in numerical precision using sigmoid + nn.BCELoss.
If you remove the sigmoid in your model and use nn.BCEWithLogitsLoss as your criterion (which uses the LogSumExp trick for stability), your m… |
Subho | I stumbled upon a rather weird issue while debugging a larger code in PyTorch. A simple instance to reproduce the issue is here:https://colab.research.google.com/drive/11kBaxMOxN9i0X1vtaX47Yz7rkkHz7KpuAs you can see, the variable x gets updated in every epoch (see that their norms are different), however, the norm of t... | ptrblck | Use x_old = x.detach().clone(), since .data will be a reference and point to the same location in x_old and x_new. |
FilipAndersson245 | i have a mask file saved as a .tiff file ranging from 0…255.I would like to split it intoXclasses so my tensor look something like this [batch, classes, width, height].My network currently does Binary classification and outputs [9, 2, 256, 256].So i would like to match this with the segmentation mask?, and understand h... | ptrblck | The segmentation mask in a multi-class classification use case should have the shape [batch_size, height, width] and contain the class indices in the range [0, nb_classes-1].
Does your target image contain 256 unique classes? If not, you should map each color value to a class index.
The output of … |
Shisho_Sama | I created a dataset for a very small set of images (408 images download link ishere).it contains a csv file that has image file names and labels. and this is the class I made :# we use csv for reading csv file
import csv
# we use PIL.Image for reading an image
import PIL.Image as Image
import os
class AnimeMTLDataset(... | ptrblck | Could you specify the size in Resize as a tuple?
transforms.Resize((224, 224))
as a single value will work differently, if your images are not quadratic. |
hristo-vrigazov | Let’s say I have the following example (modified from [Data parallel tutorial])(https://pytorch.org/tutorials/beginner/blitz/data_parallel_tutorial.html#simple-model)class Model(nn.Module):
# Our model
def __init__(self, input_size, output_size):
super(Model, self).__init__()
self.fc = nn.Linea... | ptrblck | Most likely self.f is not pushed to the right device, since it is neither registered as an nn.Parameter nor as a buffer (using self.register_buffer).
Use the former case, if self.f should require gradients and the latter if not.
The manual cuda() call inside your __init__ method won’t work, as the… |
Jose615243 | In a simple linear network:4(input)—>100100—>3(output)With a tensor X for the input and Y for output. Where should I use requires_grad=True in X,Y or the nn.Linear creates weights tensors that have the requires_grad=True automatically set? | ptrblck | Usually you don’t need to set this attribute manually.
The parameters inside the layers will be created as nn.Parameter, which will automatically have requires_grad=True.
A use case for setting this attribute manually, would be e.g. if you use some extra parameters in your model (for your fancy op… |
hanspinckaers | I’m trying to understand the behaviour of the Conv2d layer in Pytorch, but it gives different results in scenarios in which I expect the same results.Maybe I’m missing something?Example (link tojupyter notebook):import torch
torch.set_printoptions(precision=9)
torch.manual_seed(1)
data = torch.autograd.Variable( torch.... | ptrblck | The observed differences might be caused by different implementations or different order of the operations.
Since the differences are at approx. 1e-6 it’s likely the reason in my opinion.
Have a look at the following code:
a = torch.randn(10, 10, 10)
b = a.sum()
c = a.sum(2).sum(1).sum(0)
print(b… |
lorenzo_fabbri | I noticed an improvement by doing per-channel normalization (6-channel images). It would be nice to simply use scikit-learn’s scalers likeMinMaxScaler, but I noticed it’s much slower. The code for doing it is (inside__getitem__):scaler = MinMaxScaler()
for i in range(img.size()[0]):
img[i] = torch.tensor(scaler.fit... | ptrblck | This should be caused by dividing by zero, if the max and min values are equal.
I naively implemented sklearn’s approach without checks.
Add this check to your implementation:
class PyTMinMaxScalerVectorized(object):
"""
Transforms each channel to the range [0, 1].
"""
def __call_… |
Shisho_Sama | Hello everyone.How can I do multiclass multi label classification in Pytorch? Is there a tutorial or example somewhere that I can use?I’d be grateful if anyone can help in this regardThank you all in advance | ptrblck | Have a look atthis postfor a small example on multi label classification.
You could use multi-hot encoded targets, nn.BCE(WithLogits)Loss and an output layer returning [batch_size, nb_classes] (same as in multi-class classification). |
slavavs | resnet-neural-e15487723889211130×635 31.5 KBHow can I implement resnet as in the picture? How to add X to the next layer? | ptrblck | Have a look at theresnet implementationin torchvision.
In particular the definition of BasicBlock and Bottleneck might be helpful. |
achim | Hi!I’m trying tojit.script-compile a model which uses thet[t != t] = ...trick to fill the nans of a tensor with a default value. However, torchscript does not seem to appreciate this kind of indexing. Does anyone know a solution/workaround?Thank you!Here’s a small example plus error message:@torch.jit.script
def f():... | ptrblck | I’m not sure if it’s the indexing or rather the rhs of the assignment, since the error says:
Expected a value of type ‘Tensor’ for argument ‘values’ but instead found type ‘int’.
This seems to work:
@torch.jit.script
def f():
t = torch.tensor([0.])
t[t!=t] = torch.tensor(7.)
retur… |
Phoenix1327 | The example code is:# input_size: N * 1024 * 1
output = torch.squeeze(input)
# output_size: N * 1024where N is batch_size.When the code is running with single GPU mode, the output size is correct, i.e., N * 1024.However, when using multiple GPUs (for example, 4 GPUs), the output size is wired:When N is large, e.g. 64, ... | ptrblck | torch.squeeze will squeeze all dimensions with size 1:
x = torch.randn(1, 2, 1, 2, 1, 2, 1)
print(x.squeeze().shape)
> torch.Size([2, 2, 2])
In the case of a small batch size, each device might get a chunk where N==1, which will also squeeze the batch dimension.
To avoid such errors, I would reco… |
11130 | This is very weird. I have loaded CIFAR10 dataset:import torchvision.datasets as datasets
import torchvision.transforms as transforms
dataloader = datasets.CIFAR10
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
trans... | ptrblck | Since you are using random transformations, you’ll get randomly transformed samples every time.
Remove RandomHorizontalFlip and RandomCrop and you should get the same outputs. |
Valiox | My model has its tensors on cuda, and its state is saved as such. When I load the model state for inference withcheckpoint = torch.load(weights_fpath), the model state keeps the same device configuration. This adds overhead to torch.load (in my case 1-2 seconds). Callingcheckpoint = torch.load(weights_fpath, "cpu")take... | ptrblck | The map_location argument remaps the tensors to the specified device. This is useful, if your current machine does not have a GPU and you are trying to load a tensor, which was saved as a CUDATensor.
From the docs:torch.load()uses Python’s unpickling facilities but treats storages, which und… |
talhak | As the title clearly describes, the images in the dataset I use do have 3 color channels despite they are grayscale. So, I usedtransforms.Grayscale(num_output_channels=1)transformation in order to reduce the number of color channels to 1, but still the loaded images do have 3 channels.Here is my implementation:data_tra... | ptrblck | If I run your code, I get the valid error:
RuntimeError: output with shape [1, 334, 690] doesn't match the broadcast shape [3, 334, 690]
which is thrown, since Grayscale returns a single-channel image, while Normalize uses three values.
Fixing the mean and std to a single value, yields valid outp… |
gokul_uf | Hi Everyone, I am working with the ImageNet dataset. As a part of the experiments, I want to shift the input images right by 10 pixels (among other affine transforms).I can’t usetorchvision.transforms.RandomAffinebecause I want deterministic transformations. So I’m left withtorchvision.transforms.functional.affine.Any ... | ptrblck | Your suggestion should work. Alternatively you could use transforms.Lambda to warp your functional transformation. |
kl_divergence | I’ve two models (based on faster_rcnn from torchvision). I want to replace the weights of roi_head in model 2 with that of model 1’s.My dict keys from model 1 has these keys:'roi_heads.box_head.fc6.weight'
'roi_heads.box_head.fc6.bias'
'roi_heads.box_head.fc7.weight'
'roi_heads.box_head.fc7.bias'
'roi_heads.box_pre... | ptrblck | In that case something like this should work:
modelA.roi_head.load_state_dict(modelB.roi_head.state_dict())
Alternatively, remove the roi_heads strings from the checkpoint keys and try:
checkpoint = chpt['model']
# Remove 'roi_heads'
checkpoint_cleaned = ...
model.roi_head.load_state_dict(checkpo… |
ajhanwar | I’ve trained on ann.Sequentialmodel and would like to load the previously saved weights into another instance of the model. However, I’ve been trying to add names to the layers in this new model definition (which I didn’t previously do) and am running into an error with missing/unexpected keys.Any ideas for how to circ... | ptrblck | You could load the state_dict and rename all keys to the newly given names.
The fastest way would probably be to use the state_dict of your new model definition and just create a loop over the keys of both dicts changing one to the other. |
sunshineatnoon | Hi, I have a model with agrid_samplelayer, I tried to train my model on multiple GPUs, but got the following error:RuntimeError: grid_sampler(): expected input and grid to be on same device, but input is on cuda:1 and grid is on cuda:0Is there anyway to use this layer on multiple GPUs? Thanks | ptrblck | Try to use grid.device instead.
Might be and you should stick to your work flow, as I was just using it as an example.You could also try to register self.grid as a buffer using self.register_buffer, which would move the tensor automatically using model.to(). |
Shisho_Sama | I’m trying to finetune a resnet18 on cifar10, everyhting is straight foward yet for some weird reason I’m getting :**RuntimeError** : element 0 of tensors does not require grad and does not have a grad_fnI have seen a similar questionherebut I cant understand why I’m getting this error as im not doing anything like tha... | ptrblck | You set the requires_grad attribute of all parameters to False, thus nothing in your computation graph requires gradients, which will raise this error. |
Haydnspass | Hey,since I can generate my training data, I basically have access to unlimited datasets and generate the samples using a torch Dataset and Dataloader on the fly.But as generating samples is (medium) expensive I want to reuse the generated data for a limited lifetime, let’s say 10 epoches until I would get overfitting ... | ptrblck | The Dataset is copied for each worker, if I’m not mistaken, which will lose all changes performed on these copies.
Have a look atthis exampleof shared arrays and let me know, if that would help in your use case. |
Wayne_Mai | Hi, I am a newcomer to PyTorch.Ascuda()give a better performance since it’s on GPU, I wonder if I can call other module during CUDA calculation.I have known that currently we can not use numpy directly in GPU mode, and if I want to do that I have to use.cpu().numpy()to migrate the data to CPU first.So I am curious abou... | ptrblck | What are you trying to achieve using the queue?
Have a look at theMultiprocessing Best Practices, as it might get tricky.
No, plain Python types won’t be pushed to the GPU. You would have to create a tensor and register it as an nn.Parameter (if trainable) or buffer (using self.register_buffer, … |
Shisho_Sama | Hi everyone.I come from a C++/C# background and this has made me thinking for sometime now! Here is my question :SincePytorchhas a dynamic nature, there will be many situations in which you’d be dealing with different classes on the fly and checking for which classes you are dealing with.Currently one way to access the... | ptrblck | The isinstance comparison is working:
resnet18 = models.resnet18(pretrained=True)
resnet18.fc = nn.Linear(512, 10)
for module in resnet18.modules():
if isinstance(module, nn.Linear):
print(module)
> Linear(in_features=512, out_features=10, bias=True)
as it returns the only nn.Linear … |
Shisho_Sama | Hello All, I’m trying to fine-tune a resnet18 model.I want to freeze all layers except the last one. I didresnet18 = models.resnet18(pretrained=True)
resnet18.fc = nn.Linear(512, 10)
for param in resnet18.parameters():
param.requires_grad = FalseHowever, doingfor param in resnet18.fc.parameters():
param.requir... | ptrblck | Your code works.
After running your code snippets, you can print the requires_grad attributes:
for name, param in resnet18.named_parameters():
print(name, param.requires_grad)
which shows, that fc.weight and fc.bias both require the gradient.
You will also get a valid gradients in these laye… |
Pritesh_Gohil | I have batch size = 5my network output is given by the following codeOutput = F.upsample(per_frame_logits, t, mode='linear')Shape of output is = torch.Size([5, 2, 64])Shape of target is = torch.Size([5]) (i.e. ex [1.0, 0.0, 0.0, 1.0, 1.0])Then i pass it to following loss functionloss = F.binary_cross_entropy_with_logit... | ptrblck | If you would like to classify each video sequence (64 frames) to a single class (binary classification), your output and target should both have the shape [batch_size, 1].
To achieve this you would need to reduce the model’s output, e.g. using an nn.Linear layer as the final classifier. |
talhak | As the title clearly describes, theaccuracyof myCNNstays the same when thecriterionis selected asCrossEntropyLoss. I especially selectedCrossEntropyLosssince only it achieves thetest lossclose to thetraining loss. No issues at all for the other loss functions.Here is the overview of the constructedCNNmodel:MyNet(
(ac... | ptrblck | Balancing the dataset should trace the accuracy of the majority class for an increase in the accuracy of the minority classes.
I’ve created a tutorial a while agohere, which is quite old by now, but might give you some insight. |
Andrea_Rosasco | I’ve noticed that if I take slices of a big tensor with the standard numpy syntax (a = b[0:2]) and then save it to a file with pickle, the size is for the two tensors is the same.What is actually happening?I found that I can make the change of size effective by converting the newly created tensor to a numpy vector and ... | ptrblck | a and b will share the same memory, but some attributes in a such as the size and possibly storage_offset will be changed. Here is a small example
b = torch.zeros(3, 2)
a = b[1:3]
print(b)
> tensor([[0., 0.],
[0., 0.],
[0., 0.]])
a[:] = 1.
print(b)
> tensor([[0., 0.],
[1., 1… |
ysleer | The size of y1, y2, y3 is different so ‘torch.cat’ is not used.input_shape = [5, 256, 4, 64, 64]y1_shape = [5, 128, 4, 64, 64]y2_shape = [5, 128, 2, 62, 62]y3_shape = [5, 128, 1, 62, 62]The code is shown below.class _test(nn.Sequential):
def __init__(self, num_input_features):
super(_test, self).__init__()
... | ptrblck | You could add padding=1 to the conv layers in b2 and b3, which would keep the spatial size.
EDIT: For b3 you would need to pad the output in dim2, as you won’t get the same output shape for a kernel_size of 4 and padding of 1. |
nandof | Consider a network(i) -> (h) -> (o)wherei,h,o, are input, hidden, and output layers, respectively.I would like to associate a lossLhand a lossLoto layershando, respectively. However, I wish to backpropagateLhonly from layerh, backward, and lossLofrom layerobackward.Could anyone please point me through the right directi... | ptrblck | Here is a small example:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(10, 10)
self.fc2 = nn.Linear(10, 10)
self.act = nn.ReLU()
def forward(self, x):
x1 = self.act(self.fc1(x))
x =… |
Can_Keles | I tried training a UNet model written in pytorch but i cant seem to make it work. I tried training on a single image (the dataset is Carvana) for 500 epochs but the output is pure black. Any help would be appreciated.Here is the link to my Kaggle kernel:Carvana-Pytorch | ptrblck | Did you make sure the target tensor do represent the valid segmentation mask?
Your current code is:
class MyDataset(Dataset):
def __init__(self, image_paths, mask_paths, train=True):
self.image_paths = image_paths
self.mask_paths = mask_paths
def transforms(self,… |
styx97 | Hi All,I have a network that takesthreeimages in the input layer. Now the three images must be frames of the same video (this can be known only from the filename of the image). I understood how to change the dataloader’s__getitem__to send multiple inputs fromhere. But how do I make sure three images from the same video... | ptrblck | Here is a small dummy example using multiple video folders.
Note that I’ve used tensors directly, so you should add your frame loading logic into the Dataset.
class MyDataset(Dataset):
def __init__(self, videos, transform=None, nb_frames=3):
self.nb_frames = nb_frames
self.tran… |
zhao_jing | When SPP is invoked, the system reports errors:code:import torch
import math
import torch.nn.functional as F
def spatial_pyramid_pool(previous_conv, num_sample, previous_conv_size, out_pool_size):
for i in range(len(out_pool_size)):
kernel_size = (math.ceil(previous_conv_size[0] / out_pool_size[i]), math.ce... | ptrblck | nn.MaxPool2d is a module, so you would have to pass the tensor to it:
pool = nn.MaxPool2d(kernel_size, stride)
x = pool(previous_conv)
It looks like you are trying to pass the tensor directly to the constructor of the class.
The functional approach (using F.max_pool2d) should also work. |
goffta | Ah, thanks for catching that silly error. It should be idx+i, then. Doing so shouldhopefullygive me the correct shape. I must have a fundamental misunderstanding of what’s actually happening here. After making the change in thegetitemmethod of the custom dataset to:defgetitem(self, idx):data = torch.zeros(100, 2)for i ... | ptrblck | The batch index 19 would get the last part of the dataset wouldn’t it?
Using 400 samples, a sequence length of 100 and a batch size of 2 seems to work:
class OUDataset(Dataset):
def __init__(self, window_size=100):
self.oudataframe = pd.DataFrame(np.random.randn(400, 2))
self.window_size… |
ibraheemmoosa | Dropout and Batch-Norm already have this kind of behavior. In other words what a Dropout or Batch-Norm module outputs when it is in eval mode is different from when it is in train mode. How can I achieve something similar with my custom module? | ptrblck | You could use the internal self.training attribute.
Here is a dummy example:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc = nn.Linear(10, 10)
def forward(self, x):
x = self.fc(x)
if self.training:
… |
copyrightly | I want to use a custom filter in CNN. The filter has size 5*5 and each entry is a function of three variables: theta, Lambda, psi. There are two convolutional layers followed by two fully connected layers. I tested my filter on MNIST dataset. But when I run it on GPU, I encounter the error:RuntimeError: expected backen... | ptrblck | Try to use nn.Parameter for your return values in whole_filter and one_filter, as this will properly register these filters as internal parameters, and will thus push them also to the GPU in the model.to(device) call. |
maralm | Is that possible to load one specific layer of the model from the pretrained checkpoint? | ptrblck | If you just want to load a single layer, this code should work fine:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = nn.Linear(10, 10)
self.fc2 = nn.Linear(20, 20)
self.act = nn.ReLU()
def forward(self, x):
… |
Animesh_Kumar_Paul | I am trying to implement the following general NN model (Not CNN) using Pytorch.Boki3HCcAbmFrCHLfyLEOUaQOQlTffYSGi5iAzGyne_dG3YUbonkl5O8n0iUcWSDQQHdxiZON-l2SYksF8L2RI5hjO4MQTRGQPdbtJqn0Z1EIQAf8YnhSvVNnqNwJXLUGpoQRMvowvQ768×584Here, 3rd, 4th, 5th layers are fully connected-- and Network 1,2, 3 itself are fully connected... | ptrblck | The parameters of MySmallModels are most likely missing in model.parameters(), since you are storing them in a plain Python list, thus the optimizer is ignoring them.
Try to use self.networks = nn.ModuleList instead. |
KFrank | Hi Forum!Would anybody know of a pre-built pytorch windows / CUDA 3.0version? (It’s windows 10, if that matters.)I’m aware that pytorch no longer formally supports older CUDAversions, but I have seen older pre-built packages floatingaround on the internet – just not this configuration.(I will be installing pytorch on ... | ptrblck | Hi Frank,
I assume you are referring to the compute capability 3.0, which should work with CUDA6.0 - CUDA10.1.
If I’m not mistaken, the minimal compute capability for the current binaries is >=3.5, so you could build from source to support this older GPU.
However, if you would like to play around… |
zahra | Hi,I want to assign filter = [[[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]]as weight of convolution layer. Is this command ok?self.conv1 = conv2d(...)
self.conv1.weight = Parameter(filter)Thanks | ptrblck | I would recommend to wrap the assignment in a with torch.no_grad() block just to make sure Autograd won’t complain later. |
Rahul_Yadav | Hi,What are criteria for choosing “dim=0 or 1” for nn.Softmax and nn.LogSoftmax | ptrblck | Usually you would like to normalize the probabilities (log probabilities) in the feature dimension (dim1) and treat the samples in the batch independently (dim0).
If you apply F.softmax(logits, dim=1), the probabilities for each sample will sum to 1:
# 4 samples, 2 output classes
logits = torch.ra… |
prabhuteja12 | Hi,I’m trying to understand the difference between aDatasetandDataLoaderfor a specific case. TheDataLoaderallows us to specify a sampler.Lets say I’ve a sampler that looks like the following.class MyAwesomeSampler(Sampler):
def __init__(self, indices):
self.indices = indices
def __iter__(self):
... | ptrblck | Your custom sampler and the Subset will yield the same data samles, if you don’t use shuffle=True for the DataLoader using the Subset.
The main difference is, that a custom sampler can do much more than just returning a subset of the data.
E.g. the WeightedRandomSampler implements a sample weight,… |
muon | I am trying to rewrite inference part so as to also return hidden layer activations like embeddings.is this correct implementation, any potential issues with this ?class FeatureExtration(torch.nn.Module):
def __init__(self, pretrained_model):
super().__init__()
self.__dict__ = pretrained_model.__di... | ptrblck | If you would like to return additional values in the forward method, but keep the model at it was otherwise, you could directly derive your class from the base model:
class FeatureExtractedModel(BaseModel)
This would make the implementation cleaner in my opinion. |
tkelestemur | Hello all,I have a network that generates kernel weights for a 2D convolution operation. It takes a single input and generates a weight vector which then reshaped into KxK kernel where K is the kernel size. Finally, I apply this kernel to an image. I’m trying to make this work with batches. So when the network generate... | ptrblck | Since you are using single channel images, you could swap the batch and the channel dimension and use a grouped convolution:
class FilterNet(nn.Module):
def __init__(self, obs_size, hidden_size, kernel_size, activation_func='tanh'):
super(FilterNet, self).__init__()
self.kernel… |
fyy | I want to use the inception_v3 framework that comes with torchversion ,but it nake a mistake.model.fc = nn.Sequential(nn.Linear(2048,512),nn.ReLU(),nn.Dropout(0.2),nn.Linear(512,5),nn.LogSoftmax(dim=1))for epoch in range(epochs):for inputs,labels in train_loader:inputs,labels = inputs.to(device),labels.to(device)optim... | ptrblck | By default the inception model returns two outputs, the output of the last linear layer and the aux_logits.
If you don’t want to use the aux_logits for your training, just index out at 0:
loss = criterion(out[0], labels)
If you are training from scratch, you might just disable it the aux_logits: m… |
johannes.br | Hi folks,I am interested in your view or best practices ontraining, validation & test strategies!For a research project, I am working on using a CNN for defect detection on images of weld beads, using a dataset containing about 500 images. To do so, I am currently testing different models (e.g. ResNet18-50), as well as... | ptrblck | I always have a look at@rasbt’sblog post about CV, which explains the model selection in CV very well. |
Soumyajit_Das | import torchimport torch.nn as nnimport torch.optim as optimimport torch.nn.functional as Fimport torchvisionimport torchvision.transforms as transformsimport numpy as npfrom torch.utils.data.dataset import Datasetckpt_path=’/home/students/soumyajit_po/hsd_cnn_code/SOUMYA/checkpoint/vggCifar10TEST.pth’checkpoint=torch.... | ptrblck | Your script should already thrown an error in from model import vgg, since model doesn’t seem to be a valid module.
I would recommend to look intoPython modulesto get an idea how your model should be defined inside vgg.py.
That being said, I would recommend to save and load the state_dict approa… |
Valiox | I’d like to know the torch dtype that will result from applyingtorch.from_numpy(array)without actually calling this function. Since torch and numpy dtypes are incompatible (e.g. doingtorch.zeros(some_shape, dtype=array.dtype)will yield an error), how can I do that? | ptrblck | I’m not sure, ifthis methodis exposed in the Python API, but you might create a custom dict mapping the numpy dtypes to PyTorch ones. |
hcl | Q1: How doesBatchNorm1d()judge the currentforward()is training or inference? Is there some parameters can be observed and setted manually?Q2: Specifically speaking, I’m trying to implement a reinforcement learning task. While in the training process, the transition tuple <state, action, state_next, reward> has to be ge... | ptrblck | The internal .training attribute determines the behavior of some layers, e.g. batch norm layers.
If you call model.train() or model.eval() (or model.bn_layer.train()), this internal flag will be switched.
If you are using a single sample as your batch, you might consider using other normalizat… |
nurettinabaci | Hello, I havethis datasetcontains the labels of english letters and its points, I want to train yolov3 with that dataset so I need to use anchor images, but before that I need to convert this file into original images. I found thisscriptto convert but it didn’t help me so much. Do anyone know any other way to train yol... | ptrblck | There seem to be a few scripts which are loading the data and visualizing a few examples using matplotlib.
E.g. have a look atthis script, which loads the data using pandas.
After loading, you can directly index the DataFrame using .iloc and reshape the numpy array to [28, 28] in order to get the… |
bala | Tensor.backward, as per documentation, frees the computation graph after the call to backward unless retain_graph is set to True. This is the exactly the behaviour I observed for the following example.x = torch.ones(1., requires_grad=True)y = torch.ones(1., requires_grad = True)w = x+yu=2*wu.backward()u.backward()2nd b... | ptrblck | Similar tothis question: |
111116 | In the source code, there is float(scale_factor),but the document supports tuple. | ptrblck | The current master branch supports a tuple for the scale_factor (line of code).
Which PyTorch version are you using?
It looks like@vishwakftwadded this functionality inthis PR. |
bulubulubu-Yu | Hello, I have some questions about torch.unique().For a cpu tensor:input = torch.tensor([[2,5,7,6],[9,7,4,8],[1,3,2,3],[2,5,7,6]])
input
tensor([[2, 5, 7, 6],
[9, 7, 4, 8],
[1, 3, 2, 3],
[2, 5, 7, 6]])
torch.unique(input)
tensor([3, 1, 8, 4... | ptrblck | Depending on the underlying implementation the tensor is sorted e.g. for performance reasons.
All CUDA tensors are sorted by default, due to limitations in thrust. |
RicLaGra | Hello everyone, can anyone suggest me the right approach to get from datafeaturesandoutputfromsoftmaxusing VGG19?I watched the class of VGG, but that return only the features. Is it possible to obtain the value from the softmax? I need to this for the cross-entropy and to the testing phase.Thanks in advance. | ptrblck | F.log_softmax is fine if you are using nn.NLLLoss. |
pytorchuser | I’m implementing an algorithm that involves some tricks to allow parallelism in the forward runs and gradient computations during the training process. I’m doing these computations using the multiprocessing library, which seems to mean that I can’t set requires_grad=True for my variables even if I do not use the backwa... | ptrblck | The optimizers should still work, as they are just using the .grad attribute of each passed parameter:
x = torch.zeros(1)
optimizer = torch.optim.SGD([x], lr=1.)
x.grad = torch.tensor([10.])
optimizer.step()
print(x)
> tensor([-10]) |
Joel_Wu | I’m trying building pytorch from source following thisinstruction. However, I encounter an error below, what am I missing?In file included from ../caffe2/contrib/aten/aten_op.cc:1:0:
./caffe2/contrib/aten/aten_op.h: In lambda function:
./caffe2/contrib/aten/aten_op.h:9551:33: error: ‘pstrf’ is not a member of ‘at’
... | ptrblck | Could you try to sync and update the submodules again, run python setup.py clean and rebuild it again? |
yui_88 | My goal is to train a CNN where the initial FC layer is concatenated with additional data as described here:Source:https://discuss.pytorch.org/t/concatenate-layer-output-with-additional-input-data/20462?u=yui_88I was able to build such a model with a vgg16 base.class MyModel(nn.Module):
def __init__(self, model, da... | ptrblck | Could you try to isolate the iteration which causes the NaNs and check the input for invalid values as well as the loss in this and the last few iterations? |
Haimin_Hunter_Zhang | Hi guys, please see the following image.image779×343 7.3 KBI don’t get why the third element of a.grad is -0.333. Could anyone fill me in? | ptrblck | The gradients you are seeing is accumulated from the division and the max operation.
Here is the step by step approach:
a = torch.tensor([1., 2., 3.], requires_grad=True)
# Get div gradients
y = a / a.max().detach()
y.backward(torch.ones_like(y))
print('div grad: ', a.grad)
a.grad.zero_()
# Get … |
arnold | I’m experiencing memory leak when using a linear layer and a Relu layer.def forward(self, noise, elem_class):
process = psutil.Process(os.getpid())
print("Memory 1.1: ", process.memory_info().rss, "bytes", flush=True)
in_vector = torch.cat((noise, elem_class), dim=-1)
process = psutil.Pr... | ptrblck | Could you post an executable code snippet to reproduce this issue?
Using the forward method and removing undefined parts of the code does not result in a memory leak:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.shared_gen_linear = nn.Linea… |
SamChung_Hwang | loss1 is ok, but loss2 makes the error “the derivative for ‘target’ is not implemented”Why the error occurs ?import torchimport torch.nn as nnfrom torch.autograd import Variablefrom torch.autograd import Variableimport torch.nn.functional as Fm = nn.Sigmoid()loss = nn.BCELoss()a = Variable(torch.Tensor([[1,2],[3,4]]), ... | ptrblck | You are passing a target tensor, which requires gradients (labels) in the second use case.
Since the derivative for the target is not supported for nn.BCELoss, you should detach it before calling loss_fn. |
kombucha | Hi guys,I am working withArcFaceLoss, code taken from:https://github.com/ronghuaiyang/arcface-pytorch/blob/master/models/metrics.py.Here is the following snippet:class ArcMarginProduct(nn.Module):
r"""Implement of large margin arc distance: :
Args:
in_features: size of each input sample
... | ptrblck | label.view(-1, 1).long() contains invalid indices for the scatter_ operation.
Since one_hot has the shape [32, 1108], and you are trying to scatter into dim1, label should be clamped at [0, 1108]:
label = label.clamp(0, 1108)
one_hot.scatter_(1, label.view(-1, 1).long(), 1) |
spacemeerkat | I have a neural network model that I have mapped to a GPU device (hence the CUDA network description in the topic title) and during training I wish to put the entire training set through the network. (For exploratory purposes,notfor training)If I was in evaluation mode for a test set I would map the saved (trained) mod... | ptrblck | I assume “overloading” means your GPU is running our of memory?
If so, you could try to wrap this special forward pass in a with torch.no_grad() block so avoid storing the intermediate activations (which are not needed, if you don’t plan on calling backward).
If that doesn’t help and you are still… |
amirhf | Hi,I’m trying to train some part of a model like below:IMG_5BC31395F3B4-11349×880 733 KBinput is high dimensional and I’m using a simple NN on a small partition of the data (f0) to reduce dimension and then concatenate with the rest of the data (f1) on which nothing has been applied. then I pass them to a frozen modelM... | ptrblck | A dummy approach would be:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.fc = nn.Linear(4, 2)
self.base = models.resnet50()
def forward(self, x):
# split x to x0, x1
x0, x1 = x[:, :4], x[:, 4:]
x0 … |
ellax123 | I am encountering some very strange behavior with my model. I am trying to take the feature extraction layers of ResNet34 and add a final classifier layer onto the end. When I change the final nn.Linear layer from a binary output to a multiclass output, the gradient disappears and my model fails to update its weights.P... | ptrblck | You are creating a new tensor as your loss, thus detaching the original output of your criterion from the computation graph:
loss = torch.tensor(criterion(output_var, y_batch), requires_grad=True)
Instead just call:
loss = criterion(output, y_batch)
loss.backward()
Note, that nn.CrossEntropyLoss … |
spnova12 | Can “set_grad_enabled” replace “no_grad” and “enable_grade”? | ptrblck | set_grad_enabled can be used as a function or context manager as an alternative for torch.no_grad and torch.enable_grad. |
adishegde | I wanted to save my model while training every few epochs and was wondering about the best way to go about it. The approach suggested inthis linkseems to be a common/popular way to do so.However, I don’t fully understand how the above method works. By callingmodel.cpuand thenmodel.cudawon’t we be creating new objects f... | ptrblck | The push to the CPU and back to GPU shouldn’t be a problem, as the id of the parameters shouldn’t change, thus the optimizer still holds valid references to the parameters.
However, I would suggest to use the same device after storing the state_dict, since internal states of the optimizer (e.g. usi… |
sudocoder | Does the following cause parameter sharing between the conv layers?self.conv = nn.Conv2d(channels_in, channels_out)
layers = []
for _ in range(num_iters):
layers.append(self.conv)
self.model = nn.Sequential(*layers)If so, does the following remedy it?layers = []
for _ in range(num_iters):
layers.append(nn.Con... | ptrblck | In the first code snippet you will use the same conv layer num_iters times, so yes the parameters will be shared (or rather reused).
The second code snippet created num_iters new conv layers, each containing new parameters. |
shivangi | Step 1 : I am loading pretrained xception model on ImageNet and fine-tuning for binary classification on my dataset.from pretrainedmodels.models.xception import Xception
self.xception_model = Xception(num_classes=1000)
.
.
.
.
checkpoint = torch.load('/home/shivangi/Desktop/Projects/pretrained_models/checkpoints/xcepti... | ptrblck | It looks like the actual factory to create the model is defiendhere, i.e. as pretrainedmodels.models.xception(), while you created an instance of xception.Xception manually.
Since self.last_linear is only redefined in the factory (line of code), you could try to set the last_linear again to your c… |
ajhanwar | Hey all! I’m using the MNIST dataset available throughtorchvisionand trying to use transform operations to create synthetic data.In addition to a regulartrain_setwhere I only usedtransforms.ToTensor(), I wrote the following with the intention of appending it to the originaltrain_set:train_set2 = torchvision.datasets.MN... | ptrblck | You are directly indexing the underlying non-transformed data using train_set2.data.
Try to index the Dataset, to get the transformed tensors train_set2[index]. |
blackbirdbarber | Is there any way to get id of module when I need that.I can currently have a name but names may be duplicates:for c in model.children():
name = c._get_name() | ptrblck | for name, moduke in model.named_modules(): # or model.named_children():
print(name)
should return the module names, which should be unique.
Would this work for you? |
tjl | I am trying to use the given vgg16 network to extract features (not fine-tuning) for my own task dataset,such as UCF101, rather than Imagenet. Since vgg16 is trained on ImageNet, for image normalization, I see a lot of people just use the mean and std statistics calculated for ImageNet (mean=[0.485, 0.456, 0.406], std... | ptrblck | This should work:
class MyDataset(Dataset):
def __init__(self):
self.data = torch.randn(100, 3, 24, 24)
def __getitem__(self, index):
x = self.data[index]
return x
def __len__(self):
return len(self.data)
dataset = MyDataset()
loader = Dat… |
vip | The current load_state_dict API with strict=False returns an IncompatibleKeys named tuple which is misleading in the case of successful loading of weights. I don’t think IncompatibleKeys is the correct name for a return object for loading the state dict. I was thrown off for a while trying to figure out why I was repea... | ptrblck | This issue was trackedhereand should be fixed in the current master or nightly build by now.
Could you check it again with one of the current versions? |
Deeply | I am trying to move the image to the GPU during transforms.Compose but I am getting the errortransforms.Lambda(lambda x: x.to(device)),
RuntimeError: CUDA error: initialization errorI need to do this as I am using one of the trained models during Compose.transformation; something like:device = torch.device('cuda')
tra... | ptrblck | If you are using multiple workers in your DataLoader, multiple initializations of the CUDA context might yield this error.
Try to use the spawn method for multiprocessing as describedhereor alternatively use a single worker (num_workers=0). |
NCTX | I ran into some issues with occasionally getting a NaN during the forward pass which leads to my loss function becoming NaN as well and breaking the training process. Since the graphs I’m generating are quite complex, it’s difficult for me to pin down just what in the forward pass causes the NaNs.I tried usingtorch.aut... | ptrblck | What output does detect_anomaly yield?
Were you able to isolate the NaN to a few (or a single) iteration?
If so, you could use forward hooks and store temporarily each submodules output in order to track down the source of the first NaN occurrence. |
John_Deterious | I have a model, it is a bit complicated, and I want parts of it to be grouped under one name and other part, ditto. The reason why I want this is so that I can train the parts individually, specifically, so that I can pass the parameters of that part alone to the optimizer. How can I do that?To be concrete, here’s a sn... | ptrblck | You could create a custom submodule inside your main module:
class MySubmodule(nn.Module):
def __init__(self):
super(MySubmodule, self).__init__()
self.feat1 = nn.Conv2d(1, 1, 3, 1, 1)
# ...
def forward(self, x):
x = self.feat1(x)
return x
… |
ahmed | I am trying to plot a loss curve by each epoch, but I’m not sure how to do that. I can do it for 1 epoch using the following method:def train(model, num_epoch):
for epoch in range(num_epoch):
running_loss = 0.0
loss_values = []
for i, data in enumerate(trainloader, 0):
images, l... | ptrblck | You could use theImageNet exampleor the following manual approach:
for epoch in range(num_epochs):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
running_loss =+ loss.item() * images.size(0)
loss_values.append(running_loss / len(train_dataset))
plt.plot(loss_va… |
lorenzo_fabbri | I’m using ResNet18 for a classification task.I tried using the pretrained model and training it from scratch: one thing that bothers me is that the time per epoch is more or less the same for both. On my GPU (GTX 1060), it takes roughly 19 minutes if I use the pretrained model, and around 23 minutes if I train it from ... | ptrblck | If you train all layers, it’s obviously expected, since you won’t save any computations.
However, if you freeze some layers, you might save the backward computation, since you don’t need the gradients before a certain layer.
In your use case, it seems you are retraining the input layer, thus the b… |
cat-loves-donuts | Well, when I finally upgraded my final project codes, I found a very interesting thing that I tried to reduce the feature dimensions after each conv layers. I had 3 conv layers and the input image have 3 dimensions and 28X28 size. The size would not change because I used padding to keep size the same. After the first c... | ptrblck | Do you mean the number of channels by “feature dimension”?
If so, you could reduce it by using another conv layer with the desired number of output channels. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.