id
stringlengths
3
8
text
stringlengths
1
115k
st32668
Hi, I am pretty new to deep learning let alone geometric deep learning. Nonetheless, I would prefer to start with some best practices from the beginning - such as using lightning with PyTorch. However, I have some trouble converting the temporal graph-specific structure of the training loop to lightning. So far, it is really unclear for me how to manually iterate the snapshots. github.com/benedekrozemberczki/pytorch_geometric_temporal [question] link prediction - how to formulate the dataloader in a non-regression way 5 opened May 15, 2021 geoHeil How can I perform spatio-temporal link prediction on an unweighted graph with fe…atures on the edges? My graph is a `DynamicGraphTemporalSignal`, but I do not want to regress on some signal, rather perform link prediction as also outlined in https://pytorch-geometric-temporal.readthedocs.io/en/latest/_modules/torch_geometric_temporal/nn/recurrent/gc_lstm.html?highlight=link But from looking at the example code of: https://github.com/benedekrozemberczki/pytorch_geometric_temporal/blob/4fb610326811906eb4f95152a80f5df3f62fb459/test/recurrent_test.py#L305 it is still unclear to me how to create a suitable data loader. So far I have looked into all the available ones from https://github.com/benedekrozemberczki/pytorch_geometric_temporal/tree/master/torch_geometric_temporal/dataset and think that the Twitter tennis data loader https://github.com/benedekrozemberczki/pytorch_geometric_temporal/blob/master/torch_geometric_temporal/dataset/twitter_tennis.py is the most suitable one. However, even this one seems to be stuck in formulating a regression problem. > NOTICE: even though the edge has features such as location, time, and hobby when making a prediction I am happy when only predicting a new suitable link from a topological perspective even if the features such as time, location, or hobby would not be required to match the ground truth data when evaluating a match on the test dataset. Please find the code to produce the dummy data below. It also contains the transformations I have come up with so far from looking at existing data loaders. But for me, it remains unclear how to structure the data loader for a link prediction problem and not for a regression. <img width="618" alt="JupyterLab" src="https://user-images.githubusercontent.com/1694964/118352217-7c30e880-b560-11eb-8a91-e8d1879b7a23.png"> ``` import pandas as pd import numpy as np n_people = 20 links = 80 seed = 47 time_steps = 10 hobby_categories = 3 np.random.seed(47) df_dummy = pd.DataFrame({'person_1':np.random.randint(0, n_people-1, links), 'person_2':np.random.randint(0, n_people-1, links), 'time':np.random.randint(0, time_steps-1, links), 'lat': np.random.uniform(10,19, links), 'lng':np.random.uniform(45,49, links), 'hobby':np.random.randint(0, hobby_categories-1, links)}) display(df_dummy.head()) df_dummy['edge_index'] = df_dummy[['person_1', 'person_2']].values.tolist() df_dummy['edge_features'] = df_dummy[['lat', 'lng', 'hobby']].values.tolist() df_dummy = df_dummy[['time', 'edge_index', 'edge_features']] display(df_dummy.head()) df_dummy = df_dummy.groupby(['time']).agg(lambda x: list(x)) display(df_dummy.head()) ``` ## edit I guess somehow the target must be the lagged edge-index of a future time index? Perhaps even of any future time index? depending on the forecast horizon. Perhaps something along these lines would work? Here in this example a prediction horizon with an unlimited boundary is assumend. ``` current_timestep = 3 # get the n+1 future_edges_target = pd.DataFrame(df_dummy.loc[current_timestep +1:].edge_index).explode('edge_index').edge_index#.unique() # as the graph is undirected, sorting the edges is fine. future_edges_target = future_edges_target.apply(sorted).transform(tuple).unique() future_edges_target array([(8, 8), (1, 7), (7, 11), (2, 16), (5, 18), (11, 18), (6, 11), (2, 5), (14, 16), (6, 6), (16, 18), (9, 17), (1, 2), (0, 6), (0, 5), (0, 15), (9, 18), (9, 12), (1, 17), (2, 14), (8, 13), (1, 18), (1, 8), (14, 17), (5, 6), (3, 6), (11, 14), (10, 17), (4, 14), (7, 12), (0, 18), (13, 15), (9, 15)], dtype=object) ``` Furthermore, PyTorch geometric temporal seems to utilize a concept of temporal snapshots (!= batch size) where they assume every snapshot fully fits into memory. from tqdm import tqdm model = RecurrentGCN(node_features = 4) # chickenpox model optimizer = torch.optim.Adam(model.parameters(), lr=0.01) model.train() for epoch in tqdm(range(200)): cost = 0 for time, snapshot in enumerate(train_dataset): y_hat = model(snapshot.x, snapshot.edge_index, snapshot.edge_attr) cost = cost + torch.mean((y_hat-snapshot.y)**2) cost = cost / (time+1) cost.backward() optimizer.step() optimizer.zero_grad()
st32669
Solved by geoHeil in post #2 pytorch_geometric_temporal/dcrnn.py at a13ea7876525ed9ba7c48ec69408024346eaded3 · benedekrozemberczki/pytorch_geometric_temporal · GitHub seems to already hold the answer
st32670
pytorch_geometric_temporal/dcrnn.py at a13ea7876525ed9ba7c48ec69408024346eaded3 · benedekrozemberczki/pytorch_geometric_temporal · GitHub 46 seems to already hold the answer
st32671
hello, I can not in phase test after changing one layer, to giving data for changed model and taking the images in output of test phase. please guide me for get image to changed model and take outputs… my code: import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import matplotlib.pyplot as plt from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data import DataLoader from torchvision import datasets, transforms #Converting data to torch.FloatTensor transform = transforms.ToTensor() # Download the training and test datasets train_data = datasets.MNIST(root='data', train=True, download=True, transform=transform) test_data = datasets.MNIST(root='data', train=False, download=True, transform=transform) #Prepare data loaders train_loader = torch.utils.data.DataLoader(train_data, batch_size=32, num_workers=0) test_loader = torch.utils.data.DataLoader(test_data, batch_size=32, num_workers=0) #Define the Convolutional Autoencoder class ConvAutoencoder(nn.Module): def __init__(self): super(ConvAutoencoder, self).__init__() #Encoder self.conv1 = nn.Conv2d(1, 16, 3, stride=2, padding=1) self.conv2 = nn.Conv2d(16, 8, 3, stride=2, padding=1) self.conv3 = nn.Conv2d(8,8,3) #Decoder self.conv4 = nn.ConvTranspose2d(8, 8, 3) self.conv5 = nn.ConvTranspose2d(8, 16, 3, stride=2, padding=1, output_padding=1) self.conv6 = nn.ConvTranspose2d(16, 1, 3, stride=2, padding=1, output_padding=1) def forward(self, x): x = F.relu(self.conv1(x)) x = F.relu(self.conv2(x)) x = F.relu(self.conv3(x)) x = F.relu(self.conv4(x)) x = F.relu(self.conv5(x)) x = F.relu(self.conv6(x)) return x #Instantiate the model model = ConvAutoencoder() print(model) def train(model, num_epochs=20, batch_size=64, learning_rate=1e-3): torch.manual_seed(42) criterion = nn.MSELoss() # mean square error loss optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=1e-5) # <-- # train_loader =train_loader; outputs = [] for epoch in range(num_epochs): for data in train_loader: img, _ = data recon = model(img) loss = criterion(recon, img) loss.backward() optimizer.step() optimizer.zero_grad() print('Epoch:{}, Loss:{:.4f}'.format(epoch+1, float(loss))) outputs.append((epoch, img, recon),) return outputs model = ConvAutoencoder() max_epochs =10 outputs = train(model, num_epochs=max_epochs) for k in range(0, max_epochs, 9): plt.figure(figsize=(9, 2)) imgs = outputs[k][1].detach().numpy() recon = outputs[k][2].detach().numpy() for i, item in enumerate(imgs): if i >= 9: break plt.subplot(2, 9, i+1) plt.imshow(item[0]) for i, item in enumerate(recon): if i >= 9: break plt.subplot(2, 9, 9+i+1) plt.imshow(item[0]) a=(ConvAutoencoder().conv3.weight) a0=a[:,0,:,:] a1=a[:,1,:,:] a2=a[:,2,:,:] a3=a[:,3,:,:] a4=a[:,4,:,:] a5=a[:,5,:,:] a6=a[:,6,:,:] a7=a[:,7,:,:] a0=a1 a1=a2 a2=a3 a3=a4 a4=a5 a5=a6 a6=a7 a7=a0 a = torch.cat((a0, a1, a2, a3, a4, a5, a6, a7)) model = ConvAutoencoder() a = a.reshape(8, 8, 3, 3) model.conv3.weight = nn.Parameter(a) print(model.conv3.weight) #test phase def test(model,test_loader): with torch.no_grad(): for data in test_loader: output = model(data) return output output.view(1, 28, 28) error in test phase: NameError Traceback (most recent call last) <ipython-input-23-b8f79c214741> in <module>() 25 # plt.imshow(item) 26 ---> 27 output.view(1, 28, 28) NameError: name 'output' is not defined
st32672
The output variable is undefined in the global scope, so you won’t be able to use it there. Did you mean to use outputs instead?
st32673
I want to implement U-net from article. https://arxiv.org/pdf/1505.04597.pdf There is copy and crop operation, then 512 channels need to concatenate with 1024 channels. I have torch.Size([2, 1024, 32, 32]) after upsample middle layer, and torch.Size([2, 512, 32, 32]) after last encoder layer. And after concat operation: torch.Size([2, 1536, 32, 32]) Hence, I got: RuntimeError: Given groups=1, weight of size [1024, 1024, 3, 3], expected input[2, 1536, 32, 32] to have 1024 channels, but got 1536 channels instead , when I gave this input to my decoder layer What should I do?
st32674
I did change input size of layers - train is starting but I got: RuntimeError: CUDA out of memory. Tried to allocate 400.00 MiB (GPU 0; 11.17 GiB total capacity; 10.24 GiB already allocated; 262.81 MiB free; 10.49 GiB reserved in total by PyTorch) Is it normal that 12 GB of Collab gpu memory is not enough? And even 16 GB memory is not enough! Ok, I changed input size and batch size and now model is trainable.
st32675
Hey Admin and all, I am trying to train model called SECOND for 3D object detection on waymo data set, but model is getting over fit on waymo data set. Used hyper parameters and model architecture are both same as for kitti data set. But from observation, waymo data set is sequence, where as kitti is random. So I randomly feeding the data into the network in both data set cases. Still model is overfitting just on waymo. I am doing the batch normalization, instead of dropout and regularization. From my understanding, batch normalization gives same effect as regularization. More info about data set and model: Size of data set is almost same around 6k in both kitti and waymo? But, target instance number is different, 5k in kitti and 30k in waymo. 800 and 5k in valid and test respectively. Here target is pedestrian. Could someone help me with this problem? Thanks in advance
st32676
I have a pretrained network whose layers have similar names like the following code. Is there any way to extract the features from the intermediate layer? class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(...) self.conv2 = nn.Conv2d(....) self.conv3 = nn.Conv2d(....) def forward(self, x1): x1 = self.conv1(x1) x1 = self.conv2(x1) <-------------------- the variable that I want to visualize x1 = self.conv3(x1) x1 return x1
st32677
You could use forward hooks as described in this post 3 or rename the output activation and return it in the forward method. The latter approach might be useful in case you would like to always return this activation, while the former one is more ad hoc.
st32678
I have a set of ID labels from 0…24 that encodes 19 classes and I want basically to have a 1 hot encoding of them: if I use : target = torch.sparse.torch.eye(19).index_select(dim=0, index=target) I get index out of range which I completely understand since some labels are 24 (but the number of total classes is 19), strange but the data set is built this way., and if I use: targets=torch.nn.functional.one_hot(targets) I get a tensor of 18 columns instead of 19, does anyone knows how to solve this? even if I set nbr classes to 19 this still blocks due to the fact that some labels are 24 but refers to another lower class Thanks in advance.
st32679
Solved by ptrblck in post #2 You could map the current class indices from [0, 24] to the expected range [0, 18] for 19 classes, since your use case would otherwise work with 25 classes where some might never be used.
st32680
You could map the current class indices from [0, 24] to the expected range [0, 18] for 19 classes, since your use case would otherwise work with 25 classes where some might never be used.
st32681
Hi, I have a neural network model in pytorch that was trained on a labeled dataset where feature selection was performed (2000 → 800 features). Now I want to apply this model to an unlabeled test dataset. However, this test dataset still has the old number of features (2000). I saved the trained model using pickle and Pytorch’s state dict saving function, but both options give me dimension errors when I want to apply the model to the test set. How can I save and load my model in such a way that it works on the new data size? Thanks!
st32682
Could you post the model definition, the code raising this error, as well as the complete error message, please?
st32683
Hey there is there an efficient way to do a strided sum in pytorch? Particularly when the number of elements that fall under each stride is variable but specified? For example: a = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) stride = torch.tensor([3, 3, 4]) result = torch.strided_sum(a, stride) (something like this) Meaning, I want to sum the first 3 elements, the next 3 and the last 4 the resulting tensor would be result = torch.tensor([(1 + 2 + 3), (4 + 5 + 6), (7 + 8 + 9 + 10)]) = torch.tensor([6, 15, 34]) I would like to do this without having to loop as that would make the function too slow. Is this possible?
st32684
Solved by ptrblck in post #2 You can use scatter_add_ to accumulate these values to a new tensor. Assuming you have already calculated the stride tensor, you would need to create the index tensor from it as seen here: a = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) stride = torch.tensor([3, 3, 4]) idx = torch.tensor(sum([[i…
st32685
You can use scatter_add_ to accumulate these values to a new tensor. Assuming you have already calculated the stride tensor, you would need to create the index tensor from it as seen here: a = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) stride = torch.tensor([3, 3, 4]) idx = torch.tensor(sum([[i]*s for i, s in zip(range(stride.size(0)), stride)], [])) out = torch.zeros(stride.size(0), dtype=a.dtype).scatter_add_(0, idx, a) print(out) > tensor([ 6, 15, 34])
st32686
@ptrblck Is there a way to do this for other reduction operations? For instance if I wanted to apply a scatter_max or scatter_softmax?
st32687
I’m running into an strange error with CUDA and Pytorch when I try to use torch_scatter. RuntimeError: nvrtc: error: failed to open libnvrtc-builtins.so.11.1. Make sure that libnvrtc-builtins.so.11.1 is installed correctly. nvrtc compilation failed: Would you happen to know why this is happening? I’m running pytorch 1.8.1 + cu111
st32688
This seems to be a known issue with the CUDA11.1 pip wheels as described here 60, so you might need to use the conda binaries, a source build, or the CUDA10.2 pip wheels.
st32689
I’m trying to use 365 days to predict the next 30, for stock prediction, with 5 features (open, high, close, low, volume). I’m using a batch size of 64. My network looks like this: Input > (64, 365, 5) LSTM > (64, 365, 200) Linear > (64, 365, 100) Permute to (64, 100, 365) to fit into batch normalization Batched Normalization > (64, 100, 365) Permute to (64, 365, 100) to fit into ReLU ReLU > (64, 365, 100) Linear > (64, 365, 30) Going roughly based on this for the structure. The output I want is either (64, 30, 5) or (64, 30, 1). The 5 would be the same 5 features as the inputs, and the 1 would just be the average of the four price values or something… All the sources I looked at for this kind of thing do something like lstm_out.view(-1, hidden_dim) with the LSTM output which gives me (23360, 100) and obviously won’t work for me as it gets rid of the batch organization. I could do (64, 36500) but that’s nothing like what any of the articles I read did, it’s a ridiculous amount of hidden units, and I don’t know how I would get back to (64, 30, 5) if I went down that route.
st32690
I am trying to convert the output from a layer in my network whose size is [batch, 3] using a function which I wrote: def W300_EulerAngles2Vectors(self,x): ''' rx: pitch ry: yaw rz: roll ''' b,_ = x.shape rx=x[:,0]* (3.14 / 180.0) ry=x[:,1]* (3.14 / 180.0) rz=x[:,2]* (3.14 / 180.0) ry= ry * (-1) ''' R_x = torch.tensor([[1.0, 0.0, 0.0], [0.0, rx.cos(), -rx.sin()], [0.0, rx.sin(), rx.cos()]], requires_grad=True) R_y =torch.tensor([[np.cos(ry), 0.0, np.sin(ry)], [0.0, 1.0, 0.0], [-np.sin(ry), 0.0, np.cos(ry)]], requires_grad=True) R_z = torch.tensor([[np.cos(rz), -np.sin(rz), 0.0], [np.sin(rz), np.cos(rz), 0.0], [0.0, 0.0, 1.0]], requires_grad=True) ''' tensor_0 = torch.zeros(b) tensor_1 = torch.ones(b) print('rx',x[1][0].size(),rx.size()) R_x = torch.stack([ torch.stack([tensor_1, tensor_0, tensor_0]), torch.stack([tensor_0, torch.cos(rx), -torch.sin(rx)]), torch.stack([tensor_0, torch.sin(rx), torch.cos(rx)])]).reshape(b,3,3) R_y = torch.stack([ torch.stack([torch.cos(ry), tensor_0, torch.sin(ry)]), torch.stack([tensor_0, tensor_1, tensor_0]), torch.stack([-torch.sin(ry), tensor_0, torch.cos(ry)])]).reshape(b,3,3) R_z = torch.stack([ torch.stack([torch.cos(rz), -torch.sin(rz), tensor_0]), torch.stack([torch.sin(rz), torch.cos(rz), tensor_0]), torch.stack([tensor_0, tensor_0, tensor_1])]).reshape(b,3,3) R = torch.matmul(R_x,R_y) R = torch.matmul(R,R_z) l_vec = torch.matmul(R, torch.t(torch.tensor([1, 0, 0]))) b_vec = torch.matmul(R, torch.t(torch.tensor([0, 1, 0]))) f_vec = torch.matmul(R, torch.t(torch.tensor([0, 0, 1]))) # R @ np.array([0, 0, 1]).T return [l_vec, b_vec, f_vec] But, unfortunately, if I use the definitions of R_x, R_y, R_z in strings (comments), then it gives me error: ‘‘Only one element tensors can be converted to Python scalars’’ If I use define R_x, R_y, R_z using stacks, then it gives me error: ‘‘RuntimeError: All input tensors must be on the same device. Received cpu and cuda:0’’ I want to use the output this function in my loss function. So, I want to backpropagate. Please help. I will be very thankful for it @ptrblck
st32691
I have a binary semantic segmentation model (resnet16 + unet) which works out well but I got additional annotations so it won’t be binary anymore. I have an image and 3 separate annotation masks (.png not .json) - https://imgur.com/NIKf2CQ.png 15 How can I combine and format the masks so I can pass them to the model?
st32692
You would need to transform the annotation masks to class indices by e.g. mapping the color codes to class indices, depending on your current mask format. The linked image seems to show a binary mask, so I’m unsure if you are using 3 binary masks now or a single mask with different colors/values.
st32693
Thanks for the help! At first, I had just 1 binary mask. I got 2 more and I want to combine/format all 3 into a single mask that can be used as ground truth (so I can segment more things with just one model). The training image has a shape of (3, 224, 224) and each mask has a shape of (1, 224, 224). What should be the shape of the combined formatted mask and what values should it contain? How can I achieve that?
st32694
In that case you could map each mask to a class index assuming that the targets do not overlap and you are thus working on a multi-class segmentation use case as seen here: # Create non-overlapping masks mask1 = torch.zeros(1, 24, 24).long() mask1[:, :2, :2] = 1 mask2 = torch.zeros(1, 24, 24).long() mask2[:, 3:6, 3:6] = 1 mask3 = torch.zeros(1, 24, 24).long() mask3[:, 15:18, 15:18] = 1 # map masks to class indices mask2[mask2==1] = 2 mask3[mask3==1] = 3 # create target mask mask = mask1 + mask2 + mask3 plt.imshow(mask.squeeze(0)) print(mask.unique()) > tensor([0, 1, 2, 3])
st32695
Thanks, I will give it a shot! Although I guess the different targets do overlap since we have three classes: Roof Edge, Roof Corner, Roof Footprint. Some of them do share a part of the same pixels since corners are contained within edges and everything is contained inside the footprint. Will there be issues with your current proposed approach? What is another possible approach to overcome overlapping targets? Tried to merge them to visualise them: https://i.imgur.com/TiVULYL.png 3 I guess I can make 3 separate binary segmentation models but I am pretty sure that it’s not better.
st32696
My proposed approach wouldn’t work in this case, since the addition would create new classes. E.g. if a specific pixel location contains a class label 1 and 2, the result would be class index 3, which would be a new class representing the occurrence of both classes. This could be of course a valid approach, in case you want to create new class indices for the overlaps. On the other hand, you could also use a multi-label segmentation, where the output might contain zero, one, or multiple active classes for each pixel. In that case you would use nn.BCEWithLogitsLoss as the criterion and the target would be a multi-hot encoded mask, which can be created by stacking the binary maps. You could also stick to the multi-class segmentation use case, but would need to make sure to only keep one active class for the overlaps.
st32697
When I use num_workers >0, my threads get extremely slow randomly at the end of each iteration. Here’s part of my code: for epoch in range(1, num_epochs): for i, (x_train, y_train) in enumerate(train_batch): # y_train stands for label trainPhase_start_time = time.time() print('trainPhaseEnd-NextTrainPhaseStart:', i, ' ', trainPhase_start_time -trainPhase_end_time) x_train = x_train.type(torch.FloatTensor) y_train = y_train.type(torch.FloatTensor) x_train = x_train.to(device) y_train = y_train.to(device) predict_train = net(x_train) loss = criterion(predict_train, y_train) optimizer.zero_grad() loss.backward() # backward optimizer.step() trainPhase_end_time = time.time() print('trainPhaseStart-trainPhaseEnd:(single batch)', trainPhase_end_time - trainPhase_start_time) Every 16(num_worker) iterations, data loading may get stuck: image1772×592 273 KB And after like 100 iterations, it may happen irregularity.
st32698
So I have a trained LSTM and I want to load ONLY its rnn.weight_hh_l[k] to a new LSTM? I don’t want to load the entire state_dict, just that set of weights
st32699
Can this do the trick? import torch emb_dim = 1 hidden_dim = 2 n_layers = 2 bidirectional = False dropout = 0.1 pattern = "weight_hh_l" torch.manual_seed(0) model1 = torch.nn.LSTM(emb_dim, hidden_dim, num_layers = n_layers, bidirectional=bidirectional, dropout = 0 if n_layers < 2 else dropout) {k : v for k, v in model1.state_dict().items() if k.startswith(pattern)} """ {'weight_hh_l0': tensor([[-0.0628, 0.1871], [-0.2137, -0.1390], [-0.6755, -0.4683], [-0.2915, 0.0262], [ 0.2795, 0.4243], [-0.4794, -0.3079], [ 0.2568, 0.5872], [-0.1455, 0.5291]]), 'weight_hh_l1': tensor([[ 0.1318, -0.5482], [-0.4901, -0.3653], [ 0.3199, 0.2844], [-0.4189, 0.2136], [ 0.3882, -0.0892], [ 0.0270, 0.1638], [ 0.4387, 0.6790], [-0.5449, -0.2591]])} """ torch.manual_seed(1) model2 = torch.nn.LSTM(emb_dim, hidden_dim, num_layers = n_layers, bidirectional=bidirectional, dropout = 0 if n_layers < 2 else dropout) {k : v for k, v in model2.state_dict().items() if k.startswith(pattern)} """ {'weight_hh_l0': tensor([[ 0.0983, -0.0866], [ 0.1961, 0.0349], [ 0.2583, -0.2756], [-0.0516, -0.0637], [ 0.1025, -0.0028], [ 0.6181, 0.2200], [-0.2633, -0.4271], [-0.1185, -0.3050]]), 'weight_hh_l1': tensor([[-0.0331, -0.4720], [ 0.4306, 0.2195], [-0.4571, 0.4593], [ 0.4293, 0.6271], [-0.3964, -0.1164], [-0.0137, 0.1033], [-0.5366, -0.5018], [ 0.3847, -0.1658]])} """ state_dict = {} for item1, item2 in zip(model1.state_dict().items(), model2.state_dict().items()) : key = item1[0] # = item2[0] if key.startswith(pattern) : # or another condition ... state_dict[key] = item1[1] # take one of model1 else : state_dict[key] = item2[1] # take one of model2 model2.load_state_dict(state_dict) """ <All keys matched successfully> """ #assert {k : v for k, v in model1.state_dict().items() if k.startswith(pattern)} "costum =" {k : v for k, v in model2.state_dict().items() if k.startswith(pattern)} """ True """
st32700
Hello, I managed to implement a solution that is different to yours, but I will see if yours works too. Could you check if there are any obvious errors in my solution? torch.manual_seed(42) model_NA1 = LSTM(1, 10, 10, 1) model_NA2 = LSTM(1, 10, 10, 1) model_NA1.to(device) model_NA2.to(device) learning_rate = 0.0001 optimizer1 = torch.optim.Adam(model_NA1.parameters(), lr = learning_rate) optimizer2 = torch.optim.Adam(model_NA2.parameters(), lr = learning_rate) no_epochs = 1000 losses1 = np.zeros(no_epochs) losses2 = np.zeros(no_epochs) test_losses1 = np.zeros(no_epochs) test_losses2 = np.zeros(no_epochs) for i in range(no_epochs): optimizer1.zero_grad() optimizer2.zero_grad() # Forward pass output1 = model_NA1(x_train_model) loss1 = loss_function(output1, y_train_model) loss1.backward() optimizer1.step() losses1[i] = loss1.item() torch.save(model_NA1.state_dict(), 'W_hh.pt') state_dict = torch.load('W_hh.pt') with torch.no_grad(): model_NA2.rnn.weight_hh_l0.copy_(state_dict['rnn.weight_hh_l0']) model_NA2.rnn.weight_hh_l1.copy_(state_dict['rnn.weight_hh_l1']) model_NA2.rnn.weight_hh_l2.copy_(state_dict['rnn.weight_hh_l2']) model_NA2.rnn.weight_hh_l3.copy_(state_dict['rnn.weight_hh_l3']) model_NA2.rnn.weight_hh_l4.copy_(state_dict['rnn.weight_hh_l4']) model_NA2.rnn.weight_hh_l5.copy_(state_dict['rnn.weight_hh_l5']) model_NA2.rnn.weight_hh_l6.copy_(state_dict['rnn.weight_hh_l6']) model_NA2.rnn.weight_hh_l7.copy_(state_dict['rnn.weight_hh_l7']) model_NA2.rnn.weight_hh_l8.copy_(state_dict['rnn.weight_hh_l8']) model_NA2.rnn.weight_hh_l9.copy_(state_dict['rnn.weight_hh_l9']) #model_NA2.load_state_dict('W_hh.pt', strict = False) output2 = model_NA2(x_train_model) loss2 = loss_function(output2, y_train_obs) loss2.backward() optimizer2.step() losses2[i] = loss2.item() with torch.no_grad(): test_outputs1 = model_NA1(x_val_model) test_outputs2 = model_NA2(x_val_model) test_loss1 = loss_function(test_outputs1, y_val_model) test_loss2 = loss_function(test_outputs2, y_val_obs) test_losses1[i] = test_loss1.item() test_losses2[i] = test_loss2.item() if (i + 1) %100 == 0: print(f'Epoch {i+1}/{no_epochs}, NA1 Loss: {loss1.item():.4f}, NA2 Loss: {loss2.item():.4f}') #print(f'Epoch {i+1}/{no_epochs}, NA1 Test Loss: {test_loss1.item():.4f}, NA2 Test Loss: {test_loss2.item():.4f}') I am slightly concered in that when I run this consecutive times, it gives me different out of sample accuracy metrics. Any thoughts why this may be?
st32701
Of course your solution works, but it is agnostic to the model’s hyperparameters, and so for each model you will have to rework the code. Moreover your code becomes very long (and therefore difficult to implement) if the values of these hyperparameters become very large (which is generally the case in practice) I think this function is enough (Instead of select the parameters name by yourself…) def get_state_dic(model1, model2, pattern) : state_dict = {} for item1, item2 in zip(model1.state_dict().items(), model2.state_dict().items()) : key = item1[0] # = item2[0] if key.startswith(pattern) : # or another condition ... state_dict[key] = item1[1] # take one of model1 else : state_dict[key] = item2[1] # take one of model2 return stat_dict
st32702
That is very helpful, I will try to add this in later tonight. I shall update you with how it works. Thank you!
st32703
File “/opt/conda/lib/python3.6/site-packages/torch/utils/cpp_extension.py”, line 970, in load build_directory or _get_build_directory(name, verbose), File “/opt/conda/lib/python3.6/site-packages/torch/utils/cpp_extension.py”, line 1454, in _get_build_directory os.makedirs(build_directory, exist_ok=True) File “/opt/conda/lib/python3.6/os.py”, line 210, in makedirs makedirs(head, mode, exist_ok) File “/opt/conda/lib/python3.6/os.py”, line 210, in makedirs makedirs(head, mode, exist_ok) File “/opt/conda/lib/python3.6/os.py”, line 220, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: ‘/.cache’
st32704
It seems you don’t have permission to create folders in /, so you could try to create a /workspace folder or any other home folder and see, if Python could write to it. Alternatively you might want to change permissions inside your docker container (but you should be root by default, shouldn’t you?).
st32705
Thanks! i solved it with os.environ[‘TORCH_EXTENSIONS_DIR’] = ‘path/to/folder/inside/project’ since the code was not allowed to create folder in /, and the ‘.cache’ folder(which hold pre-trained weights and extentions) is created by default in root
st32706
Dear all, im trying to use Lasso regression for loss function, any one have an idea how to use ? thanks
st32707
Suppose you have an autoencoder (but this approch is valid for any other netweork). You could write a function that takes the current weights values and computes the L1 regulatization (or Lasso regression). For instance: def L1_reg(self): weights = torch.cat([x.view(-1) for x in self.encoder.parameters()]) L1_reg = LAMBDA_L1 * torch.norm(weights, 1) return L1_reg where LAMBDA_L1 is the lambda paramether of the Lasso (remember that this is a hyperparameter). With this little function you only compute the L1 regression on the encoder’s weights, but feel free to use also the decoder’s ones if you want to! If you want to use the Ridge, use 2 insted of 1 in torch.norm. Check the torch.linalg.norm method to better understand it. Hope I’ve been helpful!
st32708
Hi everyone! Currently, I’m trying to replicate a DeblurGanV2 network (link). At the moment, I’m working on performing the training. Here is my current status of my trainings pipeline: torch.autograd.set_detect_anomaly(mode=True) total_generator_loss = 0 total_discriminator_loss = 0 psnr_score = 0.0 used_loss_function = ‘wgan_gp_loss’ for epoch in range(n_epochs): #set to train mode generator.train(); discriminator.train() tqdm_bar = tqdm(train_loader, desc=f’Training Epoch {epoch} ', total=int(len(train_loader))) for batch_idx, imgs in enumerate(tqdm_bar): #load imgs to cpu blurred_images = imgs["blurred"].cuda() sharped_images = imgs["sharp"].cuda() # generator output deblurred_img = generator(blurred_images) # denormalize with torch.no_grad(): denormalized_blurred = denormalize(blurred_images) denormalized_sharp = denormalize(sharped_images) denormalized_deblurred = denormalize(deblurred_img) # get D's output sharp_discriminator_out = discriminator(sharped_images) deblurred_discriminator_out = discriminator(deblurred_img) # set critic_updates if used_loss_function== 'wgan_gp_loss': critic_updates = 5 else: critic_updates = 1 #train discriminator discriminator_loss = 0 for i in range(critic_updates): discriminator_optimizer.zero_grad() # train discriminator on real and fake if used_loss_function== 'wgan_gp_loss': gp_lambda = 10 alpha = random.random() interpolates = alpha * sharped_images + (1 - alpha) * deblurred_img interpolates_discriminator_out = discriminator(interpolates) kwargs = {'gp_lambda': gp_lambda, 'interpolates': interpolates, 'interpolates_discriminator_out': interpolates_discriminator_out, 'sharp_discriminator_out': sharp_discriminator_out, 'deblurred_discriminator_out': deblurred_discriminator_out } wgan_loss_d, gp_d = wgan_gp_loss('D', **kwargs) discriminator_loss_per_update = wgan_loss_d + gp_d discriminator_loss_per_update.backward(retain_graph=True) discriminator_optimizer.step() discriminator_loss += discriminator_loss_per_update.item() But when I run this code, I receive the following error message: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [1, 512, 4, 4]] is at version 2; expected version 1 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck! RuntimeError Traceback (most recent call last) in () 62 # discriminator_loss_per_update = gan_loss_d 63 —> 64 discriminator_loss_per_update.backward(retain_graph=True) 65 discriminator_optimizer.step() 66 discriminator_loss += discriminator_loss_per_update.item() 1 frames /usr/local/lib/python3.7/dist-packages/torch/tensor.py in backward(self, gradient, retain_graph, create_graph, inputs) 243 create_graph=create_graph, 244 inputs=inputs) → 245 torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs) 246 247 def register_hook(self, hook): /usr/local/lib/python3.7/dist-packages/torch/autograd/init.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs) 145 Variable.execution_engine.run_backward( 146 tensors, grad_tensors, retain_graph, create_graph, inputs, → 147 allow_unreachable=True, accumulate_grad=True) # allow_unreachable flag 148 149 Unfortunately, I can’t really trace the in-place operation that would cause this error. Does anybody maybe has an idea or advice for me? I would appreciate any input
st32709
This is a typical pre forward hook function. def pre_forward_hook_function(self, input): # Input would be tuple of size 1. To obtain the tensor x = input[0] # perform computations (simple addition/multiplication) on x and return it return x The preforward hook has the input in the form a tuple, which is immutable. So to change the input, a new variable is assigned. x = input[0] Note that here, the input I am refering to is the input that is accessed within the pre forward hook function. The problem is will this assignment on x result in breaking of the computation graph for the input(input to the network, not the input to the pre hook function) ? I have this doubt since the input of the pre hook function is a tuple and x is torch.tensor type, two different data types.
st32710
Solved by hrushi in post #2 After running the code, I can confirm this does not break the computation graph
st32711
Hello! I am working with a dataset of around 100K images ,All images are of different rectangular shapes and I tried transforms.Resize(),But it distorts most of the images and therefore I settled for a training loader with a batch size of 1 and using gradient accumulation , with images as their original size ,but even with num_workers : 0 and pin_memory : True the speed up gain after first epoch is almost negligible, I assume this is because of high resolution of images because with the same setting for smaller images it worked faster .I want to know about any other approaches I can use to speed up the training(using PyTorch) as it takes more than 45 mins to just complete one epoch.
st32712
This model is for recognizing 20 different classes of leaves from 28x28 RGB images. Capture.PNG1191×792 181 KB
st32713
The model architecture seems somewhat strange compared to typical classification architectures. What is the purpose of the sigmoid layer applied directly on the input?
st32714
Additionally to @eqy’s comment it also is uncommon to avoid using non-linear activations between the trainable layers. PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging easier and allows the search engine to index the code.
st32715
I tried to run the network inside this repository but actually when I need to update the different parts of the GAN from here I get a painfull error: /home/francesco/Desktop/test/VAE-GAN/network.py:187: UserWarning: nn.init.uniform is now deprecated in favor of nn.init.uniform_. nn.init.uniform(m.weight,-scale,scale) /home/francesco/Desktop/test/VAE-GAN/network.py:189: UserWarning: nn.init.constant is now deprecated in favor of nn.init.constant_. nn.init.constant(m.bias, 0.0) Epoch:0 /home/francesco/Desktop/test/test/lib/python3.8/site-packages/torch/nn/functional.py:1709: UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead. warnings.warn("nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.") [W python_anomaly_mode.cpp:104] Warning: Error detected in AddmmBackward. Traceback of forward call that caused the error: File "main.py", line 97, in <module> x_tilde, disc_class, disc_layer, mus, log_variances = net(x) File "/home/francesco/Desktop/test/VAE-GAN/network.py", line 224, in __call__ return super(VaeGan, self).__call__(*args, **kwargs) File "/home/francesco/Desktop/test/test/lib/python3.8/site-packages/torch/nn/modules/module.py", line 889, in _call_impl result = self.forward(*input, **kwargs) File "/home/francesco/Desktop/test/VAE-GAN/network.py", line 199, in forward mus, log_variances = self.encoder(x) File "/home/francesco/Desktop/test/VAE-GAN/network.py", line 79, in __call__ return super(Encoder, self).__call__(*args, **kwargs) File "/home/francesco/Desktop/test/test/lib/python3.8/site-packages/torch/nn/modules/module.py", line 889, in _call_impl result = self.forward(*input, **kwargs) File "/home/francesco/Desktop/test/VAE-GAN/network.py", line 75, in forward logvar = self.l_var(ten) File "/home/francesco/Desktop/test/test/lib/python3.8/site-packages/torch/nn/modules/module.py", line 889, in _call_impl result = self.forward(*input, **kwargs) File "/home/francesco/Desktop/test/test/lib/python3.8/site-packages/torch/nn/modules/linear.py", line 94, in forward return F.linear(input, self.weight, self.bias) File "/home/francesco/Desktop/test/test/lib/python3.8/site-packages/torch/nn/functional.py", line 1753, in linear return torch._C._nn.linear(input, weight, bias) (function _print_stack) Traceback (most recent call last): File "main.py", line 140, in <module> loss_decoder.backward(retain_graph=True) #[p.grad.data.clamp_(-1,1) for p in net.decoder.parameters()] File "/home/francesco/Desktop/test/test/lib/python3.8/site-packages/torch/tensor.py", line 245, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs) File "/home/francesco/Desktop/test/test/lib/python3.8/site-packages/torch/autograd/__init__.py", line 145, in backward Variable._execution_engine.run_backward( RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.FloatTensor [1024, 128]], which is output 0 of TBackward, is at version 3; expected version 2 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck! I already searched online and it seems that I’m not able to do the second backward pass because the network has already updated the variables but since it’s very delicate I’m asking you a support.
st32716
Based on the linked repository it seems you are working on a GAN-like model, so you might hit this error 10.
st32717
Can anyone help me what is the difference between these two codes? I mean what happens when we use the same layer for a second time by another variable. Any graphical model would be highly appreciated! class Net(nn.Module): def init(self): super(Net, self).init() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) def forward(self, x1,x2): x1 = self.conv1(x1) x2 = self.conv2(x2) out=x1+x2 return output class Net(nn.Module): def init(self): super(Net, self).init() self.conv1 = nn.Conv2d(1, 32, 3, 1) def forward(self, x1,x2): x1 = self.conv1(x1) x2 = self.conv1(x2) out=x1+x2 return output
st32718
The difference would be in the parameters used. The first example has two convolutions each with their own parameters (weights) while the second shares parameters across the two inputs. As is, I don’t think both versions can work at the same time because the the two convs in the first example have a different number of input and output channels implying that x1/x2 have different inputs channels. This means that in the second example self.conv(x2) isn’t possible. Summing x1 and x2 in the first example is also strange though it might be possible via broadcasting.
st32719
Thank you for your response. If we consider each generator as an encoder, the first one has two different encoders with different weights while the second one has two encoders with the shared weights. Am I correct? This is the concept of two encoders with shared weights that sometimes papers refer to it?
st32720
This is not specific programming or API-related question but more of modeling and framing of the problem statement in to PyTorch models. I am interested in training an ML model that would predict improvement in a patient’s injury. Assume doctors have collected two sets of MRI images from hundreds of patients who have suspected brain injury. The first set was taken at 2 weeks after the injury and the second set was taken 6 months after the injury. Additionally, doctors have their own assessment of the injury (say a score indicating the strength of the injury). So the patient’s recovery from the injury can be better (increase in the score and hence positive) or worse (decrease in the score and hence negative) from 2 weeks to 6 months. How to frame this problem so that I can train an ML model that takes the 2 weeks image and 6 months image as its inputs and predicts if the recovery is positive or negative? I can use the injury score provided by the doctors as a ground truth. But what sort of loss function to use to train this model in an end-to-end fashion? I know I need an ML model that takes in two inputs X and X' and outputs a score s and the score should be any positive number if the recovery is good or any negative number if the recovery is bad. I am not sure what loss function to use so that I can train the model. Note that X represents the MRI scan taken at 2 weeks and X' represents the MRI scan taken at 6 months.
st32721
I think the easy way is to approach this as [binary] classification problem, with added probability calibration 1 after training. If you want to also utilize the magnitude of change of doctor scores, perhaps KLDivLoss could be used (map value to “soft” targets like (0.9, 0.1) by some ad-hoc formula, calibrating doctors’ scores).
st32722
Screenshot 2021-05-15 at 2.19.39 AM1440×900 216 KB Here is my model: <bound method Module.state_dict of model( (hidden_layers): ModuleList( (0): Linear(in_features=3, out_features=10, bias=True) (1): Linear(in_features=10, out_features=10, bias=True) ) (output_layers): ModuleList( (0): Linear(in_features=10, out_features=4, bias=True) (1): Linear(in_features=10, out_features=4, bias=True) ) )>
st32723
I think your model input has a wrong dimension: the model expects 3 (…x3), but you give it 10 (…x10)…As the message says More details about this would be useful to help you
st32724
Thanks for reply, when first example of 1*3 is passed through first hidden layer it works, below is weight matrix 3 * 10 of first hidden layer: (Pytorch output): tensor([[ 0.4778, 0.4947, -0.4435], [-0.0535, 0.5000, 0.1650], [-0.5120, 0.5192, -0.0072], [-0.1666, 0.0537, 0.5399], [-0.5655, -0.4967, 0.0043], [ 0.1430, 0.0842, -0.4497], [-0.1533, 0.2130, -0.4762], [-0.2144, -0.3397, -0.1646], [-0.1230, -0.3268, 0.4827], [-0.4620, -0.3071, 0.3321]], dtype=torch.float64) when second example of same batch is passed then it throws error of size mismatching.Below is the weight matrix of first hidden layer after updating tensor([[-1.9652e-05, -5.2278e-04, 5.1098e-05], [ 6.4976e-06, 1.7285e-04, -1.6894e-05], [ 3.9244e-06, 1.0440e-04, -1.0204e-05], [-9.4330e-06, -2.5093e-04, 2.4527e-05], [ 8.6443e-06, 2.2995e-04, -2.2476e-05], [ 4.9573e-06, 1.3187e-04, -1.2889e-05], [-9.0200e-07, -2.3995e-05, 2.3453e-06], [-9.8638e-06, -2.6239e-04, 2.5647e-05], [ 8.2014e-06, 2.1817e-04, -2.1324e-05], [-8.1189e-06, -2.1598e-04, 2.1110e-05]], dtype=torch.float64) Dimensions are same for the second example also how could it be possible ??
st32725
I am trying to implement Attention Model to lstm, where I am trying to predict a sentiment class given a sequence. For calculating attention I have chosen a learnable decoder which will get the attention probability wrt the hidden states of the lstm. The decoder is learnable. Lastly the weighted sum of the attentions and hidden states give the context vector. I am getting very low train accuracy. The model doesn’t seem to learn much. Can you suggest anything which I can do ? What could be the reason for this ?
st32726
data_transforms = { 'train': transforms.Compose([ transforms.ToPILImage(), transforms.RandomRotation(15), transforms.RandomHorizontalFlip(), transforms.ToTensor(), ]), 'valid': transforms.Compose([ transforms.ToPILImage(), transforms.CenterCrop(224), transforms.ToTensor(), ]), } class Dataset_load(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(np.uint8).reshape((28,28,1)) label = self.data.iloc[index, 0] if self.transform is not None: image = self.transform(image) return image , label train_dataset=Dataset_load(train_dir,transform=data_transforms['train']) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True) test_dataset=Dataset_load(test_dir,transform=data_transforms['valid']) test_loader =torch.utils.data.DataLoader(test_dataset, batch_size=32, shuffle=True) import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net,self).__init__() #input depth , output depth , kernel size(filter)x self.conv1=nn.Conv2d(1,16,kernel_size=(3, 3),padding=(1, 1),stride=(1, 1)) self.conv2=nn.Conv2d(16,32,kernel_size=(3, 3),padding=(1, 1),stride=(1, 1)) self.conv3=nn.Conv2d(32,64,kernel_size=(3, 3),padding=(1, 1),stride=(1, 1)) #padding for last conv layer self.adapt = nn.AdaptiveMaxPool2d((4,4)) #padding layer self.pool=nn.MaxPool2d(2,2) #dropout layer self.drop=nn.Dropout(p=0.2) #fc layers self.fc1=nn.Linear(64*4*4,512) self.fc2=nn.Linear(512,256) self.fc3=nn.Linear(256,128) self.fc4=nn.Linear(128,24) def forward(self,x): x=self.pool(F.leaky_relu(self.conv1(x))) x=self.pool(F.leaky_relu(self.conv2(x))) x=self.adapt(F.leaky_relu(self.conv3(x))) #flatten Images x = x.view(x.size(0), -1) x=self.drop(x) x=F.leaky_relu(self.fc1(x)) x=self.drop(x) x=F.leaky_relu(self.fc2(x)) x=self.drop(x) x=F.leaky_relu(self.fc3(x)) x=self.drop(x) x=self.fc4(x) return F.log_softmax(x) model = Net() optimizer = optim.Adam(model.parameters(), lr=0.001) criterion = nn.BCEWithLogitsLoss() exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=4, gamma=0.1) if torch.cuda.is_available(): model = model.cuda() criterion = criterion.cuda() def train(n_epochs=100): for epoch in range(1, n_epochs+1): # keep track of training and validation loss train_loss = 0.0 #train model.train() for data, target in train_loader: print(data.shape) print(target.shape) if torch.cuda.is_available(): data, target = data.cuda(), target.cuda() # clear the gradients of all optimized variables optimizer.zero_grad() # forward pass: compute predicted outputs by passing inputs to the model output = model(data) # calculate the batch loss loss = criterion(output, target) # backward pass: compute gradient of the loss with respect to model parameters loss.backward() # perform a single optimization step (parameter update) optimizer.step() # update training loss train_loss += loss.item()*data.size(0) train_loss = train_loss/len(train_loader) # print training/validation statistics print('Epoch: {} \tTraining Loss: {:.6f}}'.format( epoch, train_loss)) train(10) torch.Size([32, 1, 28, 28]) torch.Size([32]) /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:61: UserWarning: Implicit dimension choice for log_softmax has been deprecated. Change the call to include dim=X as an argument. --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-73-c813bd3a9aca> in <module>() 1 from torch.autograd import Variable ----> 2 train(10) 3 frames /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight) 2159 2160 if not (target.size() == input.size()): -> 2161 raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size())) 2162 2163 return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum) ValueError: Target size (torch.Size([32])) must be the same as input size (torch.Size([32, 24]))
st32727
Solved by ptrblck in post #4 Your target should contain class indices in the range [0, nb_classes-1]. In your case this would be [0, 23]. To debug this issue, you could add a print statement and check, which target batch fails this assumption.
st32728
If you are dealing with a multi-class classification use case and your target tensor contains class indices, you should use nn.NLLLoss as your criterion. Alternatively, you could also remove the F.Log_softmax from your model and use nn.CrossEntropyLoss (identical to F.log_softmax + nn.NLLLoss). However, if you are dealing with a multi-label classification (each sample can have more than a single active class), you should remove the F.log_softmax and would have to provide a target for each class output.
st32729
thanks for replying I removed log_softmax and used CrossEntropyLoss but I got this Error Assertion `cur_target >= 0 && cur_target < n_classes' failed. at /pytorch/aten/src/THNN/generic/ClassNLLCriterion.c:92
st32730
Your target should contain class indices in the range [0, nb_classes-1]. In your case this would be [0, 23]. To debug this issue, you could add a print statement and check, which target batch fails this assumption.
st32731
Please could you tell about doing it on nn.BCEWithLogitsLoss() def real_loss(D_out): labels = torch.ones(D_out.size(0)) * 0.9 #smoothing by default criterion = nn.BCEWithLogitsLoss() if train_on_gpu: labels = labels.cuda() loss = criterion(D_out.squeeze(), labels) return loss It is giving error ValueError: Target size (torch.Size([32])) must be the same as input size (torch.Size([32, 4096])) But i tried to debug it, printed results and found that error were coming from using criterion(D_out.squeeze(), labels) I printed out shape of D_out found that torch.Size([32, 4096]) I hit trialed any possible combination to accept criterion but it throws same error. Please could you give me any idea why this kind of error is occuring in my code? Thank you for helping us
st32732
nn.BCEWihtLogitsLoss expects the model output and target to have the same shape. Based on your provided shapes, it seems that your target might have the shape [batch_size] and might contain the class indices for each sample? If that’s the case, you are dealing with a multi-class classification use case and should use nn.CrossEntropyLoss instead. Based on your model output you might also be dealing with a multi-label classification use case, where each sample might belong to zero, one, or multiple classes. If that’s the case, your target should contain values in the range [0, 1] and have the shape [batch_size, nb_classes].
st32733
Thanks explaining , after changing to torch.Size([32, 1]) error was i was returning 4096 in discriminator.
st32734
Greetings, I’m working on multi-label classification with 8 labels and BCEWithLogitsLoss as a loss function. My target is in the range [0, 7]. I’m getting this error and I can’t figure out what I should change… Any help is appreciated. 56 #labels = labels.unsqueeze(1) ---> 57 loss = loss_fn(logits, labels) 58 ~/anaconda3/envs/env/lib/python3.8/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 720 result = self._slow_forward(*input, **kwargs) 721 else: --> 722 result = self.forward(*input, **kwargs) 723 for hook in itertools.chain( 724 _global_forward_hooks.values(), ~/anaconda3/envs/env/lib/python3.8/site-packages/torch/nn/modules/loss.py in forward(self, input, target) 626 627 def forward(self, input: Tensor, target: Tensor) -> Tensor: --> 628 return F.binary_cross_entropy_with_logits(input, target, 629 self.weight, 630 pos_weight=self.pos_weight, ~/anaconda3/envs/env/lib/python3.8/site-packages/torch/nn/functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight) 2536 2537 if not (target.size() == input.size()): -> 2538 raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size())) 2539 2540 return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum) ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 8]))
st32735
Agatha: I’m working on multi-label classification with 8 labels and BCEWithLogitsLoss as a loss function. My target is in the range [0, 7]. This sounds rather like a multi-class classification (one active class per sample) and you could use nn.CrossEntropyLoss instead. nn.BCEWithLogitsLoss is used for a multi-label classification (zero, one, or multiple active classes per sample) and expects the model output and target in the same shape.
st32736
How does the target value range of [0, 7] fit this use case, i.e. if the target contains an integer the the sample, how would you select e.g. two active classes?
st32737
Its text classification using BertModel, where one text can have multiple labels. The idea of [0, 7] comes because I use PyTorch and the labels have to range from [0- n_labels-1]. Now I’m stuck because it’s said on Multilabel, nn.BCEWithLogitsLoss is applicable, but when I tried I get the above error…
st32738
Agatha: The idea of [0, 7] comes because I use PyTorch and the labels have to range from [0- n_labels-1]. That’s true for a multi-class classification use case using nn.CrossEntropyLoss or nn.NLLLoss, but wrong for a multi-label classification using nn.BCEWithLogitsLoss. For the latter use case, your targets should have the same shape as the model outputs and be multi-hot encoded, so that you can set multiple classes to “active” or “inactive” (1 and 0).
st32739
Your targets would have to be already multi-hot encoded. If your current target shape is [batch_size] and the targets contain values in [0, nb_classes-1], then they are multi-class classification targets and you could use nn.CrossEntropyLoss as described before. However, if you want to use these targets for a multi-label classification for specific reasons, you could use F.one_hot to create the expected shape for nn.BCEWithLogitsLoss.
st32740
Hi @ptrblck , How about I used criterion = nn.BCEWithLogitsLoss() in binary classification and get the Error: Target size (torch.Size([1, 2])) must be the same as input size (torch.Size([1, 1000]))
st32741
The posted shaped don’t match a binary classification case, as the input seems to have the shape [batch_size=1, nb_classes=1000], while the target has the shape [batch_size=1, nb_classes=2]. Based on the target shape it seems you are working on a multi-label classification. However based on the model output shape it seems you might have forgotten to replace the last linear layer of a pretrained classification model, so that the 1000 ImageNet class logits will be returned. The error is raised, since nn.BCEWithLogitsLoss expects the model output and target so have the same shape.
st32742
Hi I am having some trouble figuring out why my code (in particular the loss function) runs faster on a CPU (~ 0.03 sec) than on a GPU (~ 0.2 sec). Is there a way I can fix this? Here is how I define my loss: def loss(X, u_r): t1 = perf_counter() ################################# For testing X.requires_grad = True u_r_X = torch.zeros(X.shape[0], X.shape[1], X.shape[1], device=device) for i in range(X.shape[0]): u_r_X[i,:,:] = torch.autograd.functional.jacobian(u_r, X[i][None,:], create_graph=True)[0,:,0,:] energy_tensor = torch.zeros(X.shape[0], 1, device=device) for j in range(X.shape[0]): F = torch.eye(u_r_X[j].shape[0], device=device) + u_r_X[j] energy_tensor[j] = 0.5 * (torch.sum((F)**2) - 2.0) - torch.log((torch.det(F))) + 50.0 * torch.log((torch.det(F)))**2 t2 = perf_counter() ################################# For testing print(t2-t1, ' secs') ################################# For testing return torch.mean(energy_tensor)
st32743
Hi, I guess this might be caused because you create new tensors and they have to be moved to the GPU if your device is set to GPU. Regards, Unity05
st32744
You’ll have to try to not having to initialize a new tensor every time you call the loss function.
st32745
A few days ago we upgraded JetPack to v4.5 on our Xavier Ubuntu 18.04 aarch64 machine. After installing PyTorch v1.7.0 with torchvision v8.1.0 I receive the following error when running import torch in Python v3.6.9 ImportError: /lib/aarch64-linux-gnu/libc.so.6: version `GLIBC_2.28' not found (required by /home/venv/lib/python3.6/site-packages/torch/lib/libtorch_python.so) Currently there is GLIBC v2.27 installed. Do you know how can I solve this problem? I read online that upgrading GLIBC is not my best option as this requires a lot of effort and some risk as may other aprty of my system depend on GLIBC v2.27 .
st32746
Hi mate, try to run Pytorch in a docker-container. This worked for me. NVIDIA Developer Forums – 11 May 21 PyTorch and GLIBC compatibility error after upgrading JetPack to 4.5 16 Hi @dusty_nv Thanks a lot. With the docker container it is working like charm. Just one additional question. How can I save this docker image locally? Because additionally to pytorch I need to install some other dependencies and it would be messy...
st32747
In PyTorch CTC gradient takes log-probabilities as input (after log_softmax operation). It seems that the CTC gradient formula in PyTorch (cpu version for simplicity 2) refers to and seems to be implementing eq. 16 from the original CTC paper 4. Eq. 16 seems to compute gradients wrt logits, not log_probs, and PyTorch must compute gradients wrt log_probs, so it’s strange if they are using the same equation. This mismatch confuses me, I must be missing something obvious because gradcheck passes well, so the formula in PyTorch must be correct…
st32748
Solved by tom in post #2 At the risk of being the CTC person that I don’t want to be: The key that the paper is not using log space, so we are not interested in the derivative by y, but by log y. With this, we can remind ourselves that is that log probs are logits (i.e. x.log_softmax(dim=1) == x.log_softmax(dim=1).log_soft…
st32749
At the risk of being the CTC person that I don’t want to be: The key that the paper is not using log space, so we are not interested in the derivative by y, but by log y. With this, we can remind ourselves that is that log probs are logits (i.e. x.log_softmax(dim=1) == x.log_softmax(dim=1).log_softmax(dim=1) ), so the derivative w.r.t. log y will be the one w.r.t. u. The worst thing that happens is that you project the gradient onto the tangent space of the space (not a manifold, but close) of log probs twice (in CTC loss backward and then again in log_softmax backward). Is there a speedup to be had? In theory, yes, because the backward of the log_softmax you’ll be doing in PyTorch will compute the mean that we know is zero. But will we save from not doing it in the ctc backward? I haven’t thought about it much, but I expect not much, as we would need to specify ctc to take logits and take the logsoftmax in the ctc forward (but then we don’t need the backward). Best regards Thomas
st32750
I also find the ctc backward is not consistent with the forward. It is kind of annoying that I find my network cannot converged, just because I do not use the log probability directly from the log_softmax function. I’d like to share a workaround if someone need the “true” gradient. CTCLoss gradient is incorrect · Issue #52241 · pytorch/pytorch · GitHub 1
st32751
suppose a tensor shape [x, y, z …], I want to interpolate it to [nx, y, z …], every value in dim 0 repeat n times. For example, I have tensor[2, 3] = [[1, 2, 3], [4, 5, 6]] I want to interpolate it to tensor[6, 3], which is [[1, 2, 3], [1, 2, 3], [1, 2, 3], [4, 5, 6], [4, 5, 6], [4, 5, 6]] every value in dim 0 repeat 3 times, how to achieve it?
st32752
Solved by pascal_notsawo in post #2 Thanks to this post (Repeat examples along batch dimension), I used torch.repeat_interleave to do it. import torch torch.manual_seed(0) shape = x, y = 2, 3 """ or : - shape = x, y, z = _, _, _, ... - shape = x, y, z, t, ... = _, _, _, _, ... ... """ n = 3 t = torch.rand(shape) """ tensor([…
st32753
Thanks to this post (Repeat examples along batch dimension) 1, I used torch.repeat_interleave 2 to do it. import torch torch.manual_seed(0) shape = x, y = 2, 3 """ or : - shape = x, y, z = _, _, _, ... - shape = x, y, z, t, ... = _, _, _, _, ... ... """ n = 3 t = torch.rand(shape) """ tensor([[0.4963, 0.7682, 0.0885], [0.1320, 0.3074, 0.6341]]) """ t_interpolate = torch.repeat_interleave(t, repeats=n, dim=0) """ tensor([[0.4963, 0.7682, 0.0885], [0.4963, 0.7682, 0.0885], [0.4963, 0.7682, 0.0885], [0.1320, 0.3074, 0.6341], [0.1320, 0.3074, 0.6341], [0.1320, 0.3074, 0.6341]]) """ assert t_interpolate.size() == torch.Size([n * shape[0], *shape[1:]])
st32754
I learned something about the difference between view() and reshape(). The view() does not change the original data stored. But reshape() may change the original data (when the original data is not continuous),reshape() may create a new memory space for the data My doubt is whether the use of reshape() in RNN, CNN or other networks will affect the back propagation of errors, and affecting the final result?
st32755
Solved by JuanFMontesinos in post #2 It just make the computations less efficient. For example, RNN usually take temporal dimensions 1st because blocks are contiguous from left to right. If you slice through other dimensions, you are taking parts of different memory blocks.
st32756
It just make the computations less efficient. For example, RNN usually take temporal dimensions 1st because blocks are contiguous from left to right. If you slice through other dimensions, you are taking parts of different memory blocks.
st32757
Hi guys, I am relatively new to neural networks and for a project I am currently working on I am given a train_dataloader and I need to get the input data. Can somebody please help me on this? I know that you can get the labels with train_dataloader.dataset.targets but how do I get the features? Thank you so much!
st32758
To train what is usually done is to iterate over the dataloader such as: for i, (x, y) in enumerate(train_loader) Where i is the iteration, x are the features and y is the target.
st32759
Thanks, but I need the whole input data because I need to do some preprocessing and I would prefer not to get it with a for loop for efficiency reasons
st32760
Hi everybody! I am newbee in machine learning and I have a bit stupid question… i have trained my model and got .pt file. How can i test my model with unseen data? My code for learning is the following: import torch import numpy as np from torchsummary import summary # check if CUDA is available train_on_gpu = torch.cuda.is_available() if not train_on_gpu: print('CUDA is not available. Training on CPU ...') else: print('CUDA is available! Training on GPU ...') ###################В Data loading ################### import torchvision.datasets from torchvision import datasets import torchvision.transforms as transforms from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler # Read data from folders main_path = 'D:/RTU/dataset/ready_dataset_2classes' train_data_path = main_path + '/train' test_data_path = main_path + '/test' weigths_path = 'D:/RTU/dataset/ready_dataset_2classes/weights' # number of subprocesses to use for data loading num_workers = 0 # how many samples per batch to load batch_size = 20 #20 # percentage of training set to use as validation valid_size = 0.2 # convert data to a normalized torch.FloatTensor transform = transforms.Compose([ transforms.Resize(32), transforms.CenterCrop(32), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) # choose the training and test datasets train_data = torchvision.datasets.ImageFolder(root=train_data_path, transform=transform) train_data_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=0) test_data = torchvision.datasets.ImageFolder(root=test_data_path, transform=transform) test_data_loader = DataLoader(test_data, batch_size=batch_size, shuffle=True, num_workers=0) # obtain training indices that will be used for validation num_train = len(train_data) indices = list(range(num_train)) np.random.shuffle(indices) split = int(np.floor(valid_size * num_train)) train_idx, valid_idx = indices[split:], indices[:split] # define samplers for obtaining training and validation batches train_sampler = SubsetRandomSampler(train_idx) valid_sampler = SubsetRandomSampler(valid_idx) # prepare data loaders (combine dataset and sampler) train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, sampler=train_sampler, num_workers=num_workers) valid_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, sampler=valid_sampler, num_workers=num_workers) test_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, num_workers=num_workers) # specify the image classes classes = ['Modified', 'Original'] # helper function to un-normalize and display an image def imshow(img): img = img / 2 + 0.5 # unnormalize plt.imshow(np.transpose(img, (1, 2, 0))) # convert from Tensor image # creating checkpoints def savePoint(main_path, model, optimizer, epoch, valid_loss_min): torch.save({ 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'epoch': epoch, 'valid_loss_min': valid_loss_min, }, main_path) def loadPoint(main_path, model, optimizer, epoch, valid_loss_min): checkpoint = torch.load(main_path) model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) epoch = checkpoint['epoch'] valid_loss_min = checkpoint['valid_loss_min'] ################### Network architecture definition ################### import torch.nn as nn import torch.nn.functional as F # define the CNN architecture class Net(nn.Module): def __init__(self): super(Net, self).__init__() # convolutional layer (sees 32x32x3 image tensor) self.conv1 = nn.Conv2d(3, 16, 3, padding=1) # convolutional layer (sees 16x16x16 tensor) self.conv2 = nn.Conv2d(16, 32, 3, padding=1) # convolutional layer (sees 8x8x32 tensor) self.conv3 = nn.Conv2d(32, 64, 3, padding=1) # max pooling layer self.pool = nn.MaxPool2d(2, 2) # linear layer (64 * 4 * 4 -> 500) self.fc1 = nn.Linear(64 * 4 * 4, 500) # linear layer (500 -> 10) self.fc2 = nn.Linear(500, 250) self.fc3 = nn.Linear(250, 2) # dropout layer (p=0.25) self.dropout = nn.Dropout(0.25) #0.25 def forward(self, x): # add sequence of convolutional and max pooling layers x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = self.pool(F.relu(self.conv3(x))) # flatten image input x = x.view(-1, 64 * 4 * 4) # add dropout layer x = self.dropout(x) # add 1st hidden layer, with relu activation function x = F.relu(self.fc1(x)) # add dropout layer x = self.dropout(x) # add 2nd hidden layer, with relu activation function x = F.relu(self.fc2(x)) x = self.dropout(x) x = self.fc3(x) return x # create a complete CNN model = Net() summary(model, input_size=(3, 32, 32)) # print(model) # move tensors to GPU if CUDA is available if train_on_gpu: model.cuda() #Loss and optimization specification import torch.optim as optim # specify loss function (categorical cross-entropy) criterion = nn.CrossEntropyLoss() # specify optimizer optimizer = optim.SGD(model.parameters(), lr=0.000001) ################### Network training ################### # number of epochs to train the model n_epochs = 8 #5000 print('Starting training!') valid_loss_min = np.Inf # track change in validation loss for epoch in range(1, n_epochs+1): # keep track of training and validation loss train_loss = 0.0 valid_loss = 0.0 loadPoint(weigths_path, model, optimizer, epoch, valid_loss_min) ################### # train the model # ################### model.train() for data, target in train_loader: # move tensors to GPU if CUDA is available if train_on_gpu: data, target = data.cuda(), target.cuda() # clear the gradients of all optimized variables optimizer.zero_grad() # forward pass: compute predicted outputs by passing inputs to the model output = model(data) # calculate the batch loss loss = criterion(output, target) # backward pass: compute gradient of the loss with respect to model parameters loss.backward() # perform a single optimization step (parameter update) optimizer.step() # update training loss train_loss += loss.item()*data.size(0) ###################### # validate the model # ###################### model.eval() for data, target in valid_loader: # move tensors to GPU if CUDA is available if train_on_gpu: data, target = data.cuda(), target.cuda() # forward pass: compute predicted outputs by passing inputs to the model output = model(data) # calculate the batch loss loss = criterion(output, target) # update average validation loss valid_loss += loss.item()*data.size(0) # calculate average losses train_loss = train_loss/len(train_loader.sampler) valid_loss = valid_loss/len(valid_loader.sampler) # print training/validation statistics print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format( epoch, train_loss, valid_loss)) #checkpoint if valid_loss <= valid_loss_min: print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( valid_loss_min, valid_loss)) savePoint(weigths_path, model, optimizer, epoch, valid_loss_min) valid_loss_min = valid_loss # Loading the model with the lowest validation loss #loadPoint(weigths_path, model, optimizer, epoch, valid_loss_min) #model.load_state_dict(torch.load('weights.pt')) ################### Neural network testing with UNSEEN data ################### # track test loss test_loss = 0.0 class_correct = list(0. for i in range(2)) class_total = list(0. for i in range(2)) model.eval() # iterate over test data for data, target in test_loader: # move tensors to GPU if CUDA is available if train_on_gpu: data, target = data.cuda(), target.cuda() # forward pass: compute predicted outputs by passing inputs to the model output = model(data) # calculate the batch loss loss = criterion(output, target) # update test loss test_loss += loss.item()*data.size(0) # convert output probabilities to predicted class _, pred = torch.max(output, 1) # compare predictions to true label correct_tensor = pred.eq(target.data.view_as(pred)) correct = np.squeeze(correct_tensor.numpy()) if not train_on_gpu else np.squeeze(correct_tensor.cpu().numpy()) # calculate test accuracy for each object class for i in range(len(target.data)): label = target.data[i] class_correct[label] += correct[i].item() class_total[label] += 1 # average test loss test_loss = test_loss/len(test_loader.dataset) print('Test Loss: {:.6f}\n'.format(test_loss)) for i in range(2): if class_total[i] > 0: print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % ( classes[i], 100 * class_correct[i] / class_total[i], np.sum(class_correct[i]), np.sum(class_total[i]))) else: print('Test Accuracy of %5s: N/A (no training examples)' % (classes[i])) print('\nTest Accuracy (Overall): %2d%% (%2d/%2d)' % ( 100. * np.sum(class_correct) / np.sum(class_total), np.sum(class_correct), np.sum(class_total))) So the idea is that i will give the image, which the model did not see at all and model will give me an answer for which class does this image fits. I have tried to cut the part of code where i am testing the model after the learning but i got some errors, so it seems like i am doing something wrong p.s. sorry for my bad english
st32761
Solved by Franz in post #2 Hi, what you are doing right is to split the data into training and validation. You are training the model and then validating it already on unseen data (that is the idea of the validation loop). Your testing loop currently does exact the same, which is not needed in most cases. I think you want t…
st32762
Hi, what you are doing right is to split the data into training and validation. You are training the model and then validating it already on unseen data (that is the idea of the validation loop). Your testing loop currently does exact the same, which is not needed in most cases. I think you want to use your model simply on any other, new data right? This would then be called “inference”. You simply pass data to your model and want the output. By doing that, you don’t want to perform the gradient calculation nor the loss calculation which speeds up the process and uses way less ram (this is also recommended at the validation loop since you want to validate and not train.). If i get you right, you loaded the model from a checkpoint, which is good! Then you set your model to eval mode, good. Now you want to deactivate the autograd engine before your loop. Do: with torch.no_grad(): <your loop here> Then you need to do some decision making. Your model ouputs two values so i guess you are doing a binary classification (either one or the other output), am i right? If so, then you should replace: self.fc3 = nn.Linear(250, 2) with self.fc3 = nn.Linear(250, 1) In this case your model outputs logits as well but the CrossEntropyLoss would not work. Use: torch.nn.BCEWithLogitsLoss() for that (but this is just a hint, your current approach works as well). Back to the for loop over your test data: your model outputs logits so you need to process and interpret them. You can do the following: output_logits = your_model(input_batch) # shaped like: batch_size, num_classes if output_logits.size(1) == 1: # this is for binary classification: # you have one output, everything below 0.5 relates to class 1, everything above to class 2 output_probabilities = torch.sigmoid(output_logits) # out logits are now in between 0 and 1 outs = (output_probabilities.squeeze(1) > 0.5).float() # outputs a vector ontaining zeroes and ones correct = outs.eq(targets).sum().item() # number of correct predictions else: # this would fit to your current approch assuming exact one class is correct # get the index of the highest output logit for each sample (no need to use sigmoid here): values, predictions = torch.max(output_logits, dim=1) correct = predictions.eq(targets).sum().item() And that’s it. You have your predictions as a tensor and the amount of correct predictions if you have the ground truth. If no ground truth is given, then remove the parts including the targets If you are facing errors: please include the errors in your question as well. We as the readers might help better in that case.
st32763
Hello all; I’ve an unbalanced dataset for a 3 classes output. I managed to have well stratified train and test sets. My question please: Using WeightedRandomSampler gives me bad results rather than without using it. (74% vs 91% accuracies) Is there any logical explanation for this ? Last question: assuming all my dataset was well balanced, I’m I required to have balanced mini-batches during the epoch ? Can I have for example first mini-batches with only 2 classes, and the last ones with the last class ? Is this okay for the training ? note that this question isn’t pertaining to my use. Thank you very much, Habib
st32764
Solved by ptrblck in post #2 You might be running into the Accuracy Paradox, which explains that the accuracy might be a misleading metric for imbalanced classification use cases. E.g. in case the majority class occurs in 91% of all cases, your model might only predict this single class to achieve the accuracy of 91%. While t…
st32765
twister9458: My question please: Using WeightedRandomSampler gives me bad results rather than without using it. (74% vs 91% accuracies) Is there any logical explanation for this ? You might be running into the Accuracy Paradox 2, which explains that the accuracy might be a misleading metric for imbalanced classification use cases. E.g. in case the majority class occurs in 91% of all cases, your model might only predict this single class to achieve the accuracy of 91%. While the model would be not very useful, the accuracy “looks good”. Balancing the dataset might thus reduce the accuracy, but increase other metrics such as the F1 score.
st32766
Hello, everyone! I am training a 2-class resnet18 network using images(about 4000 pieces) from cocodataset. I find all test and training loss vibrate greatly. It looks like something wrong in training parameters. I have changed batch size 64 and 128, also pretrained True and false. But nothing changed. Please help me. 41024×462 68.8 KB
st32767
I am trying to use drop connect in rnn, but just to receive a warning: ‘UserWarning: RNN module weights are not part of single contiguous chunk of memory. This means they need to be compacted at every call, possibly greately increasing memory usage. To compact weights again call flatten_parameters()’ here is the weight dropout code: def _weight_drop(module, weights, dropout): """ Thanks to pytorchnlp, here is the LICENSE:https://hub.fastgit.org/PetrochukM/PyTorch-NLP/blob/master/LICENSE """ for name_w in weights: w = getattr(module, name_w) del module._parameters[name_w] module.register_parameter(name_w + '_raw', nn.Parameter(w)) original_module_forward = module.forward def forward(*args, **kwargs): for name_w in weights: raw_w = getattr(module, name_w + '_raw') w = F.dropout(raw_w, p=dropout, training=module.training) setattr(module, name_w, w) return original_module_forward(*args, **kwargs) setattr(module, 'forward', forward) And in rnn module, I write something like this: if wdrop: weights = ["weight_hh_l" + str(i) for i in range(self.n_layers)] if bidirectional: weights_reverse = ["weight_hh_l" + str(i) + "_reverse" for i in range(self.n_layers)] weights = weights+weights_reverse _weight_drop(self.rnn, weights, wdrop) Notice: It’s ok to run my model(verified), but just annoyed for me to see the warning! I have googled this problem and find flatten parameters, but after add "rnn.flatten_parameters() " still can not avoid this warning. So, my question is why it happens, and how to eliminate it?