sub
stringclasses
4 values
title
stringlengths
3
304
selftext
stringlengths
3
30k
upvote_ratio
float64
0.07
1
id
stringlengths
9
9
created_utc
float64
1.6B
1.65B
pytorch
Do I need to save the loss function if I'm checkpointing my model during training?
Before I begin training, I initialize my loss function like this loss_func = torch.nn.CrossEntropyLoss() Then during the training I use loss = loss_func(logits, train_y) If I want to checkpoint my model during the training process by saving to file and resuming at the same point later, do I need to save loss_func too, or can I re-initialize with a clean slate and see the same behavior. Basically I'm curious if the loss_func object updates some attributes when it's used so it behaves differently on further uses, which I would want to save if that does happen. On a similar note I am wondering if I can use the same loss function object with different models being trained at the same time without them interfering with each other, and I guess answering my original question will give me an answer to this too.
1
t3_k7hnvz
1,607,208,931
pytorch
Pytorch using Simulink model inputs
I'm trying to perform SL or RL on a super simple model to predict the gain of a transfer function. I can use pandas and the Matlab python engine to correctly pass inputs to my model and extract workspace variables back out. However, then I try and wrap my NN around this training data, my gradients never update and my rained solution is essentially identical to my inputs, which is nonsensical. I'm wondering if anyone has experience performing SL or RL using pytorch that calls a Simulink model or if there is literature (examples) i could search for reference?
1
t3_k7h6o9
1,607,207,236
pytorch
The amount of boilerplate and imperative magic-behind-the-scenes is infuriating in pytorch
I think everything could be so much simpler with a more functional-programming style approach. I haven't coded in a mostly imperative style in ages - and suddenly it hits me just how confusing an imperative approach can be. The main pytorch tutorial is written like that, and the installation/dependencies is yet another pita to resolve. I'm really optimistic about pytorch/ML in general, but yeah this could be so much better and we would be able to reach a much bigger audience.
0.4
t3_k79ulh
1,607,183,785
pytorch
I want to make my decoder weights equal the transpose of my encoder part
Hello community, I want to reduce overfitting of my auto encoder because I don't have enough data to train on, and I found that making the decoder weight = transpose of the encoder weight will increase the efficiently of my model. How can I do so in my model ?
1
t3_k6pkza
1,607,103,640
pytorch
Can't use num_workers > 0 with CUDA
I'm currently using the following code: ``` dataloader = DataLoader(dataset=data, batch_size=batch_size, shuffle=True, num_workers=0) ``` If I enable CUDA with my model it works. But the moment I set `num_workers` to a value `> 0`, it produces the following error: ``` RuntimeError: Caught RuntimeError in DataLoader worker process 0. ``` Is this a known bug? Performance is just as good as CPU with this setup. But I can confirm that the GPU is running with `nvidia-smi` Stack trace: ``` Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/research/lib/python3.8/runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "/home/ubuntu/anaconda3/envs/research/lib/python3.8/runpy.py", line 87, in _run_code exec(code, run_globals) File "/home/ubuntu/workspace/pyntrainer/pyntrainer/__main__.py", line 107, in <module> net.train(training_data, epochs=epochs, lr=lr, batch_size=batch_size, loss="aml") File "/home/ubuntu/workspace/pyntrainer/pyntrainer/./lib/autoencoder.py", line 153, in train for i, (inputs, labels) in enumerate(dataloader): File "/home/ubuntu/anaconda3/envs/research/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 345, in __next__ data = self._next_data() File "/home/ubuntu/anaconda3/envs/research/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 856, in _next_data return self._process_data(data) File "/home/ubuntu/anaconda3/envs/research/lib/python3.8/site-packages/torch/utils/data/dataloader.py", line 881, in _process_data data.reraise() File "/home/ubuntu/anaconda3/envs/research/lib/python3.8/site-packages/torch/_utils.py", line 394, in reraise raise self.exc_type(msg) RuntimeError: Caught RuntimeError in DataLoader worker process 0. Original Traceback (most recent call last): File "/home/ubuntu/anaconda3/envs/research/lib/python3.8/site-packages/torch/utils/data/_utils/worker.py", line 178, in _worker_loop data = fetcher.fetch(index) File "/home/ubuntu/anaconda3/envs/research/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 44, in fetch data = [self.dataset[idx] for idx in possibly_batched_index] File "/home/ubuntu/anaconda3/envs/research/lib/python3.8/site-packages/torch/utils/data/_utils/fetch.py", line 44, in <listcomp> data = [self.dataset[idx] for idx in possibly_batched_index] File "/home/ubuntu/workspace/pyntrainer/pyntrainer/./lib/./abstract_dataset.py", line 10, in __getitem__ return self.x[index], self.x[index] RuntimeError: CUDA error: initialization error ```
0.84
t3_k6o3yh
1,607,099,235
pytorch
Augmenting Image Dataset Based Upon Distance
Hello all, I am doing a project which involves me to get a comprehensive image set via augmentation, although the one which is the most hard for me to do (if possible) is augmenting based on distance. Basically, I want to be able to take a set of images which is considered to be like a seed for augmentation, and augment them based on distance to make it seem that the image is farther away from the point of the picture (along with other factors to augment them on). I have been looking through torchvision.transforms for a viable transformation, but I can't seem to find one. I was wondering for those who may know more about different image processing/computer graphics algorithms to know if this is possible for me to do, or if I will have to go through the work of getting more data from different distances.
0.8
t3_k5m8ps
1,606,955,157
pytorch
Neural network on CIFAR-10 and GPU showing wildly different accuracies on different sessions
Newbie to PyTorch. I'm following along with the third in this tutorial online [https://www.youtube.com/watch?v=GIsg-ZUy0MY&ab\_channel=freeCodeCamp.org](https://www.youtube.com/watch?v=GIsg-ZUy0MY&ab_channel=freeCodeCamp.org) for one-layer neural network with the MNIST dataset. I decided to try out the same thing for practice on the CIFAR-10 dataset, which can be accessed directly through the pytorch library. I'm working in a google colab document and wrote a bunch of notes for myself. I worked my way through the tutorial pretty well. I ran it a bunch of times, and only got accuracies of around 35%, a little worse than even logistic regression on the same dataset. Then, I tinkered around, I think I had forgot to switch to the GPU - that was the issue - and replayed, and was able to get my algorithm to a much better 67% accuracy, and after tinkering with the learning rate, I settled at 0.0005 being the best. But now, when I run my algorithm, even on the GPU, I get stuff around the 35% (sometimes lower) mark. I looked in my diff, and even *restored the version that I was getting 67% on,* but when I ran it now, I got low accuracy. [Heres my Colab Doc](https://colab.research.google.com/drive/14lhvXjjOHeHoVrQYjGxffsiNlB9dbncz?usp=sharing) I'm pretty confused as to what this may be - any ideas? More importantly, any ideas on how to start getting high accuracies again? Thanks a lot! a
0.86
t3_k4wsd2
1,606,864,808
pytorch
need help with cnn pytorch
Hello mates, Im trying to do a cnn for chord recognition based on a paper that i found. Im a noob so im stuck.For now i have this: class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() in_channels=1 out_channels=1 kernel_size=(1,16,6,25) self.conv1 = nn.Sequential(nn.Conv3d(in_channels, out_channels,kernel_size,stride=1, padding=2), nn.Conv3d(in_channels, out_channels,kernel_size,stride=1, padding=2)) I know maybe its wrong so any help will be usefull. Hope someone can let me a hand to continue with it because i dont know how to continue. And this is the explanation on the paper to model the cnn: https://preview.redd.it/iis0k4ivzk261.png?width=549&format=png&auto=webp&s=e1bfe7a472c30442ac20dc522da8878be479c3c7
1
t3_k4lc7w
1,606,831,187
pytorch
A library to help run distributed PyTorch training on remote computers
We wrote this simple library [https://github.com/lab-ml/remote](https://github.com/lab-ml/remote) that can connect to remote computers and run PyTorch training jobs. [Here's a guide on running distributed PyTorch 🔥 training with it](https://github.com/lab-ml/remote/blob/master/notes/pytorch-ddp.md) Looking forward to any feedback that could help us improve the library. Thanks
0.92
t3_k4i7lc
1,606,817,366
pytorch
Semantic segmentation - background removal preprocess?
Hello, I want to do semantic segmentation with U-Net, with the data I have I'm able to remove the background automatically. Is it beneficial for the model feature extraction if remove the background and replace it with a white/geen/yellow ect background. Maybe use multiple colors mixed in the training set or something.
1
t3_k493c8
1,606,781,731
pytorch
HOW to build PyTorch with OpenBLAS and CUDA on Linux??????
Hi, After trying everything I can (and after hours of trying to debug the problems) I have been still unable to build Pytorch using Openblas and Cuda (on a AMD cpu + Nvidia gpu using Manjaro/Arch). I've tried deleting all mkl libraries from the system, using conda, building from source - but everything runs into error when I try to build it without MKL (conda has conflicts with nomkl installation and building from source runs into errors is using BLAS=OpenBLAS) and I can only build Pytorch with MKL (via pip or aur). This is harming my system's performance significantly.
0.6
t3_k3zlxo
1,606,755,066
pytorch
are there any good fixed point arithmetic libraries for pytorch?
Hello, I am searching for a library that enables me to work with int8 based fixed point arithmetic in pytorch on the gpu, are there any libraries out there ?
1
t3_k3vq9f
1,606,742,829
pytorch
Deep Learning with PyTorch: Free Course
nan
0.87
t3_k3m54s
1,606,700,432
pytorch
How to implement differentiable sign function?
I'm trying to implement DNF-Net ( [https://arxiv.org/abs/2006.06465](https://arxiv.org/abs/2006.06465) ) in pytorch. In the paper, the authors used differentiable sign function, using the following trick: Calculate the step function *exactly* in forward pass, use a differentiable proxy in backward pass. So: * sign(x) - forward pass * tanh(x) - backward pass How to create such function in pytorch? I will be calling this function on a 1 dimensional tensor, if it helps. Also, do tell your thoughts about this architecture if you happen to know it.
1
t3_k0aen0
1,606,241,777
pytorch
[Tutorial] A Comprehensive Guide to the DataLoader Class and Abstractions in PyTorch
In this tutorial, we'll deal with a fundamental challenge in Machine Learning and Deep Learning that is easier said than done: loading and handling different types of data. Specifically, we'll cover: * Looking at built-in datasets in-depth * Using the Dataloader class * Using GPUs vs. CPUs * Transforming and rescaling images * Loading and visualizing built-in datasets * Building and loading custom datasets with PyTorch Tutorial link: [https://blog.paperspace.com/dataloaders-abstractions-pytorch/](https://blog.paperspace.com/dataloaders-abstractions-pytorch/) Run the code on a free GPU with Gradient Community Notebooks: [https://ml-showcase.paperspace.com/projects/working-with-data-in-pytorch](https://ml-showcase.paperspace.com/projects/working-with-data-in-pytorch)
0.95
t3_k07uzq
1,606,234,255
pytorch
[Q] How can I extract the positive labels to calculate the recall ?
Hi all, I trained a CNN in Pytorch to classify images as benign or malignant and calculated the accuracy for a training and a testing set. Now I wanna additionally calculate the recall. The recall is defined as TP/TP+FN. Therefore, I wanna extract the cases where my labels match 0 and then calculate the fraction of where my prediction also equals 0 at these places. Could you maybe give me a hint on how to do this in Pytorch? I have insered an image of my code here. https://preview.redd.it/i7fzlrf7zz061.png?width=626&format=png&auto=webp&s=eeb91b0faf48f0fc65746021fd898015fe25557a
1
t3_jzi8m8
1,606,140,555
pytorch
Why does a model definition have both a __init__ and forward function?
Could someone explain to me why pytorch has both **init** and forward function in a model definition, and what each one does, and why do we need 2 function rather than just one?
0.58
t3_jyneu4
1,606,010,429
pytorch
Deep Dive in Datasets for Machine translation in NLP Using TensorFlow and PyTorch
[https://analyticsindiamag.com/deep-dive-in-datasets-for-machine-translation-in-nlp-using-tensorflow-and-pytorch/](https://analyticsindiamag.com/deep-dive-in-datasets-for-machine-translation-in-nlp-using-tensorflow-and-pytorch/)
0.75
t3_jy87s7
1,605,951,986
pytorch
How do the loss function and model parameters connect with each other ?
To connect the optimizer and model together, we pass in \`model.parameters()\` as an arguement to the optimizer, so that it can zero out the gradients and perform the step. Whereas I wasn't able to understand how does the backprop weights from the loss function reflect onto the model, when we never connected them ?
0.88
t3_jxw02k
1,605,901,528
pytorch
How can I label my data?
Hi Pytorch Community, I am really new to Pytorch (some hours now). I have two datasets of images (malignant vs benign pictures of breast cancer). I have uploaded them into Google Colab and now I have all my variables for malignant in one variable and for benign in another. How can I "label" them, such that I can mix them together afterwards into training and testing data?
1
t3_jxv8j5
1,605,899,015
pytorch
When using nn.Transformer for inference is there any way to speed up the autoregressive generation?
I have a basic transformer model: ``` class Reconstructor(nn.Module): """Container module with an encoder, a recurrent or transformer module, and a decoder.""" 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.embedding = nn.Linear(input_dim, dim_embedding) 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.init_weights() 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 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, tgt_mask=None): embedding_inp = self.embedding(src).permute(1, 0, 2) embedding_out = self.embedding(tgt).permute(1, 0, 2) pe_src = embedding_inp + self.pos_encoder(embedding_inp) # (seq, batch, features) pe_tgt = embedding_out + self.pos_encoder(embedding_out) # (seq, batch, features) transformer_output = self.transformer(pe_src, pe_tgt) decoder_output = self.decoder(transformer_output).permute(1, 0, 2) decoder_output = self.decoder_act_fn(decoder_output) return decoder_output def initHidden(self): return torch.zeros(1, 1, 128) ``` During training, I have: ``` tgt_mask = gen_nopeek_mask(ground_truth.size(1)).to(DEVICE) tgt = torch.ones(ground_truth.size()).to(DEVICE) * -1 tgt[:, 1:, :] = ground_truth[:, 0:-1, :] pred = model(x, tgt, tgt_mask=tgt_mask) ``` which I believe will do the training in parallel. During inference, I have: ``` tgt = torch.ones(x.size(0), 1, 128) * -1 for i in range(x.size(1)): print(i) tgt = torch.randn(tgt.size()) pred = reconstruct_spect_model(x, tgt) tgt = torch.cat((tgt, pred[:, -1, :].unsqueeze(1)), 1) ``` given that my sequence has 499 steps, it takes A WHILE to go through autoregressively. Is there any way to speed this up?
1
t3_jxt55g
1,605,892,637
pytorch
What stands in the way of making your model useful?
Hey there, I've been working on a concept that allows you to upload your ML models (Tensorflow, Pytorch, etc) and turn them into sharable web apps super quickly, without writing code (for the deployment/ UI part at least). Here's the landing page I threw together for a more in-depth description of what I'm imagining it could look like: [https://www.getaiko.com/](https://www.getaiko.com/?fbclid=IwAR2eWORlgX2FlBpl9Y42R-_b1wzNuIcfWTaItESr1BP6WmAMmN994SugD78) Some questions that would help guide me on this project: * What stands in your way of making your model useful/ getting it out into the world? * What are your pain points and major goals when it comes to getting your model deployed?
1
t3_jx81zd
1,605,810,032
pytorch
Intel vs AMD cpu performance
How is the performance of AMD CPUs vs Intel? Are there any problems faced by AMD due to the use of MKL in pytorch?
1
t3_jx6qzg
1,605,806,118
pytorch
GuitarML/PedalNetRT - PyTorch for emulating guitar amplifiers/effects (for anyone interested in deep learning on audio)
nan
1
t3_jx1eip
1,605,787,007
pytorch
PyTorch Releases Prototype Features To Execute Machine Learning Models On-Device Hardware Engines
PyTorch has recently released four new PyTorch prototype features. The first three enable mobile machine-learning developers to execute models on the full set of hardware (HW) engines making up a system-on-chip (SOC) system. This allows developers to optimize their model execution for a unique performance, power, and system-level concurrency. Summary: [https://www.marktechpost.com/2020/11/18/pytorch-releases-prototype-features-to-execute-machine-learning-models-on-device-hardware-engines/](https://www.marktechpost.com/2020/11/18/pytorch-releases-prototype-features-to-execute-machine-learning-models-on-device-hardware-engines/) GitHub: [https://github.com/pytorch/tutorials/tree/master/prototype\_source](https://github.com/pytorch/tutorials/tree/master/prototype_source) Source: [https://pytorch.org/blog/prototype-features-now-available-apis-for-hardware-accelerated-mobile-and-arm64-builds/](https://pytorch.org/blog/prototype-features-now-available-apis-for-hardware-accelerated-mobile-and-arm64-builds/)
0.88
t3_jwyg5z
1,605,771,188
pytorch
What is the performance of Pytorch running on Apple M1?
I haven't received my M1, but I see that TensorFlow has optimized for training on M1, so I am looking forward to the performance of Pytorch on M1, although it may be weaker than on x86.
0.96
t3_jwye04
1,605,770,885
pytorch
Setting up a C++ project in Visual Studio 2019 with LibTorch 1.6
nan
1
t3_jwq25r
1,605,738,696
pytorch
Sequence of for loops to access different dimensions of a tensor
My problem is a bit hard to explain. * I want to update probability distributions recursively in \[0, 1\]\^n. * I discretized it with 10 bins per dimension, so there are 10\^n cells indexed by an n-tuple. * Initially, I should have a uniform distribution; but then I take a threshold parameter that dictates how I propagate the distribution: every point that is "below" all the n thresholds must receive zero probability. I would need to access and update `tensor[j, :, ..., :], tensor[:, j, ..., :], ..., tensor[:, :, ..., j]` recursively, and the problem is that I wanted the number of dimensions to be dynamic. How could I implement it? I have added a question on StackOverflow with a snippet that may help to understand: [https://stackoverflow.com/questions/64885859/sequence-of-for-loops-to-access-different-dimensions-of-a-tensor](https://stackoverflow.com/questions/64885859/sequence-of-for-loops-to-access-different-dimensions-of-a-tensor)
1
t3_jwfj2f
1,605,705,176
pytorch
Pytorch image recognition logistic regression - CIFAR-10 has flat loss curve (no improvement in accuracy after training)
​ Complete newbie to pytorch, Just started pytorch last week, but I've been dabbling in the theory and mathematics of machine learning for a few months, so I understand that part, mostly. I'm following along with the second course in this tutorial online [https://www.youtube.com/watch?v=GIsg-ZUy0MY&ab\_channel=freeCodeCamp.org](https://www.youtube.com/watch?v=GIsg-ZUy0MY&ab_channel=freeCodeCamp.org) for logistic regression with the MNIST dataset. I decided to try out the same thing for practice on the CIFAR-10 dataset, which can be accessed directly through the pytorch library. I'm working in a google colab document and wrote a bunch of notes for myself. I worked my way through the tutorial pretty well. Near the end, where I step through each epoch, I tried (a probably very code inefficent way) to plot the training and validation accuracy w.r.t the amount of epochs and found it to be a flat line, my accuracy starting at around 30% and wavering around there indefinitely. ​ https://preview.redd.it/enu9urvrnyz51.png?width=536&format=png&auto=webp&s=ab475d11fffe8220203e3b8ebca424534fee1818 I'm really confused at what this is suggesting!! It isn't at 10%, so that means that it worked a bit (since it's more than just guessing) but why would it stay? I tried a bunch of arbitrary learning rates and found it hover between 10-35% accuracy, but it would never improve much more than 5 percentage points after the initial step. Here's my google colab page for this document: [https://colab.research.google.com/drive/1lWmBlI2BTLw3B-jW5uum0GfYiFNA5kQv?usp=sharing](https://colab.research.google.com/drive/1lWmBlI2BTLw3B-jW5uum0GfYiFNA5kQv?usp=sharing) I'm pretty confused - also, some tips on how to better plot learning curves and loss curves would be much appreciated! I feel like my implementation is not efficient. Thanks, A
0.67
t3_jwcaci
1,605,688,870
pytorch
How to load checkpoints across different versions of pytorch (1.3.1 and 1.6.x) using ppc64le and x86?
nan
1
t3_jvza7v
1,605,640,546
pytorch
[Q] Rtx 3000
Hey, So I got my rtx 3070 on my ubuntu pc. Is there already support for pytorch with rtx 3070? I read that you need cuda 11.1 for it, but pytorch didn't release a version with cuda 11.1 yet
1
t3_jvycs7
1,605,637,721
pytorch
Pytorch vs Pytorch Lightning speed
Hello, I've started to port some of my Pytorch trainers to Pytorch Lightning. I like the modularity of it but it seems to train a lot slower than regular Pytorch. Have any of you noticed any significant differences in speed between Pytorch and Pytorch Lightning? I'm using the same data loading and network codes in both versions.
0.81
t3_jvqtbo
1,605,609,157
pytorch
PyTorch 3D: Digging Deeper in Deep Learning
nan
1
t3_jvp39i
1,605,599,504
pytorch
Checking test accuracy using vectorized code?
I have checked pytorch docs to find test accuracy after each epoch and found basic for loop and updating a counter. This works but is fairly slow on cifar10 dataset. Is there a way to use numpy like vectorizations to make it faster. I'm new to pytorch. Any help would be appreciated.
0.5
t3_jv905w
1,605,541,745
pytorch
RuntimeError: arguments are located on different GPUs at /pytorch/aten/src/THC/generic/THCTensorIndex.cu:403
Hi there, ​ I have a Pytorch Bert model was originally trained with 1 GPU. Now i moved it to 4GPU due to memory issue. However, when I moved it to 4GPU. I got an error message as below during the validation part: \`\`\` RuntimeError: Caught RuntimeError in replica 1 on device 1. Original Traceback (most recent call last): File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/parallel\_apply.py", line 60, in \_worker output = module(\*input, \*\*kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in \_\_call\_\_ result = self.forward(\*input, \*\*kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/data\_parallel.py", line 155, in forward outputs = self.parallel\_apply(replicas, inputs, kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/data\_parallel.py", line 165, in parallel\_apply return parallel\_apply(replicas, inputs, kwargs, self.device\_ids\[:len(replicas)\]) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/parallel\_apply.py", line 85, in parallel\_apply output.reraise() File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/\_utils.py", line 395, in reraise raise self.exc\_type(msg) RuntimeError: Caught RuntimeError in replica 0 on device 0. Original Traceback (most recent call last): File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/parallel/parallel\_apply.py", line 60, in \_worker output = module(\*input, \*\*kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in \_\_call\_\_ result = self.forward(\*input, \*\*kwargs) File "/home/ec2-user/SageMaker/Anecdotes/model.py", line 117, in forward inputs\_embeds=None, File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in \_\_call\_\_ result = self.forward(\*input, \*\*kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/transformers/modeling\_bert.py", line 727, in forward input\_ids=input\_ids, position\_ids=position\_ids, token\_type\_ids=token\_type\_ids, inputs\_embeds=inputs\_embeds File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in \_\_call\_\_ result = self.forward(\*input, \*\*kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/transformers/modeling\_bert.py", line 174, in forward inputs\_embeds = self.word\_embeddings(input\_ids) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 550, in \_\_call\_\_ result = self.forward(\*input, \*\*kwargs) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/modules/sparse.py", line 114, in forward self.norm\_type, self.scale\_grad\_by\_freq, self.sparse) File "/home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages/torch/nn/functional.py", line 1724, in embedding return torch.embedding(weight, input, padding\_idx, scale\_grad\_by\_freq, sparse) RuntimeError: arguments are located on different GPUs at /pytorch/aten/src/THC/generic/THCTensorIndex.cu:403 \`\`\` ​ My [model.py](https://model.py) is as below: \`\`\` import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import MultiheadAttention, EmbeddingBag, CrossEntropyLoss, MultiLabelSoftMarginLoss, BCEWithLogitsLoss from transformers import BertPreTrainedModel, BertModel, BertTokenizer, AdamW ​ from utils import LABEL\_NAME ​ ​ class ReviewClassification(BertPreTrainedModel): def \_\_init\_\_(self, config, add\_agent\_text, agent\_text\_heads): """ :param config: Bert configuration, can set up some parameters, like output\_attention, output\_hidden\_states :param add\_agent\_text: whether to use the non text feature, and how. It can have three options: None, "concat" and "attention" :param agent\_text\_heads: number of the heads in agent attention mechanism. Only useful if add\_agent\_text are set to "attention" """ super().\_\_init\_\_(config) \# self.num\_labels = 2 self.add\_agent\_text = add\_agent\_text ​ self.bert = BertModel(config) self.dropout = nn.Dropout(config.hidden\_dropout\_prob) ​ embedding\_size = config.hidden\_size ​ if self.add\_agent\_text == "concat": embedding\_size = 2 \* embedding\_size elif self.add\_agent\_text == "attention": self.agent\_attention = nn.MultiheadAttention(embedding\_size, num\_heads=agent\_text\_heads) else: \# don't use the information in Agent text pass ​ self.classifier = nn.Linear(embedding\_size, 1) # self.classifier = nn.Linear(embedding\_size, len(LABEL\_NAME)) # bias: If set to False, the layer will not learn an additive bias self.init\_weights() ​ print( """ add agent text :{} agent text multi-head :{} """.format(self.add\_agent\_text, agent\_text\_heads) ) ​ def forward( self, review\_input\_ids=None, review\_attention\_mask=None, review\_token\_type\_ids=None, agent\_input\_ids=None, agent\_attention\_mask=None, agent\_token\_type\_ids=None, labels=None, ): """ labels (:obj:\`torch.LongTensor\` of shape :obj:\`(batch\_size,)\`, \`optional\`, defaults to :obj:\`None\`): Labels for computing the sequence classification/regression loss. Indices should be in :obj:\`\[0, ..., config.num\_labels - 1\]\`. If :obj:\`config.num\_labels == 1\` a regression loss is computed (Mean-Square loss), If :obj:\`config.num\_labels > 1\` a classification loss is computed (Cross-Entropy). ​ Returns: :obj:\`tuple(torch.FloatTensor)\` comprising various elements depending on the configuration (:class:\`\~transformers.BertConfig\`) and inputs: loss (:obj:\`torch.FloatTensor\` of shape :obj:\`(1,)\`, \`optional\`, returned when :obj:\`label\` is provided): Classification (or regression if config.num\_labels==1) loss. logits (:obj:\`torch.FloatTensor\` of shape :obj:\`(batch\_size, config.num\_labels)\`): Classification (or regression if config.num\_labels==1) scores (before SoftMax). hidden\_states (:obj:\`tuple(torch.FloatTensor)\`, \`optional\`, returned when \`\`config.output\_hidden\_states=True\`\`): Tuple of :obj:\`torch.FloatTensor\` (one for the output of the embeddings + one for the output of each layer) of shape :obj:\`(batch\_size, sequence\_length, hidden\_size)\`. ​ Hidden-states of the model at the output of each layer plus the initial embedding outputs. attentions (:obj:\`tuple(torch.FloatTensor)\`, \`optional\`, returned when \`\`config.output\_attentions=True\`\`): Tuple of :obj:\`torch.FloatTensor\` (one for each layer) of shape :obj:\`(batch\_size, num\_heads, sequence\_length, sequence\_length)\`. ​ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. ​ Examples:: ​ from transformers import BertTokenizer, BertForSequenceClassification import torch ​ tokenizer = BertTokenizer.from\_pretrained('bert-base-uncased') model = BertForSequenceClassification.from\_pretrained('bert-base-uncased') ​ input\_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add\_special\_tokens=True)).unsqueeze(0) # Batch size 1 labels = torch.tensor(\[1\]).unsqueeze(0) # Batch size 1 outputs = model(input\_ids, labels=labels) ​ loss, logits = outputs\[:2\] ​ """ ​ review\_outputs = self.bert( review\_input\_ids, attention\_mask=review\_attention\_mask, token\_type\_ids=review\_token\_type\_ids, position\_ids=None, head\_mask=None, inputs\_embeds=None, ) if self.add\_agent\_text is not None: \# means that self.add\_agent\_text is "concat" or "attention" \# TODO: we can try that agent\_outputs do not share the same parameter agent\_outputs = self.bert( agent\_input\_ids, attention\_mask=agent\_attention\_mask, token\_type\_ids=agent\_token\_type\_ids, position\_ids=None, head\_mask=None, inputs\_embeds=None, ) ​ if self.add\_agent\_text == "attention": review\_hidden\_states = review\_outputs\[0\].transpose(0, 1) # before trans: (bs, seq\_len, hidden\_size) agent\_hidden\_states = agent\_outputs\[0\].mean(axis=1).unsqueeze(dim=0) # (1, batch\_size, hidden\_size) ​ attn\_output, \_ = self.agent\_attention(agent\_hidden\_states, review\_hidden\_states, review\_hidden\_states) feature = attn\_output.squeeze() # (batch\_size, seq\_len) else: feature = review\_outputs\[1\] # (batch\_size, seq\_len) -? Should it be (batch\_size, hidden\_size) ​ if self.add\_agent\_text == "concat": feature = [torch.cat](https://torch.cat)(\[feature, agent\_outputs\[1\]\], axis=1) ​ \# nn.CrossEntropyLoss applies F.log\_softmax and nn.NLLLoss internally on your input, \# so you should pass the raw logits to it. ​ \# torch.nn.functional.binary\_cross\_entropy takes logistic sigmoid values as inputs \# torch.nn.functional.binary\_cross\_entropy\_with\_logits takes logits as inputs \# torch.nn.functional.cross\_entropy takes logits as inputs (performs log\_softmax internally) \# torch.nn.functional.nll\_loss is like cross\_entropy but takes log-probabilities (log-softmax) values as inputs ​ \# CrossEntropyLoss takes prediction logits (size: (N,D)) and target labels (size: (N,)) \# CrossEntropyLoss expects logits i.e whereas BCELoss expects probability value logits = self.classifier(feature).squeeze() ​ outputs = (logits,) # + outputs\[2:\] # add hidden states and attention if they are here ​ ​ if labels is not None: \##### original \# loss\_fct = MultiLabelSoftMarginLoss() \# loss = loss\_fct(logits, labels) \# outputs = (loss,) + outputs \#### Version 1 try \# pos\_weight = dataset.label\_proportion.iloc\[0\]/dataset.label\_proportion.iloc\[1\] ​ \# Version 1.1 for weight \# weight = torch.tensor(\[0.101521, 0.898479\]) # hard code from entire training dataset \# pos\_weight = weight\[labels.data.view(-1).long()\].view\_as(labels) \# Version 1.2 for weight pos\_weight=torch.tensor(1) \# Version 1.3 for weight \#weight = torch.tensor(\[1.0, 8.85\]) # hard code from entire training dataset \#pos\_weight = weight\[labels.data.view(-1).long()\].view\_as(labels) loss\_fct = nn.BCEWithLogitsLoss(pos\_weight=pos\_weight).cuda() loss = loss\_fct(logits, labels) \# loss = loss\_fct(logits.view(-1, self.num\_labels), labels.view(-1, self.num\_labels)) outputs = (loss,) + outputs \### Version 2 try \# loss\_fct = nn.CrossEntropyLoss() \# loss = loss\_fct(logits.view(-1, self.num\_labels), labels.view(-1)) \# outputs = (loss,) + outputs ​ return outputs # (loss, logits, hidden\_states, attentions) \`\`\` ​ And my train\_valid\_test.py for the training, validation, test process is as below: \`\`\` import time import pickle from path import Path import numpy as np import pandas as pd ​ from sklearn.metrics import precision\_recall\_fscore\_support, classification\_report, confusion\_matrix import torch import torch.nn as nn ​ from utils import LABEL\_NAME, isnotebook, set\_seed, format\_time ​ if isnotebook(): from tqdm.notebook import tqdm else: from tqdm import tqdm ​ ​ set\_seed(seed=228) ​ def model\_train(model, train\_data\_loader, valid\_data\_loader, test\_data\_loader, logger, optimizer, scheduler, num\_epochs, seed, out\_dir): \# move model to gpu device = torch.device('cuda' if torch.cuda.is\_available() else 'cpu') [model.to](https://model.to)(device) if torch.cuda.device\_count() > 1: model = nn.DataParallel(model) ​ num\_gpus = torch.cuda.device\_count() [logger.info](https://logger.info)("Let's use {} GPUs!".format(num\_gpus)) ​ \# Set the seed value all over the place to make this reproducible. \# set\_seed(seed=seed) ​ \# We'll store a number of quantities such as training and validation loss, \# validation accuracy, and timings. training\_stats = \[\] print\_interval = 100 ​ \# Measure the total training time for the whole run. total\_t0 = time.time() batch\_size = train\_data\_loader.batch\_size num\_batch = len(train\_data\_loader) best\_f1\_score = { "weighted": 0, "averaged": 0 } best\_test\_f1\_score = 0 ​ \# For each epoch... for epoch\_i in range(0, num\_epochs): ​ \# ======================================== \# Training \# ======================================== ​ \# Perform one full pass over the training set. [logger.info](https://logger.info)("") [logger.info](https://logger.info)('======== Epoch {:} / {:} ========'.format(epoch\_i + 1, num\_epochs)) [logger.info](https://logger.info)('Training...') ​ \# Reset the total loss for this epoch. total\_train\_loss = 0 ​ \# Measure how long the training epoch takes. t\_train = time.time() ​ model.train() ​ \# For each batch of training data... for step, batch in tqdm(enumerate(train\_data\_loader), desc="Training Iteration", total=num\_batch): \# Progress update every 100 batches. if step % print\_interval == 0 and not step == 0: \# Calculate elapsed time in minutes. elapsed = format\_time(time.time() - t\_train) avg\_train\_loss = total\_train\_loss / print\_interval ​ \# Report progress. [logger.info](https://logger.info)('| epoch {:3d} | {:5d}/{:5d} batches | lr {:.3e} | loss {:5.3f} | Elapsed {:s}'.format( epoch\_i+1, step, num\_batch, scheduler.get\_last\_lr()\[0\], avg\_train\_loss, elapsed) ) total\_train\_loss = 0 training\_stats.append( { 'epoch': epoch\_i + 1, 'step': step, 'train loss': avg\_train\_loss, } ) ​ \# Unpack this training batch from our dataloader. \# \# As we unpack the batch, we'll also copy each tensor to the GPU using the \# \`to\` method. \# \# \`batch\` contains four pytorch tensors: \# "input\_ids" \# "attention\_mask" \# "token\_type\_ids" \# "binarized\_labels" ​ b\_review\_input\_ids = batch\["review\_input\_ids"\].to(device) b\_review\_attention\_mask = batch\["review\_attention\_mask"\].to(device) b\_review\_token\_type\_ids = batch\["review\_token\_type\_ids"\].to(device) b\_agent\_input\_ids = batch\["agent\_input\_ids"\].to(device) b\_agent\_attention\_mask = batch\["agent\_attention\_mask"\].to(device) b\_agent\_token\_type\_ids = batch\["agent\_token\_type\_ids"\].to(device) ​ b\_binarized\_label = batch\["binarized\_label"\].to(device) ​ model.zero\_grad() (loss, \_) = model(review\_input\_ids=b\_review\_input\_ids, review\_attention\_mask=b\_review\_attention\_mask, review\_token\_type\_ids=b\_review\_token\_type\_ids, agent\_input\_ids=b\_agent\_input\_ids, agent\_attention\_mask=b\_agent\_attention\_mask, agent\_token\_type\_ids=b\_agent\_token\_type\_ids, ​ labels=b\_binarized\_label ) ​ \# Accumulate the training loss over all of the batches so that we can \# calculate the average loss at the end. \`loss\` is a Tensor containing a \# single value; the \`.item()\` function just returns the Python value \# from the tensor. ​ if num\_gpus > 1: total\_train\_loss += loss.mean().item() loss.mean().backward() # use loss.mean().backward() instead of loss.backward() for multiple gpu trainings else: total\_train\_loss += loss.item() loss.backward() ​ \# Clip the norm of the gradients to 1.0. \# This is to help prevent the "exploding gradients" problem. torch.nn.utils.clip\_grad\_norm\_(model.parameters(), 1.0) ​ \# Update parameters and take a step using the computed gradient. \# The optimizer dictates the "update rule"--how the parameters are \# modified based on their gradients, the learning rate, etc. optimizer.step() scheduler.step() \# End of training epoch ​ \# Measure how long this epoch took. training\_time = format\_time(time.time() - t\_train) ​ [logger.info](https://logger.info)("") [logger.info](https://logger.info)(" Training epoch took: {:s}".format(training\_time)) ​ \# evaluate the model after one epoch. ​ \# ======================================== \# Validation \# ======================================== \# After the completion of each training epoch, measure our performance on \# our validation set. ​ [logger.info](https://logger.info)("") [logger.info](https://logger.info)("Validating...") ​ t\_valid = time.time() model.eval() ave\_valid\_loss, valid\_f1\_table, cm\_table, f1\_score = model\_validate(model=model, data\_loader=valid\_data\_loader) \# Measure how long this epoch took. validation\_time = format\_time(time.time() - t\_valid) ​ [logger.info](https://logger.info)("") [logger.info](https://logger.info)('| loss {:5.3f} | Elapsed {:s}'.format(ave\_valid\_loss, validation\_time)) [logger.info](https://logger.info)(" \\n{:s}".format(valid\_f1\_table.to\_string())) [logger.info](https://logger.info)("") [logger.info](https://logger.info)(" \\n{:s}".format(cm\_table.to\_string())) ​ \# need to store the best model for key in best\_f1\_score.keys(): if best\_f1\_score\[key\] < f1\_score\[key\]: \# remove the old model: file\_list = \[f for f in out\_dir.files() if f.name.endswith(".pt") and f.name.startswith(key)\] for f in file\_list: Path.remove(f) model\_file = out\_dir.joinpath('{:s}\_epoch\_{:02d}-f1\_{:.3f}.pt'.format( key, epoch\_i + 1, f1\_score\[key\]) ) best\_f1\_score\[key\] = f1\_score\[key\] if num\_gpus > 1: [torch.save](https://torch.save)(model.module.state\_dict(), model\_file) else: [torch.save](https://torch.save)(model.state\_dict(), model\_file) ​ \# ======================================== \# Test \# ======================================== [logger.info](https://logger.info)("") [logger.info](https://logger.info)("Testing...") ​ result\_df = model\_test(model=model, data\_loader=test\_data\_loader) y\_true = np.array(result\_df\["review\_label"\], dtype=np.bool) # This part may need double check y\_pred = result\_df\["Probability"\] > 0.5 ​ report = classification\_report(y\_true, y\_pred, output\_dict=True) metrics\_df = pd.DataFrame(report).transpose() ​ metrics\_df = metrics\_df.sort\_index() ​ weighted\_f1\_score = metrics\_df.loc\['weighted avg', 'f1-score'\] averaged\_f1\_score = metrics\_df.loc\['macro avg', 'f1-score'\] ​ best\_test\_f1\_score = metrics\_df.loc\['weighted avg', 'f1-score'\] \\ if best\_test\_f1\_score < metrics\_df.loc\['weighted avg', 'f1-score'\] else best\_test\_f1\_score ​ metrics\_df = metrics\_df.astype(float).round(3) ​ \# Calculate confusion matrix tn, fp, fn, tp = confusion\_matrix(y\_true, y\_pred).ravel() cm\_df = pd.DataFrame(columns = \['Predicted No', 'Predicted Yes'\], index = \['Actual No', 'Actual Yes'\]) \# adding rows to an empty \# dataframe at existing index cm\_df.loc\['Actual No'\] = \[tn,fp\] cm\_df.loc\['Actual Yes'\] = \[fn,tp\] [logger.info](https://logger.info)("use model: {} batch / {} step".format(epoch\_i + 1, step)) [logger.info](https://logger.info)("\\n" + "=" \* 50) [logger.info](https://logger.info)("\\n" + metrics\_df.to\_string()) [logger.info](https://logger.info)("\\n" + "=" \* 50) [logger.info](https://logger.info)("\\n" + cm\_df.to\_string()) [logger.info](https://logger.info)("best test F1 score: {}".format(best\_test\_f1\_score)) [logger.info](https://logger.info)("\\n" + "=" \* 50) \# Below is to save the result files \# result\_filename = "result\_df\_epoch\_" + str(epoch\_i + 1) + ".xlsx" \# result\_df.to\_excel(out\_dir.joinpath(result\_filename), index=False) ​ [logger.info](https://logger.info)("") [logger.info](https://logger.info)("Training complete!") [logger.info](https://logger.info)("Total training took {:} (h:mm:ss)".format(format\_time(time.time() - total\_t0))) ​ \# Save training\_stats to csv file pd.DataFrame(training\_stats).to\_csv(out\_dir.joinpath("model\_train.log"), index=False) return model, optimizer, scheduler ​ ​ def model\_validate(model, data\_loader): \# Put the model in evaluation mode--the dropout layers behave differently \# during evaluation. model.eval() device = torch.device('cuda' if torch.cuda.is\_available() else 'cpu') [model.to](https://model.to)(device) if torch.cuda.device\_count() > 1: model = nn.DataParallel(model) ​ label\_prop = data\_loader.dataset.dataset.label\_prop() ​ total\_valid\_loss = 0 ​ batch\_size = data\_loader.batch\_size num\_batch = len(data\_loader) ​ y\_pred, y\_true = \[\], \[\] ​ \# Evaluate data for step, batch in tqdm(enumerate(data\_loader), desc="Validation...", total=num\_batch): b\_review\_input\_ids = batch\["review\_input\_ids"\].to(device) b\_review\_attention\_mask = batch\["review\_attention\_mask"\].to(device) b\_review\_token\_type\_ids = batch\["review\_token\_type\_ids"\].to(device) b\_agent\_input\_ids = batch\["agent\_input\_ids"\].to(device) b\_agent\_attention\_mask = batch\["agent\_attention\_mask"\].to(device) b\_agent\_token\_type\_ids = batch\["agent\_token\_type\_ids"\].to(device) ​ b\_binarized\_label = batch\["binarized\_label"\].to(device) ​ \# Tell pytorch not to bother with constructing the compute graph during \# the forward pass, since this is only needed for backprop (training). with torch.no\_grad(): (loss, logits,) = model(review\_input\_ids=b\_review\_input\_ids, review\_attention\_mask=b\_review\_attention\_mask, review\_token\_type\_ids=b\_review\_token\_type\_ids, agent\_input\_ids=b\_agent\_input\_ids, agent\_attention\_mask=b\_agent\_attention\_mask, agent\_token\_type\_ids=b\_agent\_token\_type\_ids, ​ labels=b\_binarized\_label) ​ total\_valid\_loss += loss.item() \### The sigmoid function is used for the two-class logistic regression, \### whereas the softmax function is used for the multiclass logistic regression \# Version 1 \# numpy\_probas = logits.detach().cpu().numpy() \# y\_pred.extend(np.argmax(numpy\_probas, axis=1).flatten()) \# y\_true.extend(b\_binarized\_label.cpu().numpy()) ​ \# Version 2 \# transfored\_logits = F.log\_softmax(logits,dim=1) \# numpy\_probas = transfored\_logits.detach().cpu().numpy() \# y\_pred.extend(np.argmax(numpy\_probas, axis=1).flatten()) \# y\_true.extend(b\_binarized\_label.cpu().numpy()) ​ \# Version 3 \# transfored\_logits = torch.sigmoid(logits) \# numpy\_probas = transfored\_logits.detach().cpu().numpy() \# y\_pred.extend(np.argmax(numpy\_probas, axis=1).flatten()) \# y\_true.extend(b\_binarized\_label.cpu().numpy()) ​ \# New version - for num\_label = 1 transfored\_logits = torch.sigmoid(logits) numpy\_probas = transfored\_logits.detach().cpu().numpy() y\_pred.extend(numpy\_probas) y\_true.extend(b\_binarized\_label.cpu().numpy()) \# End of an epoch of validation ​ \# put model to train mode again. model.train() ​ ave\_loss = total\_valid\_loss / (num\_batch \* batch\_size) ​ y\_pred = np.array(y\_pred) y\_pred\[y\_pred < 0.5\] = 0 y\_pred\[y\_pred >= 0.5\] = 1 \# Below is in case the input and target are not the same data format y\_pred = np.array(y\_pred, dtype=np.bool) y\_true = np.array(y\_true, dtype=np.bool) \# compute the various f1 score for each label report = classification\_report(y\_true, y\_pred, output\_dict=True) metrics\_df = pd.DataFrame(report).transpose() \# metrics\_df = pd.DataFrame(0, index=LABEL\_NAME, columns=\["Precision", "Recall", "F1","support"\]) \# metrics\_df.Precision = precision\_recall\_fscore\_support(y\_true, y\_pred)\[0\] \# metrics\_df.Recall = precision\_recall\_fscore\_support(y\_true, y\_pred)\[1\] \# metrics\_df.F1 = precision\_recall\_fscore\_support(y\_true, y\_pred)\[2\] \# metrics\_df.support = precision\_recall\_fscore\_support(y\_true, y\_pred)\[3\] ​ \# y\_pred = np.array(y\_pred) \# y\_pred\[y\_pred < 0\] = 0 \# y\_pred\[y\_pred > 0\] = 1 \# y\_pred = np.array(y\_pred, dtype=np.bool) \# y\_true = np.array(y\_true, dtype=np.bool) ​ \# metrics\_df = pd.DataFrame(0, index=LABEL\_NAME, columns=\["Precision", "Recall", "F1"\], dtype=np.float) \# # or\_y\_pred = np.zeros(y\_pred.shape\[0\], dtype=np.bool) \# # or\_y\_true = np.zeros(y\_true.shape\[0\], dtype=np.bool) \# for i in range(len(LABEL\_NAME)): \# metrics\_df.iloc\[i\] = precision\_recall\_fscore\_support( \# y\_true=y\_true\[:, i\], y\_pred=y\_pred\[:, i\], average='binary', zero\_division=0)\[0:3\] ​ \# or\_y\_pred = or\_y\_pred | y\_pred\[:, i\] \# or\_y\_true = or\_y\_true | y\_true\[:, i\] ​ metrics\_df = metrics\_df.sort\_index() \# metrics\_df.loc\['Weighted Average'\] = metrics\_df.transpose().dot(label\_prop) \# metrics\_df.loc\['Average'\] = metrics\_df.mean() ​ \# metrics\_df.loc\['Weighted Average', 'F1'\] = 2 / (1/metrics\_df.loc\['Weighted Average', "Recall"\] + \# 1/metrics\_df.loc\['Weighted Average', "Precision"\]) \# metrics\_df.loc\['Average', 'F1'\] = 2 / (1/metrics\_df.loc\['Average', "Recall"\] + \# 1/metrics\_df.loc\['Average', "Precision"\]) ​ weighted\_f1\_score = metrics\_df.loc\['weighted avg', 'f1-score'\] averaged\_f1\_score = metrics\_df.loc\['macro avg', 'f1-score'\] ​ \# Calculate confusion matrix tn, fp, fn, tp = confusion\_matrix(y\_true, y\_pred).ravel() cm\_df = pd.DataFrame(columns = \['Predicted No', 'Predicted Yes'\], index = \['Actual No', 'Actual Yes'\]) \# adding rows to an empty \# dataframe at existing index cm\_df.loc\['Actual No'\] = \[tn,fp\] cm\_df.loc\['Actual Yes'\] = \[fn,tp\] ​ \# pooled\_f1\_score = f1\_score(y\_pred=or\_y\_pred, y\_true=or\_y\_true) ​ return ave\_loss, metrics\_df, cm\_df,{ "weighted": weighted\_f1\_score, "averaged": averaged\_f1\_score, } ​ ​ def model\_test(model, data\_loader): \# Put the model in evaluation mode--the dropout layers behave differently \# during evaluation. device = torch.device('cuda' if torch.cuda.is\_available() else 'cpu') model.eval() [model.to](https://model.to)(device) if torch.cuda.device\_count() > 1: model = nn.DataParallel(model) ​ num\_batch = len(data\_loader) \# Below need to modify if change the input review\_id, review\_label, hmd\_text, head\_cust\_text = \[\], \[\], \[\], \[\] agent = \[\] pred\_logits = \[\] ​ \# Evaluate data for step, batch in tqdm(enumerate(data\_loader), desc="Inference...", total=num\_batch): if "anecdote\_lead\_final" in batch.keys(): review\_label.extend(batch\["anecdote\_lead\_final"\]) review\_id.extend(batch\["\_id"\].tolist()) hmd\_text.extend(batch\["hmd\_comments"\]) head\_cust\_text.extend(batch\["head\_cust"\]) agent.extend(batch\["new\_transcript\_agent"\]) ​ b\_review\_input\_ids = batch\["review\_input\_ids"\].to(device) b\_review\_attention\_mask = batch\["review\_attention\_mask"\].to(device) b\_review\_token\_type\_ids = batch\["review\_token\_type\_ids"\].to(device) b\_agent\_input\_ids = batch\["agent\_input\_ids"\].to(device) b\_agent\_attention\_mask = batch\["agent\_attention\_mask"\].to(device) b\_agent\_token\_type\_ids = batch\["agent\_token\_type\_ids"\].to(device) ​ ​ \# Tell pytorch not to bother with constructing the compute graph during \# the forward pass, since this is only needed for backprop (training). with torch.no\_grad(): (logits,) = model(review\_input\_ids=b\_review\_input\_ids, review\_token\_type\_ids=b\_review\_token\_type\_ids, review\_attention\_mask=b\_review\_attention\_mask, agent\_input\_ids=b\_agent\_input\_ids, agent\_token\_type\_ids=b\_agent\_token\_type\_ids, agent\_attention\_mask=b\_agent\_attention\_mask ) ​ if logits.detach().cpu().numpy().size == 1: pred\_logits.extend(logits.detach().cpu().numpy().reshape(1,)) else: pred\_logits.extend(logits.detach().cpu().numpy()) \# End of an epoch of validation \# put model to train mode again. model.train() pred\_logits = np.array(pred\_logits) pred\_prob = np.exp(pred\_logits) pred\_prob = pred\_prob / (1 + pred\_prob) pred\_label = pred\_prob.copy() pred\_label\[pred\_label < 0.5\] = 0 pred\_label\[pred\_label >= 0.5\] = 1 \# compute the f1 score for each tags d = {'Probability':pred\_prob,'Anecdotes Prediction':pred\_label} pred\_df = pd.DataFrame(d, columns=\['Probability','Anecdotes Prediction'\]) result\_df = pd.DataFrame( { "review\_id": review\_id, "hmd\_text": hmd\_text, "head\_cust\_text": head\_cust\_text, "agent": agent } ) if len(review\_label) != 0: result\_df\["review\_label"\] = \[x.item() for x in review\_label\] return pd.concat(\[result\_df, pred\_df\], axis=1).set\_index("review\_id") \`\`\` ​ Can anyone help me how to fix this issue? Thank you so much!!!
0.25
t3_jv2s5o
1,605,511,955
pytorch
LibreASR – An On-Premises, Streaming Speech Recognition System
nan
1
t3_juotjr
1,605,458,658
pytorch
Introduce Pytorch C++ API Go binding
[https://github.com/sugarme/gotch](https://github.com/sugarme/gotch) We are happy to share a new toolkit for developing deep learning in Go - [gotch](https://github.com/sugarme/gotch). **Some features are**: * Comprehensive Pytorch tensor APIs (\~ 1404) * Fully featured Pytorch dynamic graph computation * JIT interface to run model trained/saved using PyTorch Python API * Load pretrained Pytorch models and run inference * Pure Go APIs to build and train neural network models with both CPU and GPU support * Most recent image models * NLP Language models - [Transformer](https://github.com/sugarme/transformer) in separate package built with GoTch and [pure Go Tokenizer](https://github.com/sugarme/tokenizer).
0.92
t3_juek7b
1,605,408,161
pytorch
PyTorch Dataloading for Videos: A Small but Powerful Helper Repo
Need to use a video dataset for Training? Theres not much on the internet about easily and efficiently using video datasets for deep learning. So, I hope this is useful to some people. Would greatly appreciate any feedback! [https://github.com/RaivoKoot/Video-Dataset-Loading-Pytorch](https://github.com/RaivoKoot/Video-Dataset-Loading-Pytorch)
1
t3_ju3zjb
1,605,369,127
pytorch
Convenience library for PyTorch training
For the past year or so I have been plugging away on a side project - [torchutils](https://gitlab.com/avilay/torchutils) - a PyTorch library for quick but systematic experimentation. It'd be great if you could take it for a spin when training your next mL model and give me some feedback. Here are the [detailed docs](https://avilay.gitlab.io/torchutils/).
0.94
t3_ju38cn
1,605,366,190
pytorch
Facebook AI and OpenMined create PyTorch privacy and machine learning courses
nan
0.94
t3_jtlyjq
1,605,294,324
pytorch
Real-world video Super resolution!
nan
1
t3_jte5qa
1,605,259,546
pytorch
Plexiglass: A PyTorch toolbox for cybersecurity research and testing against adversarial attacks and deepfakes.
Hi everyone, my name is Enoch and I am a researcher studying deep generative models. I've started this project called Plexiglass, which is a PyTorch toolbox for cybersecurity research and testing against adversarial attacks and deepfakes. I would very much appreciate any suggestions/ feedbacks and even contributions. Repo is here: [https://github.com/enochkan/p](https://github.com/enochkan/safetynet)lexiglass
1
t3_jtchnd
1,605,250,397
pytorch
iou computation code
Could anyone explain the last four lines (*lt, rb, inter,* and the return expression) of the following code ? I do not quite understand how : works inside \[\] for pytorch def box_iou(boxes1, boxes2): # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py """ Return intersection-over-union (Jaccard index) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format. Arguments: boxes1 (Tensor[N, 4]) boxes2 (Tensor[M, 4]) Returns: iou (Tensor[N, M]): the NxM matrix containing the pairwise IoU values for every element in boxes1 and boxes2 """ def box_area(box): # box = 4xn return (box[2] - box[0]) * (box[3] - box[1]) area1 = box_area(boxes1.t()) area2 = box_area(boxes2.t()) lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] inter = (rb - lt).clamp(min=0).prod(2) # [N,M] return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
1
t3_jsy47s
1,605,199,881
pytorch
More info on the popular browser extension in AI/ML community!
nan
1
t3_jsm1md
1,605,147,185
pytorch
How To Use UCF101, The Largest Dataset Of Human Actions
nan
0.9
t3_js7gwr
1,605,098,660
pytorch
Appending tensor to itself ?
Hello All I have a tensor of size (1, 8, 1024). I wish to append this tensor to itself to make it (77, 8, 1024). How can I do it ?
1
t3_jrsvk6
1,605,040,153
pytorch
Random seed with external GPU
Hi all, I bought a new Palit GeForce RTX 3070 GPU, to speed up my deep learning projects. My laptop is a Dell Latitude 5491 with an Nvidia GeForce MX130 and Intel UHD Graphics 630. I am using the GeForce RTX 3070 in a Razer Core X via Thunderbolt 3.0. I would like to make my pytorch training reproducible, so I am using: torch.manual_seed(1) np.random.seed(1) random.seed(1) torch.cuda.manual_seed(1) torch.cuda.manual_seed_all(1) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False Symptom: When the device=“cuda:0” its addressing the MX130, and the seeds are working, I got the same result every time. When the device=“cuda:1” its addressing the RTX 3070 and I dont get the same results. Seems like with the external GPU the random seed is not working. When device=“cuda” its automatically uses the RTX 3070 and no reproducibility. I am working with num_workers=0 and worker_init_fn=np.random.seed(1) in the dataloder. So practically changing the executor GPU has effect on the random seed. I dont want to, and I am not using both GPU-s in parallel. How can I make the work with external GPU reproducible? I would very appreciate any help. Thanks in advance! Pytorch version: 1.7.0 Cuda toolkit: 11.0.221 Anaconda version: 2020.07 According to NVIDIA-SMI: Cuda version: 11.1 Driver version: 457.09
1
t3_jri43u
1,605,000,992
pytorch
Constrained Optimization
Let's say I have a dataset X of size n x m (n rows, m columns) and Y of size n x 1. I have a model that uses X_i as an input and makes a prediction Y_hat_i. I suppose this means that I have a differentiable function: y_hat_i = F(X_i) Assuming my model is accurate and precise, I want to find the values of X_i that minimize Y_hat_i. Where X_i is a 1 x m vector and Y_hat_i is a scaler value, under a set of constraints. I have looked into many ways to this including SciPy's Optimize.minimize as well as linear programming but either I'm doing something wrong or it simply doesn't work for this use case. What is a good way to approach this? Essentially I have a function that models a business and I want to find optimal operational values (inventory, costs etc) that minimize (or maximize) a given performance metric. Simply predicting is not enough here, I want to actually "optimize" the business so I am looking for some insights to this.
1
t3_jr3gpy
1,604,947,385
pytorch
CompressAI: A PyTorch Library For End-To-End Compression Research
A recent [research paper published by InterDigital AI Lab](https://arxiv.org/abs/2011.03029) introduces CompressAI. CompressAI is a platform that provides custom operations, layers, models, and tools to research, develop, and evaluate end-to-end image and video compression codecs. It uses pre-trained models and evaluation tools to compare learned methods with traditional codecs. Various models have been trained on learned end-to-end compression from scratch and re-implemented in PyTorch. Artificial Neural Network (ANN) based codecs have shown remarkable outcomes for compressing images. This framework currently implements models only for still-picture compression; however, it is believed to soon extend over to the video compression domain. Summary: [https://www.marktechpost.com/2020/11/09/compressai-a-pytorch-library-for-end-to-end-compression-research/](https://www.marktechpost.com/2020/11/09/compressai-a-pytorch-library-for-end-to-end-compression-research/) Paper: [https://arxiv.org/abs/2011.03029](https://arxiv.org/abs/2011.03029) ​ https://preview.redd.it/ef0i6odlr8y51.png?width=696&format=png&auto=webp&s=cffc12b8130db42d4190081bef2fc3eb14e315cd
1
t3_jr0u11
1,604,939,542
pytorch
How do I train two different models on two different GPUs at the same time?
Hello everyone! This might sound as a very basic question, but I'm new to distributed training in Pytorch. ​ So I have two models (net1 and net2) and I have two dataloaders for training and testing (train\_dl and test\_dl). I also have two available GPUs ("cuda:0" and "cuda:1"). There is a function called "training" that takes a model and two dataloders and returns the testing accuracy. How do I use this function a the same time? [net1.to](https://net1.to)("cuda:0") [net2.to](https://net2.to)("cuda:1") accuracy1 = training(net1, train\_dl, test\_dl) accuracy2 = training(net2, train\_dl, test\_dl) ​ What do I need to do to make the last two lines to execute at the same time? Simultaneously, not sequentially. I read something about "spawn" in the Pytorch distributed packages, but I have no clue of how to implement it. The simplest solution would be appreciated. ​ Thank you! ​ **EDIT:** I should mention that this is for a Neuroevolution project. This means, I have, say, 10 networks saved in python list. I need to train them all, and I have two GPUs. To speed up the process, I'm going to take the networks in groups of two networks to train them. This means that I need to be able to train them at the same time inside the same program/script.
1
t3_jqzfsy
1,604,935,109
pytorch
How does Pytorch handles BackPropagation in this case?
Hello! I have a question. Let's say I have this network example. class NetExple(nn.Module): def \_\_init\_\_(self): super(NetExple,self).\_\_init\_\_() self.fc1 = nn.Linear(784,128) self.fc2 = nn.Linear(128,64) self.fc3 = nn.Linear(64,10) def forward(self,x,mask1, mask2): x = F.relu(self.fc1(x)) x = x \* mask1 x = F.relu(self.fc2(x)) x = x \* mask2 x = F.softmax(self.fc3(x),dim=1) return x A custom mask is multiplied (This mask is customized). In this case, how does Pytorch handles backpropagation? Does it still apply the mask1/mask2 on the gradients during BackProp? Thanks a lot!
0.84
t3_jqw27b
1,604,921,717
pytorch
In-reproducible loss/result for Bert model training with same settings but >=2 times
Hi there, ​ I am using my customized bert script to train a model. However, everything even I keep the same setting for lr, AdamW weight decay and epoch, and run on the same platform (cuda on SageMaker) with same torch (1.5.0) and transformers (2.11.0) versions, the results still change a lot in terms of the loss. This make my different experiments not comparable. ​ Can someone who has experienced this before or have any ideas please advice me on what should I do? I really want to solve this inreproducible issue so that I can continue on my experiments. Super appreciated for your help! ​ ​ Details as below: ​ For example, if I set epoch = 4, lr = 1e-5, decay for AdamW as 0.01. For one run I got this result for the first epoch only showing the last complete 100 batches result: `2020-10-19 03:45:29,032 - utils - INFO - | epoch 1 | 1300/ 1320 batches | lr 2.261e-05 | loss 0.267 | Elapsed 0:12:29` `2020-10-19 03:45:40,550 - utils - INFO - Training epoch took: 0:12:41` `2020-10-19 03:45:40,550 - utils - INFO - Validating...` `2020-10-19 03:46:14,588 - utils - INFO - | loss 0.019 | Elapsed 0:00:34` `precision recall f1-score support` `False 0.906472 0.979875 0.941745 2087.000000` `True 0.475000 0.152610 0.231003 249.000000` `accuracy 0.891695 0.891695 0.891695 0.891695` `macro avg 0.690736 0.566243 0.586374 2336.000000` `weighted avg 0.860480 0.891695 0.865986 2336.000000` `2020-10-19 03:46:15,403 - utils - INFO - Testing...` `2020-10-19 03:46:55,182 - utils - INFO - use model: 1 batch / 1319 step` `precision recall f1-score support` `False 0.906 0.984 0.944 2344.000` `True 0.413 0.098 0.159 265.000` `accuracy 0.894 0.894 0.894 0.894` `macro avg 0.659 0.541 0.551 2609.000` `weighted avg 0.856 0.894 0.864 2609.000` `2020-10-19 03:46:55,188 - utils - INFO - best test F1 score: 0.8638224640164368` ​ And for the second attempt I got this for the first epoch: `2020-11-07 17:08:08,821 - utils - INFO - | epoch 1 | 1300/ 1320 batches | lr 2.261e-05 | loss 0.286 | Elapsed 0:12:25` `2020-11-07 17:08:20,487 - utils - INFO - Training epoch took: 0:12:37` `2020-11-07 17:08:20,487 - utils - INFO - Validating...` `2020-11-07 17:08:54,609 - utils - INFO - | loss 0.018 | Elapsed 0:00:34` `precision recall f1-score support` `False 0.893408 1.000000 0.943703 2087.000000` `True 0.000000 0.000000 0.000000 249.000000` `accuracy 0.893408 0.893408 0.893408 0.893408` `macro avg 0.446704 0.500000 0.471852 2336.000000` `weighted avg 0.798177 0.893408 0.843112 2336.000000` `2020-11-07 17:08:55,313 - utils - INFO - Testing...` `2020-11-07 17:09:34,934 - utils - INFO - use model: 1 batch / 1319 step` `precision recall f1-score support` `False 0.898 1.000 0.946 2344.000` `True 0.000 0.000 0.000 265.000` `accuracy 0.898 0.898 0.898 0.898` `macro avg 0.449 0.500 0.473 2609.000` `weighted avg 0.807 0.898 0.850 2609.000` `2020-11-07 17:09:34,938 - utils - INFO - best test F1 score: 0.8503599608647853` ​ Note that, the last used lr rate per 100 batches are the same, while the average loss per 100 batches are slightly different. But this result in the predictions for the validation and testing data set very different. ​ I already set the seed during my model with this function below: ​ `def set_seed(seed):` `""" Set all seeds to make results reproducible (deterministic mode).` `When seed is a false-y value or not supplied, disables deterministic mode. """` `random.seed(seed)` `np.random.seed(seed)` `torch.manual_seed(seed)` `torch.cuda.manual_seed_all(seed)` `torch.backends.cudnn.deterministic = True` `torch.backends.cudnn.benchmark = False` ​ The model is just using the bert layers + nn.linear layer on the top.
1
t3_jq3agg
1,604,800,702
pytorch
Prepare strings for prediction using torchtext
Hey all :) There are good instructions on how train a model using torchtext. But how do I preper it to production? **How to create a PREDICT pipeline?** Cuz the eval function is simple - I have everything ready to go. **How to preper some new data in the same way?** For example, here is some standard training process: tokenize => padding => split=> iterator ​ tokenizer = BertTokenizer.from_pretrained('bert-base-uncased') # Model parameter MAX_SEQ_LEN = 32 PAD_INDEX = tokenizer.convert_tokens_to_ids(tokenizer.pad_token) UNK_INDEX = tokenizer.convert_tokens_to_ids(tokenizer.unk_token) # Fields id_field = Field(sequential=False, use_vocab=False, batch_first=True, dtype=torch.float) label_field = Field(sequential=False, use_vocab=False, batch_first=True, dtype=torch.float) text_field = Field(use_vocab=False, tokenize=tokenizer.encode, lower=False, include_lengths=False, batch_first=True, fix_length=MAX_SEQ_LEN, pad_token=PAD_INDEX, unk_token=UNK_INDEX) fields = [('id',id_field), ('message', text_field),('label', label_field),] # TabularDataset train, valid, test = TabularDataset.splits(path=data_dir, train='train.csv', validation='valid.csv',test='test.csv', format='CSV', fields=fields, skip_header=True) # Iterators train_iter = BucketIterator(train, batch_size=16, sort_key=lambda x: len(x.message), device=device, train=True, sort=True, sort_within_batch=True) valid_iter = BucketIterator(valid, batch_size=16, sort_key=lambda x: len(x.message), device=device, train=True, sort=True, sort_within_batch=True) test_iter = Iterator(test, batch_size=16, device=device, train=False, shuffle=False, sort=False) **How to prepare a simple list of strings for the model to predict?** list_of_sentences= ['not sure, still in progress', 'Yes', 'How can I increase my mbps', 'I have had to call every single month', 'Hi! Can you help me get started with my new phone?'] ] ....? ....? ....? model(please_predict_this) Thanks :)
1
t3_jp27ha
1,604,655,104
pytorch
Image Classification with OpenCV Java
We have used OpenCV with C++ and Python API and now we have a surprise for you. In this blog, we will show an example of how it can be used in a 3rd language - Java - using OpenCV Java API. https://www.learnopencv.com/image-classification-with-opencv-java-2/ Here is what we will do in the blog post: 1. Convert the MobileNet classification model trained in PyTorch to ONNX 2. Check the model prediction on a simple example 3. Construct a Java pipeline for image classification https://preview.redd.it/9utokc01ujx51.png?width=600&format=png&auto=webp&s=86e2a73805fbd10245ab289674c0cb3caeca8089
0.67
t3_joyr9z
1,604,638,352
pytorch
2x 2080 Ti vs 1x 3080?
What would you rather get?
1
t3_jomks9
1,604,596,179
pytorch
Is this loss function differentiable?
I am trying to develop a loss function by combining dice loss and cross-entropy loss for semantic segmentation (Multiclass). Got the idea from [this](https://www.kaggle.com/bigironsphere/loss-function-library-keras-pytorch#BCE-Dice-Loss) (Look at DiceBCELoss class for PyTorch), but it's for single class. I want an exact definition for multiclass for which I have written this code in my forward method, (`inputs` are predictions from model & `targets` is ground truth tensor one-hot encoded from masks. Both are of shape `(batch_size, C, H, W)`) inputs = F.softmax(inputs, 1) CE = F.cross_entropy(inputs, torch.argmax(targets, 1), reduction='mean') inputs = inputs.view(-1) targets = targets.view(-1) intersection = (inputs * targets).sum() dice_loss = 1 - (2.*intersection + smooth)/(inputs.sum() + targets.sum() + smooth) Dice_CE = CE + dice_loss return Dice_CE The problem is cross-entropy requires `targets` tensor to contain values b.w. 0 to C-1. And in dice loss, targets need to be one-hot encoded. So I chose to apply `torch.argmax` on targets (which is already one-hot encoded) to find cross-entropy loss. But I saw somewhere that `torch.argmax` is not differentiable, though I only use it on `targets`. So I am confused, is this loss function differentiable? If not how can I make it differentiable? Thanks for your time.
1
t3_jojoau
1,604,586,497
pytorch
Is this a good way to use pytorch to build dense cnn?
I'm new to pytorch and I'm trying to build a dense cnn architecture. So I made 4 classes DenseUnit, DenseBlock, BottleNeck and Output. class DenseUnit(nn.Module): def __init__(self,in_channels): def forward(self, x): return x class DenseBlock(nn.Module): def __init__(self,in_channels): def forward(self, x): for _ in range(12): return x class BottleNeck(nn.Module): def __init__(self,in_channels): def forward(self, x): return x class Output(nn.Module): def __init__(self,in_channels): def forward(self, x): return x and finally I'm using these class objects in my model's `__init__()` and `forward()` to build my model. I have sent a random input and it gives me output without errors, but when used model summary it shows 0 trainable params for denseblocks. I'm wondering am I using pytorch correctly? If yes, how can I get params info for class objects too.
1
t3_jn8wsa
1,604,404,129
pytorch
Suggested Environment for Developing C++/Cuda Extensions in Windows 10
I am trying to write a c++ extension using CUDA libraries in windows 10 following the tutorial \[here\]([https://pytorch.org/tutorials/advanced/cpp\_extension.html](https://pytorch.org/tutorials/advanced/cpp_extension.html)) I have python 3.6.11, pytorch 1.8.0.dev20201021, rtx 3080 gpu, cuda 11.1. I ended up getting pytorch c++ 1.7 (stable/debug) with cuda 11.0 working in Microsoft Visual Studio 2019 v 16.6.5 with the cl.exe compiler, and I am wondering what is the best way to write code with syntax completion, debugging abilities so that when I run python [setup.py](https://setup.py) install, that I can be sure it will work. Questions are what is your suggested environment/debugging tools for windows 10 ? Do I need to use Nvidia Nsight Compute to debug the Cuda Code? What flags will I need to pass in to the nvcc compiler (c++11 and maybe --gpu-architecture=compute\_86 --gpu-code=sm\_86) Should I use debug/release pytorch c++ ? ​ My question with code is in the discuss pytorch forum here [https://discuss.pytorch.org/t/suggested-environment-for-developing-c-cuda-extensions-in-windows-10/101426](https://discuss.pytorch.org/t/suggested-environment-for-developing-c-cuda-extensions-in-windows-10/101426) ​ Any tips or insights very much appreciated, would be happy to provide more information.
1
t3_jn1erz
1,604,368,230
pytorch
Multi GPU Training
I want to test the performance of a power supply unit by accelerating multiple GPU usage. I have 6 parallel GTX 1050 ti. Looking for a deep learning program which will take long time to train and put pressure on the GPUs. I will use the CUDA platform, can anyone help me out with this?
0.67
t3_jn0vz5
1,604,366,377
pytorch
Weights resets after each kfold?
Is is normal that the weights 'resets' after each kfold run ? Because the loss value seems to be poor at the beginning of each training iteration. Or do I have to load the best weights for every kfold in some way? ​ for n in range(EPOCHS):         num\_epochs\_run=n         train\_loss= eng.train(train\_loader)         valid\_loss= eng.validate(valid\_loader)         score +=train\_loss         score\_v +=valid\_loss \#Early stopping checking if model validation loss does imporve other wise stop after n steps. \#Bstops if no improves is seen  if valid\_loss < best\_loss:             epochs\_no\_improve=0             best\_loss= valid\_loss print( f"Best loss: {best\_loss} at epoch: {n}") if n==EPOCHS:                 torch.save(model.state\_dict(),f"fold{fold}-epoch{num\_epochs\_run}.pth") else:             epochs\_no\_improve += 1 if epochs\_no\_improve == early\_stopping: print(f" Early stopping at epoch: {n}")                 early\_stop= True                 torch.save(model.state\_dict(),weights\_path+'best\_pytorch\_weights.pth') break else: continue if early\_stop: print('Stopped') \#torch.save(model.state\_dict(),weights\_path+'best\_pytorch\_weights.pth') break
1
t3_jmcx8l
1,604,274,858
pytorch
Weights resets after each epoch?
Is is normal that the weights 'resets' after each kfold run ? Because the loss value seems to be poor at the beginning of each training iteration. Or do I have to load the best weights for every kfold in some way? https://preview.redd.it/sajzy1pwrpw51.png?width=336&format=png&auto=webp&s=582ce271f99915c8fb1b3829bfc06ae9cb7f63c0 This is the model training code for n in range(EPOCHS): num\_epochs\_run=n train\_loss= eng.train(train\_loader) valid\_loss= eng.validate(valid\_loader) score +=train\_loss score\_v +=valid\_loss \#Early stopping checking if model validation loss does imporve other wise stop after n steps. \#Bstops if no improves is seen  if valid\_loss < best\_loss: epochs\_no\_improve=0 best\_loss= valid\_loss print( f"Best loss: {best\_loss} at epoch: {n}") if n==EPOCHS: torch.save(model.state\_dict(),f"fold{fold}-epoch{num\_epochs\_run}.pth") else: epochs\_no\_improve += 1 if epochs\_no\_improve == early\_stopping: print(f" Early stopping at epoch: {n}") early\_stop= True torch.save(model.state\_dict(),weights\_path+'best\_pytorch\_weights.pth') break else: continue if early\_stop: print('Stopped') \#torch.save(model.state\_dict(),weights\_path+'best\_pytorch\_weights.pth') break
0.75
t3_jmcmin
1,604,273,738
pytorch
How to use PyTorch’s DataLoader together with skorch’s GridSearchCV
I have a question on how to use PyTorch’s DataLoader together with skorch’s GridSearchCV, which I have posted here in stackoverflow: https://stackoverflow.com/questions/64628130/how-to-use-pytorch-s-dataloader-together-with-skorch-s-gridsearchcv Would really appreciate any help on this. Many thanks in advance.
1
t3_jlvrmt
1,604,201,161
pytorch
CNN: accuracy and loss are increasing and decreasing
Hello, i am trying to create 3d CNN using pytorch. the problem that the accuracy and loss are increasing and decreasing (accuracy values are between 37% 60%) NOTE: if I delete dropout layer the accuracy and loss values remain unchanged for all epochs Do you know what I am doing wrong here? Thanks in advance! import numpy as np import torch torch.autograd.set_detect_anomaly(True) REBUILD_DATA = True # set to true to one once, then back to false unless you want to change something in your training data. import time start_time = time.time() import os import cv2 import numpy as np import nibabel as nib from nibabel.testing import data_path from sklearn.utils import shuffle import matplotlib.pyplot as plt import cv2 from sklearn.metrics import ConfusionMatrixDisplay# Build the confusion matrix of our 2-class classification problem from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score # for evaluating the model import torch # PyTorch libraries and modules import torch.nn as nn import torch.nn.functional as F from torch.optim import * from sklearn.metrics import classification_report import seaborn as sns # color of graphe '''from owlready2 import * import textdistance ''' import numpy as np #Channels ordering : first channel (taille , shape of each element ) to ==> last channel ( shape, size ) def changechannel(data, a, b): data = np.asarray(data) data = np.rollaxis(data, a, b) return(data) # convert (240,240,155) to ======> (120, 120, 120) # def resize3Dimages(data): train_x = [] for i in range(len(data)): image = data[i] width = 120 height = 120 img_zeros = np.zeros((len(image), width, height)) #### len(image) means the first dim /// in other words shape[0] for idx in range(len(image)): img = data[i][idx, :, :] img_sm = cv2.resize(img, (width, height), interpolation=cv2.INTER_CUBIC) #une interpolation bicubique sur un voisinage de 4 × 4 voxels img_zeros[idx, :, :] = img_sm # convert (240,120,120) to ======> (120,120,120) img_zeros = img_zeros[::2, :, :] ### 240/2 =120 train_x.append(img_zeros) ############################# save images in list ################################ return(np.asarray(train_x)) ## convert list to nd array # end ... # 1 channel to 3 channel def channel1to3 (data): data = np.stack((data,) * 3, axis=-1) return(data) print(" preprocessing --- %s seconds ---" % (time.time() - start_time)) print('Building of CNN') import os # for reading and displaying images import matplotlib.pyplot as plt # for evaluating the model from sklearn.metrics import accuracy_score # PyTorch libraries and modules import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import * num_classes = 2 # Create CNN Model class CNNModel(nn.Module): def __init__(self): super(CNNModel, self).__init__() self.conv_layer1 = self._conv_layer_set(3, 32) self.conv_layer2 = self._conv_layer_set(32, 64) self.conv_layer3 = self._conv_layer_set(64, 128) self.conv_layer4 = self._conv_layer_set(128, 256) self.conv_layer5 = self._conv_layer_set(256, 512) self.fc1 = nn.Linear(512, 128) self.fc2 = nn.Linear(128, num_classes) self.relu = nn.ReLU() self.batch=nn.BatchNorm1d(128) self.drop=nn.Dropout(p=0.6, inplace = True) def _conv_layer_set(self, in_c, out_c): conv_layer = nn.Sequential( nn.Conv3d(in_c, out_c, kernel_size=(3, 3, 3), padding=0), nn.ReLU(), nn.MaxPool3d((2, 2, 2)), ) return conv_layer def forward(self, x): # Set 1 out = self.conv_layer1(x) out = self.conv_layer2(out) out = self.conv_layer3(out) out = self.conv_layer4(out) out = self.conv_layer5(out) out = out.view(out.size(0), -1) out = self.fc1(out) out = self.relu(out) out = self.batch(out) # batchnormalization out = self.drop(out) out = self.fc2(out) #out = F.softmax(out, dim=1) return out #Definition of hyperparameters n_iters = 2 num_epochs =25 # Create CNN model = CNNModel() model.cuda() # GPU print(model) # Cross Entropy Loss for param in model.parameters(): param.requires_grad = False # prendre false si "you want to freeze model weights" TRUE si le poids change error = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.000001) ###################################################accuracy function ################################## def accuracyCalc (predicted, targets): correct = 0 p = predicted.tolist() t = targets.flatten().tolist() # flatten [[0],[1]] ===> [1,0] tolist for i in range(len(p)): if (p[i] == t[i]): correct +=1 accuracy = 100 * correct / targets.shape[0] return(accuracy) ####################################################################################################### print(" build model --- %s seconds ---" % (time.time() - start_time)) #######################################################{{{{{{{training}}}}}}}################################## print('data preparation ') training_data = np.load("Datasets/brats/Train/training_data.npy", allow_pickle=True) targets = np.load("Datasets/brats/Train/targets.npy", allow_pickle=True) from sklearn.utils import shuffle training_data, targets = shuffle(training_data, targets) training_data = changechannel(training_data, 1, 5) #Channels ordering : first channel to ==> last channel' training_data = resize3Dimages(training_data) #resize images training_data = channel1to3(training_data,)#1 channel to 3 channel ===> RGB training_data = changechannel(training_data, 4, 1)# last to first #Definition of hyperparameters loss_list_train = [] accuracy_list_train = [] for epoch in range(num_epochs): outputs = [] outputs= torch.tensor(outputs).cuda() for fold in range(0, len(training_data), 4): # we will take 4 images xtrain = training_data[fold : fold+4] xtrain =torch.tensor(xtrain).float().cuda() # GPU xtrain = xtrain.view(4, 3, 120, 120, 120) # Clear gradients # Forward propagation optimizer.zero_grad() v = model(xtrain) outputs = torch.cat((outputs,v.detach()),dim=0) # Calculate softmax and ross entropy loss targets = torch.Tensor(targets) labels = targets.cuda() outputs = torch.tensor(outputs, requires_grad=True) _, predicted = torch.max(outputs, 1) accuracy = accuracyCalc(predicted, targets) labels = labels.long() labels=labels.view(-1) # loss = nn.CrossEntropyLoss() loss = loss(outputs, labels) # Calculating gradients loss.backward() # Update parameters optimizer.step() loss_list_train.append(loss.data) accuracy_list_train.append(accuracy/100) np.save('Datasets/brats/accuracy_list_train.npy', np.array(accuracy_list_train)) np.save('Datasets/brats/loss_list_train.npy', np.array(loss_list_train)) print('Iteration: {}/{} Loss: {} Accuracy: {} %'.format(epoch+1, num_epochs, loss.data, accuracy)) print('Model training : Finished') ​ result is : Iteration: 1/25 Loss: 0.8488530516624451 Accuracy: 48.0 % Iteration: 2/25 Loss: 0.7767133116722107 Accuracy: 48.0 % Iteration: 3/25 Loss: 0.7962564826011658 Accuracy: 52.0 % Iteration: 4/25 Loss: 0.7540275454521179 Accuracy: 49.333333333333336 % Iteration: 5/25 Loss: 0.9554114937782288 Accuracy: 38.666666666666664 % Iteration: 6/25 Loss: 0.8776708245277405 Accuracy: 45.333333333333336 % Iteration: 7/25 Loss: 0.9581964015960693 Accuracy: 37.333333333333336 % Iteration: 8/25 Loss: 0.8645199537277222 Accuracy: 52.0 % Iteration: 9/25 Loss: 0.862994909286499 Accuracy: 50.666666666666664 % Iteration: 10/25 Loss: 0.6595868468284607 Accuracy: 60.0 % Iteration: 11/25 Loss: 0.8252826929092407 Accuracy: 45.333333333333336 % ​
0.75
t3_jlgwrw
1,604,144,194
pytorch
A template to write my first neural network (that classifies digits) with pytorch??
I have searched a lot, and I am still confused. Is there any easy guide to write a neural network in pytorch? I work on the classic example with digits - image classification).
1
t3_jlf0ku
1,604,133,786
pytorch
current GPU recommendation for pytorch
Hi i am building a new computer specifically for pytorch ML and looking to make a purchase around December. First question, are AMD rx 6000 series compatible with pytorch? I hear the nvidia rtx 3080/3090 are not very well optimized for pytorch at the moment, when is it likely developers will make full use of these cards? How do these cards compare to the rtx 2000 series in terms of performance at the moment with torch?
1
t3_jl1a15
1,604,079,253
pytorch
Struggling with moving code over to a GPU, Reposted with link to forum with better formatting.
nan
1
t3_jkkxz8
1,604,012,517
pytorch
Tips for training PyTorch models on TPUs
I spend the last few weeks getting my PyTorch code working on TPUs. I made a short thread on points that might be helpful ([https://twitter.com/KaliTessera/status/1321454533671870466](https://twitter.com/KaliTessera/status/1321454533671870466)).
1
t3_jjok7x
1,603,894,644
pytorch
MRI Image Classification : A step by step guide
Today we have an exciting post on Classifying Knee MRI images using Deep Learning. In this post, you will learn 1. What an MRI dataset looks like. 2. What is Stanford MRNet Challenge 3. How to create an AI model for MRI data classification 4. Results 5. Suggestions for alternative approaches. [https://www.learnopencv.com/stanford-mrnet-challenge-classifying-knee-mris/](https://click.convertkit-mail.com/v8u6ek0726urhm5krpcw/9qhzhdu277vrwkf9/aHR0cHM6Ly93d3cubGVhcm5vcGVuY3YuY29tL3N0YW5mb3JkLW1ybmV0LWNoYWxsZW5nZS1jbGFzc2lmeWluZy1rbmVlLW1yaXMv) and the **PyTorch code** is at [https://github.com/spmallick/learnopencv/tree/master/MRNet-Single-Model](https://click.convertkit-mail.com/v8u6ek0726urhm5krpcw/3ohphdudww5gmoar/aHR0cHM6Ly9naXRodWIuY29tL3NwbWFsbGljay9sZWFybm9wZW5jdi90cmVlL21hc3Rlci9NUk5ldC1TaW5nbGUtTW9kZWw=) https://preview.redd.it/xmovkhbp4pv51.jpg?width=600&format=pjpg&auto=webp&s=641c1e7b4ed9d23edb12b8e7c95939822aa943d0
1
t3_jj91ge
1,603,830,081
pytorch
PyTorch 1.7 released w/ CUDA 11, New APIs for FFTs, Windows support for Distributed training and more
nan
0.98
t3_jj8dbc
1,603,828,056
pytorch
IDE for python (pytorch)
Hallo, I recently trying to migrate from **MATLAB** to **python**. I am trying to find a decent **IDE**. I work with **pytorch** mostly. I find **Spyder** very appealing due to variable explorer (reminds me MATLAB). However I read that **Visual Studio** is more widely used. Also I see that **jupyter** is good for the "portability". Any guidance here?
0.5
t3_jj2cub
1,603,809,651
pytorch
Cannot move batch of images to gpu
Hello, I have a "train" method as shown below. When I run it, I get an error that my input and weight type should be the same - which I understand as meaning that my network has been pushed to the GPU but my batch of images has not been. Indeed, when I print out the device of my batch of images it says it is still on the CPU even though doing basically the same thing to the network moves it to the GPU. Do you know what I am doing wrong here? Thanks in advance! ​ def train(net, trainset, testset, n, bs): device = torch.device('cuda:0') net.to(device) o = optim.Adam(net.parameters(), lr=0.01) trainloader = torch.utils.data.DataLoader(trainset, batch_size=bs) testloader = torch.utils.data.DataLoader(testset, batch_size=bs) best_net = net best_loss = float('inf') #This is the epoch loop - one execution = one epoch for e in range(n): total_loss = 0 total_accuracy = 0 validation_loss = 0 validation_accuracy = 0 #Will need gradient while training... net.requires_grad = True #Get all batches... for batch in trainloader: images, labels = batch images.to(device) labels.to(device) for l in net.parameters(): print(l.device) print(images.device) #Get predictions from the network preds = net(images) output from print statements: cuda:0 cuda:0 cuda:0 cuda:0 cuda:0 cuda:0 cuda:0 cuda:0 cuda:0 cuda:0 cpu Error Message: RuntimeError Traceback (most recent call last) <ipython-input-107-764051b26d04> in <module> ----> 1 bnet = train(net, train_set, test_set, 10, 100) <ipython-input-106-c6b2a1bc7e39> in train(net, trainset, testset, n, bs) 30 31 #Get predictions from the network ---> 32 preds = net(images) 33 34 #Find the loss ~/miniconda3/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 720 result = self._slow_forward(*input, **kwargs) 721 else: --> 722 result = self.forward(*input, **kwargs) 723 for hook in itertools.chain( 724 _global_forward_hooks.values(), <ipython-input-10-fd501e1e41e9> in forward(self, t) 14 15 #Layer 1 ---> 16 t = self.conv1(t) 17 t = F.relu(t) 18 t = F.max_pool2d(t, kernel_size=2, stride=2) ~/miniconda3/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs) 720 result = self._slow_forward(*input, **kwargs) 721 else: --> 722 result = self.forward(*input, **kwargs) 723 for hook in itertools.chain( 724 _global_forward_hooks.values(), ~/miniconda3/lib/python3.7/site-packages/torch/nn/modules/conv.py in forward(self, input) 417 418 def forward(self, input: Tensor) -> Tensor: --> 419 return self._conv_forward(input, self.weight) 420 421 class Conv3d(_ConvNd): ~/miniconda3/lib/python3.7/site-packages/torch/nn/modules/conv.py in _conv_forward(self, input, weight) 414 _pair(0), self.dilation, self.groups) 415 return F.conv2d(input, weight, self.bias, self.stride, --> 416 self.padding, self.dilation, self.groups) 417 418 def forward(self, input: Tensor) -> Tensor: RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same ​
1
t3_jirz7v
1,603,762,219
pytorch
Loss flattens out
Hi all, I made a post on the Pytorch forums about my issue, please could someone help? [https://discuss.pytorch.org/t/loss-flattens-out/100699](https://discuss.pytorch.org/t/loss-flattens-out/100699) \-------------------------------------------------- I have worked on a couple of projects now where I have constructed a neural net for binary classification and something like this has happened. This leads me to believe it's something to do with how I am programming it rather than the data itself. I have tried all kinds of things, even posted here before but I'm not sure why. I did not recycle my own code or anything so I don't know how this problem persists across projects. ​ The model is simple: `# A simple binary classification model` `class BinaryClassifier(nn.Module):` `def __init__(self, input_size, hidden_size, num_classes=1):` `super().__init__()` `self.input_size = input_size` `self.num_classes = num_classes` `self.linear1 = nn.Linear(input_size, hidden_size)` `self.linear2 = nn.Linear(hidden_size, num_classes)` `self.relu = nn.ReLU()` `def forward(self, x):` `x = self.linear1(x)` `x = self.relu(x)` `x = self.linear2(x)` `return x` I have set num\_classes as 1 in order to get a probability that the label is 1. I wasn't sure how else to structure this binary classification. I use BCEWithLogitsLoss, Adam with a StepLR scheduler `model = BinaryClassifier(X_tensor.shape[1], 512)` `criterion = nn.BCEWithLogitsLoss()` `optimizer = torch.optim.Adam(model.parameters(), lr=lr)` `scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.5)` It's worth mentioning here I only added the scheduler to fix the problem and it did improve the loss but not the flattening out effect. This is how I train the model: `def sub_train_(model, dataloader):` `model.train()` `losses = list()` `for idx, (X, y) in enumerate(dataloader):` `out = model(X)` `loss = criterion(out, y.unsqueeze(1))` `optimizer.zero_grad()` `loss.backward()` `optimizer.step()` `losses.append(loss.item())` `return np.mean(losses), model` ​ `def train(model, trainloader, testloader, scheduler, n_epochs):` `best_model = model` `best_loss = math.inf` `ts = time.time()` `losses = list()` `for epoch in range(n_epochs):` `train_loss, model = sub_train_(model, trainloader)` `test_loss = sub_valid_(model, testloader)` `scheduler.step()` `losses.append(train_loss)` `if train_loss < best_loss:` `best_loss = train_loss` `best_model = model` `print('Epoch: {}, train_loss: {}, test_loss: {}'.format(` `epoch, train_loss, test_loss` `))` `te = time.time()` `fig, ax = plt.subplots()` `ax.plot(range(n_epochs), losses)` [`plt.show`](https://plt.show)`()` `mins = int((te-ts) / 60)` `secs = int((te-ts) % 60)` `print('Training completed in {} minutes, {} seconds.'.format(mins, secs))` `return losses, best_model` And every time it yields a loss plot like this: https://preview.redd.it/ocwt26vg0iv51.png?width=457&format=png&auto=webp&s=dcc9935fa17cc008a488d659ffc9a66dbda20069 ​ What am I doing wrong here? How can I avoid this happening? Thank you in advance to anyone who helps me out with this!
0.67
t3_jimfls
1,603,743,813
pytorch
Pytorch hackathon went against its own rules, who should I contact?
For your reference, [this](https://pytorch2020.devpost.com/project-gallery) is the link to the hackathon. According to the [rules](https://imgur.com/a/oFyw8Ia), there are honorable mention prizes for those who are scoring 3rd to 8th. Although it is not a big deal to most, I find that people should be correctly awarded the right prize given the circumstance. Edit: As you can clearly see, there are no honorable mention prizes given to participants Thus I asked twice, [once](https://imgur.com/a/pbAw9mF) in the official slack channel where I got straight up ignored, and on the [official](https://imgur.com/Zv5er2d) devpost q/a section, where the manager was irresponsive. This is a literal shot in the dark but what should I do to solve this?? To whom do I even contact at this point?
0.43
t3_jhwdoe
1,603,643,866
pytorch
Matrix-NMS Questions
nan
1
t3_jhui6a
1,603,637,243
pytorch
How does one install custom binaries for the Knights Landing CPU architecture for PyTorch?
nan
0.5
t3_jhsy7w
1,603,630,792
pytorch
Does DataLoader accept string values as labels? What values does it accept?
I'm trying to train a simple classifier with PyTorch, and in an attempt to do something other than just follow along a tutorial I am training it to classify lists into two categories: "repeating" and "increasing". So I tried to build some code to work with DataLoader, as I'm generating these lists. It looks like this: class ListDataset (Dataset): def __init__(self, num_lists = num_data, verbose = 0): x_data = [] y_data = [] # Generate the appropriate number of lists for i in range (num_lists): x, y = generate_list(verbose=verbose) x_data.append(x) y_data.append(y) # Record, though I could have done this with less code self.x_data = x_data self.y_data = y_data self.length = len(self.x_data) print(self.y_data) print(self.y_data[0]) It's not working properly, when I try to call `label =` [`label.to`](https://label.to)`(self.device)` I get the error `AttributeError: 'tuple' object has no attribute 'to'` and printing the label before that gives something which looks like this: `("increasing", "repeating" .... "repeating", "increasing")` The problem is not with this part of the code, as it was pretty much lifted from a tutorial. I'm sure that the problem is with the data code, but I'm not quite sure, is it that my labels are strings? What should they be? 1 and 0 ints?
1
t3_jhqlny
1,603,617,816
pytorch
A new deep learning computer vision library!
Hi guys, I hope you are well and healthy! I have put together a compact, concise, and customizable deep learning computer vision library called "glasses". Github: [https://github.com/FrancescoSaverioZuppichini/glasses](https://github.com/FrancescoSaverioZuppichini/glasses) Website: [https://francescosaveriozuppichini.github.io/glasses-webapp/](https://francescosaveriozuppichini.github.io/glasses-webapp/) It is the first beta so there are a lot of missing models and features that I will add in the future. I do computer vision for a living and I wanted to have a flexible easy to use tool for my daily work. Most of the current libraries are very badly written with tons of code repetition and not very easy to customize. Moreover, it is hard to understand how most models are implemented and I hope my library will make it easier for new people in the field. Unfortunately, I still haven't found a good place to host the pre-trained models so they are not available at the moment (any suggestions?) I also would like to know if anyone wants to help me out with some feedback or in the coding!
0.96
t3_jhc7od
1,603,558,200
pytorch
Dynamic Sky Replacement and Harmonization in Videos
nan
1
t3_jh1uxv
1,603,509,829
pytorch
scatter_add reduce output dimensions/shape
I have memory issues with the scatter\_add function. The standard implementation computes, e.g. self\[i\]\[index\[i\]\[j\]\[k\]\[m\]\]\[k\]\[m\] += src\[i\]\[j\]\[k\]\[m\], where the output, will have shape I x Index\_Max x K x M. This is often a large tensor, causing memory issues. I then sum over certain dimensions., e.g. if choose dimension 0,3 it will then compute a tensor shape 1x Index\_Max x K x 1. I am looking for an option, or workaround, to choose some of the output dimensions to have shape 1. In the example above, the scatter\_add function would compute self\[0\]\[index\[i\]\[j\]\[k\]\[m\]\]\[k\]\[0\] += src\[i\]\[j\]\[k\]\[m\] (or ignore dimensions 0,3 altogether), not computing the entire output tensor. Thank you for the suggestions!
1
t3_jgs94p
1,603,476,014
pytorch
Is there something like torch.utils.data.TensorDataset(*tensors) for TensorFlow/Keras?
I am "translating" a notebook made in Pytorch to one made in Keras. And they use that app to pack the data from a tensor into the dataset that will be used for the network. But I can't find something that fulfills that function. I would greatly appreciate the help! Pytorch documentation says that torch.utils.data.TensorDataset (* tensors) does: "Dataset wrapping tensors. Each sample will be retrieved by indexing Tensor a along the first dimension." Thank you everybody!
1
t3_jgii9y
1,603,438,254
pytorch
How to apply a safe softmax
I'm training a model that applies softmax across an axis, in the following way: x = F.softmax(x.float(), dim=-1) However, some rows in x are only -inf, leading to an output of NaN. As such, I would like these rows to be outputted with something else, like a zero vector, for example. So in affect, I want an if statement that only applies softmax when the values aren't all -inf. How does one do this in pytorch?
1
t3_jgfloz
1,603,425,306
pytorch
Experiment Logging with TensorBoard and wandb
Training a machine learning model is an iterative process. You first implement a baseline solution and measure its quality. Often, quite a few experiments need to be performed before a good solution is obtained. Once you obtain a good solution, it is important that you have all the information necessary to reproduce the same result. That’s why tracking the best hyperparameter set is so important. https://preview.redd.it/w2y64aca1ou51.jpg?width=600&format=pjpg&auto=webp&s=14345263d51671f89f187cce474e92c1690b3881 It is also cumbersome without the right tools! In today's post, we will learn how to log your experiments like a pro using these two tools. 1. **Tensorboard** 2. **Weights and Biases Developer Tools** To learn the details please check out the post below. [https://www.learnopencv.com/experiment-logging-with-tensorboard-and-wandb/](https://click.convertkit-mail.com/xmu2qe4ng2a6hk4exlbg/e0hph0unxznz08i8/aHR0cHM6Ly93d3cubGVhcm5vcGVuY3YuY29tL2V4cGVyaW1lbnQtbG9nZ2luZy13aXRoLXRlbnNvcmJvYXJkLWFuZC13YW5kYi8=)
0.5
t3_jg1wdc
1,603,380,973
pytorch
Can someone explain problems of running multiple jobs on 1 gpu?
Say I wanted to run a hyperparameter search over a model. If I was running on a CPU theres options like GridSearchCV that allows me to parallelise this process over a single CPU, resulting in a speedup. However, situations like this don't seem to exist on a GPU. I guess I could spawn several workers on a GPU and send a job to each of them. However, people seem sceptical of this approach (https://discuss.pytorch.org/t/split-single-gpu/18651/8) saying that it will not result in a performance increase. Can someone explain to me why? I thought GPUs were "good" at parallelising ML problems. They can vectorise some problems and parallelise them, so why not my neural network? What am I missing here?
1
t3_jfxi2n
1,603,364,498
pytorch
Image-Driven Furniture Style for Interactive 3D Scene Modeling
nan
1
t3_jfrvag
1,603,336,532
pytorch
Size of LSTM input
I am trying to make LSTM network and I am having some problems. Let's say I have 600 sequences each has 90 elements. What should be the size of LSTM input? Documentation imply shape \[600,1,90\] but my LSTM doesn't seem to work and I am trying to find the issue.
1
t3_je621p
1,603,128,290
pytorch
get(self, idx) vs __getitem__(self, idx) for custom datasets
Hi everyone, I'm confused about a matter regarding custom datasets and indexing. I create a custom dataset class inheriting from Dataset class. I recently noticed that I implemented the following method for getting samples: def get(self, idx): ... while people usually implement the following, as far as I've seen from the online tutorials: def _ _ getitem _ _(self, idx): ... Is there any difference between them? I tested both functions and they seem to have the same functionality. But I couldn't find anything on web to justify it. Thank you very much.
1
t3_jdzo1y
1,603,105,793
pytorch
Which state should i pass in siamese network?
I am using embedding- lstm - and confused in lstm\_out, (hidden, cell) = nn.LSTM()(..) ​ what should i take in those of three in final layer, I am not including fully connected layer here Anybody help!!
1
t3_jdwxxu
1,603,090,818
pytorch
Should I pass hidden state to LSTM with every input?
I am training LSTM network and wondering whether I should pass any hidden cell state along with input. Documentation doesn't say much about it, even in example they pass it in one case but not in the other. So, do I have to pass hidden cell state with every input or not? If yes then what does it change in training process?
1
t3_jdpk27
1,603,059,348
pytorch
Need help in implementing a pytorch equivalent.
https://discuss.pytorch.org/t/how-to-implement-pytorch-equivalent-of-keras-kernel-weight-regulariser/99773?u=paganpasta Posting the forum link to the problem as it contains a description of the problem and keras code. Any help is appreciated.
0.8
t3_jdfx1m
1,603,025,964
pytorch
HELP with encoder_decoder \ seq2seq model ?
for reference i used this code right here : [https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/more\_advanced/Seq2Seq/seq2seq.py](https://github.com/aladdinpersson/Machine-Learning-Collection/blob/master/ML/Pytorch/more_advanced/Seq2Seq/seq2seq.py) it has been a WEEK since i am trying to do a seq2seq model in Pytorch. MOST the example uses NLP but i need TIME SERIES FORECASTING. i know the teory and enough practice but i still can't make the model works. What should have been an easy task done in a day or two has turned into a nightmare week full of frustration where now i am at the point where i just wanna quit everything and go plant potato. ​ Edit. so i tried to remove the embedding layer and use Linear layer instead. and obviously use MSE loss instead of CrossEntropy. the problem is in the decoder when you do target\[0\] wich should be the first word (<sos>), but in my case it should be the fist number of every batch . Ex suppose we have batch two so the input is: (\[1,2,3,4\],\[9,10,11,12\]) and target is (\[5,6,7,8\],\[13,14,15,16\]). if i do target\[0\] i get\[5\] wich has shape 1x1 instead target\[0\] should be (\[5,13\]) wich has shape 1xbatch\_size i need this shape for the LSTM in the decoder. obviously the same problem is for the next target\[1\] and the other number in the sequence. another problem is the LSTM that require 3 dimensions : in the tutorial is used embedding and the input form shape (batch\_size,seq\_length) goes to (batch\_size,seq\_length,embedding\_features) but i just do x.unsqueeze(0) is it the same thing or is gonna be a problem ? PS. my discord is Bisd#9079
1
t3_jd14hu
1,602,961,731
pytorch
Neural net spits out same number in testing
I trained my model and after some epochs loss was very low. I tried to to test it and it spits out the same number again and again, if I add `optimizer.step()` to the testing code it works fine. Where's the problem? ​ Sorry for such basic question but I really can't think of any solution
1
t3_jczcyj
1,602,955,888
pytorch
Groundbreaking research from UWashington researchers: Remove any background noise/voice when in a video call! (See video)
nan
0.67
t3_jcnndw
1,602,903,312
pytorch
Cloud traning
I dont have nvidia gpu, what is best cloud environment where can i write scripts and train models.?
0.5
t3_jcbxtq
1,602,862,305
pytorch
A trick for training on large batches
Hi everyone, Since I'm having memory issues for training on larger batches, I thought of a trick but I'm not sure it would work. So, normally we do the following: For each batch: ¬Calculate loss ¬Back prop ¬Optimizer step ¬Optimizer zero grad Instead, I want to do the following, for instance a batch size of 1024: Set batch size equal to 1. For each batch: ¬Calculate loss ¬Back prop If (batch_idx+1) % 1024 == 0: ¬Optimizer step ¬Optimizer zero grad Would that be equivalent to training on batches of 1024 samples, since I accumulate the gradients for 1024 samples and update once for every 1024 samples? Thank you.
0.75
t3_jc97jl
1,602,852,617
pytorch
Tutorial on using PyTorch to emulate guitar amps and effects in a plugin.
nan
0.97
t3_jaz1nu
1,602,675,583
pytorch
Microsoft Joined pytorch, What about our privacy? GNU when?
I've been die hard fan of Pytorch since i encounter it. I am linux user, although I am also not fan of microsoft or facebook, but anyway, I heard microsoft joined Pytorch? what does it means? Do they track us or do survellience on us, and put our privacy at risk? ​ We would be happy if Pytorch would fan of FSF community. Thanks
0.5
t3_jax1ux
1,602,665,512
pytorch
Pytorch vs tensorflow for job opurtunities/freelancing
I have seen some charts of the popularity of pytorch going up(maybe surpassing tensorflow in the future) should I learn pytorch or tensorflow if I want to get a data scientist job / do freelancing ? Or does it not matter ?
0.88
t3_jarkh8
1,602,640,755
Python
Demo a python app in a web browser
nan
0.75
t3_udzqyt
1,651,165,264
Python
Build a Comment Toxicity Model with Deep Learning and Python
nan
0.67
t3_udzgw0
1,651,164,553
Python
Let the computer test your Python GUI application
How to [write easy automated GUI tests](https://blog.rareschool.com/2022/04/let-computer-test-your-python-gui.html) for Python applications that use guizero.
0.33
t3_udyqv0
1,651,162,650