instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Concatenating branches(of different dimensions) of googlenet on Pytorch
is there any way I can concatenate branches of different dimensions of a small inception(googlenet)? For example, at a 32 x 32 x 3 image (torch.Size([1, 3, 32, 32])), it will pass through an inception module with the following branches: a convolution with (32 channels, 1 x 1 filters) another convolution with (32 channels, 3 x3 filters) merge (concatenate along the channel dimension) Inception Module The issue however is that the torch sizes as a result of the two convolutions are different. (32 channels, 1 x 1 filters) -> [1, 32, 30, 30] (32 channels, 3 x3 filters) -> [1, 32, 28, 28] How can I concatenate the two branches? Should I add padding? I tried ZeroPad2d. It’s not working. For your reference: class Inception(nn.Module): def __init__(self, in_channel, ch1, ch3): super(Inception, self).__init__() self.branch1 = nn.Sequential( ConvBlock(in_channel, ch1, kernel_size = 1,stride=1, padding=0) ) self.branch2 = nn.Sequential( ConvBlock(in_channel, ch3, kernel_size = 3,stride=1, padding=0) ) def forward(self, x): branch1 = self.branch1(x) branch2 = self.branch2(x) return torch.cat([branch1, branch2], 1) *(error here)*
You need to match your kernel size and padding. For kernel_size=1 no padding is needed, but for kernel_size=3 you need padding to be 1: self.branch2 = nn.Sequential( ConvBlock(in_channel, ch3, kernel_size=3,stride=1, padding=1) ) See this nice tutorial for more details.
https://stackoverflow.com/questions/64651005/
How to make PyTorch DataLoader from scratch?
Is it possible to recreate a simple version of PyTorch DataLoader from scratch? The class should be able to return current batch based on the batch size. For example, the code bellow only allows me to return one example at the time X = np.array([[1,2],[3,4],[5,6],[6,7]]) class DataLoader: def __init__(self, X, b_size): self.X = X self.b_size = b_size def __len__(self): return len(self.X) def __getitem__(self, index): return self.X[index] But what I want to achieve is that if I specify b_size=2, it would return: Iteration 0: [[1,2],[3,4]] Iteration 1: [[5,6],[7,8]] Is it possible to do something like that in Python? I can't use the DataLoader class.
X = np.array([[1,2],[3,4],[5,6],[6,7]]) class DataLoader: def __init__(self, X, b_size): self.X = X self.b_size = b_size def __len__(self): return len(self.X)//self.b_size def __getitem__(self, index): return self.X[index*self.b_size:index*self.b_size+self.b_size] d = DataLoader(X, 2) for i in range(len(d)): print (f"Iteration {i}: {d[i]}") Output: Iteration 0: [[1 2] [3 4]] Iteration 1: [[5 6] [6 7]]
https://stackoverflow.com/questions/64654268/
Error Compiling C++/Cuda extension with Pytorch Cuda c++ in MSVC using CMake
I am trying to build a c++/cuda extension with Pytorch following the tutorial here, (with instructions how to use pytorch with c++ here). My environment details are: Using Microsoft Visual Studio 2019 version 16.6.5 Windows 10 libtorch c++ debug 1.70 with cuda 11.0 installed from the pytorch website I am using this cmake code where I set the include directory for python 3.6 and the library for python36.lib cmake_minimum_required (VERSION 3.8) project ("DAConvolution") find_package(Torch REQUIRED) # Add source to this project's executable. add_executable (DAConvolution "DAConvolution.cpp" "DAConvolution.h") include_directories("C:/Users/James/Anaconda3/envs/masters/include") target_link_libraries(DAConvolution "${TORCH_LIBRARIES}" "C:/Users/James/Anaconda3/envs/masters/libs/python36.lib") if (MSVC) file(GLOB TORCH_DLLS "${TORCH_INSTALL_PREFIX}/lib/*.dll") add_custom_command(TARGET DAConvolution POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${TORCH_DLLS} $<TARGET_FILE_DIR:DAConvolution>) endif (MSVC) I set the CMake command arguments to be -DCMAKE_PREFIX_PATH=C:\libtorch (my path to libtorch debug mentioned above). I am building with the x64-debug option in MSVC version (as building with the x-64 Release option gives me a torch-NOTFOUND error). The example DAConvolution.cpp file is: #ifdef _DEBUG #undef _DEBUG #include <python.h> #define _DEBUG #else #include <python.h> #endif #include <torch/extension.h> Where I have undefined the _DEBUG flag so that the linker does not look for the python36_d.lib file (which I do not have). I am getting a linking error: Simply including torch.h works fine, but when I want to include the extension header thats when I get these problems, as it uses Pybind 11 I believe. Any insights much appreciated. I have tried to include all the info I can, but would be happy to give more information.
For Windows and with Visual studio, you are better to work with the Visual Studio rather than the CMake. Just create a simple Console Application, go to the project's Properties, change the Configuration type to Dynamic Library (dll), Configure the include and Library directories, add the required enteries to your linker in Linker>Input (such as torch.lib, torch_cpu.lib, etc) and you are good to go click build, and if you have done everything correctly you'll get yourself a dll that you can use (e.g loading it using torch.classes.load_library from Python and use it. The Python debug version is not shipped with Anaconda/ normal python distribution, but if you install the Microsoft Python distribution which I believe can be downloaded/installed from Visual Studio installer, its available. Also starting from Python 3.8 I guess the debug binaries are also shipped. In case they are not, see this. For the cmake part you can follow something like the following. This is a butchered version taken from my own cmake that I made for my python extension some time ago. Read it and change it based on your own requirements it should be straight forward : # NOTE:‌ # TORCH_LIB_DIRS needs to be set. When calling cmake you can specify them like this: # cmake -DCMAKE_PREFIX_PATH="somewhere/libtorch/share/cmake" -DTORCH_LIB_DIRS="/somewhere/lib" .. cmake_minimum_required(VERSION 3.1 FATAL_ERROR) project(DAConvolution) find_package(Torch REQUIRED) # we are using the C++17, if you are not change this or remove it altogether set(CMAKE_CXX_STANDARD 17) #define where your headers and libs are, specify for example where your DaConvolution.h resides! include_directories( somewhere/Yourinclude_dir ${TORCH_INCLUDE_DIRS}) set(DAConvolution_SRC ./DAConvolution.cpp ) LINK_DIRECTORIES(${TORCH_LIB_DIRS}) add_library( DAConvolution SHARED ${DAConvolution_SRC} ) # if you use some custom libs, you previously built, specify its location here # target_link_directories(DAConvolution PRIVATE somewhere/your_previously_built_stuff/libs) target_link_libraries(DAConvolution ${TORCH_LIB_DIRS}/libc10.so) target_link_libraries(DAConvolution ${TORCH_LIB_DIRS}/libtorch_cpu.so) install(TARGETS DAConvolution LIBRARY DESTINATION lib ) Side note: I made the cmake for Linux only, so under Windows, I always use Visual Studio (2019 to be exact), in the same way I explained earlier. its by far the best /easiest approach imho. Suit yourself and choose either of them that best fits your problem.
https://stackoverflow.com/questions/64654586/
PyTorch Tutorial freeze_support() issue
I tried following the tutorial from PyTorch here: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py. Full code is here: import torch import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import numpy as np import torch.nn as nn import torch.nn.functional as F import torch.optim as optim # Loading and normalizing CIFAR10 transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2) classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') # Shows training images, DOESN'T WORK def imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show() # get some random training images dataiter = iter(trainloader) images, labels = dataiter.next() # show images imshow(torchvision.utils.make_grid(images)) # print labels print(' '.join('%5s' % classes[labels[j]] for j in range(4))) # define a convolutional neural network class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 5 * 5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() # Define a loss function and optimizer criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # Train the network for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 # DOESN'T WORK for i, data in enumerate(trainloader, 0): # get the inputs; data is a list of [inputs, labels] inputs, labels = data # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() # print statistics running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 2000)) running_loss = 0.0 print('Finished Training') # save trained model PATH = './cifar_net.pth' torch.save(net.state_dict(), PATH) # test the network on the test data dataiter = iter(testloader) images, labels = dataiter.next() # print images dataiter = iter(testloader) images, labels = dataiter.next() imshow(torchvision.utils.make_grid(images)) print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4))) # load back saved model net = Net() net.load_state_dict(torch.load(PATH)) # see what the nueral network thinks these examples above are: ouputs = net(images) # index of the highest energy _, predicted = torch.max(outputs, 1) print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(4))) # accuracy on the whole dataset correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total)) # classes that perfomed well vs classes that didn't perform well class_correct = list(0. for i in range(10)) class_total = list(0. for i in range(10)) with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs, 1) c = (predicted == labels).squeeze() for i in range(4): label = labels[i] class_correct[label] += c[i].item() class_total[label] += 1 for i in range(10): print('Accuracy of %5s : %2d %%' % ( classes[i], 100 * class_correct[i] / class_total[i])) if __name__ == '__main__': torch.multiprocessing.freeze_support() However I got this issue: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable. I'm just trying to run this in a regular python file. When I added if __name__ == '__main__': freeze_support() to the end of my file, I still get the error.
To anyone else with this issue, I believe you need to define a main function and run the training there. Then add: if __name__ == '__main__': main() at the end of the python file. This fixed the freeze_support() issue for me on a different PyTorch training program.
https://stackoverflow.com/questions/64654838/
in Torchaudio=0.7.0, where is torchaudio.functional.istft?
I used torchaudio.functional.isftf when the version torchaudio=0.4.0 But now, the version of torchaudio has been upgraded to 0.7.0, so I installed it, but torchaudio.functional.istft is gone. I need to learn a deep learning model using torchaudio.functional.istft. How do I do it??
It's deprecated now in favor of torch.istft. Check release notes and PR#523.
https://stackoverflow.com/questions/64661065/
Formula to compute the padding in convolutions pytorch (googlenet)
I am implementing googlenet (smaller version) from scratch in pytorch. The architecture is below: For the Downsample Module I have the following code: class DownSampleModule(nn.Module): def __init__(self, in_channel, ch3, w): super(DownSampleModule, self).__init__() kernel_size = 3 padding = (kernel_size-1)/2 self.branch1 = nn.Sequential( ConvBlock(in_channel, ch3, kernel_size = 3,stride=2, padding=int(padding)) ) self.branch2 = nn.Sequential( nn.MaxPool2d(3, stride=2, padding=0, ceil_mode=True) ) def forward(self, x): branch1 = self.branch1(x) branch2 = self.branch2(x) return torch.cat([padded_tensor, branch2], 1) The ConvBlock is from this module class ConvBlock(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding): super(ConvBlock, self).__init__() #padding = (kernel_size -1 )/2 #print(padding) self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding) self.bn = nn.BatchNorm2d(out_channels) self.act = nn.ReLU() def forward(self, x): x = self.conv(x) x = self.bn(x) x = self.act(x) return x Basically, we are creating two branches: a convolution module and a max pool. The output of these two branches are then concatenated on the channel dimension. However, I have the following problem: Firstly, we call self.pool1 = DownSampleModule(in_channel=80, ch3 = 80, w=30). The dimensions of the two branches are similar. These are: Downsample Convolution:torch.Size([1, 80, 15, 15]) Maxpool Convolution:torch.Size([1, 80, 15, 15]) However, when we call self.pool2 = DownSampleModule(in_channel = 144, ch3 = 96, w=15). The dimensions are different which prevents it from being concatenated. Downsample Convolution:torch.Size([1, 96, 8, 8]) Maxpool Convolution:torch.Size([1, 144, 7, 7]) Does anyone know the formula to compute the correct padding? Thank you. In Keras, you can just set the padding="same" or "valid" but it's not supported on pytorch.
Your maxpool and conv branches have the same input, and will produce identically-shaped output if you give them the same parameters for kernel size, stride and padding. So just replacing your padding = 0 with padding = int(padding) should be enough to make both branches be concat-compatible. ceil_modeshould also be set to False. When the resulting dimension is not an integer, the rounding behavior of conv2d is to use floor, so you want your maxpool to do that as well. By the way, you can remove your nn.Sequential. Your "sequences" of layers are made of only one layer, so... not really sequential :)
https://stackoverflow.com/questions/64661402/
How to build pytorch from source using numpy
I am trying to build pytorch v1.4.0 from source because I need it for another module. I have succeeded in building pytorch from source but when I try to run the intended python script I get this error: RuntimeError: PyTorch was compiled without NumPy support So I looked up what I did wrong and it turns out I needed to install numpy before i build pytorch from source, so thats what I did. I used the command: pip3 install numpy==1.19.4 When installing pytorch the console gives me a lot of information, including the build settings. The build settings looked like this: -- Compile definitions : ONNX_ML=1;ONNX_NAMESPACE=onnx_torch;HAVE_MMAP=1;_FILE_OFFSET_BITS=64;HAVE_SHM_OPEN=1;HAVE_SHM_UNLINK=1;HAVE_MALLOC_USABLE_SIZE=1 -- CMAKE_PREFIX_PATH : /home/elvygcp/venv/lib/python3.6/site-packages;/usr/local/cuda -- CMAKE_INSTALL_PREFIX : /home/elvygcp/venv/pytorch-1.4.0/torch -- -- TORCH_VERSION : 1.4.0 -- CAFFE2_VERSION : 1.4.0 -- BUILD_CAFFE2_MOBILE : ON -- USE_STATIC_DISPATCH : OFF -- BUILD_BINARY : OFF -- BUILD_CUSTOM_PROTOBUF : ON -- Link local protobuf : ON -- BUILD_DOCS : OFF -- BUILD_PYTHON : True -- Python version : 3.6.9 -- Python executable : /home/elvygcp/venv/bin/python3 -- Pythonlibs version : 3.6.9 -- Python library : /usr/lib/libpython3.6m.so.1.0 -- Python includes : /usr/include/python3.6m -- Python site-packages: lib/python3.6/site-packages -- BUILD_CAFFE2_OPS : ON -- BUILD_SHARED_LIBS : ON -- BUILD_TEST : True -- BUILD_JNI : OFF -- INTERN_BUILD_MOBILE : -- USE_ASAN : OFF -- USE_CUDA : ON -- CUDA static link : OFF -- USE_CUDNN : OFF -- CUDA version : 10.2 -- CUDA root directory : /usr/local/cuda -- CUDA library : /usr/local/cuda/lib64/stubs/libcuda.so -- cudart library : /usr/local/cuda/lib64/libcudart.so -- cublas library : /usr/lib/x86_64-linux-gnu/libcublas.so -- cufft library : /usr/local/cuda/lib64/libcufft.so -- curand library : /usr/local/cuda/lib64/libcurand.so -- nvrtc : /usr/local/cuda/lib64/libnvrtc.so -- CUDA include path : /usr/local/cuda/include -- NVCC executable : /usr/local/cuda/bin/nvcc -- CUDA host compiler : /usr/bin/cc -- USE_TENSORRT : OFF -- USE_ROCM : OFF -- USE_EIGEN_FOR_BLAS : ON -- USE_FBGEMM : ON -- USE_FFMPEG : OFF -- USE_GFLAGS : OFF -- USE_GLOG : OFF -- USE_LEVELDB : OFF -- USE_LITE_PROTO : OFF -- USE_LMDB : OFF -- USE_METAL : OFF -- USE_MKL : OFF -- USE_MKLDNN : ON -- USE_MKLDNN_CBLAS : OFF -- USE_NCCL : ON -- USE_SYSTEM_NCCL : OFF -- USE_NNPACK : ON -- USE_NUMPY : OFF -- USE_OBSERVERS : ON -- USE_OPENCL : OFF -- USE_OPENCV : OFF -- USE_OPENMP : ON -- USE_TBB : OFF -- USE_PROF : OFF -- USE_QNNPACK : ON -- USE_REDIS : OFF -- USE_ROCKSDB : OFF -- USE_ZMQ : OFF -- USE_DISTRIBUTED : ON -- USE_MPI : OFF -- USE_GLOO : ON -- BUILD_NAMEDTENSOR : OFF There are 2 things I do not understand: The line: USE_CUDNN : OFF, which I think is strange since i followed the pytorch build instructions from their github page which mentions I need CuDNN to build pytorch from source, and CuDNN is installed on my system. The line: USE_NUMPY : OFF, I dont know why but pytorch does not recognize numpy. My system: OS: Ubuntu 18.04 LTS Cuda version: 10.2 CuDNN version: 8 python venv in Google Cloud Compute Engine VM How I build pytorch 1.4.0 from source: git clone --branch v1.4.0 https://github.com/pytorch/pytorch.git pytorch-1.4.0 cd pytorch-1.4.0/ git submodule update --init --recursive sudo apt install cmake -y sudo apt-get update cd ../ sudo apt install python3-venv -y python3 -m venv venv/ cd venv source bin/activate cd pytorch-1.4.0/ pip install pyyaml python3 setup.py install cd ../ git clone --branch v0.5.0 https://github.com/pytorch/vision.git torchvision-0.5.0 cd torchvision-0.5.0/ python3 setup.py install cd ../ If anyone could tell how I make pytorch recognize and build with numpy I'd be very grateful. If I need to supply more information I'd be happy to.
Okay so I don't exactly know what the solution was since I did two things: I installed a lower version of numpy since my torch version is also a bit older. I cleared all the pytorch install cache with the command: sudo USE_ROCM=1 USE_LMDB=1 USE_OPENCV=1 MAX_JOBS=15 python3 setup.py clean Downgrading numpy might have been unnecessary, since I can't remember if I cleared all the pytorch installation cache after installing numpy and trying again. Now my installation log contains USE_NUMPY : ON. Dont know if this fixed all my problems, building pytorch takes forever so I'll just have to wait and see, but at least it fixed this one :)
https://stackoverflow.com/questions/64662102/
Split DataLoader PyTorch
Is it possible to split a dataloader object of training dataset into training and validation dataloader? from torch.utils.data import DataLoader from torchvision import datasets, transforms train_dataset = datasets.ImageFolder(train_data_directory, transform=transforms.ToTensor()) # Data loader train_loader = DataLoader(train_dataset, batch_size=100, shuffle=True) Now I would like to split a train_loader to train and validation dataloader.
Look at random_split in torch.utils.data. It will handle a random Dataset split (you have to split before creating the DataLoader, not after).
https://stackoverflow.com/questions/64669043/
Embedding layer in neural machine translation with attention
I am trying to understanding how to implement a seq-to-seq model with attention from this website. My question: Is nn.embedding just returns some IDs for each word, so the embedding for each word would be the same during whole training? Or are they getting changed during the procedure of training? My second question is because I am confused whether after training, the output of nn.embedding is something such as word2vec word embeddings or not. Thanks in advance
According to the PyTorch docs: A simple lookup table that stores embeddings of a fixed dictionary and size. This module is often used to store word embeddings and retrieve them using indices. The input to the module is a list of indices, and the output is the corresponding word embeddings. In short, nn.Embedding embeds a sequence of vocabulary indices into a new embedding space. You can indeed roughly understand this as a word2vec style mechanism. As a dummy example, let's create an embedding layer that takes as input a total of 10 vocabularies (i.e. the input data only contains a total of 10 unique tokens), and returns embedded word vectors living in 5-dimensional space. In other words, each word is represented as 5-dimensional vectors. The dummy data is a sequence of 3 words with indices 1, 2, and 3, in that order. >>> embedding = nn.Embedding(10, 5) >>> embedding(torch.tensor([1, 2, 3])) tensor([[-0.7077, -1.0708, -0.9729, 0.5726, 1.0309], [ 0.2056, -1.3278, 0.6368, -1.9261, 1.0972], [ 0.8409, -0.5524, -0.1357, 0.6838, 3.0991]], grad_fn=<EmbeddingBackward>) You can see that each of the three words are now represented as 5-dimensional vectors. We also see that there is a grad_fn function, which means that the weights of this layer will be adjusted through backprop. This answers your question of whether embedding layers are trainable: the answer is yes. And indeed this is the whole point of embedding: we expect the embedding layer to learn meaningful representations, the famous example of king - man = queen being the classic example of what these embedding layers can learn. Edit The embedding layer is, as the documentation states, a simple lookup table from a matrix. You can see this by doing >>> embedding.weight Parameter containing: tensor([[-1.1728, -0.1023, 0.2489, -1.6098, 1.0426], [-0.7077, -1.0708, -0.9729, 0.5726, 1.0309], [ 0.2056, -1.3278, 0.6368, -1.9261, 1.0972], [ 0.8409, -0.5524, -0.1357, 0.6838, 3.0991], [-0.4569, -1.9014, -0.0758, -0.6069, -1.2985], [ 0.4545, 0.3246, -0.7277, 0.7236, -0.8096], [ 1.2569, 1.2437, -1.0229, -0.2101, -0.2963], [-0.3394, -0.8099, 1.4016, -0.8018, 0.0156], [ 0.3253, -0.1863, 0.5746, -0.0672, 0.7865], [ 0.0176, 0.7090, -0.7630, -0.6564, 1.5690]], requires_grad=True) You will see that the first, second, and third rows of this matrix corresponds to the result that was returned in the example above. In other words, for a vocabulary whose index is n, the embedding layer will simply "lookup" the nth row in its weights matrix and return that row vector; hence the lookup table.
https://stackoverflow.com/questions/64675228/
BERT always predicts same class (Fine-Tuning)
I am fine-tuning BERT on a financial news dataset. Unfortunately BERT seems to be trapped in a local minimum. It is content with learning to always predict the same class. balancing the dataset didnt work tuning parameters didnt work as well I am honestly not sure what is causing this problem. With the simpletransformers library I am getting very good results. I would really appreciate if somebody could help me. thanks a lot! Full code on github: https://github.com/Bene939/BERT_News_Sentiment_Classifier Code: from transformers import BertForSequenceClassification, AdamW, BertTokenizer, get_linear_schedule_with_warmup, Trainer, TrainingArguments import torch from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset import pandas as pd from pathlib import Path import sklearn from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, precision_recall_fscore_support import numpy as np from torch.nn import functional as F from collections import defaultdict import random #defining tokenizer, model and optimizer tokenizer = BertTokenizer.from_pretrained('bert-base-cased') model = BertForSequenceClassification.from_pretrained('bert-base-cased', num_labels=3) if torch.cuda.is_available(): print("\nUsing: ", torch.cuda.get_device_name(0)) device = torch.device('cuda') else: print("\nUsing: CPU") device = torch.device('cpu') model = model.to(device) #loading dataset labeled_dataset = "news_headlines_sentiment.csv" labeled_dataset_file = Path(labeled_dataset) file_loaded = False while not file_loaded: if labeled_dataset_file.exists(): labeled_dataset = pd.read_csv(labeled_dataset_file) file_loaded = True print("Dataset Loaded") else: print("File not Found") print(labeled_dataset) #counting sentiments negative = 0 neutral = 0 positive = 0 for idx, row in labeled_dataset.iterrows(): if row["sentiment"] == 0: negative += 1 elif row["sentiment"] == 1: neutral += 1 else: positive += 1 print("Unbalanced Dataset") print("negative: ", negative) print("neutral: ", neutral) print("positive: ", positive) #balancing dataset to 1/3 per sentiment for idx, row in labeled_dataset.iterrows(): if row["sentiment"] == 0: if negative - neutral != 0: index_name = labeled_dataset[labeled_dataset["news"] == row["news"]].index labeled_dataset.drop(index_name, inplace=True) negative -= 1 elif row["sentiment"] == 2: if positive - neutral != 0: index_name = labeled_dataset[labeled_dataset["news"] == row["news"]].index labeled_dataset.drop(index_name, inplace=True) positive -= 1 #custom dataset class class NewsSentimentDataset(torch.utils.data.Dataset): def __init__(self, encodings, labels): self.encodings = encodings self.labels = labels def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} item['labels'] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.labels) #method for tokenizing dataset list def tokenize_headlines(headlines, labels, tokenizer): encodings = tokenizer.batch_encode_plus( headlines, add_special_tokens = True, truncation = True, padding = 'max_length', return_attention_mask = True, return_token_type_ids = True ) dataset = NewsSentimentDataset(encodings, labels) return dataset #splitting dataset into training and validation set #load news sentiment dataset all_headlines = labeled_dataset['news'].tolist() all_labels = labeled_dataset['sentiment'].tolist() train_headlines, val_headlines, train_labels, val_labels = train_test_split(all_headlines, all_labels, test_size=.2) val_dataset = tokenize_headlines(val_headlines, val_labels, tokenizer) train_dataset = tokenize_headlines(train_headlines, val_labels, tokenizer) #data loader train_batch_size = 8 val_batch_size = 8 train_data_loader = DataLoader(train_dataset, batch_size = train_batch_size, shuffle=True) val_data_loader = DataLoader(val_dataset, batch_size = val_batch_size, sampler=SequentialSampler(val_dataset)) #optimizer and scheduler num_epochs = 1 num_steps = len(train_data_loader) * num_epochs optimizer = AdamW(model.parameters(), lr=5e-5, eps=1e-8) scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=num_steps*0.06, num_training_steps=num_steps) #training and evaluation seed_val = 64 random.seed(seed_val) np.random.seed(seed_val) torch.manual_seed(seed_val) torch.cuda.manual_seed_all(seed_val) for epoch in range(num_epochs): print("\n###################################################") print("Epoch: {}/{}".format(epoch+1, num_epochs)) print("###################################################\n") #training phase average_train_loss = 0 average_train_acc = 0 model.train() for step, batch in enumerate(train_data_loader): input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['labels'].to(device) token_type_ids = batch['token_type_ids'].to(device) outputs = model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids = token_type_ids) loss = F.cross_entropy(outputs[0], labels) average_train_loss += loss if step % 40 == 0: print("Training Loss: ", loss) logits = outputs[0].detach().cpu().numpy() label_ids = labels.to('cpu').numpy() average_train_acc += sklearn.metrics.accuracy_score(label_ids, np.argmax(logits, axis=1)) print("predictions: ",np.argmax(logits, axis=1)) print("labels: ",label_ids) print("#############") optimizer.zero_grad() loss.backward() #maximum gradient clipping torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() scheduler.step() model.zero_grad() average_train_loss = average_train_loss / len(train_data_loader) average_train_acc = average_train_acc / len(train_data_loader) print("======Average Training Loss: {:.5f}======".format(average_train_loss)) print("======Average Training Accuracy: {:.2f}%======".format(average_train_acc*100)) #validation phase average_val_loss = 0 average_val_acc = 0 model.eval() for step,batch in enumerate(val_data_loader): input_ids = batch['input_ids'].to(device) attention_mask = batch['attention_mask'].to(device) labels = batch['labels'].to(device) token_type_ids = batch['token_type_ids'].to(device) pred = [] with torch.no_grad(): outputs = model(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids) loss = F.cross_entropy(outputs[0], labels) average_val_loss += loss logits = outputs[0].detach().cpu().numpy() label_ids = labels.to('cpu').numpy() print("predictions: ",np.argmax(logits, axis=1)) print("labels: ",label_ids) print("#############") average_val_acc += sklearn.metrics.accuracy_score(label_ids, np.argmax(logits, axis=1)) average_val_loss = average_val_loss / len(val_data_loader) average_val_acc = average_val_acc / len(val_data_loader) print("======Average Validation Loss: {:.5f}======".format(average_val_loss)) print("======Average Validation Accuracy: {:.2f}%======".format(average_val_acc*100)) ################################################### Epoch: 1/1 ################################################### Training Loss: tensor(1.1006, device='cuda:0', grad_fn=<NllLossBackward>) predictions: [1 0 2 0 0 0 2 0] labels: [2 0 1 1 0 1 0 1] ############# predictions: [2 2 0 0 0 2 0 0] labels: [1 2 1 0 2 0 1 2] ############# predictions: [0 0 0 0 1 0 0 1] labels: [0 1 1 0 1 1 2 0] ############# predictions: [0 0 0 2 0 1 0 0] labels: [0 0 0 2 0 0 2 1] ############# predictions: [1 0 0 0 0 0 2 0] labels: [0 2 2 1 0 0 0 0] ############# predictions: [0 0 0 0 0 1 0 0] labels: [1 0 2 2 2 1 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 2 2 2 0 2 0] ############# predictions: [0 1 0 0 0 0 0 0] labels: [2 2 0 2 0 0 0 1] ############# predictions: [0 0 0 0 0 2 0 1] labels: [0 1 0 2 2 0 1 2] ############# predictions: [0 0 2 0 0 0 1 0] labels: [0 0 0 1 2 1 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 1 0 1 0 1 1] ############# predictions: [0 2 0 0 0 0 0 0] labels: [2 2 0 1 0 1 2 1] ############# predictions: [0 1 0 0 0 0 1 2] labels: [2 2 1 0 2 0 0 2] ############# predictions: [0 0 1 1 1 1 0 1] labels: [1 2 1 1 1 1 2 2] ############# predictions: [1 0 0 0 0 1 2 1] labels: [1 0 1 1 0 0 0 2] ############# predictions: [0 1 1 1 1 0 2 1] labels: [2 2 1 2 2 1 1 2] ############# predictions: [0 0 1 0 1 1 0 0] labels: [1 0 0 1 0 1 0 2] ############# predictions: [1 2 0 0 1 2 0 0] labels: [0 2 2 1 2 0 1 0] ############# predictions: [0 2 1 1 0 1 1 0] labels: [2 2 0 1 1 0 1 2] ############# predictions: [1 0 1 1 1 1 1 0] labels: [0 2 0 1 0 1 2 2] ############# predictions: [0 2 1 2 0 0 1 1] labels: [2 1 1 1 1 2 2 0] ############# predictions: [0 1 2 2 2 1 1 2] labels: [2 2 1 1 2 1 0 1] ############# predictions: [2 2 2 1 2 1 1 1] labels: [0 1 1 0 0 2 2 1] ############# predictions: [1 2 2 2 1 2 1 2] labels: [0 0 0 0 2 0 1 2] ############# predictions: [2 1 1 1 2 2 2 2] labels: [1 0 2 2 1 0 0 0] ############# predictions: [2 1 2 2 2 1 2 2] labels: [2 1 1 1 1 1 2 2] ############# predictions: [1 1 0 2 1 2 1 2] labels: [2 2 0 2 0 1 2 0] ############# predictions: [0 1 1 2 0 1 2 1] labels: [2 2 2 1 2 2 0 1] ############# predictions: [2 1 1 1 1 2 1 1] labels: [0 1 1 2 1 0 0 2] ############# predictions: [1 2 2 0 1 1 1 2] labels: [0 1 2 1 2 1 0 1] ############# predictions: [0 1 1 1 1 1 1 0] labels: [0 2 0 1 1 2 2 2] ############# predictions: [1 2 1 1 2 1 1 0] labels: [0 2 2 2 0 0 1 0] ############# predictions: [2 2 2 1 2 1 1 2] labels: [2 2 1 2 1 0 0 0] ############# predictions: [2 2 1 2 2 2 1 2] labels: [1 1 2 2 2 0 2 1] ############# predictions: [2 2 2 2 2 0 2 2] labels: [2 2 1 2 0 1 1 2] ############# predictions: [1 1 2 1 2 2 0 1] labels: [2 1 1 1 0 0 2 2] ############# predictions: [2 1 2 2 2 2 1 0] labels: [0 2 0 2 0 0 0 0] ############# predictions: [2 2 2 2 2 2 2 2] labels: [1 1 0 2 0 1 2 1] ############# predictions: [2 2 2 2 1 2 2 2] labels: [1 0 0 1 1 0 0 0] ############# predictions: [2 2 2 1 2 2 2 2] labels: [1 0 1 1 0 2 2 0] ############# Training Loss: tensor(1.1104, device='cuda:0', grad_fn=<NllLossBackward>) predictions: [2 0 1 2 1 2 2 0] labels: [2 2 0 0 1 0 0 2] ############# predictions: [0 2 2 0 2 1 1 1] labels: [0 0 0 1 0 0 1 0] ############# predictions: [0 2 2 0 1 1 1 2] labels: [2 1 1 1 2 2 1 0] ############# predictions: [2 1 1 2 2 0 2 0] labels: [1 2 1 2 1 0 2 1] ############# predictions: [0 2 2 0 0 2 1 2] labels: [0 0 2 2 0 0 2 0] ############# predictions: [0 0 1 2 2 0 2 2] labels: [0 0 0 0 0 0 0 0] ############# predictions: [1 1 2 1 2 0 1 2] labels: [0 0 2 0 0 0 1 1] ############# predictions: [0 0 2 1 0 2 0 1] labels: [1 1 2 1 1 0 2 0] ############# predictions: [0 0 0 0 1 0 0 0] labels: [2 2 1 1 2 1 1 1] ############# predictions: [0 0 0 0 1 0 0 0] labels: [1 1 2 2 1 1 2 0] ############# predictions: [0 0 0 0 0 1 1 1] labels: [2 0 1 1 0 1 2 2] ############# predictions: [0 0 1 0 0 1 2 1] labels: [1 2 0 2 2 0 2 1] ############# predictions: [1 1 1 1 0 1 0 1] labels: [2 0 1 0 1 0 1 2] ############# predictions: [1 2 2 0 0 0 1 1] labels: [2 0 0 2 1 2 2 2] ############# predictions: [1 0 2 1 0 2 2 0] labels: [0 0 2 1 2 1 1 1] ############# predictions: [0 0 0 1 1 1 1 1] labels: [1 2 1 0 0 0 1 0] ############# predictions: [1 1 1 0 1 1 0 1] labels: [0 2 1 2 1 2 2 0] ############# predictions: [2 1 0 1 1 2 0 0] labels: [0 1 0 0 1 2 0 2] ############# predictions: [0 1 1 0 0 1 0 1] labels: [1 0 0 2 2 1 1 2] ############# predictions: [1 1 1 1 1 1 1 1] labels: [2 0 1 0 2 0 0 2] ############# predictions: [1 0 0 1 0 1 0 2] labels: [1 0 0 1 1 2 2 1] ############# predictions: [1 1 1 1 1 1 0 0] labels: [1 1 0 2 1 0 2 0] ############# predictions: [1 1 2 1 0 1 0 0] labels: [0 2 1 2 1 1 0 2] ############# predictions: [1 1 0 0 1 2 1 1] labels: [0 2 1 0 2 2 0 1] ############# predictions: [0 1 1 0 0 1 0 1] labels: [0 0 1 2 2 0 1 2] ############# predictions: [1 0 2 2 2 1 1 0] labels: [2 2 1 0 0 1 1 2] ############# predictions: [1 2 2 1 1 2 1 1] labels: [1 0 0 1 0 0 0 0] ############# predictions: [0 2 0 2 2 0 2 2] labels: [2 0 0 0 2 1 1 2] ############# predictions: [0 0 1 0 1 0 2 2] labels: [0 0 1 0 1 0 2 0] ############# predictions: [0 2 0 1 1 2 2 0] labels: [0 2 0 2 0 2 0 0] ############# predictions: [2 2 2 2 2 2 2 1] labels: [2 2 1 1 0 0 2 2] ############# predictions: [2 0 0 2 2 1 1 0] labels: [1 0 0 1 0 2 1 2] ############# predictions: [2 0 0 2 0 2 2 0] labels: [2 2 2 2 0 1 1 1] ############# predictions: [0 2 2 0 2 2 0 0] labels: [1 0 1 2 0 1 1 1] ############# predictions: [0 0 0 0 0 0 0 2] labels: [2 1 1 0 0 0 1 2] ############# predictions: [2 0 2 0 2 1 0 2] labels: [2 1 1 2 1 1 0 0] ############# predictions: [1 1 2 0 2 0 2 2] labels: [0 2 1 2 1 2 1 0] ############# predictions: [2 0 1 1 0 2 0 0] labels: [2 1 0 1 1 0 2 0] ############# predictions: [2 0 0 2 0 2 1 0] labels: [0 0 0 0 2 1 0 1] ############# predictions: [1 2 1 0 0 2 0 2] labels: [2 0 2 1 0 0 1 1] ############# Training Loss: tensor(1.1162, device='cuda:0', grad_fn=<NllLossBackward>) predictions: [2 0 0 1 1 1 0 1] labels: [0 1 1 1 1 2 2 1] ############# predictions: [0 2 0 1 2 0 0 1] labels: [2 2 1 0 1 0 0 0] ############# predictions: [0 0 1 0 0 0 0 1] labels: [1 0 2 0 0 2 2 0] ############# predictions: [2 1 2 2 0 1 2 0] labels: [2 0 1 0 2 1 0 1] ############# predictions: [1 0 0 2 0 0 1 1] labels: [2 2 0 2 0 2 0 0] ############# predictions: [0 0 1 0 0 0 0 0] labels: [2 2 2 1 2 2 2 2] ############# predictions: [0 0 1 1 0 1 1 0] labels: [2 1 1 1 0 2 1 0] ############# predictions: [0 0 0 1 0 0 1 0] labels: [2 0 2 2 0 0 1 2] ############# predictions: [1 0 1 0 0 2 0 0] labels: [1 1 2 0 0 1 0 0] ############# predictions: [2 1 0 0 0 1 0 0] labels: [1 2 0 0 0 0 0 0] ############# predictions: [0 2 0 0 0 0 0 0] labels: [2 0 1 1 2 2 1 1] ############# predictions: [0 1 0 0 0 1 0 2] labels: [0 2 1 1 0 0 1 2] ############# predictions: [0 2 1 0 0 1 1 1] labels: [1 1 0 2 0 1 1 0] ############# predictions: [0 1 1 0 0 0 1 0] labels: [0 0 1 0 1 2 1 1] ############# predictions: [0 1 1 0 1 0 0 0] labels: [0 1 1 1 2 2 2 0] ############# predictions: [0 0 0 0 1 1 0 0] labels: [2 0 2 2 1 2 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 0 2 2 0 1 1] ############# predictions: [0 1 0 0 0 0 0 0] labels: [0 2 0 1 1 2 0 2] ############# predictions: [1 1 0 1 0 1 0 2] labels: [1 2 0 0 2 2 2 1] ############# predictions: [1 1 0 0 0 1 2 1] labels: [0 0 1 2 2 1 2 2] ############# predictions: [1 1 1 0 1 1 2 0] labels: [0 0 0 2 0 1 0 2] ############# predictions: [0 1 0 0 1 1 2 1] labels: [2 0 0 1 2 2 1 2] ############# predictions: [1 0 0 0 1 0 0 1] labels: [1 2 2 2 2 1 0 1] ############# predictions: [2 0 0 0 0 0 0 0] labels: [1 2 0 2 2 1 1 1] ############# predictions: [2 0 1 1 0 0 1 0] labels: [0 0 0 0 2 2 1 1] ############# predictions: [2 0 0 1 0 0 1 1] labels: [2 2 1 1 0 0 1 0] ############# predictions: [1 1 1 1 1 2 0 0] labels: [0 0 2 1 0 0 0 0] ############# predictions: [1 1 2 0 1 2 0 1] labels: [0 2 1 0 2 0 0 1] ############# predictions: [0 0 2 1 0 2 0 1] labels: [1 2 0 2 2 1 0 0] ############# predictions: [0 0 2 0 2 1 1 2] labels: [2 2 1 2 2 2 0 0] ############# predictions: [0 1 0 0 0 0 2 1] labels: [1 1 0 1 1 1 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 0 0 2 0 0 2] ############# predictions: [2 2 2 0 1 1 1 0] labels: [1 0 2 1 1 2 0 0] ############# predictions: [0 0 1 0 0 0 2 0] labels: [0 1 2 1 1 0 0 0] ############# predictions: [0 2 0 1 0 2 0 0] labels: [0 0 2 1 1 0 2 2] ############# predictions: [0 0 1 2 0 2 0 1] labels: [2 2 0 0 0 2 2 2] ############# predictions: [1 0 0 0 2 0 0 1] labels: [2 0 1 1 1 0 0 1] ############# predictions: [0 1 0 0 0 0 0 2] labels: [1 1 1 0 0 0 2 2] ############# predictions: [0 2 0 1 0 2 0 0] labels: [1 1 1 1 2 2 1 0] ############# predictions: [1 2 0 0 0 0 0 0] labels: [2 0 2 1 0 1 1 1] ############# Training Loss: tensor(1.2082, device='cuda:0', grad_fn=<NllLossBackward>) predictions: [0 2 0 0 0 0 2 0] labels: [1 0 2 1 2 2 1 1] ############# predictions: [2 0 0 0 0 0 1 0] labels: [1 0 0 0 0 2 1 0] ############# predictions: [0 0 0 0 2 1 1 1] labels: [0 2 2 0 1 2 1 1] ############# predictions: [2 1 0 1 0 0 2 0] labels: [1 0 2 1 0 2 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 0 0 0 0 1 0] ############# predictions: [0 2 1 0 0 0 1 1] labels: [0 2 2 2 2 1 1 0] ############# predictions: [0 0 0 1 1 0 0 1] labels: [0 1 0 1 2 2 2 2] ############# predictions: [0 0 0 1 1 1 1 2] labels: [2 2 1 2 0 1 1 1] ############# predictions: [0 1 2 0 0 1 0 0] labels: [0 2 1 0 0 1 0 0] ############# predictions: [1 1 1 1 0 0 0 0] labels: [2 1 2 1 0 2 2 1] ############# predictions: [0 1 2 0 0 1 1 0] labels: [2 0 2 1 1 1 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 0 0 1 1 0 0] ############# predictions: [0 0 0 0 0 1 2 2] labels: [2 2 1 1 0 2 1 2] ############# predictions: [0 1 0 0 1 1 0 1] labels: [0 1 0 2 1 0 0 1] ############# predictions: [0 2 2 0 0 0 0 2] labels: [0 0 2 1 2 2 0 1] ############# predictions: [2 0 0 2 2 0 2 0] labels: [2 1 0 2 2 0 1 0] ############# predictions: [0 2 2 0 2 1 1 2] labels: [1 1 0 0 2 1 0 0] ############# predictions: [1 1 2 2 0 0 1 2] labels: [2 0 2 0 1 1 1 1] ############# predictions: [0 1 1 0 0 1 1 0] labels: [0 2 1 0 0 2 2 0] ############# predictions: [2 1 0 0 0 0 1 1] labels: [0 2 0 2 0 0 1 1] ############# predictions: [1 2 0 1 2 0 0 0] labels: [1 0 1 1 0 2 2 2] ############# predictions: [0 0 0 0 2 2 1 2] labels: [2 2 2 1 1 1 1 0] ############# predictions: [1 2 0 1 0 0 2 0] labels: [2 2 1 1 1 0 2 0] ############# predictions: [2 0 0 0 0 2 1] labels: [0 1 1 2 2 0 2] ############# ======Average Training Loss: 1.11279====== ======Average Training Accuracy: 33.77%====== predictions: [0 0 0 0 0 0 0 0] labels: [0 2 0 1 1 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 0 2 1 0 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 2 2 2 1 2 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 1 2 0 1 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 2 0 0 1 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 0 1 2 1 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 2 1 2 0 2 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 1 2 2 1 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 0 2 2 0 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 0 0 2 0 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 0 1 1 2 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 1 2 2 0 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 0 0 1 2 2 1] ############# predictions: [0 0 0 1 0 0 0 0] labels: [0 0 1 1 0 2 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 1 2 2 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 1 2 2 2 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 2 1 2 0 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 0 0 2 2 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 1 0 1 0 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 2 2 2 2 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 2 1 1 0 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 2 1 1 2 0 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 2 1 2 2 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 0 1 0 2 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 1 2 1 1 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 0 1 2 1 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 1 1 1 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 1 0 0 2 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 1 0 0 0 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 1 1 1 2 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 0 1 2 1 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 2 0 1 1 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 1 0 1 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 1 2 2 1 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 2 0 2 0 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 1 1 1 0 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 1 2 2 0 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 1 2 0 0 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 0 0 1 0 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 2 1 1 2 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 2 2 2 2 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 2 2 1 0 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 2 2 2 1 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 0 0 1 0 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 1 0 0 0 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 2 1 2 0 2 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 2 0 1 2 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 2 0 0 0 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 1 0 0 0 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 0 1 1 2 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 0 0 0 2 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 2 1 1 1 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 0 0 2 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 2 1 0 2 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 0 1 2 2 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 0 0 2 1 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 2 0 2 1 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 0 2 0 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 0 0 1 0 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 2 2 0 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 1 1 1 0 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 1 2 2 1 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 0 2 0 2 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 0 1 1 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 1 1 1 1 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 2 1 0 0 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 1 2 1 0 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 2 2 0 0 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 2 2 0 0 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 0 2 2 2 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 0 0 1 2 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 1 2 0 1 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 0 0 0 2 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 1 2 0 2 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 1 1 0 1 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 2 0 1 0 0 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 0 0 0 2 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 1 1 2 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 2 2 0 1 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 2 0 1 1 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 0 0 1 2 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 2 1 2 0 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 1 1 1 0 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 1 1 2 0 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 1 0 1 1 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 2 0 2 1 0 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 0 0 0 2 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 0 1 2 2 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 1 2 0 1 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 2 1 0 2 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 1 2 0 2 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 1 2 2 2 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 1 1 2 0 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 0 1 1 0 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 2 2 2 2 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 0 0 0 1 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 2 1 2 1 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 0 0 0 2 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 0 1 1 1 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 1 0 2 2 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 1 1 1 2 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 2 0 1 0 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 0 2 2 0 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 1 2 2 2 1 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 0 1 0 2 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 2 1 0 2 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 2 0 2 2 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 2 0 0 1 0 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 1 0 0 0 2 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 2 0 1 2 1 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 2 2 2 2 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 0 1 2 0 2 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 2 1 1 1 1 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 0 0 0 1 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 1 2 0 1 2 2 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 1 1 1 2 1 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [1 0 1 1 1 0 0 2] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 2 0 0 0 0 1 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [0 0 1 1 2 0 0 1] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 1 1 1 0 1 0 0] ############# predictions: [0 0 0 0 0 0 0 0] labels: [2 0 2 2 2 0 0 1] ############# predictions: [0 0 0 0 0 0 0] labels: [2 2 1 1 0 0 1] ############# ======Average Validation Loss: 1.09527====== ======Average Validation Accuracy: 35.53%======
For multi-class classification/sentiment analysis using BERT the 'neutral' class HAS TO BE 2!! It CANNOT be between 'negative' = 0 and 'positive' = 2
https://stackoverflow.com/questions/64675655/
Error while installing PyTorch using pip - cannot build wheel
I get the following output when I try to run pip3 install pytorch or pip install pytorch Collecting pytorch Using cached pytorch-1.0.2.tar.gz (689 bytes) Building wheels for collected packages: pytorch Building wheel for pytorch (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/chaitanya/anaconda3/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-3v4wd97t/pytorch/setup.py'"'"'; __file__='"'"'/tmp/pip-install-3v4wd97t/pytorch/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-8rsdyb8e cwd: /tmp/pip-install-3v4wd97t/pytorch/ Complete output (5 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-3v4wd97t/pytorch/setup.py", line 15, in <module> raise Exception(message) Exception: You tried to install "pytorch". The package named for PyTorch is "torch" ---------------------------------------- ERROR: Failed building wheel for pytorch Running setup.py clean for pytorch Failed to build pytorch Installing collected packages: pytorch Running setup.py install for pytorch ... error ERROR: Command errored out with exit status 1: command: /home/chaitanya/anaconda3/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-3v4wd97t/pytorch/setup.py'"'"'; __file__='"'"'/tmp/pip-install-3v4wd97t/pytorch/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-eld9j0g4/install-record.txt --single-version-externally-managed --user --prefix= --compile --install-headers /home/chaitanya/.local/include/python3.8/pytorch cwd: /tmp/pip-install-3v4wd97t/pytorch/ Complete output (5 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-3v4wd97t/pytorch/setup.py", line 11, in <module> raise Exception(message) Exception: You tried to install "pytorch". The package named for PyTorch is "torch" ---------------------------------------- ERROR: Command errored out with exit status 1: /home/chaitanya/anaconda3/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-3v4wd97t/pytorch/setup.py'"'"'; __file__='"'"'/tmp/pip-install-3v4wd97t/pytorch/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-eld9j0g4/install-record.txt --single-version-externally-managed --user --prefix= --compile --install-headers /home/chaitanya/.local/include/python3.8/pytorch Check the logs for full command output. I downloaded the matching wheel from here, but am couldn't figure out what to do with it. My Python installation is using anaconda3, if that's needed. What should I do from here? Tips on how I could have resolved this on my own would also be appreciated.
From your error: Exception: You tried to install "pytorch". The package named for PyTorch is "torch" which tells you what you need to know, instead of pip install pytorch it should be pip install torch I downloaded the matching wheel from here, but am couldn't figure out what to do with it Installing .whl files is as easy as pip install <path to .whl file> My Python installation is using anaconda3 That is very relevant. You should generally avoid as much as possible to use pip in your conda environment. Instead, you can find the correct conda install command for your setup(cuda version etc.) from pytroch.org, e.g. for cuda 11 it would be conda install pytorch torchvision torchaudio cudatoolkit=11.0 -c pytorch
https://stackoverflow.com/questions/64679865/
Transformers get named entity prediction for words instead of tokens
This is very basic question, but I spend hours struggling to find the answer. I built NER using Hugginface transformers. Say I have input sentence input = "Damien Hirst oil in canvas" I tokenize it to get tokenizer = transformers.BertTokenizer.from_pretrained('bert-base-uncased') tokenized = tokenizer.encode(input) #[101, 12587, 7632, 12096, 3514, 1999, 10683, 102] Feed tokenized sentence to the model to get predicted tags for the tokens ['B-ARTIST' 'B-ARTIST' 'I-ARTIST' 'I-ARTIST' 'B-MEDIUM' 'I-MEDIUM' 'I-MEDIUM' 'B-ARTIST'] prediction comes as output from the model. It assigns tags to different tokens. How can I recombine this data to obtain tags for words instead of tokens? So I would know that "Damien Hirst" = ARTIST "Oil in canvas" = MEDIUM
There are two questions here. Annotating Token Classification A common sequential tagging, especially in Named Entity Recognition, follows the scheme that a sequence to tokens with tag X at the beginning gets B-X and on reset of the labels it gets I-X. The problem is that most annotated datasets are tokenized with space! For example: [CSL] O Damien B-ARTIST Hirst I-ARTIST oil B-MEDIUM in I-MEDIUM canvas I-MEDIUM [SEP] O where O indicates that it is not a named-entity, B-ARTIST is the beginning of the sequence of tokens labelled as ARTIST and I-ARTIST is inside the sequence - similar pattern for MEDIUM. At the moment I posted this answer, there is an example of NER in huggingface documentation here: https://huggingface.co/transformers/usage.html#named-entity-recognition The example doesn't exactly answer the question here, but it can add some clarification. The similar style of named entity labels in that example could be as follows: label_list = [ "O", # not a named entity "B-ARTIST", # beginning of an artist name "I-ARTIST", # an artist name "B-MEDIUM", # beginning of a medium name "I-MEDIUM", # a medium name ] Adapt Tokenizations With all that said about annotation schema, BERT and several other models have different tokenization model. So, we have to adapt these two tokenizations. In this case with bert-base-uncased, the expected outcome is like this: damien B-ARTIST hi I-ARTIST ##rst I-ARTIST oil B-MEDIUM in I-MEDIUM canvas I-MEDIUM In order to get this done, you can go through each token in original annotation, then tokenize it and add its label again: tokens_old = ['Damien', 'Hirst', 'oil', 'in', 'canvas'] labels_old = ["B-ARTIST", "I-ARTIST", "B-MEDIUM", "I-MEDIUM", "I-MEDIUM"] label2id = {label: idx for idx, label in enumerate(label_list)} tokens, labels = zip(*[ (token, label) for token_old, label in zip(tokens_old, labels_old) for token in tokenizer.tokenize(token_old) ]) When you add [CLS] and [SEP] in the tokens, their labels "O" must be added to labels. With the code above, it is possible to get into a situation that a beginning tag like B-ARTIST get repeated when the beginning word splits into pieces. According to the description in huggingface documentation, you can encode these labels with -100 to be ignored: https://huggingface.co/transformers/custom_datasets.html#token-classification-with-w-nut-emerging-entities Something like this should work: tokens, labels = zip(*[ (token, label2id[label] if (label[:2] != "B-" or i == 0) else -100) for token_old, label in zip(tokens_old, labels_old) for i, token in enumerate(tokenizer.tokenize(token_old)) ])
https://stackoverflow.com/questions/64684506/
Specifying cpu-only for pytorch in conda YAML file
I can set up a conda environment successfully as follows: conda create --name temp python=3.8.5 conda install pytorch==1.6.0 torchvision==0.7.0 cpuonly -c pytorch I then save the environment to a YAML config file. The looks like this: name: temp channels: - pytorch - defaults dependencies: - _libgcc_mutex=0.1=main - blas=1.0=mkl - ca-certificates=2020.10.14=0 - certifi=2020.6.20=pyhd3eb1b0_3 - cpuonly=1.0=0 - freetype=2.10.4=h5ab3b9f_0 - intel-openmp=2020.2=254 - jpeg=9b=h024ee3a_2 - lcms2=2.11=h396b838_0 - ld_impl_linux-64=2.33.1=h53a641e_7 - libedit=3.1.20191231=h14c3975_1 - libffi=3.3=he6710b0_2 - libgcc-ng=9.1.0=hdf63c60_0 - libpng=1.6.37=hbc83047_0 - libstdcxx-ng=9.1.0=hdf63c60_0 - libtiff=4.1.0=h2733197_1 - lz4-c=1.9.2=heb0550a_3 - mkl=2020.2=256 - mkl-service=2.3.0=py38he904b0f_0 - mkl_fft=1.2.0=py38h23d657b_0 - mkl_random=1.1.1=py38h0573a6f_0 - ncurses=6.2=he6710b0_1 - ninja=1.10.1=py38hfd86e86_0 - numpy=1.19.2=py38h54aff64_0 - numpy-base=1.19.2=py38hfa32c7d_0 - olefile=0.46=py_0 - openssl=1.1.1h=h7b6447c_0 - pillow=8.0.1=py38he98fc37_0 - pip=20.2.4=py38h06a4308_0 - python=3.8.5=h7579374_1 - pytorch=1.6.0=py3.8_cpu_0 - readline=8.0=h7b6447c_0 - setuptools=50.3.0=py38h06a4308_1 - six=1.15.0=py_0 - sqlite=3.33.0=h62c20be_0 - tk=8.6.10=hbc83047_0 - torchvision=0.7.0=py38_cpu - wheel=0.35.1=py_0 - xz=5.2.5=h7b6447c_0 - zlib=1.2.11=h7b6447c_3 - zstd=1.4.5=h9ceee32_0 prefix: /data/anaconda/envs/temp But if I try making a conda environment from the following file: name: temp channels: - defaults - pytorch dependencies: - python==3.8.5 - pytorch==1.6.0=py3.8_cpu_0 it fails, with the following incompatibilities: UnsatisfiableError: The following specifications were found to be incompatible with each other: Package ld_impl_linux-64 conflicts for: python==3.8.5 -> ld_impl_linux-64 Package sqlite conflicts for: python==3.8.5 -> sqlite[version='>=3.32.3,<4.0a0|>=3.33.0,<4.0a0'] Package * conflicts for: pytorch==1.6.0=py3.8_cpu_0 -> *[track_features=cpuonly] Package ncurses conflicts for: python==3.8.5 -> ncurses[version='>=6.2,<7.0a0'] Package mkl conflicts for: pytorch==1.6.0=py3.8_cpu_0 -> mkl[version='>=2018'] Package blas conflicts for: pytorch==1.6.0=py3.8_cpu_0 -> blas=[build=mkl] Package zlib conflicts for: python==3.8.5 -> zlib[version='>=1.2.11,<1.3.0a0'] Package openssl conflicts for: python==3.8.5 -> openssl[version='>=1.1.1g,<1.1.2a'] Package python conflicts for: pytorch==1.6.0=py3.8_cpu_0 -> python[version='>=3.8,<3.9.0a0'] Package xz conflicts for: python==3.8.5 -> xz[version='>=5.2.5,<6.0a0'] Package libffi conflicts for: python==3.8.5 -> libffi[version='>=3.3,<3.4.0a0'] Package libgcc-ng conflicts for: python==3.8.5 -> libgcc-ng[version='>=7.3.0'] Package tk conflicts for: python==3.8.5 -> tk[version='>=8.6.10,<8.7.0a0'] Package pip conflicts for: python==3.8.5 -> pip Package ninja conflicts for: pytorch==1.6.0=py3.8_cpu_0 -> ninja Package readline conflicts for: python==3.8.5 -> readline[version='>=8.0,<9.0a0'] Package numpy conflicts for: pytorch==1.6.0=py3.8_cpu_0 -> numpy[version='>=1.11'] Why? How could such a simple configuration, which was cut down from a successful environment, fail? How should I specify the CPU-only version of pytorch 1.6.0 in a YAML config file for a conda environment?
For systems that have optional CUDA support (Linux and Windows) PyTorch provides a mutex metapackage cpuonly that when installed constrains the pytorch package solve to only non-CUDA builds. Going through the PyTorch installation widget will suggest including the cpuonly package when selecting "NONE" of the CUDA option I don't know the internals of how to build packages that use such mutex metapackages, but mutex metapackages are documented with metapackages in general, and the docs include links to MKL vs OpenBLAS examples. Exactly why the simple YAML you started with fails is still unclear to me, but my guess is that cpuonly constrains more than just the pytorch build and having the specific pytorch build alone is not sufficient to constrain its dependencies.
https://stackoverflow.com/questions/64685062/
Inconsistency in loss on SAME data for train and validation modes tensorflow
I'm implementing a semantic segmentation model with images. As a good practice I tested my training pipeline with just one image and tried to over-fit that image. To my surprise, when training with the exactly the same images, the loss goes to near 0 as expected but when evaluating THE SAME IMAGES, the loss is much much higher, and it keeps going up as the training continues. So the segmentation output is garbage when training=False, but when run with training=True is works perfectly. To be able to anyone to reproduce this I took the official segmentation tutorial and modified it a little for training a convnet from scratch and just 1 image. The model is very simple, just a sequence of Conv2D with batch normalization and Relu. The results are the following As you see the loss and eval_loss are really different, and making inference to the image gives perfect result in training mode and in eval mode is garbage. I know Batchnormalization behaves differently in inference time since it uses the averaged statistics calculated whilst training. Nonetheless, since we are training with just 1 same image and evaluating in the same image, this shouldn't happen right? Moreover I implemented the same architecture with the same optimizer in Pytorch and this does not happen there. With pytorch it trains and eval_loss converges to train loss Here you can find the above mentioned https://colab.research.google.com/drive/18LipgAmKVDA86n3ljFW8X0JThVEeFf0a#scrollTo=TWDATghoRczu and at the end also the Pytorch implementation
It had to do more with the defaults values that tensorflow uses. Batchnormalization has a parameter momentum which controls the averaging of batch statistics. The formula is: moving_mean = moving_mean * momentum + mean(batch) * (1 - momentum) If you set momentum=0.0 in the BatchNorm layer, the averaged statistics should match perfectly with the statistics from the current batch (which is just 1 image). If you do so, you see that the validation loss almost immediately matches the training loss. Also if you try with momentum=0.9 (which is the equivalent default value in pytorch) and it works and converges faster (as in pytorch).
https://stackoverflow.com/questions/64687406/
Pytorch DQN, DDQN using .detach() caused very wield loss (increases exponentially) and do not learn at all
Here is my implementation of DQN and DDQN for CartPole-v0 which I think is correct. import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import gym import torch.optim as optim import random import os import time class NETWORK(torch.nn.Module): def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None: super(NETWORK, self).__init__() self.layer1 = torch.nn.Sequential( torch.nn.Linear(input_dim, hidden_dim), torch.nn.ReLU() ) self.layer2 = torch.nn.Sequential( torch.nn.Linear(hidden_dim, hidden_dim), torch.nn.ReLU() ) self.final = torch.nn.Linear(hidden_dim, output_dim) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.layer1(x) x = self.layer2(x) x = self.final(x) return x class ReplayBuffer(object): def __init__(self, capacity=50000): self.capacity = capacity self.memory = [] self.position = 0 def push(self, s0, a0, r, s1): if len(self.memory) < self.capacity: self.memory.append(None) self.memory[self.position] = (s0, a0, r, s1) self.position = (self.position + 1) % self.capacity def sample(self, batch_size=64): return random.sample(self.memory, batch_size) def __len__(self): return len(self.memory) class DQN(object): def __init__(self): self.state_dim = 4 self.action_dim = 2 self.lr = 0.001 self.discount_factor = 0.99 self.epsilon = 1 self.epsilon_decay = 0.95 self.num_train = 0 self.num_train_episodes = 0 self.batch_size = 64 self.predict_network = NETWORK(input_dim=4, output_dim=2, hidden_dim=16).double() self.memory = ReplayBuffer(capacity=50000) self.optimizer = torch.optim.Adam(self.predict_network.parameters(), lr=self.lr) self.loss = 0 def select_action(self, states: np.ndarray) -> int: if np.random.uniform(0, 1) < self.epsilon: return np.random.choice(self.action_dim) else: states = torch.from_numpy(states).unsqueeze_(dim=0) with torch.no_grad(): Q_values = self.predict_network(states) action = torch.argmax(Q_values).item() return action def policy(self, states: np.ndarray) -> int: states = torch.from_numpy(states).unsqueeze_(dim=0) with torch.no_grad(): Q_values = self.predict_network(states) action = torch.argmax(Q_values).item() return action def train(self, s0, a0, r, s1, sign): if sign == 1: self.num_train_episodes += 1 if self.epsilon > 0.01: self.epsilon = max(self.epsilon * self.epsilon_decay, 0.01) return self.num_train += 1 self.memory.push(s0, a0, r, s1) if len(self.memory) < self.batch_size: return batch = self.memory.sample(self.batch_size) state_batch = torch.from_numpy(np.stack([b[0] for b in batch])) action_batch = torch.from_numpy(np.stack([b[1] for b in batch])) reward_batch = torch.from_numpy(np.stack([b[2] for b in batch])) next_state_batch = torch.from_numpy(np.stack([b[3] for b in batch])) Q_values = self.predict_network(state_batch)[torch.arange(self.batch_size), action_batch] next_state_Q_values = self.predict_network(next_state_batch).max(dim=1)[0] Q_targets = self.discount_factor * next_state_Q_values + reward_batch loss = F.mse_loss(Q_values, Q_targets.detach()) self.optimizer.zero_grad() loss.backward() self.optimizer.step() self.loss = loss.data.item() class DDQN(object): def __init__(self): self.state_dim = 4 self.action_dim = 2 self.lr = 0.001 self.discount_factor = 0.9 self.epsilon = 1 self.epsilon_decay = 0.95 self.num_train = 0 self.num_train_episodes = 0 self.batch_size = 64 self.predict_network = NETWORK(input_dim=4, output_dim=2, hidden_dim=16).double() self.target_network = NETWORK(input_dim=4, output_dim=2, hidden_dim=16).double() self.target_network.load_state_dict(self.predict_network.state_dict()) self.target_network.eval() self.memory = ReplayBuffer(capacity=50000) self.optimizer = torch.optim.Adam(self.predict_network.parameters(), lr=self.lr) self.loss = 0 def select_action(self, states: np.ndarray) -> int: if np.random.uniform(0, 1) < self.epsilon: return np.random.choice(self.action_dim) else: states = torch.from_numpy(states).unsqueeze_(dim=0) with torch.no_grad(): Q_values = self.predict_network(states) action = torch.argmax(Q_values).item() return action def policy(self, states: np.ndarray) -> int: states = torch.from_numpy(states).unsqueeze_(dim=0) with torch.no_grad(): Q_values = self.predict_network(states) action = torch.argmax(Q_values).item() return action def train(self, s0, a0, r, s1, sign): if sign == 1: self.num_train_episodes += 1 if self.num_train_episodes % 2 == 0: self.target_network.load_state_dict(self.predict_network.state_dict()) self.target_network.eval() if self.epsilon > 0.01: self.epsilon = max(self.epsilon * self.epsilon_decay, 0.01) return self.num_train += 1 self.memory.push(s0, a0, r, s1) if len(self.memory) < self.batch_size: return batch = self.memory.sample(self.batch_size) state_batch = torch.from_numpy(np.stack([b[0] for b in batch])) action_batch = torch.from_numpy(np.stack([b[1] for b in batch])) reward_batch = torch.from_numpy(np.stack([b[2] for b in batch])) next_state_batch = torch.from_numpy(np.stack([b[3] for b in batch])) Q_values = self.predict_network(state_batch)[torch.arange(self.batch_size), action_batch] next_state_action_batch = torch.argmax(self.predict_network(next_state_batch), dim=1) next_state_Q_values = self.target_network(next_state_batch)[torch.arange(self.batch_size), next_state_action_batch] Q_targets = self.discount_factor * next_state_Q_values + reward_batch loss = F.smooth_l1_loss(Q_values, Q_targets.detach()) self.optimizer.zero_grad() loss.backward() self.optimizer.step() self.loss = loss.data.item() I used following to evaluate and train my DQN and DDQN. def eval_policy(agent, env_name, eval_episodes=10): eval_env = gym.make(env_name) avg_reward = 0. for _ in range(eval_episodes): state, done = eval_env.reset(), False while not done: action = agent.policy(state) state, reward, done, _ = eval_env.step(action) avg_reward += reward avg_reward /= eval_episodes print("---------------------------------------") print(f"Evaluation over {eval_episodes} episodes: {avg_reward:.3f}") print("---------------------------------------") return avg_reward env_name = 'CartPole-v0' env = gym.make(env_name) agent = DQN() # agent = DDQN() for i in range(1000): state, done = env.reset(), False episodic_reward = 0 while not done: action = agent.select_action(np.squeeze(state)) next_state, reward, done, info = env.step(action) episodic_reward += reward sign = 1 if done else 0 agent.train(state, action, reward, next_state, sign) state = next_state print(f'episode: {i}, reward: {episodic_reward}') if i % 20 == 0: eval_reward = eval_policy(agent, env_name, eval_episodes=50) if eval_reward >= 195: print("Problem solved in {} episodes".format(i + 1)) break The thing is that my DQN networks do not train and the loss grow exponentially using target.detach() in loss calculation. If I do not use .detach(), the DQN object would train but I believe that is not the correct way. For DDQN, my networks always do not train. Can anyone give some advice on where might be wrong?
so one mistake in your implementation is that you never add the end of an episode to your replay buffer. In your train function you return if sign==1 (end of the episode). Remove that return and adjust the target calculation via (1-dones)*... in case you sample a transition of the end of an episode. The reason why the end of the episode is important is that it is the only experience is where the target is not approximated via bootstrapping. Then DQN trains. For reproducibility I used a discount rate of 0.99 and the seed 2020 (for torch, numpy and the gym environment). I achieved a reward of 199.100 after 241 episodes of training. Hope that helps, code is very readable btw.
https://stackoverflow.com/questions/64690471/
How PyTorch implements Convolution Backward?
I read about the Pytorch's source code, and I find it's weird that it doesn't implement the convolution_backward function, The only convolution_backward_overrideable function is directly raises an error and supposed not to fall here. So I referred to CuDNN / MKLDNN implementation, they both implements functions like cudnn_convolution_backward. I got the following question: What are the native implementation of CUDA/ CPU? I can find something like thnn_conv2d_backward_out, but I could not find where are this is called. Why PyTorch didn't put the convolution_backward function in Convolution.cpp? It offers an _convolution_double_backward() function. But this is the double backward, it's the gradient of gradient. Why don't they offer a single backward function? If I want to call the native convolution/ convolution_backward function for my pure cpu/cuda tensor, how should I write code? Or where could I refer to? I couldn't find example for this. Thanks !
1- Implementation may differ depending on which backend you use, it may use CUDA convolution implementation from some library, CPU convolution implementation from some other library, or custom implementation, see here: pytorch - Where is “conv1d” implemented?. 2- I am not sure about the current version, but single backward was calculated via autograd, that is why there was not an explicit different function for it. I don't know the underlying details of autograd but you can check https://github.com/pytorch/pytorch/blob/master/torch/csrc/autograd/autograd.cpp. That double_backward function is only there if you need higher order derivatives. 3- If you want to do this in C, the file you linked (convolution.cpp) shows you how to do this (function at::Tensor _convolution...). If you inspect the function you see it just checks which implementation to use (params.use_something...) and use it. If you want to do this in python you should start tracing from conv until where this file convolution.cpp is called.
https://stackoverflow.com/questions/64693256/
Exporting forecast data from darts
I am trying to export the forecasts I made with Pytorch models in darts library to some exchangeable format like XLS or CSV. Is it somehow possible to export the predictions from the Timeseries class? How can I specify output format?
Forecasts in Darts are nothing but regular TimeSeries objects and a TimeSeries is internally represented as a pandas.DataFrame. You can access this DataFrame using series.pd_dataframe() (to get a copy of the DataFrame) or series._df directly if you want to avoid copying the DataFrame to save it. Be careful in the latter case however, as modifying the DataFrame in place will break the TimeSeries immutability. You can then use any method you'd like to save pandas dataframes, e.g. pandas.DataFrame.to_csv() or pandas.DataFrame.to_pickle(). You can have a look at this article on Medium to see a comparison of a couple different formats' performances for saving and loading dataframes.
https://stackoverflow.com/questions/64697755/
Teacher force training PyTorch
I am trying to do a seq2seq prediction. For this, I have a LSTM layer followed by a fully connected layer. I employ Teacher training during the training phase and would like to skip this (I maybe wrong here) during testing phase. I have not found a direct way of doing this so I have taken the approach shown below. def forward(self, inputs, future=0, teacher_force_ratio=0.2, target=None): outputs = [] for idx in range(future): rnn_out, _ = self.rnn(inputs) output = self.fc1(rnn_out) if self.teacher_training: new_input = output if np.random.random() >= teacher_force_ratio else target[idx] else: new_input = output inputs = new_input I use a bool variable teacher_training to check if Teacher training is needed or not. Is this correct? If yes, is there a better way to do this? Thanks.
In PyTorch all classes that extend nn.Module have a kwarg boolean param called training . So instead of teacher_training we should simply use training param. This param is automatically set depending on your model training mode (model.train() and model.eval()).
https://stackoverflow.com/questions/64703326/
Find module corresponding to the method in python
I am learning to work with fastai. And I come across this: xt = tensor(3.).requires_grad_() xt [out1]: tensor(3., requires_grad=True) I want to know where requires_grad_() is from i.e., is it from fastai or is it pytorch related. So I do: requires_grad_.__module__ [out2]: NameError: name 'require_grad_' is not defined What am I doing wrong? What am I missing?
Err The key is you cannot access requires_grad_ directly. requires_grad_ is not a global object, it is a member method of xt, so you cannot access it directly (when you do this, you'll get the not define error), the way to access it is through the class instance it belongs to (xt), like print(xt.requires_grad_.__module__). Test According to doc on python.org, all of function, member method, class and class instance have __module__ attr. So the code print(xt.requires_grad_.__module__) should work, but when I tested the code print(xt.requires_grad_.__module__) and got output None rather than torch I expect, which is a litte bit wierd. I guess for torch Tensor's member method, this __module__ varible is unavailable. So then I tested another case (print the __module__ attr of a member method for another class DataFrame): from pandas import DataFrame a = DataFrame() a.min.__module__ and I got output pandas.core.frame which means we do can get __module__ attr from a member method object. However, in you case, the fastest way is to get the module of xt, since a class method must belongs to the module of its class instance, so you can just use print(xt.__module__) and you will get correct module name: torch. BTW, requires_grad_ belongs to torch.Tensor which belongs to torch module, at backprop phase, this func set a bool flag that tells torch whether gradient of tensor `xt
https://stackoverflow.com/questions/64706227/
Difference between loading my trained model in a pretrained model and loading it in not pretrained one?
I trained an Inception_v3 for my task. I have 3 classes. After training I try to test my trained model and I use following code to load my model: model = models.inception_v3(pretrained=True, aux_logits=False) model.fc = nn.Linear(model.fc.in_features, 3) model.load_state_dict(torch.load(My Model Path.pth)) Download a pretrained Inception_v3, change output features and load my weight in this model. I obtained very good results as I expect from validation phase. If I use the same code but with pretrained=False the test go very bad. model = models.inception_v3(pretrained=False, aux_logits=False) model.fc = nn.Linear(model.fc.in_features, 3) model.load_state_dict(torch.load(My Model Path.pth)) Since in the model I download I load my weights, there should be no difference between pretrained True or False. Does anyone know what changes?
The pretrained=True has an additional effect on the inception_v3 model: it controls whether or not the input will be preprocessed according to the method with which it was trained on ImageNet (source-code here). When you set pretrained=False, if you want to make things comparable at test time, you should also set transform_input=True: model = models.inception_v3(pretrained=False, aux_logits=False, transform_input=True) model.fc = nn.Linear(model.fc.in_features, 3) model.load_state_dict(torch.load(My Model Path.pth)) In case you're wondering, this is the preprocessing: def _transform_input(self, x: Tensor) -> Tensor: if self.transform_input: x_ch0 = torch.unsqueeze(x[:, 0], 1) * (0.229 / 0.5) + (0.485 - 0.5) / 0.5 x_ch1 = torch.unsqueeze(x[:, 1], 1) * (0.224 / 0.5) + (0.456 - 0.5) / 0.5 x_ch2 = torch.unsqueeze(x[:, 2], 1) * (0.225 / 0.5) + (0.406 - 0.5) / 0.5 x = torch.cat((x_ch0, x_ch1, x_ch2), 1) return x
https://stackoverflow.com/questions/64714933/
Save Pytorch 4D tensor as image
I have a 4-d Pytorch tensor that I would like to save to disk as a .jpg My tensor is the following size: print(image_tensor.size()) >>>torch.Size([1, 3, 400, 711]) I can view the entire tensor as one image within my IDE: ax1.imshow(im_convert(image_tensor)) Since I am able to view the entire tensor as one image, I am assuming there is a way to also save it as such. However, when I try to save the image, it looks like it only saves the blue color channel. I would like to save the entire tensor as a single image. img1 = image_tensor[0] save_image(img1, 'img1.jpg')
In PyTorch this snippet is working and saving the image: from torchvision.utils import save_image import torch import torchvision tensor= torch.rand(2, 3, 400, 711) img1 = tensor[0] save_image(img1, 'img1.png') Before saving the image can you check the shape of the img1 in any case something happened.
https://stackoverflow.com/questions/64716790/
Pytorch: How to create a random int tensor where a certain percent are of a certain value? For example, 25% are 1s, and rest 0s
In pytorch I can create a random zero and one tensor with around %50 distribution of each import torch torch.randint(low=0, high=2, size=(2, 5)) I am wondering how I can make a tensor where only 25% of the values are 1s, and the rest are zeros?
Following my answer here: How to randomly set a fixed number of elements in each row of a tensor in PyTorch Say you want a matrix with dimensions n X d where exactly 25% of the values in each row are 1 and the rest 0, desired_tensor will have the result you want: n = 2 d = 5 rand_mat = torch.rand(n, d) k = round(0.25 * d) # For the general case change 0.25 to the percentage you need k_th_quant = torch.topk(rand_mat, k, largest = False)[0][:,-1:] bool_tensor = rand_mat <= k_th_quant desired_tensor = torch.where(bool_tensor,torch.tensor(1),torch.tensor(0))
https://stackoverflow.com/questions/64721321/
How to save information about the result of instance segmentation by YOLACT?
Is there any way to save the detected categories, their number, MASK area, etc. to a TXT file or CSV file when performing instance segmentation using YOLACT? I’m using YOLACT (https://github.com/dbolya/yolact) to challenge instance segmentation. I was able to use eval.py to do an instance segmentation of my own data and save that image or video. However, what I really need is the class names and their numbers detected and classified by YOLACT's AI, and the area of ​​MASK. If we can output this information to a txt file or csv file, we can use YOLACT even more advanced. If I can achieve that by adding an option in eval.py or modifying the code, please teach me. Thank you.
You already have that information from the eval.py. This line in the eval.py gives you the information. # line 160 classes, scores, boxes = [x[:args.top_k].cpu().numpy() for x in t[:3]] masks = t[3][:args.top_k] areas = [] for mask in masks: # Use OpenCV's findContours() to detect and obtain the contour of the variable mask # Use OpenCV's contourArea() to calculate the area areas.append(area) Getting the no. of detections: # line 162 num_dets_to_consider = min(args.top_k, classes.shape[0]) for j in range(num_dets_to_consider): if scores[j] < args.score_threshold: num_dets_to_consider = j break To save the classes and scores as a csv file: import pandas as pd df = pd.DataFrame(columns=['class', 'score']) c = 0 for i in reversed(range(num_dets_to_consider)): classname = cfg.dataset.class_names[classes[j]] score = scores[i] df.loc[c] = [classname, score] c += 1 df.to_csv('info.csv', index=None) EDIT1: You can return the values (classes, scores, areas) from the prep_display() and then retrieve them in evalimage(). Note that evalimage() calls prep_display(). You can do something like this: classes, scores, areas = prep_display() # Here you can include the pandas code. Note that it stores the information only for one image. You can use a loop and then store the information of all the images. EDIT2: # This is the default line in eval.py at line ~600 # This is found at evalimage() img_numpy = prep_display(preds, frame, None, None, undo_transform=False) # Change the above line to this: classes, scores, areas, img_numpy = prep_display(preds, frame, None, None, undo_transform=False) # Also, remember to return these 4 values from the prep_display(). # Otherwise, it will lead to an error. # img_numpy is the default one that will be returned from prep_display(). # You're now simply returning 4 values instead of 1. # NOTE: I have included img_numpy because I found that prep_display() is being used in many places. # You need to modify the returns wherever prep_display() is being called in the eval.py. I think it's being called 3 times from different regions in eval.py.
https://stackoverflow.com/questions/64729199/
How to implent tf.nn.in_top_k in pytorch
I want to implent tf.nn.in_top_k in pytorch. Here is the link of tf.nn.in_top_k, tf.math.in_top_k( targets, predictions, k, name=None ) It computed precision at k as a bool Tensor and will return a Tensor of type bool. tf.nn.in_top_k I wonder whether there are similar api in pytorch?
AFAIK there is no equivalent in_top_k function built into pytorch. It's relatively straightforward to write one. For example def in_top_k(targets, preds, k): topk = preds.topk(k)[1] return (targets.unsqueeze(1) == topk).any(dim=1)
https://stackoverflow.com/questions/64734480/
Initiaized class member in pytorch module
When declaring a model in pytorch, having a model class member variable declared and initialized mysteriously prevents it from being populated in the constructor. Is this expected? If so, why? Testing code below, with example models with a component member variable. The initialization value of the component (e.g. None, a number or a Tensor) does not change the behaviour. import torch class Lin1(torch.nn.Module): def __init__(self): super(Lin1, self).__init__() self.component = torch.nn.Linear(100,200) class Lin2(torch.nn.Module): component = None def __init__(self): super(Lin2, self).__init__() self.component = torch.nn.Linear(100,200) # instantiate and check member component for cl in [Lin1, Lin2]: model = cl() print("\nModel:", cl) print("Component:", model.component) print("It's None?: ", model.component is None) Model: <class '__main__.Lin1'> Component: Linear(in_features=100, out_features=200, bias=True) It's None?: False Model: <class '__main__.Lin2'> Component: None It's None?: True
This happens because nn.Module overwrites __getattr__, and it would only work as you expect if component was not in Lin2.__dict__ (nor in Lin2().__dict__). Since component is a class attribute, it is in Lin2.__dict__ and will be returned as it should. When you write self.x = nn.Linear(...) or any other nn.Module (or even nn.Buffer or nn.Parameter), x is actually registered in a dictionary called _modules (or _buffers, etc.) In this way, when you ask for self.component, if component is already in the __dict__ of the class or the instance, Python will not call the custom nn.Module's __getattr__(). You can check the source-code of __getattr__ from nn.Module here. A similar discussion was done here. There was also a discussion about changing from __getattr__ to __getattribute__ in PyTorch, but as of now, this is a wontfix issue.
https://stackoverflow.com/questions/64739330/
Gradient Exploding Using CIFAR-10 Dataset from the Official Website
I want to train a VGG16 model with Horovod PyTorch on 4 GPUs. Instead of using the CIFAR10 dataset of torch vision.datasets.CIFAR10, I would like to split the dataset on my own. So I downloaded the dataset from the official website and split the dataset. This is how I split the data: if __name__ == '__main__': import pickle train_data, train_label = [], [] test_data, test_label = [], [] for i in range(1, 6): with open('/Users/wangqipeng/Downloads/cifar-10-batches-py/data_batch_{}'.format(i), 'rb') as f: b = pickle.load(f, encoding='bytes') train_data.extend(b[b'data'].tolist()[:8000]) train_label.extend(b[b'labels'][:8000]) test_data.extend(b[b'data'].tolist()[8000:]) test_label.extend(b[b'labels'][8000:]) num_train = len(train_data) num_test = len(test_data) print(num_train, num_test) train_data = np.array(train_data) test_data = np.array(test_data) for i in range(4): with open('/Users/wangqipeng/Downloads/train_{}'.format(i), 'wb') as f: d = {b'data': train_data[int(0.25 * i * num_train): int(0.25 * (i + 1) * num_train)], b'labels': train_label[int(0.25 * i * num_train): int(0.25 * (i + 1) * num_train)]} pickle.dump(d, f) with open('/Users/wangqipeng/Downloads/test'.format(i), 'wb') as f: d = {b'data': test_data, b'labels': test_label} pickle.dump(d, f) However, I found that if I use the dataset that I downloaded from the official website, there will be an exploding gradient problem. I found that the loss will increase and be "nan" after several iterations. This is how I read the dataset: class DataSet(torch.utils.data.Dataset): def __init__(self, path): self.dataset = unpickle(path) def __getitem__(self, index): data = torch.tensor( self.dataset[b'data'][index], dtype=torch.float32).resize(3, 32, 32) return data, torch.tensor(self.dataset[b'labels'][index]) def __len__(self): return len(self.dataset[b'data']) train_dataset = DataSet("./cifar10/train_" + str(hvd.rank())) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=args.batch_size, sampler=None, **kwargs) If I print the loss of every iteration, I see something like this: Mon Nov 9 11:28:29 2020[0]<stdout>:epoch 0 iter[ 0 / 313 ] loss 7.725658416748047 accuracy 5.46875 Mon Nov 9 11:28:29 2020[0]<stdout>:epoch 0 iter[ 1 / 313 ] loss 15.312677383422852 accuracy 8.59375 Mon Nov 9 11:28:29 2020[0]<stdout>:epoch 0 iter[ 2 / 313 ] loss 16.333066940307617 accuracy 9.375 Mon Nov 9 11:28:30 2020[0]<stdout>:epoch 0 iter[ 3 / 313 ] loss 15.549728393554688 accuracy 9.9609375 Mon Nov 9 11:28:30 2020[0]<stdout>:epoch 0 iter[ 4 / 313 ] loss 14.090616226196289 accuracy 9.843750298023224 Mon Nov 9 11:28:31 2020[0]<stdout>:epoch 0 iter[ 5 / 313 ] loss 12.310989379882812 accuracy 9.63541641831398 Mon Nov 9 11:28:31 2020[0]<stdout>:epoch 0 iter[ 6 / 313 ] loss 11.578919410705566 accuracy 9.15178582072258 Mon Nov 9 11:28:31 2020[0]<stdout>:epoch 0 iter[ 7 / 313 ] loss 13.210229873657227 accuracy 8.7890625 Mon Nov 9 11:28:32 2020[0]<stdout>:epoch 0 iter[ 8 / 313 ] loss 764.713623046875 accuracy 9.28819477558136 Mon Nov 9 11:28:32 2020[0]<stdout>:epoch 0 iter[ 9 / 313 ] loss 4.590414250749922e+20 accuracy 8.984375 Mon Nov 9 11:28:32 2020[0]<stdout>:epoch 0 iter[ 10 / 313 ] loss nan accuracy 9.446022659540176 Mon Nov 9 11:28:33 2020[0]<stdout>:epoch 0 iter[ 11 / 313 ] loss nan accuracy 10.09114608168602 Mon Nov 9 11:28:33 2020[0]<stdout>:epoch 0 iter[ 12 / 313 ] loss nan accuracy 10.39663478732109 However, If I use the dataset from torchvision, everything will be fine: train_dataset = \ datasets.CIFAR10(args.train_dir, download=True, transform=transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5))])) train_sampler = torch.utils.data.distributed.DistributedSampler( train_dataset, num_replicas=hvd.size(), rank=hvd.rank()) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=args.batch_size, sampler=train_sampler, **kwargs) There can also be something wrong with the DistributedSampler. But I think the DistributedSampler only serves to split the data. I don't know whether the DistributedSampler can be a reason to this problem. Is there something wrong with the way I read the CIFAR10 dataset? Or is there something wrong with the way I "reshape" it? Thanks for your help!
Maybe it is because I did not normalize the dataset. Thanks for everyone's help!
https://stackoverflow.com/questions/64745590/
RuntimeError: Error(s) in loading state_dict for Generator: Missing key(s) in state_dict
I was trying to train a DCGAN model using MNIST datasets, but I can't load the gen.state_dict() after I finished training. import torch import torch.nn as nn import torchvision.datasets as datasets import torchvision.transforms as transforms from torch.utils.tensorboard import SummaryWriter import torchvision import os from torch.autograd import Variable workspace_dir = '/content/drive/My Drive/practice' device=torch.device('cuda' if torch.cuda.is_available else 'cpu') print(device) img_size=64 channel_img=1 lr=2e-4 batch_size=128 z_dim=100 epochs=10 features_gen=64 features_disc=64 save_dir = os.path.join(workspace_dir, 'logs') os.makedirs(save_dir, exist_ok=True) import matplotlib.pyplot as plt transforms=transforms.Compose([transforms.Resize(img_size),transforms.ToTensor(),transforms.Normalize(mean=(0.5,),std=(0.5,))]) train_data=datasets.MNIST(root='dataset/',train=True,transform=transforms,download=True) train_loader=torch.utils.data.DataLoader(train_data,batch_size=batch_size,shuffle=True) count=0 for x,y in train_loader: if count==5: break print(x.shape,y.shape) count+=1 class Discriminator(nn.Module): def __init__(self,channels_img,features_d): super(Discriminator,self).__init__() self.disc=nn.Sequential( #input:N * channels_img * 64 *64 nn.Conv2d(channels_img,features_d,4,2,1),#paper didn't use batchnorm in the early layers in the discriminator features_d* 32 *32 nn.LeakyReLU(0.2), self._block(features_d,features_d*2,4,2,1),#features_d*2 *16 *16 self._block(features_d*2,features_d*4,4,2,1),#features_d*4 *8 *8 self._block(features_d*4,features_d*8,4,2,1), #features_d*8 *4 *4 nn.Conv2d(features_d*8,1,4,2,0),#1 * 1 *1 nn.Sigmoid() ) def _block(self,in_channels,out_channels,kernel_size,stride,padding): return nn.Sequential( nn.Conv2d(in_channels,out_channels,kernel_size,stride,padding,bias=False), nn.BatchNorm2d(out_channels), nn.LeakyReLU(0.2) ) def forward(self,x): return self.disc(x) class Generator(nn.Module): def __init__(self,Z_dim,channels_img,features_g): super(Generator,self).__init__() self.gen=nn.Sequential( #input :n * z_dim * 1 *1 self._block(Z_dim,features_g*16,4,1,0),#features_g*16 * 4 * 4 self._block(features_g*16,features_g*8,4,2,1),#features_g*8 * 8 * 8 self._block(features_g*8,features_g*4,4,2,1),#features_g*4 * 16 * 16 self._block(features_g*4,features_g*2,4,2,1),#features_g*2 * 32 * 32 nn.ConvTranspose2d(features_g*2,channels_img,4,2,1), # nn.Tanh()# [-1 to 1] normalize the image ) def _block(self,in_channels,out_channels,kernel_size,stride,padding): return nn.Sequential( nn.ConvTranspose2d(in_channels,out_channels,kernel_size,stride,padding,bias=False),#w'=(w-1)*s-2p+k nn.BatchNorm2d(out_channels), nn.ReLU() ) def forward(self,x): return self.gen(x) def initialize_weights(model): for m in model.modules(): if isinstance(m,(nn.Conv2d,nn.ConvTranspose2d,nn.BatchNorm2d)): nn.init.normal_(m.weight.data,0.0,0.02) gen=Generator(z_dim,channel_img,features_gen).to(device) disc=Discriminator(channel_img,features_disc).to(device) initialize_weights(gen) initialize_weights(disc) opt_gen=torch.optim.Adam(gen.parameters(),lr=lr,betas=(0.5,0.999)) opt_disc=torch.optim.Adam(disc.parameters(),lr=lr,betas=(0.5,0.999)) criterion=nn.BCELoss() #fixed_noise=torch.randn(32,z_dim,1,1).to(device) #writer_real=SummaryWriter(f"logs/real") #writer_fake=SummaryWriter(f"logs/fake") step=0 gen.train() disc.train() z_sample = Variable(torch.randn(100, z_dim,1,1)).cuda() for epoch in range(2): for batch_idx,(real,_) in enumerate(train_loader): real=real.to(device) noise=torch.randn((batch_size,z_dim,1,1)).to(device) fake=gen(noise) #Train Discriminator max log(D(x)) + log(1-D(G(z))) disc_real=disc(real).reshape(-1) loss_disc_real=criterion(disc_real,torch.ones_like(disc_real)) disc_fake=disc(fake).reshape(-1) loss_disc_fake=criterion(disc_fake,torch.zeros_like(disc_fake)) loss_disc=(loss_disc_fake+loss_disc_real)/2 disc.zero_grad() loss_disc.backward(retain_graph=True) opt_disc.step() #Train Generator min log(1-D(G(z))) <--> max log(D(G(z))) output=disc(fake).reshape(-1) loss_gen=criterion(output,torch.ones_like(output)) gen.zero_grad() loss_gen.backward() opt_gen.step() print(f'\rEpoch [{epoch+1}/{3}] {batch_idx+1}/{len(train_loader)} Loss_D: {loss_disc.item():.4f} Loss_G: {loss_gen.item():.4f}', end='') gen.eval() f_imgs_sample = (gen(z_sample).data + 1) / 2.0 filename = os.path.join(save_dir, f'Epoch_{epoch+1:03d}.jpg') torchvision.utils.save_image(f_imgs_sample, filename, nrow=10) print(f' | Save some samples to {filename}.') # show generated image grid_img = torchvision.utils.make_grid(f_imgs_sample.cpu(), nrow=10) plt.figure(figsize=(10,10)) plt.imshow(grid_img.permute(1, 2, 0)) plt.show() gen.train() torch.save(gen.state_dict(), os.path.join(workspace_dir, f'dcgan_d.pth')) torch.save(disc.state_dict(), os.path.join(workspace_dir, f'dcgan_g.pth')) I can't load the gen state_dict in this step: # load pretrained model #gen = Generator(z_dim,1,64) gen=Generator(z_dim,channel_img,features_gen).to(device) gen.load_state_dict(torch.load('/content/drive/My Drive/practice/dcgan_g.pth')) gen.eval() gen.cuda() Here's the error: RuntimeError Traceback (most recent call last) <ipython-input-18-4bda27faa444> in <module>() 5 6 #gen.load_state_dict(torch.load('/content/drive/My Drive/practice/dcgan_g.pth')) ----> 7 gen.load_state_dict(torch.load(os.path.join(workspace_dir, 'dcgan_g.pth'))) 8 #/content/drive/My Drive/practice/dcgan_g.pth 9 gen.eval() /usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in load_state_dict(self, state_dict, strict) 1050 if len(error_msgs) > 0: 1051 raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format( -> 1052 self.__class__.__name__, "\n\t".join(error_msgs))) 1053 return _IncompatibleKeys(missing_keys, unexpected_keys) 1054 ***RuntimeError: Error(s) in loading state_dict for Generator: Missing key(s) in state_dict***: "gen.0.0.weight", "gen.0.1.weight", "gen.0.1.bias", "gen.0.1.running_mean", "gen.0.1.running_var", "gen.1.0.weight", "gen.1.1.weight", "gen.1.1.bias", "gen.1.1.running_mean", "gen.1.1.running_var", "gen.2.0.weight", "gen.2.1.weight", "gen.2.1.bias", "gen.2.1.running_mean", "gen.2.1.running_var", "gen.3.0.weight", "gen.3.1.weight", "gen.3.1.bias", "gen.3.1.running_mean", "gen.3.1.running_var", "gen.4.weight", "gen.4.bias". Unexpected key(s) in state_dict: "disc.0.weight", "disc.0.bias", "disc.2.0.weight", "disc.2.1.weight", "disc.2.1.bias", "disc.2.1.running_mean", "disc.2.1.running_var", "disc.2.1.num_batches_tracked", "disc.3.0.weight", "disc.3.1.weight", "disc.3.1.bias", "disc.3.1.running_mean", "disc.3.1.running_var", "disc.3.1.num_batches_tracked", "disc.4.0.weight", "disc.4.1.weight", "disc.4.1.bias", "disc.4.1.running_mean", "disc.4.1.running_var", "disc.4.1.num_batches_tracked", "disc.5.weight", "disc.5.bias".
You saved the weights with the wrong names. That is you saved the generator's weights as dcgan_d.pth and likewise, saved the descriminator's weights as dcgan_g.pth : torch.save(gen.state_dict(), os.path.join(workspace_dir, f'dcgan_d.pth')) # should have been dcgan_g.pth torch.save(disc.state_dict(), os.path.join(workspace_dir, f'dcgan_g.pth')) # should have been dcgan_d.pth and thus when loading, you try to load the wrong weights : gen.load_state_dict(torch.load('/content/drive/My Drive/practice/dcgan_g.pth')) dcgan_g.pth contains the descriminators weights not your generators. First fix the wrong names when you save them. and second, simply rename them accordingly you should be fine.
https://stackoverflow.com/questions/64745900/
PyTorch, when divided by zero, set the result value with 0
In Pytorch, when values are divided by zero, replace the result value with 0, as it will output NaN. Here is an example, a = th.from_numpy(np.array([ [1, 0], [0, 1], [1, 1]])) b = th.zeros_like(a) b[0, :] = 2 a = a / b How can I do that?
You can replace NaN values obtained after division with 0 using the following method - Create a ByteTensor indicating the positions of NaN a != a >> tensor([[False, False], [ True, False], [False, False]]) Replace NaN values indicated by above Tensor with 0 a = a / b >> tensor([[0.5000, 0.0000], [ nan, inf], [ inf, inf]]) a[a != a] = 0 >> tensor([[0.5000, 0.0000], [0.0000, inf], [ inf, inf]]) Note this will also replace any NaN values introduced before division.
https://stackoverflow.com/questions/64751109/
Using _scatter() to replace values in matrix
Given the following two tensors: x = torch.tensor([[[1, 2], [2, 0], [0, 0]], [[2, 2], [2, 0], [3, 3]]]) # [batch_size x sequence_length x subseq_length] y = torch.tensor([[2, 1, 0], [2, 1, 2]]) # [batch_size x sequence_length] I would like to sort the sequences in x based on their sub-sequence lengths (0 corresponds to padding in the sequence). y corresponds to the lengths of the sub-sequences in x. I have tried the following: y_sorted, y_sort_idx = y.sort(dim=1, descending=True) print(x.scatter_(dim=1, index=y_sort_idx.unsqueeze(2), src=x)) This results in: tensor([[[1, 2], [2, 0], [0, 0]], [[2, 2], [2, 0], [2, 3]]]) However what I would like to achieve is: tensor([[[1, 2], [2, 0], [0, 0]], [[2, 2], [3, 3], [2, 0]]])
This should do it y_sorted, y_sort_idx = y.sort(dim=1, descending=True) index = y_sort_idx.unsqueeze(2).expand_as(x) x = x.gather(dim=1, index=index)
https://stackoverflow.com/questions/64751685/
Pytorch: why logging fails in DDP?
I would like to use logging in one of the processes managed by Distributed Data Parallel. However, logging print nothing in the following codes (the codes are derived from this tutorial): #!/usr/bin/python import os, logging # logging.basicConfig(level=logging.DEBUG) import torch def setup(rank, world_size): os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = '12355' # Initialize the process group. dist.init_process_group('NCCL', rank=rank, world_size=world_size) def cleanup(): dist.destroy_process_group() class ToyModel(nn.Module): def __init__(self): super(ToyModel, self).__init__() self.net1 = nn.Linear(10, 10) self.relu = nn.ReLU() self.net2 = nn.Linear(10, 5) def forward(self, x): return self.net2(self.relu(self.net1(x))) def demo_basic(rank, world_size): setup(rank, world_size) if rank == 0: logger = logging.getLogger('train') logger.setLevel(logging.DEBUG) logger.info(f'Running DPP on rank={rank}.') # Create model and move it to GPU. model = ToyModel().to(rank) ddp_model = DDP(model, device_ids=[rank]) loss_fn = nn.MSELoss() optimizer = optim.SGD(ddp_model.parameters(), lr=0.001) # optimizer takes DDP model. optimizer.zero_grad() inputs = torch.randn(20, 10) # .to(rank) outputs = ddp_model(inputs) labels = torch.randn(20, 5).to(rank) loss_fn(outputs, labels).backward() optimizer.step() cleanup() def run_demo(demo_func, world_size): mp.spawn( demo_func, args=(world_size,), nprocs=world_size, join=True ) def main(): run_demo(demo_basic, 4) if __name__ == "__main__": main() However, when I uncomment the 4th line, the logging works. May I know the reason and how to fix the bug please?
UPDATE Let's briefly review how loggers in the logging module work. Loggers are organized in a tree structure, i.e. every logger has a unique parent logger. By default, it will be the root logger, while the root logger doesn't have a parent logger. When you call Logger.info method (ignore level checking here for simplicity) on a logger, the logger iterates all of its handlers and let them handle the current record, e.g. handlers can be StreamHandler which can print to stdout, or FileHandler which prints to some file). After all of the handlers of current logger finish their jobs, the record will be given to its parent logger and, the parent logger handles the record in the same way, i.e. iterates all handlers of parent logger and lets them handle the record, finnally passes the record to "grandparent". This procedure continues until reaching the root of current loggers' tree, which doesn't have a parent. Check the implementation below or here: def callHandlers(self, record): c = self found = 0 while c: for hdlr in c.handlers: found = found + 1 if record.levelno >= hdlr.level: hdlr.handle(record) if not c.propagate: c = None #break out else: c = c.parent So in your case, you didn't specify any handler for the train logger. When you uncomment the 6th line, i.e. by calling logging.basicConfig(level=logging.DEBUG), a StreamHandler is created for the root logger. Though there isn't any handler for the train logger, there is a StreamHandler for its parent i.e. the root logger, which prints anything you see actually, while train logger print nothing in this case. When the 6th line in commented, even one StreamHandler is not created for the root handler, so in this case nothing is printed. So In fact the issue has nothing to do with DDP. By the way, the reason I can't reproduce your issue at first is because I use PyTorch 1.8, where logging.info will be called during the execution of dist.init_process_group for backends other than MPI, which implicitly calls basicConfig, creates a StreamHandler for the root logger and seems to print message as expected. ====================================================================== One possible reason: Because during the execution of dist.init_process_group, it will call _store_based_barrier, which finnaly will call logging.info (see the source code here). So if you call logging.basicConfig before you call dist.init_process_group, it will be initialized in advance which makes the root logger ignore all levels of log. This is not the case in your code because logging.basicConfig is at the top of the file, which will be executed at frist before dist.init_process_group. Actually I'm able to run the code you provide, after filling the missing imports such as nn and dist though, with logging works normally. Maybe you attempted to reduce the code to reproduce the issue, but circumvent the real issue behind unconsciously? Could you double check if this resolves your issue?
https://stackoverflow.com/questions/64752343/
Converting lists of uneven size into LSTM input tensor
So I have a nested list of 1366 samples with 2 features each and varying sequence lengths that is supposed to be the input data for an LSTM. The labels are supposed to be a pair of values for each sequence, i.e. [-0.76797587, 0.0713816]. In essence the data looks like the following: X = [[[-0.11675862, -0.5416186], [-0.76797587, 0.0713816]], [[-0.5115555, 0.25823522], [0.6099151999999999, 0.21718016], [-0.0022403747, 0.6470206999999999]]] What I would like to do is convert this list into an input tensor. As I understand, LSTMs accept sequences of different lengths, so in this case the first sample has length 2 and the second has length 3. Currently I'm trying to convert the list in the following way: train_data = TensorDataset(torch.tensor(X, dtype=torch.float32), torch.tensor(Y, dtype=torch.float32)) train_dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=True) Though this produces the following error ValueError: expected sequence of length 5 at dim 1 (got 3) I'm guessing this is because the first sequence has length five and the second length 3, which is not convertible? How do I convert the given list into a tensor? Or am I thinking wrong about the way to train the LSTM? Thanks for any help!
So as you said, the sequence length can be different. But because we work with batches, in each batch the sequence length has to be the same anyways. Thats because all samples are processed simultaneously. So what you have to do is to pad the samples to the same size by taking the length longest sequence in the batch and fill all other samples with zeros so that they have the same size. For that you have to use pytorch's pad functionn, like this: from torch.nn.utils.rnn import pad_sequence # the batch must be a python list containing the tensor samples sample_batch = [torch.tensor((4,2)), torch.tensor((2,2)), torch.tensor((5,2))] # pad all samples in the batch to the length of the biggest sample padded_batch = pad_sequence(sample_batch, batch_first=True) # get the new size of the samples and reshape it to (BATCH_SIZE, SEQUENCE/PAD_SIZE. INPUT_SIZE) padded_to = list(padded_batch.size())[1] padded_batch = padded_batch.reshape(len(sample_batch), padded_to, 1) Now all samples in the batch should have the shape (5,2) because the biggest sample had a sequence length of 5. If you dont know how to implement this with the pytorch Dataloader you can create a custom collate_fn: def custom_collate(batch): batch_size = len(batch) sample_batch, target_batch = [], [] for sample, target in batch: sample_batch.append(sample) target_batch.append(target) padded_batch = pad_sequence(sample_batch, batch_first=True) padded_to = list(padded_batch.size())[1] padded_batch = padded_batch.reshape(len(sample_batch), padded_to, 1) return padded_batch, torch.cat(target_batch, dim=0).reshape(len(sample_batch) Now you can tell the DataLoader to apply this function on your batch before returning it: train_dataloader = DataLoader( train_data, batch_size=batch_size, num_workers=1, shuffle=True, collate_fn=custom_collate # <-- NOTE THIS ) Now the DataLoader returns padded batches!
https://stackoverflow.com/questions/64756123/
Creating a train, test split for data nested in multiple folders
I am preparing my data for training an image recognition model. I currently have one folder (the dataset) that contains multiple folders with the names of the labels and these folders have the images inside them. I want to somehow split this dataset so that I have two main folders with the same subfolders, but the number of images inside these folders to be according to a preferred train/test split, so for instance 90% of the images in the train dataset and 10% in the test dataset. I am struggling with finding the best way how to split my data. I have read a suggestion that pytorch torch.utils.Dataset class might be a way to do it but I can't seem to get it working as to preserve the folder hierarchy.
If you have a folder structure like this: folder │ │ └───class1 │ │ file011 │ │ file012 │ └───class2 │ file021 │ file022 You can use simply the class torchvision.datasets.ImageFolder As stated from the website of pytorch A generic data loader where the images are arranged in this way: root/dog/xxx.png root/dog/xxy.png root/dog/xxz.png root/cat/123.png root/cat/nsdf3.png root/cat/asd932_.png Then, after you have created your ImageFolder instance, like this for example dataset = torchvision.datasets.Imagefolder(YOUR_PATH, ...) you can split it in this way: test_size = 0.1 * len(dataset) test_set = torch.utils.data.Subset(dataset, range(test_size)) # take 10% for test train_set = torch.utils.data.Subset(dataset, range(test_size, len(dataset)) # the last part for train If you want to make a shuffle of the split, remember that the class subset uses the indexes for the split. So you can shuffle, and split them. Doing something like this indexes = shuffle(range(len(dataset))) indexes_train = indexes[:int(len(dataset)*0.9)] indexes_test = = indexes[int(len(dataset)*0.9):]
https://stackoverflow.com/questions/64758066/
OSError: [Errno 22] Invalid argument when using torch.load
I am trying to load my dataset and it was working before but all of the sudden this error started pooping up. When I try to load it like this: train_set = Database_load(root = "C:\\Users\\Public\\PhysNet\\",train = "train.pth") It gives me the following error: File "C:\Users\Public\Lucas\PhysNet\modt.py", line 185, in <module> train_set = Database_load(root = "C:\\Users\\Public\\Lucas\\PhysNet\\",train = "train.pth") File "C:\Users\Public\Lucas\PhysNet\database_load.py", line 21, in __init__ self.data, self.y1, self.y2= torch.load(os.path.join(self.root, self.train)) File "C:\ProgramData\Anaconda3\envs\project\lib\site-packages\torch\serialization.py", line 386, in load return _load(f, map_location, pickle_module, **pickle_load_args) File "C:\ProgramData\Anaconda3\envs\project\lib\site-packages\torch\serialization.py", line 580, in _load deserialized_objects[key]._set_from_file(f, offset, f_should_read_directly) OSError: [Errno 22] Invalid argument I have tried doing the following as well when entering the path but it has not worked: train_set = Database_load(root = r"C:\\Users\\Public\\PhysNet\\",train = "train.pth") train_set = Database_load(root = r'C:/Users/Public/PhysNet/',train = 'train.pth') Any suggestions on how to fix this issue?
This was a known issue (Issue#26998 and Issue#) caused by PR#20900. The problem happens because you're trying to load a file larger than 2GB, and it is specific to Windows in which "sizeof(long)=4 for both 32-bit and 64-system systems". This issue was fixed by PR#27069 and is only available in PyTorch 1.3+. Therefore, to fix this issue, please upgrade your PyTorch version.
https://stackoverflow.com/questions/64761518/
Why is MNIST showing as a list 4 levels deep?
Experimenting with some simple code using PyTorch on MNIST, and I'm puzzled about an aspect of how it's representing the data; maybe I'm just overlooking something really obvious. Given train_loader = torch.utils.data.DataLoader( torchvision.datasets.MNIST( "data", train=True, download=True, transform=torchvision.transforms.Compose( [ torchvision.transforms.ToTensor(), torchvision.transforms.Normalize((0.1307,), (0.3081,)), ] ), ), batch_size=batch_size_train, shuffle=True, ) and for batch_idx, (data, target) in enumerate(train_loader): print(data) I get tensor([[[[-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], ..., [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242]]], [[[-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], ..., [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242], [-0.4242, -0.4242, -0.4242, ..., -0.4242, -0.4242, -0.4242]]], I was expecting a tensor corresponding to a list three levels deep: a list of images, each of which is a list of rows, each of which is a list of numbers. Or put another way, the innermost [] is a row, the next [] is an image, the outermost [] is the list of images. But instead it is four levels deep. Why the extra level?
4 levels are Batch Channel Row Column
https://stackoverflow.com/questions/64763447/
Creating a pytorch tensor binary mask using specific values
I am given a pytorch 2-D tensor with integers, and 2 integers that always appear in each row of the tensor. I want to create a binary mask that will contain 1 between the two appearances of these 2 integers, otherwise 0. For example, if the integers are 4 and 2 and the 1-D array is [1,1,9,4,6,5,1,2,9,9,11,4,3,6,5,2,3,4], the returned mask will be: [0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,1,0,0,0]. Is there any efficient and quick way to compute this mask without iterations?
Based completely on the previous solution, here is the revised one: import torch vals=[2,8]#let's assume those are the constant values that appear in each row #target tensor m=torch.tensor([[1., 2., 7., 8., 5., 2., 6., 5., 8., 4.], [4., 7., 2., 1., 8., 2., 6., 5., 6., 8.]]) #let's find the indexes of those values k=m==vals[0] p=m==vals[1] v=(k.int()+p.int()).bool() nz_indexes=v.nonzero()[:,1].reshape(m.shape[0],4) #let's create a tiling of the indexes q=torch.arange(m.shape[1]) q=q.repeat(m.shape[0],1) #you only need two masks, no matter the size of m. see explanation below msk_0=(nz_indexes[:,0].repeat(m.shape[1],1).transpose(0,1))<=q msk_1=(nz_indexes[:,1].repeat(m.shape[1],1).transpose(0,1))>=q msk_2=(nz_indexes[:,2].repeat(m.shape[1],1).transpose(0,1))<=q msk_3=(nz_indexes[:,3].repeat(m.shape[1],1).transpose(0,1))>=q final_mask=msk_0.int() * msk_1.int() + msk_2.int() * msk_3.int() print(final_mask) and we finally get tensor([[0, 1, 1, 1, 0, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=torch.int32)
https://stackoverflow.com/questions/64764937/
How to write the einsum operation: 'i,jk->ijk' in tensorial product form?
I am using pytorch and want to broadcast a vector from 1D (features) to a 3D tensor (features×height×width) to condition the encoding of an image with a Convolutional Neural Network. As is done in Figure S1 of this Deepmind paper. For now I am using this: # features: 1D vector f = torch.einsum('i,jk->ijk',features,torch.ones([5,5]))
Using broadcast semantics you could alternatively compute this using f = features.reshape(-1, 1, 1) * torch.ones(1, 5, 5)
https://stackoverflow.com/questions/64767467/
Pytorch autograd: Make gradient of a parameter a function of another parameter
In Pytorch, how can I make the gradient of a parameter a function itself? Here is a simple code snippet: import torch def fun(q): def result(w): l = w * q l.backward() return w.grad return result w = torch.tensor((2.), requires_grad=True) q = torch.tensor((3.), requires_grad=True) f = fun(q) print(f(w)) In the code above, how can I make f(w) have gradient with respect to q? EDIT: based on the accepted answer I was able to write a code that works. Essentially I am alternating between 2 optimization steps. For dim == 1 it works and for dim == 2 it does not. I get the error "RuntimeError: Trying to backward through the graph a second time, but the saved intermediate results have already been freed. Specify retain_graph=True when calling backward the first time." import torch class f_class(): def __init__(self, dim): self.dim = dim if self.dim == 1: self.w = torch.tensor((3.), requires_grad=True) elif self.dim == 2: self.w = [torch.tensor((3.), requires_grad=True), torch.tensor((5.), requires_grad=True)] else: raise ValueError("dim 1 or 2") def forward(self, x): if self.dim == 1: return torch.mul(self.w, x) elif self.dim == 2: return torch.mul(torch.mul(self.w[0], self.w[1]), x) def set_w(self, w): self.w = w def get_w(self): return self.w class g_class(): def __init__(self): self.q = torch.tensor((4.), requires_grad=True) def forward(self, f): return torch.mul(self.q, f) def set_q(self, q): self.q = q def get_q(self): return self.q def w_new(f, g, dim): loss_g = g.forward(f.forward(xd)) if dim == 1: grads = torch.autograd.grad(loss_g, f.get_w(), create_graph=True, only_inputs=True)[0] temp = f.get_w().detach() + grads else: grads = torch.autograd.grad(loss_g, f.get_w(), create_graph=True, only_inputs=True) temp = [wi.detach() + gi for wi, gi in zip(f.get_w(), grads)] return temp def q_new(f, g): loss_f = 2 * f.forward(xd) loss_f.backward() temp = g.get_q().detach() + g.get_q().grad temp.requires_grad = True return temp dim = 1 xd = torch.tensor((2.)) f = f_class(dim) g = g_class() for _ in range(3): print(f.get_w(), g.get_q()) wnew = w_new(f, g, dim) f.set_w(wnew) print(f.get_w(), g.get_q()) qnew = q_new(f, g) g.set_q(qnew) print(f.get_w(), g.get_q())
When computing gradients, if you want to construct a computation graph for the gradient itself you need to specify create_graph=True to autograd. A potential source of error in your code is using Tensor.backward within f. The problem here is that w.grad and q.grad will be populated with the gradient of l. This means that when you call f(w).backward(), the gradients of both f and l will be added to w.grad and q.grad. In effect you will end up with w.grad being equal to dl/dw + df/dw and similarly for q.grad. One way to get around this is to zero the gradients after f(w) but before .backward(). A better way is to use torch.autograd.grad within f. Using the latter approach, the grad attribute of w and q will not be populated when calling f, only when calling .backward(). This leaves room for things like gradient accumulation during training. import torch def fun(q): def result(w): l = w * q return torch.autograd.grad(l, w, only_inputs=True, retain_graph=True)[0] return result w = torch.tensor((2.), requires_grad=True) q = torch.tensor((3.), requires_grad=True) f = fun(q) f(w).backward() print('w.grad:', w.grad) print('q.grad:', q.grad) which results in w.grad: None q.grad: tensor(1.) Note that w.grad was not populated. This is because f(w) = dl/dw = q is not a function of w, and therefore w is not part of the computation graph. If you're using a standard pytorch optimizer this is fine since None gradients are implicitly assumed to be zero. If l were instead a non-linear function of w, then w.grad would have been populated after f(w).backward(). For example import torch def fun(q): def result(w): # now dl/dw = 2 * w * q l = w**2 * q return torch.autograd.grad(l, w, only_inputs=True, create_graph=True)[0] return result w = torch.tensor((2.), requires_grad=True) q = torch.tensor((3.), requires_grad=True) f = fun(q) f(w).backward() print('w.grad:', w.grad) print('q.grad:', q.grad) which results in w.grad: tensor(6.) q.grad: tensor(4.)
https://stackoverflow.com/questions/64770638/
how to detach list of pytorch tensors to array
There is a list of PyTorch's Tensors and I want to convert it to array but it raised with error: 'list' object has no attribute 'cpu' How can I convert it to array? import torch result = [] for i in range(3): x = torch.randn((3, 4, 5)) result.append(x) a = result.cpu().detach().numpy()
You can stack them and convert to NumPy array: import torch result = [torch.randn((3, 4, 5)) for i in range(3)] a = torch.stack(result).cpu().detach().numpy() In this case, a will have the following shape: [3, 3, 4, 5]. If you want to concatenate them in a [3*3, 4, 5] array, then: a = torch.cat(result).cpu().detach().numpy()
https://stackoverflow.com/questions/64771656/
How do I list all currently available GPUs with pytorch?
I know I can access the current GPU using torch.cuda.current_device(), but how can I get a list of all the currently available GPUs?
You can list all the available GPUs by doing: >>> import torch >>> available_gpus = [torch.cuda.device(i) for i in range(torch.cuda.device_count())] >>> available_gpus [<torch.cuda.device object at 0x7f2585882b50>]
https://stackoverflow.com/questions/64776822/
PyTorch autograd: dimensionality of custom function gradients?
Question summary: How is the dimensionality of inputs and outputs handled in the backward pass of custom functions? According to the manual, the basic structure of custom functions is the following: class MyFunc(torch.autograd.Function): @staticmethod def forward(ctx, input): # f(x) = e^x result = input.exp() ctx.save_for_backward(result) return result @staticmethod def backward(ctx, grad_output): # df(x) = e^x result, = ctx.saved_tensors return grad_output * result For a single input and output dimension, this is perfectly fine and works like a charm. But for higher dimensions the backward pass becomes confusing. Apparently, PyTorch only accepts a result of backward that has the same dimensionality as the result of forward (for the same input). Returning a wrong shape yields a RuntimeError: Function MyFunc returned an invalid gradient at index 0 - got [*] but expected shape compatible with [*]. So I am wondering: What does backward actually compute? Its not a Jacobian? For example, when I have a function f(x) = ( f_1(x_1, ... , x_n), ... , f_k(x_1, ... , x_n) ) with n inputs and k outputs, I would expect that a gradient calculation would yield a Jacobian matrix of dimension k*n. However, the PyTorch implementation expects just a vector of dimension n. So what does the backward result actually mean, it can't be the Jacobian? And it does not handle batches? Moreover, what if I would like to push a batch of input vectors through this function, e.g. an input of dimension b*n with batch size b. Then, instead of something like b*k*n the gradient is expected to also have the shape b*n. Is it even intended to consider the processing of batches with custom functions? None of these questions seems to be addressed in the manual and the provided examples are very simple, which does not help at all. Maybe there are formulas hidden somewhere that explain the background of the provided Function interface in more detail, but I haven't found them yet.
It does not store/return the Jacobian (I imagine it is related to memory consideration). From a training perspective, we do not need the Jacobian for updating parameters/back-propagating further. For updating parameters, all we need is dL/dy_j, j<n: y_j -= alpha * dL/dy_j And for backpropagation to z, say z=f(y)=f(g(x)): dL/dz_k = dL/dy_j * dy_j/dz_k One may say that "but we need dy_j/dz_k here!" -- it is true, but we do not need to store it (just like we do not use the Jacobian of dx_i/dy_j at all in this step). In other words, the Jacobian is only implicitly used, is not required for the most part, and is therefore do away for the sake of memory. And for the batch part, note that mini-batch learning mostly just averages the gradient. PyTorch expects you to handle it in the backward function (again, such that the function returns at little as possible and saves as much memory as possible). Note: One can "gather" the Jacobian and obtain the n-sized vector that you have mentioned. Specifically, sum over the k dimension and average over the batch dimension. EDIT: Not 100% sure, but I think the backward call (of f(x)=y) is expected to return this vector: where \nabla x is the input argument to backward.
https://stackoverflow.com/questions/64777050/
ValueError: Expected tensor to be a tensor image of size (C, H, W). Got tensor.size() = torch.Size([1800, 800])
Here's my evaluation cell: start_time = time.time() with torch.no_grad(): best_network = Network() best_network.cuda() best_network.load_state_dict(torch.load('../moth_landmarks.pth')) best_network.eval() batch = next(iter(train_loader)) images, landmarks = batch['image'], batch['landmarks'] #images = images.unsqueeze_(1) images = torch.cat((images,images,images),1) images = images.cuda() norm_image = transforms.Normalize(0.3812, 0.1123) for image in images: image = image.float() ##image = to_tensor(image) #TypeError: pic should be PIL Image or ndarray. Got <class 'torch.Tensor'> image = norm_image(image) landmarks = (landmarks + 0.5) * 224 ##[8, 600, 800] --> [8,3,600,800] images = images.unsqueeze(1) images = torch.cat((images, images, images), 1) predictions = (best_network(images).cpu() + 0.5) * 224 predictions = predictions.view(-1,4,2) plt.figure(figsize=(10,40)) for img_num in range(8): plt.subplot(8,1,img_num+1) plt.imshow(images[img_num].cpu().numpy().transpose(1,2,0).squeeze(), cmap='gray') plt.scatter(predictions[img_num,:,0], predictions[img_num,:,1], c = 'r') plt.scatter(landmarks[img_num,:,0], landmarks[img_num,:,1], c = 'g') print('Total number of test images: {}'.format(len(test_dataset))) end_time = time.time() print("Elapsed Time : {}".format(end_time - start_time)) How should I fix the following error? --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-59-e4aa0ace8c75> in <module> 19 image = image.float() 20 ##image = to_tensor(image) #TypeError: pic should be PIL Image or ndarray. Got <class 'torch.Tensor'> ---> 21 image = norm_image(image) 22 landmarks = (landmarks + 0.5) * 224 23 ~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/transforms.py in __call__(self, tensor) 210 Tensor: Normalized Tensor image. 211 """ --> 212 return F.normalize(tensor, self.mean, self.std, self.inplace) 213 214 def __repr__(self): ~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/functional.py in normalize(tensor, mean, std, inplace) 282 if tensor.ndimension() != 3: 283 raise ValueError('Expected tensor to be a tensor image of size (C, H, W). Got tensor.size() = ' --> 284 '{}.'.format(tensor.size())) 285 286 if not inplace: ValueError: Expected tensor to be a tensor image of size (C, H, W). Got tensor.size() = torch.Size([1800, 800]). If I remove the following line: images = torch.cat((images,images,images),1) I will get this new error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-61-3e892b69015c> in <module> 19 image = image.float() 20 ##image = to_tensor(image) #TypeError: pic should be PIL Image or ndarray. Got <class 'torch.Tensor'> ---> 21 image = norm_image(image) 22 landmarks = (landmarks + 0.5) * 224 23 ~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/transforms.py in __call__(self, tensor) 210 Tensor: Normalized Tensor image. 211 """ --> 212 return F.normalize(tensor, self.mean, self.std, self.inplace) 213 214 def __repr__(self): ~/anaconda3/lib/python3.7/site-packages/torchvision/transforms/functional.py in normalize(tensor, mean, std, inplace) 282 if tensor.ndimension() != 3: 283 raise ValueError('Expected tensor to be a tensor image of size (C, H, W). Got tensor.size() = ' --> 284 '{}.'.format(tensor.size())) 285 286 if not inplace: ValueError: Expected tensor to be a tensor image of size (C, H, W). Got tensor.size() = torch.Size([600, 800]).
The following is correct: start_time = time.time() with torch.no_grad(): best_network = Network() best_network.cuda() best_network.load_state_dict(torch.load('../moth_landmarks.pth')) best_network.eval() batch = next(iter(train_loader)) images, landmarks = batch['image'], batch['landmarks'] landmarks = landmarks.view(landmarks.size(0),-1).cuda() print(landmarks.shape) for i in range(8): if(i%2==0): landmarks[:,i] = landmarks[:,i]/800 else: landmarks[:,i] = landmarks[:,i]/600 landmarks [landmarks != landmarks] = 0 #landmarks = landmarks.unsqueeze_(0) images = images.cuda() print('*, ', landmarks.shape) norm_image = transforms.Normalize(0.3812, 0.1123) print('images shape: ', images.shape) for image in images: image = image.unsqueeze_(1) #images = torch.cat((images,images,images),1) image = image.float() ##image = to_tensor(image) #TypeError: pic should be PIL Image or ndarray. Got <class 'torch.Tensor'> image = norm_image(image) print('max: ', torch.max(landmarks)) print('min: ', torch.min(landmarks)) ##landmarks = (landmarks + 0.5) * 224 #?? chera? print('**') print(images.shape, landmarks.shape) ##[8, 600, 800] --> [8,3,600,800] images = images.unsqueeze(1) images = torch.cat((images, images, images), 1) #predictions = (best_network(images).cpu() + 0.5) * 224 predictions = best_network(images).cpu() print('****', predictions.shape) for i in range(8): if(i%2==0): predictions[:,i] = predictions[:,i]*800 else: predictions[:,i] = predictions[:,i]*600 predictions = predictions.view(-1,4,2) print('****', predictions.shape) for i in range(8): if(i%2==0): landmarks[:,i] = landmarks[:,i]*800 else: landmarks[:,i] = landmarks[:,i]*600 landmarks = landmarks.view(-1,4,2) plt.figure(figsize=(10,40)) landmarks = landmarks.cpu() print(type(landmarks), landmarks.shape) for img_num in range(8): plt.subplot(8,1,img_num+1) plt.imshow(images[img_num].cpu().numpy().transpose(1,2,0).squeeze(), cmap='gray') plt.scatter(predictions[img_num,:,0], predictions[img_num,:,1], c = 'r') plt.scatter(landmarks[img_num,:,0], landmarks[img_num,:,1], c = 'g') print('Total number of test images: {}'.format(len(test_dataset))) end_time = time.time() print("Elapsed Time : {}".format(end_time - start_time))
https://stackoverflow.com/questions/64777195/
Train model in Pytorch with custom loss how to set up optimizer and run training?
I am new to pytorch and I am trying to run a github model I found and test it. So the author's provided the model and the loss function. like this: #1. Inference the model model = PhysNet_padding_Encoder_Decoder_MAX(frames=128) rPPG, x_visual, x_visual3232, x_visual1616 = model(inputs) #2. Normalized the Predicted rPPG signal and GroundTruth BVP signal rPPG = (rPPG-torch.mean(rPPG)) /torch.std(rPPG) # normalize BVP_label = (BVP_label-torch.mean(BVP_label)) /torch.std(BVP_label) # normalize #3. Calculate the loss loss_ecg = Neg_Pearson(rPPG, BVP_label) Dataloading train_loader = torch.utils.data.DataLoader(train_set, batch_size = 20, shuffle = True) batch = next(iter(train_loader)) data, label1, label2 = batch inputs= data Let's say I want to train this model for 15 epochs. So this is what I have so far: I am trying to set the optimizer and training, but I am not sure how to tie the custom loss and data loading to the model and set the 15 epoch training correctly. optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) for epoch in range(15): .... Any suggestions?
I assumed BVP_label is label1 of train_loader train_loader = torch.utils.data.DataLoader(train_set, batch_size = 20, shuffle = True) # Using GPU device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = PhysNet_padding_Encoder_Decoder_MAX(frames=128) model.to(device) optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) for epoch in range(15): model.train() for inputs, label1, label2 in train_loader: rPPG, x_visual, x_visual3232, x_visual1616 = model(inputs) BVP_label = label1 # assumed BVP_label is label1 rPPG = (rPPG-torch.mean(rPPG)) /torch.std(rPPG) BVP_label = (BVP_label-torch.mean(BVP_label)) /torch.std(BVP_label) loss_ecg = Neg_Pearson(rPPG, BVP_label) optimizer.zero_grad() loss_ecg.backward() optimizer.step() PyTorch training steps are as belows. Create DataLoader Initialize model and optimizer Create a device object and move model to the device in the train loop select a mini-batch of data use the model to make predictions calculate the loss loss.backward() updates the gradients of the model update the parameters using optimizer As you may know you can also check PyTorch Tutorials. Learning PyTorch with Examples What is torch.nn really?
https://stackoverflow.com/questions/64779266/
Trying to pass custom loss but it will not allow me to. AttributeError: 'float' object has no attribute 'backward'
I have a custom loss function that I am trying to use on my model however when i use loss.backward() in Pytorch is not working. This is my loss function: class Neg_Pearson(nn.Module): # Pearson range [-1, 1] so if < 0, abs|loss| ; if >0, 1- loss def __init__(self): super(Neg_Pearson,self).__init__() return def forward(self, preds, labels): # tensor [Batch, Temporal] loss = 0 for i in range(preds.shape[0]): sum_x = torch.sum(preds[i]) # x sum_y = torch.sum(labels[i]) # y sum_xy = torch.sum(preds[i]*labels[i]) # xy sum_x2 = torch.sum(torch.pow(preds[i],2)) # x^2 sum_y2 = torch.sum(torch.pow(labels[i],2)) # y^2 N = preds.shape[1] pearson = (N*sum_xy - sum_x*sum_y)/(torch.sqrt((N*sum_x2 - torch.pow(sum_x,2))*(N*sum_y2 - torch.pow(sum_y,2)))) loss += 1 - pearson loss = loss.tolist() loss = loss/preds.shape[0] #print(loss) return loss When I try to use it on with model like so: yp = (yp-torch.mean(yp)) /torch.std(yp) # normalize yt = (yt-torch.mean(yt)) /torch.std(yt) # normalize loss = neg_pears_loss(yp, yt) print(loss) optimizer.zero_grad() loss.backward() optimizer.step() I get the following error: AttributeError: 'float' object has no attribute 'backward' any suggestions on how to fix this issue?
backward is a function of PyTorch Tensor. When you called loss.tolist(), you broke the computation graph and you cannot backward from there. I am not sure what you are trying to accomplish with that line of code, but commenting it out should help.
https://stackoverflow.com/questions/64780471/
Reading test images for resnet18
I am trying to read an image file and classify and image. My model is resnet18 I trained it previously and planning to use a different .py script to classify a list of images. This is my network: PATH = './net.pth' model_ft = models.resnet18(pretrained=True) num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs, 16) model_ft.load_state_dict(torch.load(PATH)) model_ft.eval() And I am trying to read Images this way: imsize = 256 loader = transforms.Compose([transforms.Scale(imsize), transforms.ToTensor()]) def image_loader(image_name): #load image, returns cuda tensor image = Image.open(image_name) image = loader(image).float() image = Variable(image, requires_grad=True) image = image.unsqueeze(0) return image.cuda() image = image_loader("dataset/test/9673.png") model_ft(image) I am getting this error: "Given groups=1, weight of size [64, 3, 7, 7], expected input[1, 4, 676, 256] to have 3 channels, but got 4 channels instead" I've got recommended to remove the unsqueeze for resnet18, doing that I got the following error: "Expected 4-dimensional input for 4-dimensional weight [64, 3, 7, 7], but got 3-dimensional input of size [4, 676, 256] instead" I do not quite understand the problem I am dealing with, how should I read my test set? I'll need to write the class ID-s and the file names into a .txt afterwards.
You are using a PNG image which has 4 channels. your network expects 3 channels. Convert to RGB and you should be fine. In your image_loader simply do: image = Image.open(image_name).convert('RGB')
https://stackoverflow.com/questions/64784310/
How to handle samples with multiple images in a pytorch image processing model?
My model training involves encoding multiple variants of a same image then summing the produced representation over all variants for the image. The data loader produces tensor batches of the shape: [batch_size,num_variants,1,height,width]. The 1 corresponds to image color channels. How can I train my model with minibatches in pytorch? I am looking for a proper way to forward all the batch_size×num_variant images through the network and summing the results over all groups of variants. My current solution involves flattening the first two dimensions and doing a for loop to sum the representations, but I feel like there should be a better way an d I am not sure the gradients will remember everything.
Not sure I understood you correctly, but I guess this is what you want (say the batched image tensor is called image): Nb, Nv, inC, inH, inW = image.shape # treat each variant as if it's an ordinary image in the batch image = image.reshape(Nb*Nv, inC, inH, inW) output = model(image) _, outC, outH, outW = output.shape[1] # reshapes the output such that dim==1 indicates variants output = output.reshape(Nb, Nv, outC, outH, outW) # summing over the variants and lose the dimension of summation, [Nb, outC, outH, outW] output = output.sum(dim=1, keepdim=False) I used inC, outC, inH, etc. in case the input and output channels/sizes are different.
https://stackoverflow.com/questions/64788244/
How can I do a seq2seq task with PyTorch Transformers if I am not trying to be autoregressive?
I may be mistaken, but it seems that PyTorch Transformers are autoregressive, which is what masking is for. However, I've seen some implementations where people use just the Encoder and output that directly to a Linear layer. In my case, I'm trying to convert a spectrogram (rows are frequencies and columns are timesteps) to another spectrogram of the same dimensions. I'm having an impossible time trying to figure out how to do this. For my model, I have: class TransformerReconstruct(nn.Module): def __init__(self, feature_size=250, num_layers=1, dropout=0.1, nhead=10, output_dim=1): super(TransformerReconstruct, self).__init__() self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalEncoding(feature_size) self.encoder_layer = nn.TransformerEncoderLayer(d_model=feature_size, nhead=nhead, dropout=dropout) self.transformer_encoder = nn.TransformerEncoder(self.encoder_layer, num_layers=num_layers) self.decoder = nn.Linear(feature_size, output_dim) self.init_weights() def init_weights(self): initrange = 0.1 self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) def forward(self, src): if self.src_mask is None or self.src_mask.size(0) != len(src): device = src.device mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask src = self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask) output = self.decoder(output) return output def _generate_square_subsequent_mask(self, sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask And when training, I have: model = TransformerReconstruct(feature_size=128, nhead=8, output_dim=128, num_layers=6).to(device) This returns the right shape, but doesn't seem to learn. My basic training loop looks like: for i in range(0, len(data_source) - 1, input_window): data, target = get_batch(data_source, i, 1) output = recreate_model(data) and I'm using an MSELoss and I'm trying to learn a very simple identity. Where the input and output are the same, however this is not learning. What could I be doing wrong? Thanks in advance.
Most of the models in Huggingface Transformers are some version of BERT and thus not autoregressive, the only exceptions are decoder-only models (GPT and similar) and sequence-to-sequence model. There are two conceptually different types of masks: one is the input mask that is specific to the input batch and the purpose is allowing using sequences of different lengths in a single batch. When the sequences get padded to the same length, the self-attention should attend to the padding positions. This is what you are supposed to use when you call self.transformer_encoder in the forward method. In addition, the autoregressive Transformer decoder uses another type of mask. It is the triangular mask that prevents the self-attention to attend to tokens that are right of the current position (at inference time, words right of the current position are unknown before they are actually generated). This is what you have in the _generate_square_subsequent_mask method and this is what makes the model autoregressive. It is constant and does not depend on the input batch. To summarize: to have a bidirectional Transformer, just get rid of the triangular mask. If your input sequences are of different lengths, you should use batch-specific masking, if not, just pass a matrix with ones.
https://stackoverflow.com/questions/64789217/
Longer LSTM Prediction
I am using an LSTM to take 5 sequences as input to predict another 5. I want to know how to predict more than 5 timesteps. I assume its got something to do with the hidden_dim but I can't figure it out. Here is my code class LSTM(nn.Module): def __init__(self, seq_len=5, n_features=256, n_hidden=256, n_layers=1, output_size=1): super().__init__() self.n_features = n_features self.seq_len = seq_len self.n_hidden = n_hidden self.n_layers = n_layers self.l_lstm = nn.LSTM(input_size=self.n_features, hidden_size=self.n_hidden, num_layers=self.n_layers, batch_first=True) def init_hidden(self, batch_size): hidden_state = torch.zeros(self.n_layers,batch_size,self.n_hidden).to(device) cell_state = torch.zeros(self.n_layers,batch_size,self.n_hidden).to(device) self.hidden = (hidden_state, cell_state) def forward(self, x): lstm_out, self.hidden = self.l_lstm(x,self.hidden) return lstm_out If anyone knows how to extend the prediction range or could suggest a better way of writing LSTM, I would really appreciate it.
Right now you are running your LSTM forward for 5 timesteps, and returning the hidden state that resulted at each timestep. This kind of approach is commonly used when you know you need one output for every input, e.g. in sequence labeling problems (e.g. tagging each word in a sentence with its part of speech). If you want to encode a variable length sequence, then decode a sequence of arbitrary, possibly different length (e.g. for machine translation), you need to look up sequence-to-sequence (seq2seq) modeling more generally. This is a bit more involved and involves two LSTMs, one for encoding the input sequence, the other for decoding the output sequence (see EncoderRNN and DecoderRNN implementations in the pytorch tutorial linked above). The basic idea is to take e.g. the final state of the LSTM after consuming the input sentence, then use that state to initialize a separate LSTM decoder, from which you sample autoregressively - in other words, you generate a new token, feed the token back into the decoder, then continue either for an arbitrary number of steps that you specify, or until the LSTM samples an "end of sentence" token, if you've trained the LSTM to predict the end of sampled sequences.
https://stackoverflow.com/questions/64793522/
Pytorch: Node2Vec: TypeError: tuple indices must be integers or slices, not tuple
I am trying to run Node2Vec from the torch_geometric.nn library. For reference, I am following this example. While running the train() function I keep getting TypeError: tuple indices must be integers or slices, not tuple. I am using torch version 1.6.0 with CUDA 10.1 and the latest versions of torch-scatter,torch-sparse,torch-cluster, torch-spline-conv and torch-geometric. Here is the detailed error: Part 1 of the Error Part 2 of the Error Thanks for any help.
The error was due to torch.ops.torch_cluster.random_walk returning a tuple instead of an array/tensor. I fixed it by using replacing the functions pos_sample and neg_sample in the torch_geometric.nn.Node2Vec with these. def pos_sample(self, batch): batch = batch.repeat(self.walks_per_node) rowptr, col, _ = self.adj.csr() rw = random_walk(rowptr, col, batch, self.walk_length, self.p, self.q) if not isinstance(rw, torch.Tensor): rw = rw[0] walks = [] num_walks_per_rw = 1 + self.walk_length + 1 - self.context_size for j in range(num_walks_per_rw): walks.append(rw[:, j:j + self.context_size]) return torch.cat(walks, dim=0) def neg_sample(self, batch): batch = batch.repeat(self.walks_per_node * self.num_negative_samples) rw = torch.randint(self.adj.sparse_size(0), (batch.size(0), self.walk_length)) rw = torch.cat([batch.view(-1, 1), rw], dim=-1) walks = [] num_walks_per_rw = 1 + self.walk_length + 1 - self.context_size for j in range(num_walks_per_rw): walks.append(rw[:, j:j + self.context_size]) return torch.cat(walks, dim=0) Refer to PyTorch Node2Vec documentation.
https://stackoverflow.com/questions/64796931/
Loading manually annotated data to train RNN POS tagger
I've got a large manually annotated data. I would like to train a part of speech tagger using RNN. The data is something similar to the text below : Lorem <NP> Ipsum <NP> dummy <N> text <ADV> printing <VREL> typesetting <NUMCR> Ipsum <VREL> Ipsum <NP> Ipsum <NP> Lorem <N> Ipsum <NP> Ipsum <N> Ipsum <NP> Lorem <ADJ> Lorem <NP> Ipsum <N> Lorem <VN> Lorem <ADJ> Lorem <N> Lorem <N> ፣ <PUNC> Lorem <ADJ> Lorem <ADJ> Ipsum <NC> Ipsum <NC> Ipsum <NP> Please guide me on how to load this data to train an RNN based tagger.
To read it, I suggest you convert it to a tsv file with examples separated by blank lines (a.k.a conll format) as follows: src_fp, tgt_fp = "source/file/path.txt", "target/file/path.tsv" with open(src_fp) as src_f: with open(tgt_fp, 'w') as tgt_f: for line in src_f: words = list(line.split(' '))[0::2] tags = list(line.split(' '))[1::2] for w, t in zip(words, tags): tgt_f.write(w+'\t'+t+'\n') tgt_f.write('\n') Then, you'll be able to read it using SequenceTaggingDataset from torchtext.datasets as follows: text_field, label_field = data.Field(), data.Field() pos_dataset = torchtext.datasets.SequenceTaggingDataset( path='data/pos/pos_wsj_train.tsv', fields=[('text', text_field), ('labels', label_field)]) the last steps are to create your vocabulary and to get iterators over your data: text_field.build_vocab(pos_dataset) train_iter = data.BucketIterator.splits( (unsup_train, unsup_val, unsup_test), batch_size=MY_BATCH_SIZE, device=MY_DEVICE) # using the iterator for ex in self train_iter: train(ex.text, ex.labels) I suggest you take a moment to read the documentation about the functions used hereabove, so that you'll be able to adapt them to your needs (maximum vocabulary size, whether to shuffle your examples, sequence lengths, etc). For building an RNN with for classification, the official pytorch tutorial is very easy to learn from. So I suggest you start there and adapt the network inputs and outputs from sequence classification (1 label for each text span), to sequence tagging (1 label for each token).
https://stackoverflow.com/questions/64800029/
Loading a model checkpoint in lesser amount of memory
I had a question that I can't find any answers to online. I have trained a model whose checkpoint file is about 20 GB. Since I do not have enough RAM with my system (or Colaboratory/Kaggle either - the limit being 16 GB), I can't use my model for predictions. I know that the model has to be loaded into memory for the inferencing to work. However, is there a workaround or a method that can: Save some memory and be able to load it in 16 GB of RAM (for CPU), or the memory in the TPU/GPU Can use any framework (since I would be working with both) TensorFlow + Keras, or PyTorch (which I am using right now) Is such a method even possible to do in either of these libraries? One of my tentative solutions was not load it in chunks perhaps, essentially maintaining a buffer for the model weights and biases and performing calculations accordingly - though I haven't found any implementations for that. I would also like to add that I wouldn't mind the performance slowdown since it is to be expected with low-specification hardware. As long as it doesn't take more than two weeks :) I can definitely wait that long...
Yoy can try the following: split model by two parts load weights to the both parts separately calling model.load_weights(by_name=True) call the first model with your input call the second model with the output of the first model
https://stackoverflow.com/questions/64805828/
How can I convert PyTorch Tensor to ndarray of Numpy?
The shape of my tensor is torch.Size([3, 320, 480]) Tensor is tensor([[[0.2980, 0.4353, 0.6431, ..., 0.2196, 0.2196, 0.2157], [0.4235, 0.4275, 0.5569, ..., 0.2353, 0.2235, 0.2078], [0.5608, 0.5961, 0.5882, ..., 0.2314, 0.2471, 0.2588], ..., ..., [0.0588, 0.0471, 0.0784, ..., 0.0392, 0.0471, 0.0745], [0.0275, 0.1020, 0.1882, ..., 0.0196, 0.0157, 0.0471], [0.1569, 0.2353, 0.2471, ..., 0.0549, 0.0549, 0.0627]]]) I need something of shape 320, 480, 3 I guess So, the tensor should look like this array([[[0.29803923, 0.22352941, 0.10980392], [0.43529412, 0.34117648, 0.20784314], [0.6431373 , 0.5254902 , 0.3764706 ], ..., ..., [0.21960784, 0.13333334, 0.05490196], [0.23529412, 0.14509805, 0.05490196], [0.2627451 , 0.1764706 , 0.0627451 ]]], dtype=float32)
First change device to host/cpu with .cpu() (if its on cuda), then detach from computational graph with .detach() and then convert to numpy with .numpy() t = torch.tensor(...).reshape(320, 480, 3) numpy_array = t.cpu().detach().numpy()
https://stackoverflow.com/questions/64807876/
Chained numerical comparisons in PyTorch
In PyTorch we can do comparisons between elements in tensors like so: import torch a = torch.tensor([[1,2], [2,3], [3,4]]) b = torch.tensor([[3,4], [1,2], [2,3]]) print(a.size()) # torch.Size([3, 2]) print(b.size()) # torch.Size([3, 2]) c = a[:, 0] < b[:, 0] print(c) # tensor([ True, False, False]) However, when we try to add a condition, the snippet fails: c = a[:, 0] < b[:, 1] < b[:, 0] The expected output is tensor([ False, False, False]) So, for each element in a, compare its first element with the second element of the corresponding item in b, and compare that element with the first element of the same item in b. Traceback (most recent call last): File "scratch_12.py", line 9, in c = a[:, 0] < b[:, 1] < b[:, 0] RuntimeError: bool value of Tensor with more than one value is ambiguous Why is that, and how can we solve it?
You have to separate your condition in two conditions by using directly the & operator. As to why exactly, it's due to the syntax of torch. c = (a[:, 0] < b[:, 1]) & (b[:, 1] < b[:, 0])
https://stackoverflow.com/questions/64807928/
How can I invert a MelSpectrogram with torchaudio and get an audio waveform?
I have a MelSpectrogram generated from: eval_seq_specgram = torchaudio.transforms.MelSpectrogram(sample_rate=sample_rate, n_fft=256)(eval_audio_data).transpose(1, 2) So eval_seq_specgram now has a size of torch.Size([1, 128, 499]), where 499 is the number of timesteps and 128 is the n_mels. I'm trying to invert it, so I'm trying to use GriffinLim, but before doing that, I think I need to invert the melscale, so I have: inverse_mel_pred = torchaudio.transforms.InverseMelScale(sample_rate=sample_rate, n_stft=256)(eval_seq_specgram) inverse_mel_pred has a size of torch.Size([1, 256, 499]) Then I'm trying to use GriffinLim: pred_audio = torchaudio.transforms.GriffinLim(n_fft=256)(inverse_mel_pred) but I get an error: Traceback (most recent call last): File "evaluate_spect.py", line 63, in <module> main() File "evaluate_spect.py", line 51, in main pred_audio = torchaudio.transforms.GriffinLim(n_fft=256)(inverse_mel_pred) File "/home/shamoon/.local/share/virtualenvs/speech-reconstruction-7HMT9fTW/lib/python3.8/site-packages/torch/nn/modules/module.py", line 727, in _call_impl result = self.forward(*input, **kwargs) File "/home/shamoon/.local/share/virtualenvs/speech-reconstruction-7HMT9fTW/lib/python3.8/site-packages/torchaudio/transforms.py", line 169, in forward return F.griffinlim(specgram, self.window, self.n_fft, self.hop_length, self.win_length, self.power, File "/home/shamoon/.local/share/virtualenvs/speech-reconstruction-7HMT9fTW/lib/python3.8/site-packages/torchaudio/functional.py", line 179, in griffinlim inverse = torch.istft(specgram * angles, RuntimeError: The size of tensor a (256) must match the size of tensor b (129) at non-singleton dimension 1 Not sure what I'm doing wrong or how to resolve this.
By looking at the documentation and by doing a quick test on colab it seems that: When you create the MelSpectrogram with n_ftt = 256, 256/2+1 = 129 bins are generated At the same time InverseMelScale took as input the parameter called n_stft that indicates the number of bins (so in your case should be set to 129) As a side note, I don't understand why you need the transpose call, since according to the doc and my tests waveform, sample_rate = torchaudio.load('test.wav') mel_specgram = transforms.MelSpectrogram(sample_rate)(waveform) # (channel, n_mels, time) already returns a (channel, n_mels, time) tensor and InverseMelScale wants a tensor of shape (…, n_mels, time)
https://stackoverflow.com/questions/64809370/
Running out of GPU memory with PyTorch
I am running my own custom deep belief network code using PyTorch and using the LBFGS optimizer. After optimization starts, my GPU starts to run out of memory, fully running out after a couple of batches, but I'm not sure why. Should I be purging memory after each batch is run through the optimizer? My code is as follows (with the portion of code that causes the problem marked): def fine_tuning(self, data, labels, num_epochs=10, max_iter=3): ''' Parameters ---------- data : TYPE torch.Tensor N x D tensor with N = num samples, D = num dimensions labels : TYPE torch.Tensor N x 1 vector of labels for each sample num_epochs : TYPE, optional DESCRIPTION. The default is 10. max_iter : TYPE, optional DESCRIPTION. The default is 3. Returns ------- None. ''' N = data.shape[0] #need to unroll the weights into a typical autoencoder structure #encode - code - decode for ii in range(len(self.rbm_layers)-1, -1, -1): self.rbm_layers.append(self.rbm_layers[ii]) L = len(self.rbm_layers) optimizer = torch.optim.LBFGS(params=list(itertools.chain(*[list(self.rbm_layers[ii].parameters()) for ii in range(L)] )), max_iter=max_iter, line_search_fn='strong_wolfe') dataset = torch.utils.data.TensorDataset(data, labels) dataloader = torch.utils.data.DataLoader(dataset, batch_size=self.batch_size*10, shuffle=True) #fine tune weights for num_epochs for epoch in range(1,num_epochs+1): with torch.no_grad(): #get squared error before optimization v = self.pass_through_full(data) err = (1/N) * torch.sum(torch.pow(data-v.to("cpu"), 2)) print("\nBefore epoch {}, train squared error: {:.4f}\n".format(epoch, err)) #*******THIS IS THE PROBLEM SECTION*******# for ii,(batch,_) in tqdm(enumerate(dataloader), ascii=True, desc="DBN fine-tuning", file=sys.stdout): print("Fine-tuning epoch {}, batch {}".format(epoch, ii)) with torch.no_grad(): batch = batch.view(len(batch) , self.rbm_layers[0].visible_units) if self.use_gpu: #are we using a GPU? batch = batch.to(self.device) #if so, send batch to GPU B = batch.shape[0] def closure(): optimizer.zero_grad() output = self.pass_through_full(batch) loss = nn.BCELoss(reduction='sum')(output, batch)/B print("Batch {}, loss: {}\r".format(ii, loss)) loss.backward() return loss optimizer.step(closure) The error I get is: DBN fine-tuning: 0it [00:00, ?it/s]Fine-tuning epoch 1, batch 0 Batch 0, loss: 4021.35400390625 Batch 0, loss: 4017.994873046875 DBN fine-tuning: 0it [00:00, ?it/s] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/deep_autoencoder/deep_autoencoder.py", line 260, in fine_tuning optimizer.step(closure) File "/home/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/autograd /grad_mode.py", line 15, in decorate_context return func(*args, **kwargs) File "/home/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/optim/lb fgs.py", line 425, in step loss, flat_grad, t, ls_func_evals = _strong_wolfe( File "/home/anaconda3/envs/torch_env/lib/python3.8/site-packages/torch/optim/lb fgs.py", line 96, in _strong_wolfe g_prev = g_new.clone(memory_format=torch.contiguous_format) RuntimeError: CUDA out of memory. Tried to allocate 1.57 GiB (GPU 0; 24.00 GiB total capac ity; 13.24 GiB already allocated; 1.41 GiB free; 20.07 GiB reserved in total by PyTorch) This also racks up memory if I use CPU, so I'm not sure what the solution is here...
The official document on LBFGS says: This is a very memory intensive optimizer (it requires additional param_bytes * (history_size + 1) bytes). If it doesn’t fit in memory try reducing the history size, or use a different algorithm. Since I see you didn't specify the history_size parameter in the initialization call of torch.optim.LBFGS, it should be 100 by default. Since you have used more than 10GB memory for the first two batches, I guess you need at least hundreds of GB of memory. I'd suggest setting history_size to 1 to confirm that the problem is indeed caused by saving too much history. If it is, try solving it by reducing the history size or the parameter size.
https://stackoverflow.com/questions/64809589/
How to assert torch.float32/64 using isinstance?
I am writing a pipeline for my deep learning project, as a good practice, I try to do some assertions to make sure the data type matches, so it's easier to debug later! However, I do not know how to use isinstance to assert the torch.Tensor's dtype. For example: assert isinstance(image, torch.Tensor) and isinstance(target['boxes'], torch.Tensor) assert isinstance(image.dtype, (torch.float32, torch.float64)) and isinstance(target['boxes'].dtype, (torch.float32, torch.float64)) Is using assert image.dtype in [torch.float32, torch.float64] the only method here? Is there an elegant way to do so?
You could use torch.is_floating_point assert torch.is_floating_point(image) and torch.is_floating_point(target['boxes']) The function raises an exception if the input is not a tensor. Therefore it is not necessary to do an independent check for torch.Tensor.
https://stackoverflow.com/questions/64816159/
PyTorch model not converging
I'm training a binary classification model on a series of images. The model was derived from resnet18 in torchvision and I made the last FC as nn.Linear(512, 1) The loss function is BCELoss However, the model doesn't show any sign of converging even after 5000 iterations. I'm suspecting I might do something wrong in the training stage? But I can't find where's the bug. Here's my code: Model: ## Model import torch.nn as nn import torch.nn.functional as F import torchvision.models as models resnet18 = models.resnet18(pretrained= True) resnet18.fc = nn.Linear(512, 1) Parameters, loss, optimizers: ## parameter epochs = 200 learning_rate = 0.1 momen = 0.9 batch = 8 criterion = nn.BCELoss() resnet18.to(device) opt = optim.SGD(resnet18.parameters(), lr = learning_rate, momentum = momen) Dataloaders: # Generators training_set = Dataset(X_train) training_generator = torch.utils.data.DataLoader(training_set, batch_size= batch, shuffle=True) validation_set = Dataset(X_test) validation_generator = torch.utils.data.DataLoader(validation_set, batch_size=1, shuffle=False) Training: # training history = [] for t in range(epochs): for i, data in enumerate(training_generator, 0): inputs, labels = data # check if input size == batch size # if inputs.shape[0] < batch: break # print("labels", labels, labels.dtype) # move data to GPU # inputs, labels = inputs.to(device), labels.to(device) opt.zero_grad() # Prediction # y_pred = resnet18(inputs).view(batch,) y_pred = (y_pred > 0).float().requires_grad_() # print("y_pred", y_pred, y_pred.dtype) # Calculating loss # loss = criterion(y_pred, labels.view(batch,)) loss.backward() opt.step() if i % 10 == 0: history.append(loss.item()) print("Epoch: {}, iter: {}, loss: {}".format(t, i, loss.item()) torch.save(resnet18, 'trained_resnet18.pt') Edit: The loss values are like this: Epoch: 3, iter: 310, loss: 0.0 Epoch: 3, iter: 320, loss: 37.5 Epoch: 3, iter: 330, loss: 37.5 Epoch: 3, iter: 340, loss: 0.0 Epoch: 3, iter: 350, loss: 37.5 Epoch: 3, iter: 360, loss: 50.0 Epoch: 3, iter: 370, loss: 37.5 Epoch: 3, iter: 380, loss: 25.0 Epoch: 3, iter: 390, loss: 12.5
I belive the error lies in the following line: y_pred = (y_pred > 0).float().requires_grad_() You try to binarize the model prediction in a weird way, I suggest do the following instead: y_pred = torch.sigmoid(y_pred) And pass this to the loss function. Explanation The output of the model can be any value, but we want to normalize that values to reside in the [0,1] range. This is exactly what the sigmoid function does. Once we have the values in the range of [0,1] the comparison with the binary labels will make sense, closer to 1 will be "1" and the opposite. You can refer to the following link: https://www.youtube.com/watch?v=WsFasV46KgQ
https://stackoverflow.com/questions/64820428/
'MINST' downloading in Colab from pytorch's torchvision.datasets
The following code run in Colab and I got the following error: NameError: name 'MINST' is not defined What do I need to do? import torch import torchvision from torchvision.datasets import MNIST dataset = MINST(root='data/', download=True) len(dataset) test_dataset = MINST(root='data/', train=False) len(test_dataset) dataset[0]
It is what it say it is a NameError You imported the MNIST dataset and try to access MINST which is not a valid name. Your code should be: import torch import torchvision from torchvision.datasets import MNIST dataset = MNIST(root='data/', download=True) len(dataset) test_dataset = MINST(root='data/', train=False) len(test_dataset) dataset[0]
https://stackoverflow.com/questions/64820730/
Reshape 5-dimensional tiled image to 3-dimensional normal image
I'm creating a program that takes use of an RGB image that is tiled of the shape (n, n, 3, l, l). n is the number of each tile on each side of the image, and l is the length of each tile in pixels. I am trying to reshape this into a (3, l * n, l * n) shape. An example would be shape (7, 7, 3, 224, 224) to (3, 224, 224). I want to keep the positions of the pixels in the new matrix, so I can visualise this image later. If I start with an image of a checkerboard pattern (every other tile has all pixel values set to 1, see example below), and use .reshape((3, 224, 224)) the result is the following: Checkerboard (wanted result) Wrong way of reshaping I have made this for loop method of merging the tiles, which works, but is quite slow: # l: the pixel length of each tile img_reshaped = torch.zeros((3, 224, 224)) for i in range(len(img)): for j in range(len(img[i])): img_reshaped[:, i * l:(i + 1) * l, j * 32:(j + 1) * l] = noise[i, j] I've also tried using .fold(), but this only works with 3D matrices, and not 5D. Any tips on how to solve this? I feel it should be relatively simple, but just can't wrap my head around it just now. PS: The code I used to generate the checkerboard: noise = torch.zeros((7, 7, 3, 32, 32)) for i in range(len(noise)): for j in range(len(noise[i])): if (i % 2 == 0 and j % 2 != 0) or (i % 2 != 0 and j % 2 == 0): noise[i][j] = torch.ones((3, 32, 32))
I think you need to transpose before reshape: n,l=2,3 arr=np.zeros((n,n,3,l,l)) for i in range(n): for j in range(n): arr[i,j] = (i+j)%2 out= arr.transpose(2,0,3,1,4).reshape(3,n*l,-1) Output:
https://stackoverflow.com/questions/64820824/
Gradients returning None in huggingface module
I want to get the gradient of an embedding layer from a pytorch/huggingface model. Here's a minimal working example: from transformers import pipeline nlp = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") responses = ["I'm having a great day!!"] hypothesis_template = 'This person feels {}' candidate_labels = ['happy', 'sad'] nlp(responses, candidate_labels, hypothesis_template=hypothesis_template) I can extract the logits just fine, inputs = nlp._parse_and_tokenize(responses, candidate_labels, hypothesis_template) predictions = nlp.model(**inputs, return_dict=True, output_hidden_states=True) predictions['logits'] and the model returns a layer I'm interested in. I tried to retain the gradient and backprop with respect to a single logit I'm interested in: layer = predictions['encoder_hidden_states'][0] layer.retain_grad() predictions['logits'][0][2].backward(retain_graph=True) However, layer.grad == None no matter what I try. The other named parameters of the model have their gradients computed, so I'm not sure what I'm doing wrong. How do I get the grad of the encoder_hidden_states?
I was also very surprised of this issue. Although I have never used the library I went down and did some debugging and found out that the issue is coming from the library transformers. The problem is comming from from this line : encoder_states = tuple(hidden_state.transpose(0, 1) for hidden_state in encoder_states) If you comment it out, you will get the gradient just with some dimensions transposed. This issue is related to the fact that Pytorch Autograd does not do very well on inplace operations as mentioned here. So to recap the solution is to comment line 382 in modeling_bart.py. You will get the gradient with this shape T x B x C instead of B x T x C, but you can reshape it as you want later.
https://stackoverflow.com/questions/64823332/
Difference betwee torch.unsqueeze and target.unsqueeze
I am training a simple MLP by computing the MSE and get the following error: UserWarning: Using a target size (torch.Size([1])) that is different to the input size (torch.Size([1, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size. The following gives me the right solution target = target.unsqueeze(1) while torch.unsqueeze(target,1) does not. The former solution is from a previous question and the latter comes from the documentation Why does the latter fix the UserWarning message with the former doesn't?
torch.unsqueeze Returns a new tensor with a dimension of size one inserted at the specified position. That is its not an inplace operation thus you need to assign its output to something. i.e. simply do : target = torch.unsqueeze(target, 1) Otherwise the tensor will remain the same, as you did not store the changes back into it!
https://stackoverflow.com/questions/64828629/
Change the precision of torch.sigmoid?
I want my sigmoid to never print a solid 1 or 0, but to actually print the exact value i tried using torch.set_printoptions(precision=20) but it didn't work. here's a sample output of the sigmoid function : before sigmoid : tensor([[21.2955703735]]) after sigmoid : tensor([[1.]]) but i don't want it to print 1, i want it to print the exact number, how can i force this?
The difference between 1 and the exact value of sigmoid(21.2955703735) is on the order of 5e-10, which is significantly less than machine epsilon for float32 (which is about 1.19e-7). Therefore 1.0 is the best approximation that can be achieved with the default precision. You can cast your tensor to a float64 (AKA double precision) tensor to get a more precise estimate. torch.set_printoptions(precision=20) x = torch.tensor([21.2955703735]) result = torch.sigmoid(x.to(dtype=torch.float64)) print(result) which results in tensor([0.99999999943577644324], dtype=torch.float64) Keep in mind that even with 64-bit floating point computation this is only accurate to about 6 digits past the last 9 (and will be even less precise for larger sigmoid inputs). A better way to represent numbers very close to one is to directly compute the difference between 1 and the value. In this case 1 - sigmoid(x) which is equivalent to 1 / (1 + exp(x)) or sigmoid(-x). For example, x = torch.tensor([21.2955703735]) delta = torch.sigmoid(-x.to(dtype=torch.float64)) print(f'sigmoid({x.item()}) = 1 - {delta.item()}') results in sigmoid(21.295570373535156) = 1 - 5.642236648842976e-10 and is a more accurate representation of your desired result (though still not exact).
https://stackoverflow.com/questions/64831042/
What is the equivalent of keras NonNeg weight constraint?
Keras has an option to force the weights of the learned model to be positive: tf.keras.constraints.NonNeg() But I couldn't find the equivalent of this in pytorch, does anyone know how can I force my linear model's weights to be all positives? Tried asking this on other forums but the answers were not helpful. Let's say I have a very simple linear model as shown below, how should I change it? class Classifier(nn.Module): def __init__(self,input , n_classes): super(Classifier, self).__init__() self.classify = nn.Linear( input , n_classes) def forward(self, h ): final = self.classify(h) return final I want to do exactly what the NonNeg() does but in pytorch, don't want to change what its doing. This is the implementation of NonNeg in keras: class NonNeg(Constraint): """Constrains the weights to be non-negative. """ def __call__(self, w): w *= K.cast(K.greater_equal(w, 0.), K.floatx()) return w
You could define your own layer this way... But I am curious of why you want to do this import torch import torch.nn as nn class PosLinear(nn.Module): def __init__(self, in_dim, out_dim): super(PosLinear, self).__init__() self.weight = nn.Parameter(torch.randn((in_dim, out_dim))) self.bias = nn.Parameter(torch.zeros((out_dim,))) def forward(self, x): return torch.matmul(x, torch.abs(self.weight)) + self.bias Basically, it uses the absolute value of the weight.
https://stackoverflow.com/questions/64831567/
Pytorch : Pass from grid to image coordinate convention for use of grid_sample
I need to interpolate some deformation grid in PyTorch and decided to use the function grid_sample (see doc). I need to reshape grids as images back and forth with theses conventions : N Batch size D grid depth (for 3D images) H grid height W grid width d grid dimension (=2 or 3) images format is (N,2,H,W) in 2D (resp. (N,3,D,H,W) in 3D) when grid format is (N,H,W,2) (resp. (N,D,H,W,3)in 3D) I can't use reshape or view because they do not arrange the data as I wish. I need to have (for example) grid_in_grid_convention[0,:,:,0] == grid_in_image_convention[0,0,:,:] I came up with theses functions to make the reshaping which works fine but I am sure that there is a more compact/fast way to do so. What are your taught ? def grid2im(grid): """Reshape a grid tensor into an image tensor 2D [T,H,W,2] -> [T,2,H,W] 3D [T,D,H,W,2] -> [T,D,H,W,3] """ if grid.shape[0] == 1 and grid.shape[-1] == 2: # 2D case, batch =1 return torch.stack((grid[0,:,:,0],grid[0,:,:,1]),dim = 0).unsqueeze(0) elif grid.shape[0] == 1 and grid.shape[-1] == 3: # 3D case, batch =1 return torch.stack((grid[0,:,:,:,0],grid[0,:,:,:,1],grid[0,:,:,:,2]), dim = 0).unsqueeze(0) elif grid.shape[-1] == 2: N,H,W,d = grid.shape temp = torch.zeros((N,H,W,d)) for n in range(N): temp[n,:,:,:] = torch.stack((grid[n,:,:,0],grid[n,:,:,1]),dim = 0).unsqueeze(0) return temp elif grid.shape[-1] == 3: N,D,H,W,d =grid.shape temp = torch.zeros((N,D,H,W,d)) for n in range(N): temp[n,:,:,:,:] = torch.stack((grid[n,:,:,:,0], grid[n,:,:,:,1], grid[n,:,:,:,2]), dim = 0).unsqueeze(0) else: raise ValueError("input argument expected is [N,H,W,2] or [N,D,H,W,3]", "got "+str(grid.shape)+" instead.") def im2grid(image): """Reshape an image tensor into a grid tensor 2D case [T,2,H,W] -> [T,H,W,2] 3D case [T,3,D,H,W] -> [T,D,H,W,3] """ # No batch if image.shape[0:2] == (1,2): return torch.stack((image[0,0,:,:],image[0,1,:,:]),dim= 2).unsqueeze(0) elif image.shape[0:2] == (1,3): return torch.stack((image[0,0,:,:],image[0,1,:,:],image[0,2,:,:]), dim = 2).unsqueeze(0) # Batch size > 1 elif image.shape[0] > 0 and image.shape[1] == 2 : N,d,H,W = image.shape temp = torch.zeros((N,H,W,d)) for n in range(N): temp[n,:,:,:] = torch.stack((image[n,0,:,:],image[n,1,:,:]),dim= 2).unsqueeze(0) return temp elif image.shape[0] > 0 and image.shape[1] == 3 : N,d,D,H,W = image.shape temp = torch.zeros((N,D,H,W,d)) for n in range(N): temp[n,:,:,:] = torch.stack((image[n,0,:,:], image[n,1,:,:], image[n,2,:,:]), dim = 2).unsqueeze(0) return temp else: raise ValueError("input argument expected is [1,2,H,W] or [1,3,D,H,W]", "got "+str(image.shape)+" instead.")
You can use transpose(). For example, if you want [T,H,W,2] -> [T,2,H,W] for a tensor, say grid, you can do grid = grid.transpose(2,3).transpose(1,2)
https://stackoverflow.com/questions/64834458/
How to efficiently run multiple Pytorch Processes / Models at once ? Traceback: The paging file is too small for this operation to complete
Background I have a very small network which I want to test with different random seeds. The network barely uses 1% of my GPUs compute power so i could in theory run 50 processes at once to try many different seeds at once. Problem Unfortunately i can't even import pytorch in multiple processes. When the nr of processes exceeds 4 I get a Traceback regarding a too small paging file. Minimal reproducable code§ - dispatcher.py from subprocess import Popen import sys procs = [] for seed in range(50): procs.append(Popen([sys.executable, "ml_model.py", str(seed)])) for proc in procs: proc.wait() §I increased the number of seeds so people with better machines can also reproduce this. Minimal reproducable code - ml_model.py import torch import time time.sleep(10) Traceback (most recent call last): File "ml_model.py", line 1, in <module> import torch File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\__init__.py", line 117, in <module> import torch File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\__init__.py", line 117, in <module> raise err OSError: [WinError 1455] The paging file is too small for this operation to complete. Error loading "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\lib\cudnn_cnn_infer64_8.dll" or one of its dependencies. raise err Further Investigation I noticed that each process loads a lot of dll's into RAM. And when i close all other programs which use a lot of RAM i can get up to 10 procesess instead of 4. So it seems like a resource constraint. Questions Is there a workaround ? What's the recommended way to train many small networks with pytorch on a single gpu ? Should i write my own CUDA Kernel instead, or use a different framework to achieve this ? My goal would be to run around 50 processes at once (on a 16GB RAM Machine, 8GB GPU RAM)
I've looked a bit into this tonight. I don't have a solution (edit: I have a mitigation, see the edit at end), but I have a bit more information. It seems the issue is caused by NVidia fatbins (.nv_fatb) being loaded into memory. Several DLLs, such as cusolver64_xx.dll, torcha_cuda_cu.dll, and a few others, have .nv_fatb sections in them. These contain tons of different variations of CUDA code for different GPUs, so it ends up being several hundred megabytes to a couple gigabytes. When Python imports 'torch' it loads these DLLs, and maps the .nv_fatb section into memory. For some reason, instead of just being a memory mapped file, it is actually taking up memory. The section is set as 'copy on write', so it's possible something writes into it? I don't know. But anyway, if you look at Python using VMMap ( https://learn.microsoft.com/en-us/sysinternals/downloads/vmmap ) you can see that these DLLs are committing huge amounts of committed memory for this .nv_fatb section. The frustrating part is it doesn't seem to be using the memory. For example, right now my Python.exe has 2.7GB committed, but the working set is only 148MB. Every Python process that loads these DLLs will commit several GB of memory loading these DLLs. So if 1 Python process is wasting 2GB of memory, and you try running 8 workers, you need 16GB of memory to spare just to load the DLLs. It really doesn't seem like this memory is used, just committed. I don't know enough about these fatbinaries to try to fix it, but from looking at this for the past 2 hours it really seems like they are the issue. Perhaps its an NVidia problem that these are committing memory? edit: I made this python script: https://gist.github.com/cobryan05/7d1fe28dd370e110a372c4d268dcb2e5 Get it and install its pefile dependency ( python -m pip install pefile ). Run it on your torch and cuda DLLs. In OPs case, command line might look like: python fixNvPe.py --input=C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\lib\*.dll (You also want to run this wherever your cusolver64_*.dll and friends are. This may be in your torch\lib folder, or it may be, eg, C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\vXX.X\bin . If it is under Program Files, you will need to run the script with administrative privileges) What this script is going to do is scan through all DLLs specified by the input glob, and if it finds an .nv_fatb section it will back up the DLL, disable ASLR, and mark the .nv_fatb section read-only. ASLR is 'address space layout randomization.' It is a security feature that randomizes where a DLL is loaded in memory. We disable it for this DLL so that all Python processes will load the DLL into the same base virtual address. If all Python processes using the DLL load it at the same base address, they can all share the DLL. Otherwise each process needs its own copy. Marking the section 'read-only' lets Windows know that the contents will not change in memory. If you map a file into memory read/write, Windows has to commit enough memory, backed by the pagefile, just in case you make a modification to it. If the section is read-only, there is no need to back it in the pagefile. We know there are no modifications to it, so it can always be found in the DLL. The theory behind the script is that by changing these 2 flags that less memory will be committed for the .nv_fatb, and more memory will be shared between the Python processes. In practice, it works. Not quite as well as I'd hope (it still commits a lot more than it uses), so my understanding may be flawed, but it significantly decreases memory commit. In my limited testing I haven't ran into any issues, but I can't guarantee there are no code paths that attempts to write to that section we marked 'read only.' If you start running into issues, though, you can just restore the backups. edit 2022-01-20: Per NVIDIA: "We have gone ahead and marked the nv_fatb section as read-only, this change will be targeting next major CUDA release 11.7 . We are not changing the ASLR, as that is considered a safety feature ." This should certainly help. If it's not enough without ASLR as well then the script should still work
https://stackoverflow.com/questions/64837376/
return next(self._sampler_iter) # may raise StopIteration
Instead of using enumerate(data loader) for some reason, I am creating iterator for the data loader. In the while loop shown below, it gives me StopIteration error. Minimalistic code that depicts the cause: loader = DataLoader(dataset, batch_size=args.batch_size) dataloader_iter = iter(loader) while(dataloader_iter): X, y = next(dataloader_iter) ... What would be the correct condition (to specify within the while loop) to check if the iterator is empty?
In Python it's standard in a lot of cases to use exceptions for control flow. Just wrap it in a try-except: loader = DataLoader(dataset, batch_size=args.batch_size) dataloader_iter = iter(loader) try: while True: x, y = next(dataloader_iter) ... except StopIteration: pass If you want to catch some other errors inside the while loop, you can move the try-except inside, but you must remember to break out of the loop when you hit a StopIteration: loader = DataLoader(dataset, batch_size=args.batch_size) dataloader_iter = iter(loader) while True: try: x, y = next(dataloader_iter) ... except SomeOtherException: ... except StopIteration: break
https://stackoverflow.com/questions/64838939/
How to convert a pandas dataframe into a numpy array with the column names
This must use vectorized methods, nothing iterative I would like to create a numpy array from pandas dataframe. My code: import pandas as pd _df = pd.DataFrame({'itme': ['book', 'book' , 'car', ' car', 'bike', 'bike'], 'color': ['green', 'blue' , 'red', 'green' , 'blue', 'red'], 'val' : [-22.7, -109.6, -57.19, -11.2, -25.6, -33.61]}) item color val book green -22.70 book blue -109.60 car red -57.19 car green -11.20 bike blue -25.60 bike red -33.61 There are about 12k million rows. I need to create a numpy array like : item green blue red book -22.70 -109.60 null car -11.20 null -57.19 bike null -25.60 -33.16 each row is the item name and each col is color name. The order of the items and colors are not important. But, in numpy array, there are no row and column names, I need to keep the item and color name for each value, so that I know what the value represents in the numpy array. For example how to know that -57.19 is for "car" and "red" in numpy array ? So, I need to create a dictionary to keep the mapping between : item <--> row index in the numpy array color <--> col index in the numpy array I do not want to use iteritems and itertuples because they are not efficient for large dataframe due to How to iterate over rows in a DataFrame in Pandas and How to iterate over rows in a DataFrame in Pandas and Python Pandas iterate over rows and access column names and Does pandas iterrows have performance issues? I prefer numpy vectorization solution for this. How to efficiently convert the pandas dataframe to numpy array ? The array will also be transformed to torch.tensor. thanks
do a quick search for a val by their "item" and "color" with one of the following options: Use pandas Boolean indexing Convert the dataframe into a numpy.recarry using pandas.DataFrame.to_records, and also use Boolean indexing .item is a method for both pandas and numpy, so don't use 'item' as a column name. It has been changed to '_item'. As an FYI, numpy is a pandas dependency, and much of pandas vectorized functionality directly corresponds to numpy. import pandas as pd import numpy as np # test data df = pd.DataFrame({'_item': ['book', 'book' , 'car', 'car', 'bike', 'bike'], 'color': ['green', 'blue' , 'red', 'green' , 'blue', 'red'], 'val' : [-22.7, -109.6, -57.19, -11.2, -25.6, -33.61]}) # Use pandas Boolean index to selected = df[(df._item == 'book') & (df.color == 'blue')] # print(selected) _item color val book blue -109.6 # Alternatively, create a recarray v = df.to_records(index=False) # display(v) rec.array([('book', 'green', -22.7 ), ('book', 'blue', -109.6 ), ('car', 'red', -57.19), ('car', 'green', -11.2 ), ('bike', 'blue', -25.6 ), ('bike', 'red', -33.61)], dtype=[('_item', 'O'), ('color', 'O'), ('val', '<f8')]) # search the recarray selected = v[(v._item == 'book') & (v.color == 'blue')] # print(selected) [('book', 'blue', -109.6)] Update in response to OP edit You must first reshape the dataframe using pandas.DataFrame.pivot, and then use the previously mentioned methods. dfp = df.pivot(index='_item', columns='color', values='val') # display(dfp) color blue green red _item bike -25.6 NaN -33.61 book -109.6 -22.7 NaN car NaN -11.2 -57.19 # create a numpy recarray v = dfp.to_records(index=True) # display(v) rec.array([('bike', -25.6, nan, -33.61), ('book', -109.6, -22.7, nan), ('car', nan, -11.2, -57.19)], dtype=[('_item', 'O'), ('blue', '<f8'), ('green', '<f8'), ('red', '<f8')]) # select data selected = v.blue[(v._item == 'book')] # print(selected) array([-109.6])
https://stackoverflow.com/questions/64839600/
Using SGD on MNIST dataset with Pytorch, loss not decreasing
I tried to use SGD on MNIST dataset with batch size of 32, but the loss does not decrease at all. I checked my model, loss function and read documentation but couldn't figure out what I've done wrong. I defined my neural network as below class classification(nn.Module): def __init__(self): super(classification, self).__init__() # construct layers for a neural network self.classifier1 = nn.Sequential( nn.Linear(in_features=28*28, out_features=20*20), nn.Sigmoid(), ) self.classifier2 = nn.Sequential( nn.Linear(in_features=20*20, out_features=10*10), nn.Sigmoid(), ) self.classifier3 = nn.Sequential( nn.Linear(in_features=10*10, out_features=10), nn.LogSoftmax(dim=1), ) def forward(self, inputs): # [batchSize, 1, 28, 28] x = inputs.view(inputs.size(0), -1) # [batchSize, 28*28] x = self.classifier1(x) # [batchSize, 20*20] x = self.classifier2(x) # [batchSize, 10*10] out = self.classifier3(x) # [batchSize, 10] return out And I defined my training process as below classifier = classification().to("cuda") #optimizer optimizer = torch.optim.SGD(classifier.parameters(), lr=learning_rate_value) #loss function criterion = nn.NLLLoss() batch_size=32 epoch = 30 #array to save loss history loss_train_arr=np.zeros(epoch) #used DataLoader to make split batch batched_train = torch.utils.data.DataLoader(training_set, batch_size, shuffle=True) for i in range(epoch): loss_train=0 #train and compute loss, accuracy for img, label in batched_train: img=img.to(device) label=label.to(device) optimizer.zero_grad() predicted = classifier(img) label_predicted = torch.argmax(predicted,dim=1) loss = criterion(predicted, label) loss.backward optimizer.step() loss_train += loss.item() loss_train_arr[i]=loss_train/(len(batched_train.dataset)/batch_size) I am using a model with LogSoftmax layer, so my loss function seems right. But the loss does not decrease at all.
If the code you posted is the exact code you use, the problem is that you don't actually call backward on the loss (missing parentheses ()).
https://stackoverflow.com/questions/64841327/
How to apply distance IoU loss?
I'm currently training custom dataset using this repository: https://github.com/zylo117/Yet-Another-EfficientDet-Pytorch. The result of training is not satisfactory for me, so I'm gonna change the regression loss, which is L1-smooth loss, into distance IoU loss. The code for regresssion loss for this repo is below: anchor_widths_pi = anchor_widths[positive_indices] anchor_heights_pi = anchor_heights[positive_indices] anchor_ctr_x_pi = anchor_ctr_x[positive_indices] anchor_ctr_y_pi = anchor_ctr_y[positive_indices] gt_widths = assigned_annotations[:, 2] - assigned_annotations[:, 0] gt_heights = assigned_annotations[:, 3] - assigned_annotations[:, 1] gt_ctr_x = assigned_annotations[:, 0] + 0.5 * gt_widths gt_ctr_y = assigned_annotations[:, 1] + 0.5 * gt_heights # efficientdet style gt_widths = torch.clamp(gt_widths, min=1) gt_heights = torch.clamp(gt_heights, min=1) targets_dx = (gt_ctr_x - anchor_ctr_x_pi) / anchor_widths_pi targets_dy = (gt_ctr_y - anchor_ctr_y_pi) / anchor_heights_pi targets_dw = torch.log(gt_widths / anchor_widths_pi) targets_dh = torch.log(gt_heights / anchor_heights_pi) targets = torch.stack((targets_dy, targets_dx, targets_dh, targets_dw)) targets = targets.t() # L1 loss regression_diff = torch.abs(targets - regression[positive_indices, :]) regression_loss = torch.where( torch.le(regression_diff, 1.0 / 9.0), 0.5 * 9.0 * torch.pow(regression_diff, 2), regression_diff - 0.5 / 9.0 The code that i'm using as distance IoU is below: rows = bboxes1.shape[0] cols = bboxes2.shape[0] dious = torch.zeros((rows, cols)) if rows * cols == 0: return dious exchange = False bboxes1 = bboxes1.index_select(1, torch.LongTensor([1, 0, 3, 2]).to('cuda')) if bboxes1.shape[0] > bboxes2.shape[0]: bboxes1, bboxes2 = bboxes2, bboxes1 dious = torch.zeros((cols, rows)) exchange = True w1 = bboxes1[:, 2] - bboxes1[:, 0] h1 = bboxes1[:, 3] - bboxes1[:, 1] w2 = bboxes2[:, 2] - bboxes2[:, 0] h2 = bboxes2[:, 3] - bboxes2[:, 1] area1 = w1 * h1 area2 = w2 * h2 center_x1 = (bboxes1[:, 2] + bboxes1[:, 0]) / 2 center_y1 = (bboxes1[:, 3] + bboxes1[:, 1]) / 2 center_x2 = (bboxes2[:, 2] + bboxes2[:, 0]) / 2 center_y2 = (bboxes2[:, 3] + bboxes2[:, 1]) / 2 inter_max_xy = torch.min(bboxes1[:, 2:],bboxes2[:, 2:]) inter_min_xy = torch.max(bboxes1[:, :2],bboxes2[:, :2]) out_max_xy = torch.max(bboxes1[:, 2:],bboxes2[:, 2:]) out_min_xy = torch.min(bboxes1[:, :2],bboxes2[:, :2]) inter = torch.clamp((inter_max_xy - inter_min_xy), min=0) inter_area = inter[:, 0] * inter[:, 1] inter_diag = (center_x2 - center_x1)**2 + (center_y2 - center_y1)**2 outer = torch.clamp((out_max_xy - out_min_xy), min=0) outer_diag = (outer[:, 0] ** 2) + (outer[:, 1] ** 2) union = area1+area2-inter_area dious = inter_area / union - (inter_diag) / outer_diag dious = torch.clamp(dious,min=-1.0,max = 1.0) if exchange: dious = dious.T loss = 1 - dious return loss The question is here: Should I apply the distance IoU loss for one target bbox to all pred bbox? For example, there is 2 annotated bboxes, and 1000 predicted bboxes. Should I calculate losses for twice like each annotated bbox vs 1000 predicted bboxes? Should I change the predicted bbox into real coordinates for calculation?
I've seen this done a couple ways, but typically the methods work by assigning the boxes. Calculating 1000x2 array of IOU, you can assign each prediction box a ground truth target and threshold the IOU for good/bad predictions as seen in RetinaNet or assign each ground truth target the best prediction box as seen in older YOLO. Either way, the loss is applied only to the assigned box pairs, not each combination so each assigned prediction focuses on a single target. DIOU is invariant to scale
https://stackoverflow.com/questions/64841988/
Determine whether a model is pytorch model or a tensorflow model or scikit model
If I want to determine the type of model i.e. from which framework was it made programmatically, is there a way to do that? I have a model in some serialized manner(Eg. a pickle file). For simplicity purposes, assume that my model can be either tensorflow's, pytorch's or scikit learn's. How can I determine programmatically which one of these 3 is the one?
AFAIK, I have never heard of Tensorflow/Keras and Pytorch models to be saved with pickle or joblib - these frameworks provide their own functionality for saving & loading models: see the SO threads Tensorflow: how to save/restore a model? and Best way to save a trained model in PyTorch?. Additionally, there is a Github thread reporting all kinds of issues when trying to save Tensorflow models with pickle and joblib. Given that, if you have loaded a model with, say, pickle, it is trivial to see what type it is using type(model) and model. Here is a short demonstration with a scikit-learn linear regression model: import numpy as np from sklearn.linear_model import LinearRegression X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) y = np.dot(X, np.array([1, 2])) + 3 reg = LinearRegression() reg.fit(X, y) # save it import pickle filename = 'model1.pkl' pickle.dump(reg, open(filename, 'wb')) Now, loading the model: loaded_model = pickle.load(open(filename, 'rb')) type(loaded_model) # sklearn.linear_model._base.LinearRegression loaded_model # LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False) This will also work with frameworks like XGBoost, LightGBM, CatBoost etc.
https://stackoverflow.com/questions/64849520/
Windows keeps crashing when trying to install PyTorch via pip
I am currently trying to install PyTorch (using the installation commands posted on PyTorch.org for pip) and when I run the command, my computer completely freezes. I tried this multiple times with the same result. I had to restart the computer a few times as well. On my current try, I put "-v" when trying to install and the pip seems to be stuck on "Looking up in the cache". I do not know how to proceed. As I mentioned, I've already tried this method multiple times. It worked the first time but did not install PyTorch as it gave me an error for not using "--user". Are there any solutions to this? EDIT: I did want to add that I have Python 3.8.6 (64bit)
After troubling shooting and a lot of restart, it seems like the issue came from when pip was trying to load a pre-downloaded file. Essentially, the first time I ran the installation command, pip downloaded files for pytorch but did not install pytorch due to some user privilege issue. The fix is to add --no-cache-dir in the pip install command. This will override the cache (pre-downloaded files) and download the files all over again. For me specifically, I also needed to add --user. In other words, the command went from pip install torch===1.7.0+cu110 torchvision===0.8.1+cu110 torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html to pip --no-cache-dir install torch===1.7.0+cu110 torchvision===0.8.1+cu110 torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html --user
https://stackoverflow.com/questions/64850321/
What is tape-based autograd in Pytorch?
I understand autograd is used to imply automatic differentiation. But what exactly is tape-based autograd in Pytorch and why there are so many discussions that affirm or deny it. For example: this In pytorch, there is no traditional sense of tape and this We don’t really build gradient tapes per se. But graphs. but not this Autograd is now a core torch package for automatic differentiation. It uses a tape based system for automatic differentiation. And for further reference, please compare it with GradientTape in Tensorflow.
There are different types of automatic differentiation e.g. forward-mode, reverse-mode, hybrids; (more explanation). The tape-based autograd in Pytorch simply refers to the uses of reverse-mode automatic differentiation, source. The reverse-mode auto diff is simply a technique used to compute gradients efficiently and it happens to be used by backpropagation, source. Now, in PyTorch, Autograd is the core torch package for automatic differentiation. It uses a tape-based system for automatic differentiation. In the forward phase, the autograd tape will remember all the operations it executed, and in the backward phase, it will replay the operations. Same in TensorFlow, to differentiate automatically, It also needs to remember what operations happen in what order during the forward pass. Then, during the backward pass, TensorFlow traverses this list of operations in reverse order to compute gradients. Now, TensorFlow provides the tf.GradientTape API for automatic differentiation; that is, computing the gradient of computation with respect to some inputs, usually tf.Variables. TensorFlow records relevant operations executed inside the context of a tf.GradientTape onto a tape. TensorFlow then uses that tape to compute the gradients of a recorded computation using reverse mode differentiation. So, as we can see from the high-level viewpoint, both are doing the same operation. However, during the custom training loop, the forward pass and calculation of the loss are more explicit in TensorFlow as it uses tf.GradientTape API scope whereas in PyTorch it's implicit for these operations but it requires to set required_grad flags to False temporarily while updating the training parameters (weights and biases). For that, it uses torch.no_grad API explicitly. In other words, TensorFlow's tf.GradientTape() is similar to PyTorch's loss.backward(). Below is the simplistic form in the code of the above statements. # TensorFlow [w, b] = tf_model.trainable_variables for epoch in range(epochs): with tf.GradientTape() as tape: # forward passing and loss calculations # within explicit tape scope predictions = tf_model(x) loss = squared_error(predictions, y) # compute gradients (grad) w_grad, b_grad = tape.gradient(loss, tf_model.trainable_variables) # update training variables w.assign(w - w_grad * learning_rate) b.assign(b - b_grad * learning_rate) # PyTorch [w, b] = torch_model.parameters() for epoch in range(epochs): # forward pass and loss calculation # implicit tape-based AD y_pred = torch_model(inputs) loss = squared_error(y_pred, labels) # compute gradients (grad) loss.backward() # update training variables / parameters with torch.no_grad(): w -= w.grad * learning_rate b -= b.grad * learning_rate w.grad.zero_() b.grad.zero_() FYI, in the above, the trainable variables (w, b) are manually updated in both frameworks but we generally use an optimizer (e.g. adam) to do the job. # TensorFlow # .... # update training variables optimizer.apply_gradients(zip([w_grad, b_grad], model.trainable_weights)) # PyTorch # .... # update training variables / parameters optimizer.step() optimizer.zero_grad()
https://stackoverflow.com/questions/64856195/
Detecting fixed size objects in variable sized images
Neural networks can be trained to recognize an object, then detect occurrences of that object in an image, regardless of their position and apparent size. An example of doing this in PyTorch is at https://towardsdatascience.com/object-detection-and-tracking-in-pytorch-b3cf1a696a98 As the text observes, Most of the code deals with resizing the image to a 416px square while maintaining its aspect ratio and padding the overflow. So the idea is that the model always deals with 416px images, both in training and in the actual object detection. Detected objects, being only part of the image, will typically be smaller than 416px, but that's okay because the model has been trained to detect patterns in a scale-invariant way. The only thing fixed is the size in pixels of the input image. I'm looking at a context in which it is necessary to do the reverse: train to detect patterns of a fixed size, then detect them in a variable sized image. For example, train to detect patterns 10px square, then look for them in an image that could be 500px or 1000px square, without resizing the image, but with the assurance that it is only necessary to look for 10px occurrences of the pattern. Is there an idiomatic way to do this in PyTorch?
Even if you trained your detector with a fixed size image, you can use a different sizes at inference time because everything is convolutional in faster rcnn/yolo architectures. On the other hand, if you only care about 10X10 bounding box detections, you can easily define this as your anchors. I would recomend to you to use the detectron2 framework which is implemented in pytorch and is easily configurable/hackable.
https://stackoverflow.com/questions/64861685/
`*** RuntimeError: mat1 dim 1 must match mat2 dim 0` whenever I run model(images)
def __init__(self): super().__init__() self.conv = nn.Sequential( nn.Conv2d(1, 64, kernel_size=5, stride=2, bias=False), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, bias=False), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, bias=False), nn.BatchNorm2d(64), ) How can I deal with this error? I think the error is with self.fc, but I can't say how to fix it.
The output from self.conv(x) is of shape torch.Size([32, 64, 2, 2]): 32*64*2*2= 8192 (this is equivalent to (self.conv_out_size). The input to fully connected layer expects a single dimension vector i.e. you need to flatten it before passing to a fully connected layer in the forward function. i.e. class Network(): ... def foward(): ... conv_out = self.conv(x) print(conv_out.shape) conv_out = conv_out.view(-1, 32*64*2*2) print(conv_out.shape) x = self.fc(conv_out) return x output torch.Size([32, 64, 2, 2]) torch.Size([1, 8192]) EDIT: I think you're using self._get_conv_out function wrong. It should be def _get_conv_out(self, shape): output = self.conv(torch.zeros(1, *shape)) # not (32, *size) return int(numpy.prod(output.size())) then, in the forward pass, you can use conv_out = self.conv(x) # flatten the output of conv layers conv_out = conv_out.view(conv_out.size(0), -1) x = self.fc(conv_out) For an input of (32, 1, 110, 110), the output should be torch.Size([32, 2]).
https://stackoverflow.com/questions/64868040/
PyTorch - RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 224 and 244 in dimension 2
I am trying to do semantic segmentation with two classes. I have 224x224x3 images and 224x224 binary segmentation masks. I am reshaping the masks to be 224x224x1 (I read somewhere that this is the format that I should pass to the model). When I try to loop through the train data loader it either runs without errors or I get the following error (randomly): Traceback (most recent call last): File "/Users/nikolaykolibarov/Desktop/GATE/rooftop-recognition/rooftop-edge-segmentation-ml/main.py", line 43, in <module> for i, sample in enumerate(train_loader): File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 346, in __next__ data = self._dataset_fetcher.fetch(index) # may raise StopIteration File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/_utils/fetch.py", line 47, in fetch return self.collate_fn(data) File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/_utils/collate.py", line 79, in default_collate return [default_collate(samples) for samples in transposed] File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/_utils/collate.py", line 79, in <listcomp> return [default_collate(samples) for samples in transposed] File "/Users/nikolaykolibarov/opt/anaconda3/envs/dtcc/lib/python3.7/site-packages/torch/utils/data/_utils/collate.py", line 55, in default_collate return torch.stack(batch, 0, out=out) RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 224 and 244 in dimension 2 at /tmp/pip-req-build-9oilk29k/aten/src/TH/generic/THTensor.cpp:689 Most of the issues with the same exception I found online don’t have matching numbers like I do (Got 224 and 224). I don’t understand, this exception should occur when they aren’t equal (if I am not wrong). When I run it, occasionally I get this error a few times, and then it doesn’t occur a few times. I am not sure if I messed something up with the data types and shapes or it is something else. Here is the code: roof_edges_dataset.py import os import cv2 as cv from torch.utils.data import Dataset from torchvision.transforms import transforms from utils import create_binary_mask, get_labelme_shapes, plot_segmentation_dataset class RoofEdgesDataset(Dataset): def __init__(self, im_path, ann_path, transform=None): self.im_path = im_path self.ann_path = ann_path self.transform = transform self.im_fn_list = sorted(os.listdir(im_path), key=lambda x: int(x.split('.')[0])) self.ann_fn_list = sorted(os.listdir(ann_path), key=lambda x: int(x.split('.')[0])) def __len__(self): return len(self.im_fn_list) def __getitem__(self, index): im_path = os.path.join(self.im_path, self.im_fn_list[index]) im = cv.imread(im_path) ann_path = os.path.join(self.ann_path, self.ann_fn_list[index]) ann = create_binary_mask(im, get_labelme_shapes(ann_path)) ann = ann.reshape(ann.shape[0], ann.shape[1], 1) ann = transforms.ToTensor()(ann) if self.transform: im = self.transform(im) return im, ann main.py: import torch import torchvision.transforms as transforms from torch.utils.data import DataLoader from roof_edges_dataset import RoofEdgesDataset # Device device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Hyperparameters in_im_shape = (3, 224, 224) num_classes = 2 # Edge / Non-edge learning_rate = 0.001 batch_size = 4 n_epochs = 10 # Data - 60% Train - 20% Val - 20% Test transformations = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) dataset = RoofEdgesDataset(im_path='data/images', ann_path='data/annotations', transform=transformations) train_size = int(0.8 * len(dataset)) test_size = len(dataset) - train_size train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, test_size]) train_size = int(0.8 * len(train_dataset)) val_size = len(train_dataset) - train_size train_dataset, val_dataset = torch.utils.data.random_split(train_dataset, [train_size, val_size]) train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) val_loader = DataLoader(dataset=val_dataset, batch_size=batch_size, shuffle=True) test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) # Model # Loss and Optimizer # Train for epoch in range(n_epochs): for batch_idx, (image, annotation) in enumerate(train_loader): image = image.to(device=device) annotation = annotation.to(device=device) print(image.shape) print(annotation.shape) break # Evaluate I would be also very thankful if you let me know if something is done in a wrong or stupid way and how to do it better. Thanks in advance!
It seems like your training images have different sizes, e.g. one is 224x224 while another is 244x244. Add a crop/resize transformation to all images so they can be concatenated together to form a batch.
https://stackoverflow.com/questions/64871706/
Organize tensorboard graph with pytorch lightning
I've added the default tensorboard logger (from pytorch_lightning.loggers import TensorBoardLogger) to my pytorch lightning Trainer with log_graph=True. When I train my model, the first view of my graph shows three blocks: inputs => MyNetworkClassName => Outputs So far so good. But then, when I expand MyNetworkClassName it gives me absolutely everything that's going on in my net. That's a lot of arrows going everywhere. I would like to organize this graph into simpler blocks with expandable subgraphs. So in my case, where my network has a typical encoder - enhancer - decoder structure, I would like something more like this: First graph: inputs => MyNetworkClassName => Outputs zooming in on MyNetworkClassName: encoder => enhancer -> decoder zooming in on encoder: encoder_layer1 => encoder_layer2 => ... zooming in on encoder_layer1: conv2d => batchnorm What are my options here? Should I put everything into separate classes? Are there any commands that allow me to group certain actions together?
Refractoring code into classes also affects the tensorboard graph (where refractoring into methods does not). Typical example class that will show up as an expandable block: class EncoderLayer(nn.Module): """Encoder layer class""" def __init__(self, activation_function, kernel_num, kernel_size, idx): super().__init__() self.layer = nn.Sequential( ComplexConv2d( kernel_num[idx], kernel_num[idx + 1], kernel_size=(kernel_size, 2), ), nn.BatchNorm2d(kernel_num[idx + 1]) activation_function, ) def forward(self, x): return self.layer(x)
https://stackoverflow.com/questions/64872670/
How to use the PyTorch Transformer with multi-dimensional sequence-to-seqence?
I'm trying to go seq2seq with a Transformer model. My input and output are the same shape (torch.Size([499, 128]) where 499 is the sequence length and 128 is the number of features. My input looks like: My output looks like: My training loop is: for batch in tqdm(dataset): optimizer.zero_grad() x, y = batch x = x.to(DEVICE) y = y.to(DEVICE) pred = model(x, torch.zeros(x.size()).to(DEVICE)) loss = loss_fn(pred, y) loss.backward() optimizer.step() My model is: import math from typing import final import torch import torch.nn as nn class Reconstructor(nn.Module): def __init__(self, input_dim, output_dim, dim_embedding, num_layers=4, nhead=8, dim_feedforward=2048, dropout=0.5): super(Reconstructor, self).__init__() self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalEncoding(d_model=dim_embedding, dropout=dropout) self.transformer = nn.Transformer(d_model=dim_embedding, nhead=nhead, dim_feedforward=dim_feedforward, num_encoder_layers=num_layers, num_decoder_layers=num_layers) self.decoder = nn.Linear(dim_embedding, output_dim) self.decoder_act_fn = nn.PReLU() self.init_weights() def init_weights(self): initrange = 0.1 nn.init.zeros_(self.decoder.weight) nn.init.uniform_(self.decoder.weight, -initrange, initrange) def forward(self, src, tgt): pe_src = self.pos_encoder(src.permute(1, 0, 2)) # (seq, batch, features) transformer_output = self.transformer_encoder(pe_src) decoder_output = self.decoder(transformer_output.permute(1, 0, 2)).squeeze(2) decoder_output = self.decoder_act_fn(decoder_output) return decoder_output My output has a shape of torch.Size([32, 499, 128]) where 32 is batch, 499 is my sequence length and 128 is the number of features. But the output has the same values: tensor([[[0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], ..., [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017]]], grad_fn=<PreluBackward>) What am I doing wrong? Thank you so much for any help.
There are several points to be checked. As you have same output to the different inputs, I suspect that some layer zeros out all it's inputs. So check the outputs of the PositionalEncoding and also Encoder block of the Transformer, to make sure they are not constant. But before that, make sure your inputs differ (try to inject noise, for example). Additionally, from what I see in the pictures, your input and output are speech signals and was sampled at 22.05kHz (I guess), so it should have ~10k features, but you claim that you have only 128. This is another place to check. Now, the number 499 represent some time slice. Make sure your slices are in reasonable range (20-50 msec, usually 30). If it is the case, then 30ms by 500 is 15 seconds, which is much more you have in your example. And finally you are masking off a third of a second of speech in your input, which is too much I believe. I think it would be useful to examine Wav2vec and Wav2vec 2.0 papers, which tackle the problem of self supervised training in speech recognition domain using Transformer Encoder with great success.
https://stackoverflow.com/questions/64876788/
PyTorch dataloader shows odd behavior with string dataset
I'm working on an NLP problem and am using PyTorch. For some reason, my dataloader is returning malformed batches. I have input data that comprises sentences and integer labels. The sentences can either a list of sentences or a list of list of tokens. I will later convert the tokens to integers in a downstream component. list_labels = [ 0, 1, 0] # List of sentences. list_sentences = [ 'the movie is terrible', 'The Film was great.', 'It was just awful.'] # Or list of list of tokens. list_sentences = [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.'], ['It', 'was', 'just', 'awful.']] I created the following custom dataset: import torch from torch.utils.data import DataLoader, Dataset class MyDataset(torch.utils.data.Dataset): def __init__(self, sentences, labels): self.sentences = sentences self.labels = labels def __getitem__(self, i): result = {} result['sentences'] = self.sentences[i] result['label'] = self.labels[i] return result def __len__(self): return len(self.labels) When I provide input in the form of a list of sentences, the dataloader correctly returns batches of complete sentences. Note that batch_size=2: list_sentences = [ 'the movie is terrible', 'The Film was great.', 'It was just awful.'] list_labels = [ 0, 1, 0] dataset = MyDataset(list_sentences, list_labels) dataloader = DataLoader(dataset, batch_size=2) batch = next(iter(dataloader)) print(batch) # {'sentences': ['the movie is terrible', 'The Film was great.'], <-- Great! 2 sentences in batch! # 'label': tensor([0, 1])} The batch correctly contains two sentences and two labels because batch_size=2. However, when I instead enter the sentences as pre-tokenized list of list of token, I get weird results: list_sentences = [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.'], ['It', 'was', 'just', 'awful.']] list_labels = [ 0, 1, 0] dataset = MyDataset(list_sentences, list_labels) dataloader = DataLoader(dataset, batch_size=2) batch = next(iter(dataloader)) print(batch) # {'sentences': [('the', 'The'), ('movie', 'Film'), ('is', 'was'), ('terrible', 'great.')], <-- WHAT? # 'label': tensor([0, 1])} Note that this batch's sentences is one single list with tuples of word pairs. I was expecting sentences to be a list of two lists, like this: {'sentences': [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.'] What is going on?
This behavior is because the default collate_fn does the following when it has to collate lists (which is the case for ['sentences']): # [...] elif isinstance(elem, container_abcs.Sequence): # check to make sure that the elements in batch have consistent size it = iter(batch) elem_size = len(next(it)) if not all(len(elem) == elem_size for elem in it): raise RuntimeError('each element in list of batch should be of equal size') transposed = zip(*batch) return [default_collate(samples) for samples in transposed] The "problem" happens because, in the last two lines, it'll recursively call zip(*batch) while the batch is a container_abcs.Sequence (and list is), and zip behaves like this. As you can see: batch = [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.']] list(zip(*batch)) # [('the', 'The'), ('movie', 'Film'), ('is', 'was'), ('terrible', 'great.')] I don't see a workaround in your case, except implementing a new collator and passing it to the DataLoader(..., collate_fn=mycollator). For instance, a simple ugly one could be: def mycollator(batch): assert all('sentences' in x for x in batch) assert all('label' in x for x in batch) return { 'sentences': [x['sentences'] for x in batch], 'label': torch.tensor([x['label'] for x in batch]) }
https://stackoverflow.com/questions/64883998/
how would someone install pytorch using pip on python 3.9?
when i tried the command the website used pip install torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html and it returned the error code ERROR: Could not find a version that satisfies the requirement torch==1.7.0+cpu (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2) ERROR: No matching distribution found for torch==1.7.0+cpu even when i change the code to satisfy the requirement it comes up with more errors like ModuleNotFoundError: No module named 'tools.setup_helpers'
Searching for "1.7.0" at the https://download.pytorch.org/whl/torch_stable.html page, you can see that only wheels for Python 3.6, 3.7, and 3.8 are available. So there is no official wheel for Python 3.9. Update: PyTorch currently doesn't work with Python 3.9, there are known issues being resolved: https://github.com/pytorch/pytorch/issues/47776
https://stackoverflow.com/questions/64885565/
Unsupported ONNX opset version: 11
I'm following this guide to convert darknet to onnx. However, I'm facing the following error: "C:\Users\Scott\Anaconda3\envs\pytorch_yolov4\lib\site-packages\torch\onnx\symbolic_helper.py", line 253, in _set_opset_version raise ValueError("Unsupported ONNX opset version: " + str(opset_version)) ValueError: Unsupported ONNX opset version: 11 What does this error mean and how to deal with it?
It looks like you have an old PyTorch version, probably PyTorch 1.2. The docs here https://github.com/Tianxiaomo/pytorch-YOLOv4#4-pytorch2onnx recommend at least PyTorch 1.4.
https://stackoverflow.com/questions/64886507/
How to properly reshape a 3D tensor to a 2D forward linear layer then reshape new 3D tensor's fibers corresponding to the old 3D
I have a 3D tensor of names that comes out of an LSTM that's of shape (batch size x name length x embedding size) I've been reshaping it to a 2D to put it through a linear layer, because linear layer requires (batch size, linear dimension size) by using the following y0 = output.contiguous().view(-1, output.size(-1)) this converts outputs to (batchsize, name length * number of possible characters) then I put y0 through a linear layer and then reshape it back to a 3D using y = y0.contiguous().view(output.size(0), -1, y0.size(-1)) But I'm not really sure if the fibers of y are correlated properly with the cells of output and I worry this is messing up my learning, because batch size of 1 is actually generating proper names and any larger batch size is generating nonsense. So what I mean exactly is output = (batch size * name length, embed size) y = (batch size * name length, number of possible characters) I need to make sure y[i,j,:] is the linear transformed version of output[i,j,:]
It seems like you are using an older code example. Just 'comment out' the lines of code where you reshape the tensor as there is no need for them. This link gives you a bit more explaination: https://discuss.pytorch.org/t/when-and-why-do-we-use-contiguous/47588 Try something like this instead and take the output from the LSTM directly into the linear layer: output, hidden = self.lstm(x, hidden) output = self.LinearLayer1(output)
https://stackoverflow.com/questions/64895665/
How to index with list of indices in a multidimensional array in numpy/pytorch
I have an two multi-dimensional arrays of shape (1,169,5,1+4+4). One contains data, and the other contains zeros that is to be filled. >>> preds = np.random.random_integers(0,500,(1,169,5,1+4+4)) >>> filtered_preds = np.zeros((1,169,5,1+4+4)) For context the dimensions represent the following: batch size number of grid cells number of anchor boxes predictions (Confidence score, bounding box coords, number of classes) I have a third flattened array of shape (169) that contains indicies of the best anchor box Which looks like the following: >>> best_bboxes = np.random.random_integers(0,4,(169,)) In order to prevent using loops, my first instinct was to try the following to place the confidence values: >>> filtered_preds[:,:,best_ab_idx,0:1] = preds[:,:,best_ab_idx,0:1] However, upon inspecting the array, I do not get the disired output as the shape of filtered_preds[:,:,best_ab_idx,0:1] is (1,169,169,1) I guess my question so far is, how do I get values from my prediction array with the size of the second dimension and use the value of the third dimension to get the desired value? I'm still a bit new to array indexing, so any help would be appreciated. Note: I am using PyTorch but gave my examples in NumPy as it follows the same principle. Edit: Here is a solution of what I am trying to acheive using a loop: for idx,i in enumerate(best_bboxes): filtered_preds[:,idx,best_bboxes[idx],0:1] = preds[:,idx,best_bboxes[idx],0:1] filtered_preds[:,idx,best_bboxes[idx],1:5] = preds[:,idx,best_bboxes[idx],1:5] filtered_preds[:,idx,best_bboxes[idx],5:] = preds[:,idx,best_bboxes[idx],5:]
I'm a little confused by the description of what you want to achieve, but I can simplify your given solution with the following. seq_idx = np.arange(best_bboxes.size) filtered_preds[:, seq_idx, best_bboxes, :] = preds[:, seq_idx, best_bboxes, :]
https://stackoverflow.com/questions/64903759/
Pytorch executeable works while running from Anaconda prompt but not from Cmd or .exe?
I packaged (using Pyinstaller) a small variant of the Minimalistic Yolo github repo, found Here, the packaging was done using pyinstaller to run the object detection as a server using Flask. So while attempting to run the server, it only works when running from Anaconda Prompt (Which is where i wrote the pyinstaller command) other than that, the following error occur. Error i Get while running from (exe,Cmd,PowerShell) is: Traceback (most recent call last): File "flask\app.py", line 2446, in wsgi_app File "flask\app.py", line 1951, in full_dispatch_request File "flask\app.py", line 1820, in handle_user_exception File "flask\_compat.py", line 39, in reraise File "flask\app.py", line 1949, in full_dispatch_request File "flask\app.py", line 1935, in dispatch_request File "FlaskServerV2.py", line 53, in Hello File "torch\nn\modules\module.py", line 532, in __call__ File "models.py", line 259, in forward File "torch\nn\modules\module.py", line 532, in __call__ File "models.py", line 177, in forward RuntimeError: error in LoadLibraryA 127.0.0.1 - - [19/Nov/2020 10:28:53] "GET /detect HTTP/1.1" 500 - But when running in conda, the code works fine and runs. so I am suspecting it's an issue with a PyTorch dependency. Current Code: from __future__ import division from flask import Flask, Response, jsonify app = Flask(__name__) from models import * from utils.utils import * from utils.datasets import * import os import sys import time import datetime import argparse from PIL import Image import torch from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variable import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.ticker import NullLocator import cv2 import time import json @app.route('/CheckIfRunning') def CheckIfRunning(): return '1' @app.route('/detect') def Hello(): global device global model global classes global colors global Tensor global a img=cv2.imread("temp.jpg") PILimg = np.array(Image.fromarray(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))) imgTensor = transforms.ToTensor()(PILimg) imgTensor, _ = pad_to_square(imgTensor, 0) imgTensor = resize(imgTensor, 416) #add the batch size imgTensor = imgTensor.unsqueeze(0) imgTensor = Variable(imgTensor.type(Tensor)) with torch.no_grad(): detections = model(imgTensor) detections = non_max_suppression(detections,0.8, 0.4) a.clear() Return={} ReturnCounter=0 if detections is not None: a.extend(detections) b=len(a) if len(a) : for detections in a: if detections is not None: detections = rescale_boxes(detections, 416, PILimg.shape[:2]) unique_labels = detections[:, -1].cpu().unique() n_cls_preds = len(unique_labels) for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: box_w = x2 - x1 box_h = y2 - y1 color = [int(c) for c in colors[int(cls_pred)]] img = cv2.rectangle(img, (x1, y1 + box_h), (x2, y1), color, 2) cv2.putText(img, classes[int(cls_pred)], (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) cv2.putText(img, str("%.2f" % float(conf)), (x2, y2 - box_h), cv2.FONT_HERSHEY_SIMPLEX, 0.5,color, 2) Return[ReturnCounter]= [x1.item(),y1.item(),x2.item(),y2.item(),conf.item(),cls_conf.item(),classes[int(cls_pred)]] ReturnCounter+=1 cv2.imwrite("Temp2.jpg",img) return Return device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Set up model model = Darknet("config/yolov3.cfg", img_size=416).to(device) model.load_darknet_weights("weights/yolov3.weights") model.eval() # Set in evaluation mode classes = load_classes("data/coco.names") # Extracts class labels from file colors = np.random.randint(0, 255, size=(len(classes), 3), dtype="uint8") Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor a=[] app.run(threaded=True)
Alright, turns out this is an issue with pyinstaller. if Pytorch is installed using Conda, it requires the CUDANN , and it won't work with it (ie without that environment) if you want it to work every where, Pytorch has to be installed using pip. For reference, https://github.com/pyinstaller/pyinstaller/issues/2666#issuecomment-508013383
https://stackoverflow.com/questions/64907992/
What could cause a VAE(Variational AutoEncoder) to output random noise even after training?
I have trained a VAE on CIFAR10 data-set. However, when I try to generate images from the VAE all I get is a bunch of gray noise back. The implementation of this VAE follows the implementation from the book Generative Deep Learning, but instead of TensorFlow the code uses PyTorch. The notebook containing the training as well as the generation can be found here, while the actual implementation of the VAE can be found here. I have tried: Disabling dropouts. Increasing the dimension of the latent space. None of the methods show any improvement at all. I have verified that: The input size matches the output size Back-propagation runs successfully as the loss decreases during training.
Thanks for providing the code and a link to a Colab notebook! +1! Also, your code is well-written and easy to read. Unless I missed something, I think there are two problems with your code: The data normalization The implementation of the VAE loss. About 1., your CIFAR10DataModule class normalizes the RGB channels of the CIFAR10 images using mean = 0.5 and std = 0.5. Since the pixel values are initially in [0,1] range, the normalized images have pixel values in the [-1,1] range. However, your Decoder class applies a nn.Sigmoid() activation to the reconstructed images. Therefore, your reconstructed images have pixel values in the [0,1] range. I suggest to remove this mean-std normalization so that both the "true" images and the reconstructed images have their pixel values in the [0,1] range. About 2.: since you're dealing with RGB images the MSE loss makes sense. The idea behind the MSE loss is the "Gaussian decoder". This decoder assumes the pixel values of a "true image" is generated by independent Gaussian distributions whose mean is the pixel values of the reconstructed image (i.e. the output of the decoder) and with a given variance. Your implementation of the reconstruction loss (namely r_loss = F.mse_loss(predictions, targets)) is equivalent to a fixed variance. Using ideas from this paper, we can do better and obtain an analytic expression for the "optimal value" of this variance parameter. Finally, the reconstruction loss should be summed over all pixels (reduction = 'sum'). To understand why, have a look at analytic expression of the reconstruction loss (see, for instance, this blog post which considers the BCE loss). Here is what the refactored LitVAE class looks like: class LitVAE(pl.LightningModule): def __init__(self, learning_rate: float = 0.0005, **kwargs) -> None: """ Parameters ---------- - `learning_rate: float`: learning rate for the optimizer - `**kwargs`: arguments to pass to the variational autoencoder constructor """ super(LitVAE, self).__init__() self.learning_rate = learning_rate self.vae = VariationalAutoEncoder(**kwargs) def forward(self, x) -> _tensor_size_3_t: return self.vae(x) def training_step(self, batch, batch_idx): r_loss, kl_loss, sigma_opt = self.shared_step(batch) loss = r_loss + kl_loss self.log("train_loss_step", loss) return {"loss": loss, 'log':{"r_loss": r_loss / len(batch[0]), "kl_loss": kl_loss / len(batch[0]), 'sigma_opt': sigma_opt}} def training_epoch_end(self, outputs) -> None: # add computation graph if(self.current_epoch == 0): sample_input = torch.randn((1, 3, 32, 32)) sample_model = LitVAE(**MODEL_PARAMS) self.logger.experiment.add_graph(sample_model, sample_input) epoch_loss = self.average_metric(outputs, "loss") self.logger.experiment.add_scalar("train_loss_epoch", epoch_loss, self.current_epoch) def validation_step(self, batch, batch_idx): r_loss, kl_loss, _ = self.shared_step(batch) loss = r_loss + kl_loss self.log("valid_loss_step", loss) return {"loss": loss} def validation_epoch_end(self, outputs) -> None: epoch_loss = self.average_metric(outputs, "loss") self.logger.experiment.add_scalar("valid_loss_epoch", epoch_loss, self.current_epoch) def test_step(self, batch, batch_idx): r_loss, kl_loss, _ = self.shared_step(batch) loss = r_loss + kl_loss self.log("test_loss_step", loss) return {"loss": loss} def test_epoch_end(self, outputs) -> None: epoch_loss = self.average_metric(outputs, "loss") self.logger.experiment.add_scalar("test_loss_epoch", epoch_loss, self.current_epoch) def configure_optimizers(self): return optim.Adam(self.parameters(), lr=self.learning_rate) def shared_step(self, batch) -> torch.TensorType: # images are both samples and targets thus original # labels from the dataset are not required true_images, _ = batch # perform a forward pass through the VAE # mean and log_variance are used to calculate the KL Divergence loss # decoder_output represents the generated images mean, log_variance, generated_images = self(true_images) r_loss, kl_loss, sigma_opt = self.calculate_loss(mean, log_variance, generated_images, true_images) return r_loss, kl_loss, sigma_opt def calculate_loss(self, mean, log_variance, predictions, targets): mse = F.mse_loss(predictions, targets, reduction='mean') log_sigma_opt = 0.5 * mse.log() r_loss = 0.5 * torch.pow((targets - predictions) / log_sigma_opt.exp(), 2) + log_sigma_opt r_loss = r_loss.sum() kl_loss = self._compute_kl_loss(mean, log_variance) return r_loss, kl_loss, log_sigma_opt.exp() def _compute_kl_loss(self, mean, log_variance): return -0.5 * torch.sum(1 + log_variance - mean.pow(2) - log_variance.exp()) def average_metric(self, metrics, metric_name): avg_metric = torch.stack([x[metric_name] for x in metrics]).mean() return avg_metric After 10 epochs, that's what the reconstructed images look like:
https://stackoverflow.com/questions/64909658/
Can we reset .requires_grad of all defined tensors in a code to zero at once
I am using PyTorch 1.6.0 to learn a tensor (lets say x) with autograd. After x is learnt, how can I reset .requires_grad of every tensor that was a node in the autograd comp. graph to zero? I know about torch.detach() and about setting .requires_grad to False manually. I am searching for an one-shot instruction. Ps: I want to do that because I still want to use these tensors after the part of my code that learns x is executed. Plus, some are to be converted to numpy.
There is no "one shot instruction" to switch .requires_grad for all tensors in graph. Usually parameters are kept in torch.nn.Module instances but in case they are elsewhere, you can always add them to some list and iterate over it, I'd do something like this: import torch class Leafs: def __init__(self): self.leafs = [] def add(self, tensor): self.leafs.append(tensor) return tensor def clear(self): for leaf in self.leafs: leaf.requires_grad_(False) keeper = Leafs() x = keeper.add(torch.tensor([1.2], requires_grad=True)) y = keeper.add(torch.tensor([1.3], requires_grad=True)) print(x.requires_grad, y.requires_grad) keeper.clear() print(x.requires_grad, y.requires_grad) Usually there is no need for that, also if you don't want gradient for some part of computation you can always use with torch.no_grad() context manager.
https://stackoverflow.com/questions/64913609/
Loading n-dimensional tensor for pytorch from text file
I have a 3-dimensional tensor that I create outside of my python code and am able to encode in any human-readable format. I need to load the values of this tensor as a frozen layer to my pytorch NN. I've tried to encode the tensor as a text file in the form [[[a,b],[c,d]], [[e,f], [g,h]], [[k,l],[m,n]]] which seemed to be the most logical way for that. Then I tried to read its value via tensor = torch.from_numpy(np.loadtxt("./arrays/tensor.txt")) but got the exception in npyio.py ValueError: could not convert string to float: '[[[-2.888356,' Apparently, that's not how it works and the values are to be written as plain numbers separated by spaces and \n, but then I don't see how to easily read the data of dimension >= 2 with numpy. What could be other simple methods to write down and read the tensor value into a pytorch tensor?
Did you try using Python's built-in eval? In case you saved your tensor as a list in text file you may try something as follows: with open("./arrays/tensor.txt","r") as f: loaded_list = eval(f.read()) loaded_tensor = torch.tensor(loaded_list) eval will take care of converting your string to a list and then just cast the result to a Tensor by using torch.tensor(). The loaded tensor will then be in loaded_tensor as required.
https://stackoverflow.com/questions/64913854/
removing sample from a Pytorch dataset object
I'm loading images to pytorch using: train_data = torchvision.datasets.ImageFolder(train_dir, transform=transform) Which has some samples I want to omit. Can i remove certain images from the loader? (by index? by name?) Thx
You can modify the imgs attribute of an ImageFolder as follows: train_data.imgs.remove((PATH, INDEX)) where you should replace PATH with the path to the image you wish to remove and INDEX should be replaced with the respective class index (starting from 0 to the number of classes you have). In case you are not sure about the INDEX you can print train_data.imgs to obtain the list of all image paths with their classes in tuples.
https://stackoverflow.com/questions/64914820/
IndexError: index 39092 is out of bounds for axis 0 with size 39092; I'm trying to train a multi label classification
I think the problem is caused by the way I load the data from the csv file, but I don't know how to fix it Here is a small portion of my train csv file: train_datasets (I use 15 labels from column 1 to the end) The error looks like this: IndexError IndexError Code==> import csv import os import pandas as pd import numpy as np from PIL import Image import torch class FashionData(torch.utils.data.Dataset): def __init__(self, csv_file, mode='train', transform=None): self.mode=mode #label(img1) = [0, 0, 0, 1], label(img3) = [1, 0, 1, 0], ...), self.transform = transform self.data_info = pd.read_csv(csv_file, header=None) #print(self.data_info) # First column contains the image paths self.image_arr = np.asarray(self.data_info.iloc[1:, 0]) if mode !='test': self.label_arr = np.asarray(self.data_info.iloc[1:, 2:]) # columns 1 to N self.label_arr=self.label_arr.astype('float32') # Calculate len self.data_len = len(self.data_info.index) def __getitem__(self, index): # Get image name from the pandas df single_image_name = self.image_arr[index] # Open image img_as_img = Image.open(single_image_name) if self.transform is not None: img_as_img = self.transform(img_as_img) if self.mode=='test': return img_as_img # Get label(class) of the image based on the cropped pandas column single_image_label = self.label_arr[index] #single_image_label = torch.from_numpy(self.label_arr[index]).float() #img = torch.from_numpy(img).float().to(device) #label = torch.tensor(int(self.labels[index])) return (img_as_img, single_image_label) def __len__(self): return self.data_len transforms_train = transforms.Compose([transforms.Resize((224,224)),transforms.RandomHorizontalFlip(),transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]) transforms_test = transforms.Compose([transforms.Resize((224,224)),transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])]) dataset_train = FashionData('./deep_fashion/train.csv', mode='train', transform=transforms_train) dataset_val = FashionData('./deep_fashion/val.csv', mode='val', transform=transforms_test) dataset_test = FashionData('./deep_fashion/test.csv', mode='test', transform=transforms_test) from torch.utils.data import DataLoader train_loader = DataLoader(dataset_train, batch_size=128, shuffle=True) val_loader = DataLoader(dataset_val, batch_size=128, shuffle=False) test_loader = DataLoader(dataset_test, batch_size=128, shuffle=False) model=models.resnet50(pretrained=True) for params in model.parameters(): params.requires_grad=False model.fc=nn.Sequential( nn.Linear(2048,15), nn.Sigmoid() ) device=torch.device('cuda' if torch.cuda.is_available() else 'cpu') model=model.to(device) print(model) criterion=nn.BCELoss() #criterion=nn.BCEWithLogitsLoss() optimizer=optim.Adam(model.parameters(),lr=0.001) criterion=criterion.to(device) def train(train_loader,model,criterion,optimizer): model.train() loss_list=[] total_count=0 acc_count=0 for x,y in train_loader: x=x.to(device) y=y.to(device) optimizer.zero_grad() output=model(x) loss=criterion(output,y) loss.backward() optimizer.step() #_,predicted=torch.max(output,1) predicted=(output>0.5).float() total_count+=y.size(0) acc_count+=(predicted==y).sum().item() loss_list.append(loss.item()) acc=acc_count/total_count loss=sum(loss_list)/len(loss_list) return acc, loss def val(valid_loader,model,criterion): model.eval() loss_list=[] total_count=0 acc_count=0 with torch.no_grad(): for x,y in valid_loader: x=x.to(device) y=y.to(device) output=model(x) loss=criterion(output,y) #_,predicted=torch.max(output,1) predicted=(output>0.5).float() total_count+=y.size(0) acc_count+=(predicted==y).sum().item() loss_list.append(loss.item()) acc=acc_count/total_count loss=sum(loss_list)/len(loss_list) return acc, loss train_acc_list = [] train_loss_list = [] val_acc_list = [] val_loss_list = [] for epoch in range(10): train_acc, train_loss = train(train_loader, model, criterion, optimizer) val_acc, val_loss=val(val_loader, model, criterion) train_acc_list.append(train_acc) train_loss_list.append(train_loss) val_acc_list.append(val_acc) val_loss_list.append(val_loss) print('epoch',epoch) print('Train Acc: {:.6f} Train Loss: {:.6f}'.format(train_acc, train_loss)) print(' Val Acc: {:.6f} Val Loss: {:.6f}'.format(val_acc, val_loss)) Did I do wrong in the loading data part? Or it's the other problem? 11111111111111111 11111111111111111 11111111111111111
Your __len__ is just 1 greater than your actual data, since you loaded the df with header=None. Simply change the last line of __init__ to self.data_len = len(self.image_arr). This should fix your problem with minimal change. (Alternatively, set header=True while loading your df, in which case, you'll have to change iloc[1:, ...] to iloc[:, ...], as you no longer need to skip the first row.)
https://stackoverflow.com/questions/64915097/
Why does using a numpy array instead of a torch tensor use more memory in this example?
Using this method gives me a train_data size of about 700Mb and test of about 200Mb data_tensor = torch.Tensor([np.repeat(image[...,np.newaxis],3,-1)/255.0 for image in data]) np.save(f"/home/vedank/Desktop/code/facial_sentiment/{dataset_type}_data.npy",np.array(data_tensor)) However, using the one below increases the size of train_data to 1.6 Gb and test to ~400Mb data_tensor = np.array([np.repeat(image[...,np.newaxis],3,-1)/255.0 for image in data]) np.save(f"/home/vedank/Desktop/code/facial_sentiment/{dataset_type}_data.npy",data_tensor)
It seems that the default datatype for numpy (float) arrays is 64 bits. import numpy as np print(np.array([2.3]).dtype) # we get float 64 on the other hand, pytorch default float datatype is float32 That means the size of the array in numpy should be double the one in PyTorch.
https://stackoverflow.com/questions/64925428/
Data format and stride
First of all, What is channel last format? Is it NHWC? For the following code, how stride is calculated? import torch N, C, H, W = 10, 3, 32, 32 x = torch.empty(N, C, H, W) print(x.stride()) # Ouputs: (3072, 1024, 32, 1) Output is (3072, 1024, 32, 1) When converted to channel last format, how stride is calculated here? x = x.contiguous(memory_format=torch.channels_last) print(x.shape) # Outputs: (10, 3, 32, 32) as dimensions order preserved print(x.stride()) # Outputs: (3072, 1, 96, 3) Output is torch.Size([10, 3, 32, 32]) (3072, 1, 96, 3)
TLDR: stride is the number of elements in the storage that need to be skipped over to obtain the next element along each dimension. I believe you're referring to this tutorial. Since every tensor references an underlying storage, you can have multiple tensors referencing the same storage with different strides and dimensions. For e.g., I might have a 3x3 tensor: [1 2 4 0 4 5 7 8 0] but all that data is actually stored in a 1D contiguous storage, i.e. [1 2 4 0 4 5 7 8 0]. In order for the tensor to know how it should presented (i.e. 3x3), we need a stride property which is "the number of elements in the storage that need to be skipped over to obtain the next element along each dimension". The stride for this would be (3,1), meaning I need to step over 3 elements in storage to get my next element in the first dimension and step over 1 element to get the next element in the second dimension. E.g. starts with 1. To get the next value in the row dimension, add 3 (as indicated by stride). So the third element after 1 in storage is 0. another e.g., let's start with the 2. To get the next value in the second dimension (col), add 1 in storage, which gives me 4. That's the basics of how stride is calculated. Back to your original question, N, C, H, W = 10, 3, 32, 32 To get the stride, say of N, and let's say N is the n'th image, then I need to skip over (32 x 32 x 3 = 3072) elements in order to get to the start of the next image. Hence why stride() = (3072, 1024, 32, 1) on the first dimension. The same logic applies to the other strides. From the tutorial linked above, channels last is simply a different way to store the underlying storage object in memory (see the pic in link). The stride changes due to how the contiguous memory is allocated, but the way we interpret and understand stride remains the same.
https://stackoverflow.com/questions/64926631/
Distinguishing images from noise
Neural networks have been successfully used in supervised learning to classify images. I'm currently looking at a different problem: distinguishing images that show something, contain some manifest order, versus images that are just white noise. I'd like to get some numeric estimate of just how ordered an image is. Clearly there are several ways of doing this, e.g. PNG compressing the image and looking at how much it shrank. (Pure noise is not compressible.) But I am currently interested in trying to do it with neural networks; it seems to me that it should be possible to do this with unsupervised learning, using some sort of autoencoder. Is this something that has been done? Ideally with PyTorch but I would be happy to look at a solution using any language and framework.
This question is a bit too broad for stackoverflow, it seems more like an research question. The topic would also be more at home in https://stats.stackexchange.com/ , where machine learning people lurk. Interesting question though. In my experience going with an analytic solution is always better than trying to learn a solution if possible, I see machine learning as something to fall back on when things get too complex. Detecting images of pure noise is relatively simple, one would expect the Shannon entropy of the image to explode. You could also e.g. match the K-L divergence of the image histogram to a Gaussian or Poisson distribution or whatever the noise distribution you'd expect. If the images are really just noise then I'd expect any of these solutions to classify them very easily and fast with very little tweaking. If you want to learn the answer I'd recommend crafting few information theoretic or simple edge based etc. features and classifying them e.g. with Naive Bayes or an SVM. If you want to use neural networks then sure, I'm sure you could teach a model to get the concept of information content. Deep image prior is a popular recent article which uses the idea of an autoencoder having lower 'impedance' for structured images. They use it to denoise, impute and do superresolution but I'm sure you could use make an unsupervised or semi-supervised NN based nonsense-detector by following the same train of thought. I'd expect it to be orders of magnitude slower than an simpler hand-crafted information theoretic approach with similiar accuracy or worse.
https://stackoverflow.com/questions/64928874/
pytorch running: RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu
When I running the python code, there is a runtimeError in line 44:RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu! 42 feats = self.node_features[self.train_mask] 43 labels = self.node_labels[train_mask] 44 A = torch.mm(feats.t(), feats) + 1e-05 * torch.eye(feats.size(1)) 45 labels_one_hot = torch.zeros((feats.size(0), self.n_classes)) Can anyone who knows the reason and help me fix it! Thanks!
It seems that the tensor torch.eye(...) is on CPU. you need to pass it as - 44 A = torch.mm(feats.t(), feats) + 1e-05 * torch.eye(feats.size(1)).to(device='cuda') or 44 A = torch.mm(feats.t(), feats) + 1e-05 * torch.eye(feats.size(1)).cuda()
https://stackoverflow.com/questions/64929665/
CNN in Pytorch: labels for a custom dataset
I have a very basic question that would be really helpful for getting me started on a deep learning project I'm running. I'm planning to apply a 3D convolutional network using pytorch to a large number of medical images to predict a single numerical value. My question is, for the labelled instances (ranging from 0-40) that I'll be using to train my CNN model - how exactly are the labels of the training set fed to the model? Is it usually contained within a csv file that you load in or otherwise is the label embedded in the name of the image or alternatively a folder that contain images of the same class (e.g. folder for "0", folder for "1")? Any help you could provide would be really appreciated!
This Functions are very useful if your classes are arranged in folder structure Provided your folder structure to be like this train class1 class2 ... class_n test class1 class2 ... class_n train_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms) test_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms) print(train_data.classes) # will print all your classes Second option what you have is: torch.utils.data.Dataset is an abstract class representing a dataset. Your custom dataset should inherit Dataset and override the following methods: __len__() so that len(dataset) returns the size of the dataset. __getitem__() to support the indexing such that dataset[i] can be used to get ith sample Eg of writing custom Dataset class CustomDatasetFromCsvLocation(Dataset): def __init__(self, csv_path): """ Custom dataset example for reading image locations and labels from csv but reading images from files Args: csv_path (string): path to csv file """ # Transforms self.to_tensor = transforms.ToTensor() # Read the csv file self.data_info = pd.read_csv(csv_path, header=None) # First column contains the image paths self.image_arr = np.asarray(self.data_info.iloc[:, 0]) # Second column is the labels self.label_arr = np.asarray(self.data_info.iloc[:, 1]) # Third column is for an operation indicator self.operation_arr = np.asarray(self.data_info.iloc[:, 2]) # Calculate len self.data_len = len(self.data_info.index) def __getitem__(self, index): # Get image name from the pandas df single_image_name = self.image_arr[index] # Open image img_as_img = Image.open(single_image_name) # Check if there is an operation some_operation = self.operation_arr[index] # If there is an operation if some_operation: # Do some operation on image # ... # ... pass # Transform image to tensor img_as_tensor = self.to_tensor(img_as_img) # Get label(class) of the image based on the cropped pandas column single_image_label = self.label_arr[index] return (img_as_tensor, single_image_label) def __len__(self): return self.data_len
https://stackoverflow.com/questions/64932738/
What is the .optimizer package in Pytorch?
I am trying to write my own optimizer for pytorch and am looking at the source code https://pytorch.org/docs/stable/_modules/torch/optim/sgd.html#SGD to get started. When I try to run the code for the SGD, I get an error on the line from .optimizer import Optimizer, required. I've searched everywhere but I'm not sure where to obtain the .optimizer package. Any help here is greatly appreciated.
Here import .optimizer means import optimizer.py from the same directory as the current .py file, so this file
https://stackoverflow.com/questions/64934830/
How to use Pytorch to create a custom EfficientNet with the last layer written correctly
I have a classification problem to predict 8 classes for example, I am using EfficientNetB3 in pytorch from here. However, I got confused on whether my custom class is correctly written. I think I want to strip the last layer of the pre-trained model to suit the 8 outputs right? Did I do it correctly? Because when I print y_preds = model(images) in my DataLoader, it seems to give me 1536 predictions. Is this an expected behavior? !pip install geffnet import geffnet class EfficientNet(nn.Module): def __init__(self, config): super().__init__() self.config = config self.model = geffnet.create_model(config.effnet, pretrained=True) n_features = self.model.classifier.in_features # does the name fc matter? self.fc = nn.Linear(n_features, config.num_classes) self.model.classifier = nn.Identity() def extract(self, x): x = self.model(x) return x def forward(self, x): x = self.extract(x).squeeze(-1).squeeze(-1) return x model = EfficientNet(config=config) if torch.cuda.is_available(): model.cuda() Sample code for printing y_pred: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') for step, (images, labels) in enumerate(sample_loader): images = images.to(device) labels = labels.to(device) batch_size = images.shape[0] y_preds = model(images) print('The predictions of the 4 images is as follows\n', y_preds) break
You're not even using self.fc in forward pass. Either just introduce it as: def forward(self, x): .... x = extract(x)... x = fc(x) return x Or you can simply replace the layer named classifier (this way you don't need Identity layer): self.model.classifier = nn.Linear(n_features, config.num_classes) Also, here config.num_classes should be 8.
https://stackoverflow.com/questions/64939460/
Pytorch math calculation ( only one element tensors can be converted to Python scalars)
What does it mean by only one element tensors can be converted to Python scalars in this case and how do I suppose to debug it? x1 = (max-min)*torch.rand(1, 21) + min x2 = (max-min)*torch.rand(1, 21) + min zipped_list = zip(x1, x2) y = [math.sin(2*x1+2) * math.cos(0.5*x2)+0.5 for (x1, x2) in zipped_list] output ValueError: only one element tensors can be converted to Python scalars
problem is because of using math.cos and math.sin. math.cos isn't vectorized, but np.cos is. use np.sin and np.cos or torch.sinand torch.cos.
https://stackoverflow.com/questions/64946025/
pytorch narrow is not applicable
How to do slicing in pytorch? I tried narrow and numpy slicing? Both are not working for outputing train data and test data. Is there any suggestion for solving it? x1 = (max-min)*torch.rand(1, 21, dtype=torch.float) + min x2 = (max-min)*torch.rand(1, 21, dtype=torch.float) + min zipped_list = zip(x1, x2) y = torch.empty(1, 21) y = [torch.sin(2*x1+2) * torch.cos(0.5*x2)+0.5 for (x1, x2) in zipped_list] print(y) train_data = y.narrow(0,1) test_data = y[11:21] print(train_data) Output is AttributeError: 'list' object has no attribute 'narrow' However when I do normal slicing, the test data will not be slice properly train_data = y[0:11] test_data = y[11:21] Train Data is: [tensor([-0.0515, 0.4574, 0.5141, 0.4865, 0.9266, 1.0984, 0.5364, 0.7042, 0.1741, -0.4839, 0.4332, 0.2962, 0.2311, 0.6169, 0.4321, 0.4088, 0.2443, 0.1982, 0.7978, 0.6651, -0.4453])] Test Data is: []
In your code, y is a PyTorch tensor: y = torch.empty(1, 21) Then it is replaced with a list of PyTorch tensors (actually, just one): y = [torch.sin(2*x1+2) * torch.cos(0.5*x2)+0.5 for (x1, x2) in zipped_list] So you need to get the first element of y that is a tensor and then slice it: print(y[0][:5])
https://stackoverflow.com/questions/64947790/
How to solve the ValueError importing torch in python
After installing pytorch package, I have tried to import pytorch with import torch but got the error Traceback (most recent call last): File "<console>", line 1, in <module> File "c:\users\user\appdata\local\programs\python\python38\lib\site-packages\torch\__init__.py", line 190, in <module> from torch._C import * ValueError: module functions cannot set METH_CLASS or METH_STATIC from searching, I have read that this could be about numpy. So I have tried uninstalling and installing with those pip uninstall numpy pip install numpy -I pip install numpy -U It didn't work. I would be happy to hear from you if you have any idea why such an error occurs and how to correct it? in case needed: Python version 3.8.6 , torch version 1.7.0 , numpy version 1.19.4
The latest version of numpy for the moment is 1.19.4 I have uninstalled numpy and installed 1.19.3 version. After a complete restart of the system. The error does not show anymore. Thanks.
https://stackoverflow.com/questions/64948852/
How can I use an LSTM to classify a series of vectors into two categories in Pytorch
I have a series of vectors representing a signal over time. I'd like to classify parts of the signal into two categories: 1 or 0. The reason for using LSTM is that I believe the network will need knowledge of the entire signal to classify. My problem is developing the PyTorch model. Below is the class I've come up with. class LSTMClassifier(nn.Module): def __init__(self, input_dim, hidden_dim, label_size, batch_size): self.lstm = nn.LSTM(input_dim, hidden_dim) self.hidden2label = nn.Linear(hidden_dim, label_size) self.hidden = self.init_hidden() def init_hidden(self): return (torch.zeros(1, self.batch_size, self.hidden_dim), torch.zeros(1, self.batch_size, self.hidden_dim)) def forward(self, x): lstm_out, self.hidden = self.lstm(x, self.hidden) y = self.hidden2label(lstm_out[-1]) log_probs = F.log_softmax(y) return log_probs However this model is giving a bunch of shape errors, and I'm having trouble understanding everything going on. I looked at this SO question first.
You should follow PyTorch documentation, especially inputs and outputs part, always. This is how the classifier should look like: import torch import torch.nn as nn class LSTMClassifier(nn.Module): def __init__(self, input_dim, hidden_dim, label_size): super().__init__() self.lstm = nn.LSTM(input_dim, hidden_dim, batch_first=True) self.hidden2label = nn.Linear(hidden_dim, label_size) def forward(self, x): _, (h_n, _) = self.lstm(x) return self.hidden2label(h_n.reshape(x.shape[0], -1)) clf = LSTMClassifier(100, 200, 1) inputs = torch.randn(64, 10, 100) clf(inputs) Points to consider: always use super().__init__() as it registers modules in your neural networks, allows for hooks etc. Use batch_first=True so you can pass inputs of shape (batch, timesteps, n_features) No need to init_hidden with zeros, it is the default value if left uninitialized No need to pass self.hidden each time to LSTM. Moreover, you should not do that. It means that elements from each batch of data are somehow next steps, while batch elements should be disjoint and you probably do not need that. _, (h_n, _) returns last hidden cell from last timestep, exactly of shape: (num_layers * num_directions, batch, hidden_size). In our case num_layers and num_directions is 1 so we get (1, batch, hidden_size) tensor as output Reshape to (batch, hidden_size) so it can be passed through linear layer Return logits without activation. Only one if it is a binary case. Use torch.nn.BCEWithLogitsLoss as loss for binary case and torch.nn.CrossEntropyLoss for multiclass case. Also sigmoid is proper activation for binary case, while softmax or log_softmax is appropriate for multiclass. For binary only one output is needed. Any value below 0 (if returning unnormalized probabilities as in this case) is considered negative, anything above positive.
https://stackoverflow.com/questions/64953102/
Python Error RuntimeError: expected scalar type Long but found Double
Firstly, I am fairly new to python/ML in general. I am attempting to utilize the model depicted at stackabuse over my own data set. Everything flows smoothly until I get ready to run the epochs. In debugging I see that it is failing on CrossEntropyLoss function and I get the error expected long found double. The data set it appears to fail on is the my tdiff column that I calculated but I can't seem to figure out how to convert it to a long. Is there something that I'm missing in trying to figure this out? To be clear, this is what I THINK it is based on my extremely limited knowledge on the function: import pandas as pd import sqlite3 as sq import numpy as np import torch import torch.nn as nn import matplotlib.pyplot as plt import seaborn as sns con = sq.connect("filepath") df = pd.read_sql_query("SELECT b.actcod," + "a.trnqty, " + "b.dlytrn_id, " + "a.usr_id, " + " b.oprcod, " + "b.usr_id as usrid," + " b.tostol as frstol," + " a.tostol, " + " b.trndte as bdte," + " a.trndte as adte," + " '' as tdiff" + " FROM" + " (SELECT row_number() over(PARTITION by usr_id order by trndte) AS rown," + " trndte," + " dlytrn_id," + " trnqty, " + " oprcod," + " actcod," + " frstol," + " tostol," + " usr_id" + " FROM Master_File" + " WHERE actcod = 'PALPCK') a " + " JOIN "+ " (SELECT row_number() over(PARTITION by usr_id order by trndte) AS rown," + " trndte,dlytrn_id, trnqty, oprcod,actcod, frstol, tostol, usr_id" + " FROM Master_File" + " WHERE actcod = 'PALPCK' ) b" + " ON b.rown = (a.rown -1)" + " and b.usr_id = a.usr_id" #+ #" LIMIT 10" ,con) # Create record Count record_count = df['dlytrn_id'].count() test_records = int(record_count * .2) print(record_count) print(test_records) #Calculate time delta between scans df['tdiff'] = pd.TimedeltaIndex.total_seconds(pd.to_datetime(df['adte'].values) - pd.to_datetime(df['bdte'].values)) # Establish column types cat_column = ['usrid','actcod','tostol','frstol'] num_column = ['trnqty'] dte_column = ['bdte','adte'] op_column = ['tdiff'] #convert column datatypes for category in cat_column: df[category] = df[category].astype('category') for category in num_column: df[category] = df[category].astype('float64') for category in dte_column: df[category] = df[category].astype('datetime64') #create categorical tensor usr = df['usrid'].cat.codes.values act = df['actcod'].cat.codes.values to = df['tostol'].cat.codes.values fr = df['frstol'].cat.codes.values cat_data = np.stack([usr,act,to,fr], 1) cat_data = torch.tensor(cat_data, dtype=torch.int64) #Create Numerical Tensor num_data = np.stack([df[col].values for col in num_column], 1) num_data = torch.tensor(num_data, dtype=torch.float) #convert output array op_data = torch.tensor(df[op_column].values).flatten() print(df.shape) print(cat_data.shape) print(num_data.shape) print(op_data.shape) #convert categorical data into an N-Dimensional vector, #this will allow better ML analysis on relationships cat_col_sizes = [len(df[column].cat.categories) for column in cat_column] cat_embedding_sizes = [(col_size, min(50, (col_size+1)//2)) for col_size in cat_col_sizes] print(cat_embedding_sizes) #create test batches cat_train_data = cat_data[:record_count-test_records] cat_test_data = cat_data[record_count-test_records:record_count] num_train_data = num_data[:record_count-test_records] num_test_data = num_data[record_count-test_records:record_count] train_op = op_data[:record_count-test_records] test_op = op_data[record_count-test_records:record_count] print(len(cat_train_data)) print(len(num_train_data)) print(len(train_op)) print(len(cat_test_data)) print(len(num_test_data)) print(len(test_op)) class Model(nn.Module): def __init__(self, embedding_size, num_numerical_cols, output_size, layers, p=0.4): super().__init__() self.all_embeddings = nn.ModuleList([nn.Embedding(ni, nf) for ni, nf in embedding_size]) self.embedding_dropout = nn.Dropout(p) self.batch_norm_num = nn.BatchNorm1d(num_numerical_cols) all_layers = [] num_categorical_cols = sum((nf for ni, nf in embedding_size)) input_size = num_categorical_cols + num_numerical_cols for i in layers: all_layers.append(nn.Linear(input_size, i)) all_layers.append(nn.ReLU(inplace=True)) all_layers.append(nn.BatchNorm1d(i)) all_layers.append(nn.Dropout(p)) input_size = i all_layers.append(nn.Linear(layers[-1], output_size)) self.layers = nn.Sequential(*all_layers) def forward(self, x_categorical, x_numerical): embeddings = [] for i,e in enumerate(self.all_embeddings): embeddings.append(e(x_categorical[:,i])) x = torch.cat(embeddings, 1) x = self.embedding_dropout(x) x_numerical = self.batch_norm_num(x_numerical) x = torch.cat([x, x_numerical], 1) x = self.layers(x) return x model = Model(cat_embedding_sizes, num_data.shape[1], 1, [200,100,50], p=0.4) print(model) loss_function = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) epochs = 300 aggregated_losses = [] for i in range(epochs): i += 1 y_pred = model(cat_train_data, num_train_data) single_loss = loss_function(y_pred, train_op) aggregated_losses.append(single_loss) if i%25 == 1: print(f'epoch: {i:3} loss: {single_loss.item():10.8f}') optimizer.zero_grad() single_loss.backward() optimizer.step() print(f'epoch: {i:3} loss: {single_loss.item():10.10f}') print(train_op) print(type(train_op)) print(op_column) print(type(op_column)) print(op_data) print(type(op_data)) con.close() output: 51779 10355 (51779, 11) torch.Size([51779, 4]) torch.Size([51779, 1]) torch.Size([51779]) [(185, 50), (1, 1), (302, 50), (303, 50)] 41424 41424 41424 10355 10355 10355 Model( (all_embeddings): ModuleList( (0): Embedding(185, 50) (1): Embedding(1, 1) (2): Embedding(302, 50) (3): Embedding(303, 50) ) (embedding_dropout): Dropout(p=0.4, inplace=False) (batch_norm_num): BatchNorm1d(1, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (layers): Sequential( (0): Linear(in_features=152, out_features=200, bias=True) (1): ReLU(inplace=True) (2): BatchNorm1d(200, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (3): Dropout(p=0.4, inplace=False) (4): Linear(in_features=200, out_features=100, bias=True) (5): ReLU(inplace=True) (6): BatchNorm1d(100, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (7): Dropout(p=0.4, inplace=False) (8): Linear(in_features=100, out_features=50, bias=True) (9): ReLU(inplace=True) (10): BatchNorm1d(50, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (11): Dropout(p=0.4, inplace=False) (12): Linear(in_features=50, out_features=1, bias=True) ) ) Traceback (most recent call last): File line 193, in <module> single_loss = loss_function(y_pred, train_op) File anaconda3\lib\site-packages\torch\nn\modules\module.py", line 727, in _call_impl result = self.forward(*input, **kwargs) File anaconda3\lib\site-packages\torch\nn\modules\loss.py", line 961, in forward return F.cross_entropy(input, target, weight=self.weight, File anaconda3\lib\site-packages\torch\nn\functional.py", line 2468, in cross_entropy return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction) File anaconda3\lib\site-packages\torch\nn\functional.py", line 2264, in nll_loss ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index) RuntimeError: expected scalar type Long but found Double
nn.CrossEntropyLoss() expects target tensors of type Long, but what you're passing is of type Double. Try to change this line from: single_loss = loss_function(y_pred, train_op) to: single_loss = loss_function(y_pred, train_op.long())
https://stackoverflow.com/questions/64957007/
Error when trying to train FasterRCNN with custom backbone on GRAYSCALE images
I am following instructions from https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html#putting-everything-together tutorial in order to create object detector for 1 class on GRAYSCALE images. Here is my code (note that I am using DenseNet as a BACKBONE - pretrained model by me on my own dataset): device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') num_classes = 2 # 1 class + background model = torch.load(os.path.join(patch_classifier_model_dir, "densenet121.pt")) backbone = model.features backbone.out_channels = 1024 anchor_generator = AnchorGenerator(sizes=((32, 64, 128, 256, 512),), aspect_ratios=((0.5, 1.0, 2.0),)) roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=[0], output_size=7, sampling_ratio=2) # put the pieces together inside a FasterRCNN model model = FasterRCNN(backbone, num_classes=2, rpn_anchor_generator=anchor_generator, box_roi_pool=roi_pooler) # move model to the right device model.to(device) optimizer = torch.optim.SGD(model.parameters(), lr=0.005, momentum=0.9, weight_decay=0.0005) # and a learning rate scheduler which decreases the learning rate by # 10x every 3 epochs lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1) This is the error that I am running into: RuntimeError: Given groups=1, weight of size [64, 1, 7, 7], expected input[2, 3, 1344, 800] to have 1 channels, but got 3 channels instead Based on FasterRCNN architecture, I assume problem is in the transform component because it tries to normalize images that are initially grayscale, and not RGB: FasterRCNN( (transform): GeneralizedRCNNTransform( Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) Resize(min_size=(800,), max_size=1333, mode='bilinear') ) (backbone): Sequential( (conv0): Conv2d(1, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (norm0): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu0): ReLU(inplace=True) (pool0): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (denseblock1): _DenseBlock( (denselayer1): _DenseLayer( (norm1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu1): ReLU(inplace=True) (conv1): Conv2d(64, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (norm2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu2): ReLU(inplace=True) (conv2): Conv2d(128, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) ) ............... (norm5): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) (rpn): RegionProposalNetwork( (anchor_generator): AnchorGenerator() (head): RPNHead( (conv): Conv2d(1024, 1024, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)) (cls_logits): Conv2d(1024, 15, kernel_size=(1, 1), stride=(1, 1)) (bbox_pred): Conv2d(1024, 60, kernel_size=(1, 1), stride=(1, 1)) ) ) (roi_heads): RoIHeads( (box_roi_pool): MultiScaleRoIAlign() (box_head): TwoMLPHead( (fc6): Linear(in_features=50176, out_features=1024, bias=True) (fc7): Linear(in_features=1024, out_features=1024, bias=True) ) (box_predictor): FastRCNNPredictor( (cls_score): Linear(in_features=1024, out_features=2, bias=True) (bbox_pred): Linear(in_features=1024, out_features=8, bias=True) ) ) ) Am I correct? If so, how do I resolve this issue? Is there a STANDARD PRACTICE on dealing with grayscale images and FasterRCNN? Thanks in advance! Really appreciate it!
Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) means the normalization process is applied to all the 3 channels of the input image. 0.485 is applied to the R channel, 0.456 is applied to the G channel and 0.406 is applied to the B channel. The same goes for the standard deviation values. The 1st Conv. layer of the backbone expects a 1 channel input and that's the reason you get this error. You could do the following to solve the issue. Re-define the GeneralizedRCNNTransform and attach it to your model. You could do something like this: # put the pieces together inside a FasterRCNN model model = FasterRCNN(backbone, num_classes=2, rpn_anchor_generator=anchor_generator, box_roi_pool=roi_pooler) # Changes grcnn = torchvision.models.detection.transform.GeneralizedRCNNTransform(min_size=800, max_size=1333, image_mean=[0.485], image_std=[0.229]) model.transform = grcnn model.to(device)
https://stackoverflow.com/questions/64957944/