id
stringlengths 3
8
| text
stringlengths 1
115k
|
---|---|
st45468
|
Hello,
I want to save some intermediate feature values during training. However, I failed to assign new values to existing buffers by getattr() and setattr(), the example is as follows:
class MyNetwork(nn.Module):
def __init__(self):
self.conv1 = nn.Conv2d(3, 3, 3, 1, 1)
self.conv2 = nn.Conv2d(3, 3, 3, 1, 1)
self.register_buffer('inter_feature', torch.Tensor())
self.register_buffer('count', torch.tensor(0))
self.register_buffer('weight', torch.ones(10))
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
# case1: does not work for updating self.count
count = getattr(self, 'count')
count = count + 1
setattr(self, 'count', count)
# case2: work
count = getattr(self, 'count')
count += 1
setattr(self, 'count', count)
# case3: does not work
feature = getattr(self, 'feature')
feature = x
setattr(self, 'feature', feature)
# case4: work
feature = getattr(self, 'feature')
feature.data = x.data
return x
Could you tell me how can I correctly use getattr and setattr to update buffers during training?
Thanks in advance!
|
st45469
|
Thanks for reply!
Absolutely, using self.xxx = aaa is a convenient way to update buffers. But, in my code, I need to update buffer like this:
for i in range(stages):
self.register_buffer('feature_stage{}'.format(i))
In this case, I need to access buffers by getattr(self, feature_stage{}.format(i)), and I cannot use self.feature_stage{}.format(i) = aaa to update a buffer.
Does there exist more efficient way like self.xxx = aaa for my case?
|
st45470
|
Why not use a matric like a NxM tensor, the num N is stages.
And then you could change by self.xxx[i] = aaa.
|
st45471
|
I am comparing how much faster is the matmul on GPU, surprisingly, my test result shows that running on a GPU is slower than running on a CPU.
import torch
import numpy as np
'''
Tensor shape = (batch,
attention heads,
features per head,
height,
weight,
attention window
)
Goal: We want to apply dot product
to only the last dimension
'''
# softmax score for the Query and Key
QK = torch.randn([64, 8, 4, 28, 28, 9])
# Value Tensor
V = torch.randn([64, 8, 4, 28, 28, 9])
def method1(QK, V):
"""matmul way"""
# Preparing the right shape for dot product in the lastt dimension
out1 = torch.matmul(QK.unsqueeze(-2), V.unsqueeze(-1))
# Reshape it back to the original shape
out1 = out1.squeeze(-1).squeeze(-1)
return out1
def method2(QK,V):
"""Einstein summation"""
return torch.einsum('bnchwk,bnchwk -> bnchw', QK, V)
# torch CPU
%timeit -n 500 method1(QK,V)
%timeit -n 500 method2(QK,V)
# torch GPU
QK = QK.cuda()
V = V.cuda()
%timeit -n 500 method1(QK,V)
%timeit -n 500 method2(QK,V)
Torch CPU
Method1: 2.7 ms ± 140 µs per loop (mean ± std. dev. of 7 runs, 500 loops each)
Method2: 2.64 ms ± 92.1 µs per loop (mean ± std. dev. of 7 runs, 500 loops each)
Torch GPU
Method1: 3.34 ms ± 206 µs per loop (mean ± std. dev. of 7 runs, 500 loops each)
Method1: 3.43 ms ± 123 µs per loop (mean ± std. dev. of 7 runs, 500 loops each)
Am I doing anything wrong? The result doesn’t make sense to me.
|
st45472
|
CUDA operations are asynchronously executed so you would need to synchronize your code before starting and stopping the timers via torch.cuda.synchronize() to get proper timings. Also, the operations could be executed in a loop to calculate the average time and reduce the noise a bit.
That being said, if your workload is small you won’t be able to saturate the GPU (and would also have the kernel launch overheads) and the CPU might be indeed faster.
|
st45473
|
PyTorch Developer Day 2020 | Full Livestream
Here they mention a gym environment based on compilers. But there is literally no mention of this in entire internet
|
st45474
|
Hi,
I want to resample the 3D image to (256, 256, 166) if their shapes are different.
Example: (192, 192, 160) to (256, 256, 166)
and (256, 256, 170) to (256, 256, 166) etc
I used the below code to do that(code referred from https://www.kaggle.com/mechaman/resizing-reshaping-and-resampling-nifti-files 1)
target_img_shape = (256, 256, 166)
if img_shape != target_img_shape:
resampled_nii = resample_img(image, target_affine=np.eye(4) * 2, target_shape=target_img_shape,
interpolation='nearest')
resampled_img_data = resampled_nii.get_fdata()
else:
resampled_img_data = image.get_fdata()
I am getting the required shape but the resultant image is too small. I have the following questions:
Is the above code is correct
Is there any other ways to resample the 3D image to the required size ie., (256, 256, 166)
Thank you.
|
st45475
|
Doesn’t the original interpolate function work fine for your case ?
The input dimensions are interpreted in the form: mini-batch x channels x [optional depth] x [optional height] x width.
The modes available for resizing are: nearest, linear (3D-only), bilinear, bicubic (4D-only), trilinear (5D-only), however, you can only adopt trilinear mode.
|
st45476
|
I am wondering if there is a way to get statistics like mean and standard deviation when using the Torch dataset class to batch load very large data sets.
I need to normalize my features, which means I need the standard deviation and mean for each feature column. My data has millions of rows, so it cannot fit into memory. How might I accomplish this task? Some example code:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, Subset, DataLoader
from sklearn import datasets
import pandas as pd
import numpy as np
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
X, y = datasets.make_classification(n_samples=1000,
n_features=2,
n_informative=2,
n_redundant=0,
n_classes=2,
random_state=15)
# place data into df
df = pd.DataFrame({'x1': X[:, 0], 'x2': X[:, 1], 'y': y})
df.to_csv('classification_demo.csv', index=False)
class CSVDataset(torch.utils.data.Dataset):
def __init__(self, path, chunksize, nb_samples, transform=None):
self.path = path
self.chunksize = chunksize
self.len = nb_samples // self.chunksize
self.transform = transform
def __len__(self):
return self.len
def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
x = next(
pd.read_csv(
self.path,
skiprows=idx * self.chunksize, #+1 to skip the header
chunksize=self.chunksize))
target = torch.as_tensor(x.values)[0][-1] # last col
features = torch.as_tensor(x.values)[0][0:-1] # all but last
# pull a sample in a dict
sample = {'features': features,
'target': target,
'idx': torch.as_tensor(idx)}
if self.transform:
sample = self.transform(sample)
return sample
# instantiate the lazy data set
csv_dataset = CSVDataset('classification_demo.csv', chunksize=1, nb_samples=1000, transform=None)
|
st45477
|
I think you could calculate them before training. If you data is changing you could write a func to do it when dataset init.
|
st45478
|
LeNet architecture is like this:
CONV1->RELU1->POOL1-> CONV2->RELU2->POOL2)-> FC1->RELU->…
Suppose, in forward pass, I want to modify the output of RELU1 and then rewrite the modified version before going to POOL1 layer so that it would reflect on backward pass.
In pytorch, how can I achieve this?
|
st45479
|
Solved by mHr029 in post #3
Thank you for your help.
But I fixed this by declaring custom ReLU class to make an effect on backward pass.
|
st45480
|
You could use forward hooks as described here 4 and manipulate the output inplace in the hook.
|
st45481
|
Thank you for your help.
But I fixed this by declaring custom ReLU class to make an effect on backward pass.
|
st45482
|
Hello Experts,
I am trying to deploy a pytorch model into mediapipe. Was wondering if anyone has done such deployment into mediapipe and used it? As of now, i have mediapipe installed in my ubuntu…
Thanks
Amit
|
st45483
|
If you can convert your model to a format supported by mediapipe, that’s the easiest solution. I’ve toyed around with writing a calculator for mediapipe supporting pytorch here: https://github.com/dsuess/mediapipe-pytorch 158. It’s just a very basic setup, but it can easily be extended and refactored into separate modules for tensor conversion, inference, etc.
The biggest challenge I ran into is the build environment: pytorch has a bazel environment for linux, so that’s not too hard to get working. However, as far as I can tell, you need to use cmake for the Android/iOS builds, so that’s more challenging. What finally stopped me is the lack of GPU support on mobile in pytorch ATM.
|
st45484
|
I have a model mimicking the region proposal network(rpn) of faster r-cnn, and I wish to collect some of the intermediate feature maps before the head of the rpn. At present my code looks like:
for index, child in enumerate(self.backbone.children()):
images = child(images)
if index in self.layer_outputs_to_keep:
feature_maps.append(images)
Since the dataset I am training on is very large, I want to make sure that this is indeed the fastest possible way to do so. Any insights/tips appreciated.
|
st45485
|
I simplify the thing but I want to build the following structure:
x -> [Encoder] -> x_encoded
x_encoded -> [predictor 1] -> y_1
x_encoded -> [predictor 2] -> y_2
…
x_encoded -> [predictor n] -> y_n
output = concat(y_1, …, y_n)
All the different predictors have the same structure so I did something like that:
self.predictors = nn.ModuleDict()
for i in range(n):
self.predictors["predictor_" + str(i)] = nn.Sequential(
<< STRUCTURE OF THE PREDICTORS >>
)
And my forward will be something like:
def forward(self, x):
#Encoder
x = self.encoder(x)
#Predictors
output = torch.cat(tuple(
self.predictors["predictor_" + str(i)](x) for i in range(n))
)
Is it the right way to do it ?
|
st45486
|
Yes, the code looks generally alright.
One minor suggestion: if the first module in predictors might apply an inplace operation, you would need to clone the input via x.clone() before passing it to these predictors. Otherwise it’ll be changed inplace and the following predictors would get the already manipulated input.
|
st45487
|
Thanks for the suggestion ! A friend one mine coded a multilinear class as well to deal with that kind of problem
import torch
class MultiLinear(torch.nn.Module):
def __init__(self, input_size, output_size, nb_estimators, activation=torch.relu):
super().__init__()
self.weights = torch.nn.Parameter(torch.randn(nb_estimators, input_size, output_size))
self.weights.requires_grad = True
self.activation = activation def forward(self, x_batch):
if x_batch.ndim == 2:
# x_batch: (batch_size, input_size)
z = torch.einsum("ij,mjl->ilm", x_batch, self.weights)
elif x_batch.ndim == 3:
# x_batch: (batch_size, input_size, nb_estimators)
z = torch.einsum("ijm,mjl->ilm", x_batch, self.weights)
else:
raise ValueError("input dims must be 2 or 3")
output = self.activation(z)
# output: (batch_size, output_size, nb_estimators)
return output
|
st45488
|
I’m trying to reimplement the ResNet from this paper 13 for use in time series classification. Since it’s my first time working with convolutional layers, I’m a bit confused about how to arrange the input tensor for the convolution.
The original implementation 11 in Keras uses 2d layers. I’m given to understand that the convention in torch for a 2d layer is that the tensor should look like [batch_size, channels, height, width]. For image input, this makes sense to me but I’m not sure how multivariate time series data maps to this schema, as in my mind, a 1d layer would make much more sense. Could somebody please point out to me how [sample_axis, time_axis, feature_axis] could be mapped to this schema and why the paper uses a 2d layer?
Am I correct in assuming that in my case, channels would be 1? Is this the same as using Conv1d or am I overlooking something?
|
st45489
|
Turns out I had a thorough misunderstanding of the original paper, as all the datasets are image series, so it makes perfect sense that they used 2d layers.
|
st45490
|
Hallo everyone.
Newbie here, trying to learn.
I have some data points on the (x,y) field that are supposed to be cotegorised into two categories denoted here with X and O like this
import numpy as np
import matplotlib.pyplot as plt
x1 = np.array([0.1,0.3,0.1,0.6,0.4,0.6,0.5,0.9,0.4,0.7])
x2 = np.array([0.1,0.4,0.5,0.9,0.2,0.3,0.6,0.2,0.4,0.6])
c=np.array([ 1,1,1,1,1,0,0,0,0,0 ])
plt.plot(x1[c==0], x2[c==0], 'bo')
plt.plot(x1[c==1], x2[c==1], 'rx')
Now I want to find a way so I can find the “best fitting curve” separating those like this
First I though maybe I try nearest neighbor method but I’ve been told it cannot apply here and that there’s a much simpler way to do it with an ANN but I can’t understand how.
Any ideas on what to use and/or how to do it?
Thank you everyone in advance!
|
st45491
|
That’s a pretty general question and I would recommend to take a look at some general machine learning use cases. If you’ve never worked with ANNs before, take a look at some courses or lectures, such as fast.ai 1 or any tutorials you can find online.
Although I think the PyTorch tutorials are useful, I think they might not be the best introduction to ML in general, since they focus more on the usage of the PyTorch framework.
|
st45492
|
111398:
an you recommend some use cases?
Do you mean what courses I would recommend?
111398:
Can you help with what I’ve asked?
Sure, you can try with a simple 1-layer NN and overfit it on the dataset. Since you seem to be dealing with only 10 samples, this shouldn’t be too hard.
I’m skeptical if posting the code really helps in solving this example and would still recommend to take a look at a course.
|
st45493
|
I’m currently taking the course from coursera Deep Neural Networks with PyTorch , however the practial approach is a little bit short. It’s only good for the theoretical part
|
st45494
|
OK, cool. That’s probably a good starter. In that case, take a look at e.g .this tutorial 5 where you will learn more about how to create models.
|
st45495
|
My problem with this specific example is that the curve produced here is not real mathematical funcion thus I don’t think that it can be approximated with a logistic regression. Am I right?
|
st45496
|
If you cannot plot the curve directly, an often used approach is to feed a meshgrid into the classifier and use the predictions to create the boundaries as described here 3.
|
st45497
|
Hallo again.
I studied your tutoril. I can say it’s helpful enough.
I made think I have make some progress with my problem.
Here’s my model I built, I have a NN with 2 hidden layers and I want to use the sigmoid for my prediction. I have created the dataset with the points and the class 0 or 1 but I have come to a dead end.
Can you help please help me? Whats wrong? I can’t understand why the AttributeError: ‘data’ object has no attribute ‘len’ come on.
Also do you think that my code is close enough to the solution or I have messed up? Thank you in advance!
import torch
import numpy as np
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
class data():
def __init__(self):
x=np.array([[0.1,0.1], [0.3,0.4] , [0.1,0.5] , [0.6,0.9] , [0.4,0.2] , [0.6,0.3] , [0.5,0.6] , [0.9,0.2] , [0.4,0.4] ,[0.7,0.6]])
y=np.array([1,1,1,1,1,0,0,0,0,0])
self.y = torch.from_numpy(y).type(torch.LongTensor)
self.x = torch.from_numpy(x).type(torch.FloatTensor)
def __getitem__(self, index):
return self.x[index], self.y[index]
def __len__(self):
return self.len
class Net(nn.Module):
def __init__(self, D_in=2, H1=2, H2=3, D_out=2):
super(Net, self).__init__()
self.linear1 = nn.Linear(D_in, H1)
self.linear2 = nn.Linear(H1, H2)
self.linear3 = nn.Linear(H2, D_out)
# Prediction
def forward(self, x):
x = torch.sigmoid(self.linear1(x))
x = torch.sigmoid(self.linear2(x))
x = torch.sigmoid(self.linear3(x))
return x
def train(data_set, model, criterion, train_loader, optimizer, epochs=100):
LOSS = []
ACC = []
for epoch in range(epochs):
for x, y in train_loader:
optimizer.zero_grad()
yhat = model(x)
loss = criterion(yhat, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
LOSS.append(loss.item())
ACC.append(accuracy(model, data_set))
return LOSS
data_set=data()
model = Net()
learning_rate = 0.10
optimizer = torch.optim.SGD(model.parameters() ,lr=learning_rate)
train_loader = DataLoader(dataset=data_set, batch_size=1)
criterion = nn.MSELoss()
LOSS = train(data_set, model, criterion, train_loader, optimizer, epochs=100)
print('arrived here')
|
st45498
|
How to implement Attacks
Hello everyone, I am a math student and I am experimenting to attack a ResNet18 based classifier (Trained adverbially with FastGradientMethod(…, eps = 0.03). So far everything worked. However now I would like to try different Attacks. For this purpose I use the ART-toolbox (https://adversarial-robustness-toolbox.readthedocs.io/en/stable/index.html 1)
There are some methods working (FastGradientMethod and ProjectedGradientDescentPyTorch, Wasserstein is too slow) but the others don’t due to some Type Error. What do I have to modify?
My code:
import torch
import torch.nn as nn
import torchvision.models as models
import torchvision.datasets as datasets
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
from torchvision import transforms
import numpy as np
from art.estimators.classification import PyTorchClassifier
import rdnn.torch
import matplotlib.pyplot as plt
transform_test = transforms.Compose([
transforms.ToTensor(),
# You might want to enable this later. For now, leave it commented for compatibility
# with the TensorFlow version of this code.
# transforms.Normalize(
# mean=[0.485, 0.456, 0.406],
# std=[0.229, 0.224, 0.225]
# )
])
# Initialize the test datasets
test_dataset = rdnn.torch.CifarDataset(train=False, transform=transform_test)
x_test = test_dataset.get_x()
y_test = test_dataset.get_y()
print(len(test_dataset))
print("Loaded data.")
#################################################################################
# Load type of model -> don't forget to import if needed
model = Net()
model.eval()
#################################################################################
path_to_checkpoint = "/cluster/work/math/robust-dnn/group5/krimmelm_2020-11-27_13.01.37_247514/ratio_0_6928571428571428"
optimizer, epoch, _ = rdnn.torch.load_model(path_to_checkpoint, model, from_shared_group_dir=False)
print("Loaded model.")
criterion = nn.CrossEntropyLoss()
# optimizer = optim.Adam(model.parameters(), lr=learning_rate)
classifier = PyTorchClassifier(
model=model,
clip_values=None,
loss=criterion,
optimizer=optimizer,
input_shape=(3, 32, 32),
nb_classes=10,
)
model.eval()
from art.attacks.evasion import AutoAttack
from art.attacks.evasion import AutoProjectedGradientDescent
from art.attacks.evasion import FastGradientMethod
from art.attacks.evasion import ProjectedGradientDescentPyTorch
from art.attacks.evasion import SquareAttack
from art.attacks.evasion import TargetedUniversalPerturbation
from art.attacks.evasion import UniversalPerturbation
from art.attacks.evasion import Wasserstein
eps = 0.03
eps_step = eps/3
norm = np.inf
ATTACK_fun = [
AutoAttack(estimator=classifier, eps=eps, eps_step=eps_step, norm = norm),
AutoProjectedGradientDescent(estimator=classifier, eps=eps, eps_step=eps_step, norm = norm),
FastGradientMethod(estimator=classifier, eps=eps, eps_step=eps_step, norm = norm),
ProjectedGradientDescentPyTorch(estimator=classifier, eps=eps, eps_step=eps_step, norm = norm),
SquareAttack(estimator=classifier, eps=eps, norm = norm),
# TargetedUniversalPerturbation(classifier = classifier, eps = eps, norm = norm ),
# UniversalPerturbation(classifier = classifier, eps = eps, norm = norm ),
Wasserstein(estimator=classifier, eps=eps, eps_step=eps_step, norm = str(norm))
]
for eval_attacks in ATTACK_fun:
print(eval_attacks)
x_test_adv = eval_attacks.generate(x_test)
predictions = classifier.predict(x_test)
accuracy = np.sum(np.argmax(predictions, axis=1) == y_test) / len(y_test)
print("Accuracy on benign test examples: {}%".format(accuracy * 100))
predictions_adv = classifier.predict(x_test_adv)
accuracy_adv = np.sum(np.argmax(predictions_adv, axis=1) == y_test) / len(y_test)
print("Accuracy on adversarial examples: {}%".format(accuracy_adv * 100))
My Output
I commented all attacks out except one to get the following output for each method:
ProjectedGradientDescentPyTorch:
<art.attacks.evasion.projected_gradient_descent.projected_gradient_descent_pytorch.ProjectedGradientDescentPyTorch object at 0x2ad31c19fdd0>
Accuracy on benign test examples: 81.53%
Accuracy on adversarial examples: 11.67%
--> THIS WORKS FINE :D
#################################################################################
#################################################################################
AutoProjectedGradientDescent:
<art.attacks.evasion.auto_projected_gradient_descent.AutoProjectedGradientDescent object at 0x2af9efb31c50>
Traceback (most recent call last):
File "Attack_my-ResNet6_1.py", line 79, in <module>
x_test_adv = eval_attacks.generate(x_test)
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/attacks/attack.py", line 74, in replacement_function
return fdict[func_name](self, *args, **kwargs)
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/attacks/evasion/auto_projected_gradient_descent.py", line 465, in generate
f_0 = self.estimator.loss(x=x_k, y=y_batch, reduction="mean")
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/estimators/classification/pytorch.py", line 434, in loss
return loss.detach().numpy()
TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
#################################################################################
#################################################################################
SquareAttack:
<art.attacks.evasion.square_attack.SquareAttack object at 0x2b4b25502ad0>
Traceback (most recent call last):
File "Attack_my-ResNet6_1.py", line 79, in <module>
x_test_adv = eval_attacks.generate(x_test)
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/attacks/attack.py", line 74, in replacement_function
return fdict[func_name](self, *args, **kwargs)
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/attacks/evasion/square_attack.py", line 166, in generate
a_min=self.estimator.clip_values[0],
TypeError: 'NoneType' object is not subscriptable
#################################################################################
#################################################################################
AutoAttack:
<art.attacks.evasion.auto_attack.AutoAttack object at 0x2b2959d2add0>
Traceback (most recent call last):
File "Attack_my-ResNet6_1.py", line 79, in <module>
x_test_adv = eval_attacks.generate(x_test)
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/attacks/attack.py", line 74, in replacement_function
return fdict[func_name](self, *args, **kwargs)
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/attacks/evasion/auto_attack.py", line 176, in generate
x_adv, sample_is_robust = self._run_attack(x=x_adv, y=y, sample_is_robust=sample_is_robust, attack=attack)
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/attacks/evasion/auto_attack.py", line 222, in _run_attack
x_robust_adv = attack.generate(x=x_robust, y=y_robust)
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/attacks/attack.py", line 74, in replacement_function
return fdict[func_name](self, *args, **kwargs)
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/attacks/evasion/auto_projected_gradient_descent.py", line 465, in generate
f_0 = self.estimator.loss(x=x_k, y=y_batch, reduction="mean")
File "/cluster/home/lgraz/RDNN/rdnn-env/lib64/python3.7/site-packages/art/estimators/classification/pytorch.py", line 434, in loss
return loss.detach().numpy()
TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
#################################################################################
#################################################################################
Thank you in advance
|
st45499
|
The error message suggests to move the tensor to the CPU first in order to transform it into a numpy array:
TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
|
st45500
|
Hello! I have some sympy expressions of the form: c0*cos(c1*y) + c2 + c3*x**2 I want to turn the parameters c0, c1, c2, c3 to trainable pytorch parameters and run gradient descent on them (as I would do with an actual NN), to fit them to some data of the form (x,y,z). Is there a way to do this? Thank you!
|
st45501
|
You can define cX as an nn.Parameter, which would make them trainable.
Also, you can wrap them in an nn.Module, which could make handling them easier:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.c0 = nn.Parameter(torch.randn(1, 1))
self.c1 = nn.Parameter(torch.randn(1, 1))
self.c2 = nn.Parameter(torch.randn(1, 1))
self.c3 = nn.Parameter(torch.randn(1, 1))
def forward(self, x, y):
out = self.c0 * torch.cos(self.c1 * y) + self.c2 + self.c3 * x**2
return out
model = MyModel()
x, y = torch.randn(1, 1), torch.randn(1, 1)
out = model(x, y)
out.backward()
for name, param in model.named_parameters():
print(name, param.grad)
|
st45502
|
Thank you for your reply! This is the final form that I want to get to. However, my question was if there is a way to go automatically from the sympy expression to this from (sorry if that was not clear). I have lots of sympy expressions, and I want to pass them automatically to a pytorch module for training, not write everything by hand. For example, for the line out = self.c0 * torch.cos(self.c1 * y) + self.c2 + self.c3 * x**2 I would like some function that would turn my sympy expression to that automatically, something like: out = sympy_to_pytorch(sympy_expression). And something similar for picking the parameters out of my sympy expression and doing the self.c0 = nn.Parameter(torch.randn(1, 1)) part on its own.
|
st45503
|
Oh, in that case I misunderstood the use case.
That’s an interesting idea. I’m unfortunately not deeply familiar with sympy, but do you know, if the “parameters” have some kind of flags?
I assume we could use some parser to check for the “trainable flag” and create nn.Parameters out of them.
EDIT: I’m not sure, if the creation of the actual function would be easy. It seems we would need to have some mapping between sympy to PyTorch methods.
|
st45504
|
I’ve been working on doing exactly that by adding functionality to sympy that allows reasoning about pytorch tensors.
I’ve documented a few examples here:
GitHub
Zer0Credibility/symtorch 62
Initial Commit. Contribute to Zer0Credibility/symtorch development by creating an account on GitHub.
|
st45505
|
Downloading: “https://download.pytorch.org/models/resnet18-5c106cde.pth 2” to /root/.cache/torch/checkpoints/resnet18-5c106cde.pth
gaierror Traceback (most recent call last)
/opt/conda/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
1318 h.request(req.get_method(), req.selector, req.data, headers,
-> 1319 encode_chunked=req.has_header(‘Transfer-encoding’))
1320 except OSError as err: # timeout error
/opt/conda/lib/python3.7/http/client.py in request(self, method, url, body, headers, encode_chunked)
1251 “”“Send a complete request to the server.”""
-> 1252 self._send_request(method, url, body, headers, encode_chunked)
1253
/opt/conda/lib/python3.7/http/client.py in _send_request(self, method, url, body, headers, encode_chunked)
1297 body = _encode(body, ‘body’)
-> 1298 self.endheaders(body, encode_chunked=encode_chunked)
1299
/opt/conda/lib/python3.7/http/client.py in endheaders(self, message_body, encode_chunked)
1246 raise CannotSendHeader()
-> 1247 self._send_output(message_body, encode_chunked=encode_chunked)
1248
/opt/conda/lib/python3.7/http/client.py in _send_output(self, message_body, encode_chunked)
1025 del self._buffer[:]
-> 1026 self.send(msg)
1027
/opt/conda/lib/python3.7/http/client.py in send(self, data)
965 if self.auto_open:
–> 966 self.connect()
967 else:
/opt/conda/lib/python3.7/http/client.py in connect(self)
1413
-> 1414 super().connect()
1415
/opt/conda/lib/python3.7/http/client.py in connect(self)
937 self.sock = self._create_connection(
–> 938 (self.host,self.port), self.timeout, self.source_address)
939 self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
/opt/conda/lib/python3.7/socket.py in create_connection(address, timeout, source_address)
706 err = None
–> 707 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
708 af, socktype, proto, canonname, sa = res
/opt/conda/lib/python3.7/socket.py in getaddrinfo(host, port, family, type, proto, flags)
751 addrlist = []
–> 752 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
753 af, socktype, proto, canonname, sa = res
gaierror: [Errno -3] Temporary failure in name resolution
During handling of the above exception, another exception occurred:
URLError Traceback (most recent call last)
in
----> 1 model = SVHN_Model1()
2 criterion = nn.CrossEntropyLoss()
3 optimizer = torch.optim.Adam(model.parameters(), 0.001)
4 best_loss = 1000.0
5
in init(self)
6 super(SVHN_Model1, self).init()
7
----> 8 model_conv = models.resnet18(pretrained=True)
9 model_conv.avgpool = nn.AdaptiveAvgPool2d(1)
10 model_conv = nn.Sequential(*list(model_conv.children())[:-1])
/opt/conda/lib/python3.7/site-packages/torchvision/models/resnet.py in resnet18(pretrained, progress, **kwargs)
239 “”"
240 return _resnet(‘resnet18’, BasicBlock, [2, 2, 2, 2], pretrained, progress,
–> 241 **kwargs)
242
243
/opt/conda/lib/python3.7/site-packages/torchvision/models/resnet.py in _resnet(arch, block, layers, pretrained, progress, **kwargs)
225 if pretrained:
226 state_dict = load_state_dict_from_url(model_urls[arch],
–> 227 progress=progress)
228 model.load_state_dict(state_dict)
229 return model
/opt/conda/lib/python3.7/site-packages/torch/hub.py in load_state_dict_from_url(url, model_dir, map_location, progress, check_hash)
493 sys.stderr.write(‘Downloading: “{}” to {}\n’.format(url, cached_file))
494 hash_prefix = HASH_REGEX.search(filename).group(1) if check_hash else None
–> 495 download_url_to_file(url, cached_file, hash_prefix, progress=progress)
496
497 # Note: extractall() defaults to overwrite file if exists. No need to clean up beforehand.
/opt/conda/lib/python3.7/site-packages/torch/hub.py in download_url_to_file(url, dst, hash_prefix, progress)
392 # We use a different API for python2 since urllib(2) doesn’t recognize the CA
393 # certificates in older Python
–> 394 u = urlopen(url)
395 meta = u.info()
396 if hasattr(meta, ‘getheaders’):
/opt/conda/lib/python3.7/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
220 else:
221 opener = _opener
–> 222 return opener.open(url, data, timeout)
223
224 def install_opener(opener):
/opt/conda/lib/python3.7/urllib/request.py in open(self, fullurl, data, timeout)
523 req = meth(req)
524
–> 525 response = self._open(req, data)
526
527 # post-process response
/opt/conda/lib/python3.7/urllib/request.py in _open(self, req, data)
541 protocol = req.type
542 result = self._call_chain(self.handle_open, protocol, protocol +
–> 543 ‘_open’, req)
544 if result:
545 return result
/opt/conda/lib/python3.7/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
501 for handler in handlers:
502 func = getattr(handler, meth_name)
–> 503 result = func(*args)
504 if result is not None:
505 return result
/opt/conda/lib/python3.7/urllib/request.py in https_open(self, req)
1360 def https_open(self, req):
1361 return self.do_open(http.client.HTTPSConnection, req,
-> 1362 context=self._context, check_hostname=self.check_hostname)
1363
1364 https_request = AbstractHTTPHandler.do_request
/opt/conda/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
1319 encode_chunked=req.has_header(‘Transfer-encoding’))
1320 except OSError as err: # timeout error
-> 1321 raise URLError(err)
1322 r = h.getresponse()
1323 except:
URLError: <urlopen error [Errno -3] Temporary failure in name resolution>
|
st45506
|
Please help me
I have used the way of "model_urls[‘resnet18’] = model_urls[‘resnet18’].replace(‘https://’, ‘http://’)
resnet18 = torchvision.models.resnet18(pretrained=True)” But it is little use.I’m using the Windows system, and Google didn’t work when it was running on kaggle
|
st45507
|
Were you able to download the pretrained model before?
If so, did you change anything in your current network setup?
tinger1234:
and Google didn’t work when it was running on kaggle
Could you explain this statement a bit?
Are you running the code in a Kaggle notebook?
If so, could you check, if Kaggle uses some internet connection limitations or settings?
|
st45508
|
I could not load the pretrained model from kaggle, but later i found out the Kaggle already download all the pretrained pytorch models, what you need to do is to add it to your list. First create the model without weight, then load it with the pretrained weight file.
|
st45509
|
In the case of knowledge transfer, given two activation matrixes between two models of identical dimension, a teacher and a student, Beside L1 and L2 distances, what other distance measurements can I use to best measure the similarity between the two matrixes?
|
st45510
|
Hi,
I am using Pytorch to try to build and train a multilayer perceptron which is aimed at mapping a 450 dimension input to a 120 dimension output. Actually the data I have is in complex matrix, so I vectorize it and concatenate its real&imaginary part together (and this is why my input and output are of this high dimension). I am now hoping to use a customized loss function which includes the matrix frobenius norm between the predicted results and the target.
I searched a lot on the forum but still not sure about how to implement this, since I am not sure whether pytorch will do the auto-gradient for it and whether I should also do something with the back-propagation of the customized loss function etc. At the same time, when dealing with this kind of complex matrix data, is there any better way to handle it? Or apart from MSE, is there any good loss fuction to deal with this kind of regression problem?
Thanks in advance!
|
st45511
|
Should I figure out how the derivative will affect each element and implement the backpropagation by hand?
|
st45512
|
Hello Yuchen!
Yuchen_Mu:
Actually the data I have is in complex matrix, so I vectorize it and concatenate its real&imaginary part together
Complex tensors are still a work in progress in pytorch, with more
functionality (and more functionality that is actually correct) being
added in successive versions.
Note that as of version 1.6.0, I don’t believe that the pytorch optimizers
accept complex Parameters, so to use pytorch’s complex machinery,
you will have to either use real Parameters that you combine into
complex tensors or write your own complex-aware optimizer.
All in all, depending on what you are doing, it might be safest to
represent the real and imaginary parts of your complex tensors as
separate real tensors and carry out the complex arithmetic “by hand.”
I am now hoping to use a customized loss function which includes the matrix frobenius norm between the predicted results and the target.
The Frobenius norm of a (complex) matrix is simply the square root
of the sum of the squares of the (absolute values of the) individual
matrix elements. Pythorch’s tensor operations can do this* reasonably
straightforwardly.
*) With the proviso that complex tensors are a work in progress.
Note that as of version 1.6.0, torch.norm() is incorrect for complex
tensors – it uses the squares, rather than the squared absolute values,
of the matrix elements.
Here is a script that illustrates calculating and backpropagating the
Frobenius norm:
import torch
torch.__version__
_ = torch.random.manual_seed (2020)
x = torch.randn ([2, 3])
print ('x = ...\n', x)
print ('torch.norm (x) =', torch.norm (x)) # okay
z = torch.randn ([2, 3], dtype = torch.cfloat)
print ('z = ...\n', z)
print ('torch.norm (z) =', torch.norm (z)) # oops, should be positive real
z.requires_grad = True
znorm = torch.sqrt ((z * z.conj()).sum())
print ('znorm =', znorm)
znorm.backward()
print ('z.grad =', z.grad)
z.grad.zero_()
znormb = torch.sqrt ((torch.real (z)**2).sum() + (torch.imag (z)**2).sum())
print ('znormb =', znormb)
znormb.backward()
print ('z.grad =', z.grad)
And here is its (version 1.6.0) output:
x = ...
tensor([[ 1.2372, -0.9604, 1.5415],
[-0.4079, 0.8806, 0.0529]])
torch.norm (x) = tensor(2.4029)
z = ...
tensor([[ 0.0531+0.3378j, -0.4779-1.5195j, -0.8105-0.1923j],
[ 0.7118-0.0294j, -0.9088-0.3499j, -0.9167-0.8840j]])
torch.norm (z) = tensor(1.3644+1.4714j)
znorm = tensor(2.5350+0.j, grad_fn=<SqrtBackward>)
z.grad = tensor([[ 0.0210-0.1332j, -0.1885+0.5994j, -0.3197+0.0759j],
[ 0.2808+0.0116j, -0.3585+0.1380j, -0.3616+0.3487j]])
znormb = tensor(2.5350, grad_fn=<SqrtBackward>)
z.grad = tensor([[ 0.0210-0.1332j, -0.1885+0.5994j, -0.3197+0.0759j],
[ 0.2808+0.0116j, -0.3585+0.1380j, -0.3616+0.3487j]])
Be careful, however, with what you do with a complex gradient. You
will have to take the complex conjugate of the gradient to use it with
gradient-descent optimization.
This script illustrates this behavior by minimizing the Frobenius norm
with gradient descent:
import torch
torch.__version__
_ = torch.random.manual_seed (2020)
za = torch.randn ([2, 3], dtype = torch.cfloat)
zb = za.clone()
lr = 0.001
# gradient descent A
za.requires_grad = True
print ('za =', za)
for i in range (10001):
if not za.grad == None: _ = za.grad.zero_()
znorm = torch.sqrt ((za * za.conj()).sum())
znorm.backward()
with torch.no_grad():
_ = za.copy_ (za - lr * za.grad) # doesn't converge
if i % 1000 == 0: print ('znorm =', znorm)
print ('za =', za)
# gradient descent B
zb.requires_grad = True
print ('zb =', zb)
for i in range (10001):
if not zb.grad == None: _ = zb.grad.zero_()
znorm = torch.sqrt ((zb * zb.conj()).sum())
znorm.backward()
with torch.no_grad():
_ = zb.copy_ (zb - lr * zb.grad.conj()) # use conjugate of gradient to get convergence
if i % 1000 == 0: print ('znorm =', znorm)
print ('zb =', zb)
And here is its output:
za = tensor([[ 0.8749-0.6791j, 1.0900-0.2884j, 0.6227+0.0374j],
[ 0.0531+0.3378j, -0.4779-1.5195j, -0.8105-0.1923j]],
requires_grad=True)
znorm = tensor(2.4970+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(2.8249+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(3.6008+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(4.5226+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(5.4901+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(6.4745+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(7.4661+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(8.4612+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(9.4581+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(10.4563+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(11.4551+0.j, grad_fn=<SqrtBackward>)
za = tensor([[ 0.1324-4.4859j, 0.1649-1.9052j, 0.0942+0.2472j],
[ 0.0080+2.2312j, -0.0723-10.0381j, -0.1226-1.2704j]],
requires_grad=True)
zb = tensor([[ 0.8749-0.6791j, 1.0900-0.2884j, 0.6227+0.0374j],
[ 0.0531+0.3378j, -0.4779-1.5195j, -0.8105-0.1923j]],
requires_grad=True)
znorm = tensor(2.4970+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(1.4970+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(0.4970+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(0.0010+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(0.0010+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(0.0010+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(0.0010+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(0.0010+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(0.0010+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(0.0010+0.j, grad_fn=<SqrtBackward>)
znorm = tensor(0.0010+0.j, grad_fn=<SqrtBackward>)
zb = tensor([[ 7.4477e-06-5.7811e-06j, 9.2789e-06-2.4552e-06j,
5.3007e-06+3.1863e-07j],
[ 4.5219e-07+2.8753e-06j, -4.0686e-06-1.2936e-05j,
-6.9001e-06-1.6372e-06j]], requires_grad=True)
You can see that without taking its complex conjugate, the gradient
pushes the imaginary parts of the tensor away from zero so that the
Frobenius norm grows.
I am not sure whether pytorch will do the auto-gradient for it and whether I should also do something with the back-propagation of the customized loss function etc. At the same time, when dealing with this kind of complex matrix data, is there any better way to handle it?
As long as you write your custom loss function using pytorch tensor
operations, you will get autograd and backpropagation (but not
complex optimization) “for free.” You won’t have to write an explicit
.backward() function for your loss function.
This will certainly be true if your represent the real and imaginary parts
of your complex tensors as explicit real tensors.
However, I think its worth trying pytorch’s complex tensors, but if you
decide to go this route, you should use the latest version of pytorch
that otherwise works for you, and test your complex manipulations
carefully, especially the various functions you use and backpropagation.
Good luck.
K. Frank
|
st45513
|
Hi Frank,
Thank you very much for taking time to write this detailed reply!
Yes, I split the real and imaginary part of the original complex matrix then vectorize it. At the output side, I build a real matrix (which is the real part of the complex matrix) and a imaginart matrix (which is the imaginary part.) .
Specifically, I try to calculate the square of frobenius norm between the conjugate transpose of output and the target, here is what I did:
# First matrix V_1_Hermitian(2*5)
real_part_1 = output_from_network[i,0:5].float()
real_part_2 = output_from_network[i,5:10].float()
img_part_1 = -output_from_network[i,10:15].float()
img_part_2 = -output_from_network[i,15:20].float()
# A
real_part_final = torch.stack((real_part_1,real_part_2),0)
# B
img_part_final = torch.stack((img_part_1,img_part_2),0)
# Second matrix V_2(5*2)
real_part_1_ = torch.reshape(target[i,0:5].float(), [5,1])
real_part_2_ = torch.reshape(target[i,5:10].float(), [5,1])
img_part_1_ = torch.reshape(target[i,10:15].float(), [5,1])
img_part_2_ = torch.reshape(target[i,15:20].float(), [5,1])
# C
real_part_final_ = torch.cat((real_part_1_,real_part_2_),1)
# D
img_part_final_ = torch.cat((img_part_1_,img_part_2_),1)
# M = V_1_Hemitian * V_2
# M = Re(M) + Im(M)*j
# Re(M) = A*C-B*D, Im(M) = A*D+B*C
# frobenius norm square of M = frobenius norm square of Re(M) + frobenius norm square of Im(M)
Re_M = torch.matmul(real_part_final, real_part_final_) - torch.matmul(img_part_final, img_part_final_)
Im_M = torch.matmul(real_part_final, img_part_final_) + torch.matmul(img_part_final, real_part_final_)
Re_M_norm_square = torch.pow(torch.norm(Re_M,'fro'),2)
Im_M_norm_square = torch.pow(torch.norm(Im_M,'fro'),2)
Final_M_norm_square = Re_M_norm_square + Im_M_norm_square
Sorry about the mess. the output and the target is a vector of size 20 (corresponding to a 5*2 matix), where first 10 elements are the real part and remaning 10 elements are the imaginary part. Since before I am not sure whether Pytorch can do the auto-gradient ‘for free’, I. to some extent, write the process of calculating this frobenius norm ‘by hand’ (as shown in the code, really messy ), will this code work?
Actually I verified that the final output, which is Final_M_norm_square, is the value that I want (so the manipulation I did give the correct result as I want it to be - The frobenius norm square between two complex matrix), my concern is whether the gradients will be calculated precisely during the backpropagation, since instead of building the complex matrix from the real part and imaginary part and calculate the frobenius norm as you shown me in your script example, I just directly calculate it from the real part and imaginary part, respectively.
Again, thank you very much for taking time and look at my question
|
st45514
|
Hello Yuchen!
Yuchen_Mu:
will this code work?
Actually I verified that the final output, which is Final_M_norm_square, is the value that I want
I haven’t looked at your code in detail.
But from what you say, my understanding is that:
You are not using any complex tensors, so you don’t have
to worry about any pytorch complex issues.
Your calculation only uses pytorch tensor operations (i.e.,
you don’t switch over to something like numpy for part of
the calculation).
Your function gives you the correct “forward-pass” result.
So, yes, your code should work, it should work “for free” with
autograd, and backpropagation should work properly.
Best.
K. Frank
|
st45515
|
How to batch normalization in LSTM
My code is here…
class LSTM(nn.Module):
def __init__(self, **model_config):
super(LSTM, self).__init__()
if model_config['emb_type'] == 'glove' or 'fasttext':
self.emb = nn.Embedding(model_config['vocab_size'],
model_config['emb_dim'],
_weight = TEXT.vocab.vectors)
else:
self.emb = nn.Embedding(model_config['vocab_size'],
model_config['emb_dim'])
self.bidirectional = model_config['bidirectional']
self.num_direction = 2 if model_config['bidirectional'] else 1
self.model_type = model_config['model_type']
self.LSTM = nn.LSTM(input_size = model_config['emb_dim'],
hidden_size = model_config['hidden_dim'],
dropout = model_config['dropout'],
bidirectional = model_config['bidirectional'],
batch_first = model_config['batch_first'])
self.fc = nn.Linear(model_config['hidden_dim'] * self.num_direction,
model_config['output_dim'])
self.drop = nn.Dropout(model_config['dropout'])
def forward(self, x):
emb = self.emb(x)
output, (hidden, cell) = self.LSTM(emb)
last_output = output[:,-1,:]
return self.fc(self.drop(last_output))
|
st45516
|
Hi
I am trying to implement an Classifier but I got the following error. I have no idea why this is happening
15853077591324084114662304×1728 639 KB
15853077900038199823342304×1728 1.12 MB
|
st45517
|
Solved by Angry_potato in post #3
Thank you for the reply. I found the solution on another website.
Simply change all the parameters of model to float by using net.float() before loss and convert the input to float.
|
st45518
|
Could you check the dtype of input via print(input.type())?
I guess it might be a LongTensor and you can transform it via input = input.float().
PS: It’s better to post code directly by wrapping it into three backticks ```
|
st45519
|
Thank you for the reply. I found the solution on another website.
Simply change all the parameters of model to float by using net.float() before loss and convert the input to float.
|
st45520
|
@ptrblck
Could you elaborate why the model’s dtype is initialized to long even though he didn’t specify anywhere?
Thanks
|
st45521
|
I don’t think the model’s parameters are initialized to long, but rather the input.
torch.from_numpy() respects the data type passed to this method and often we see issues, when the original numpy array contained int values.
|
st45522
|
Could somebody help me. I am new to Pytorch and am trying to predict house prices. I am always getting the following error: Found dtype Long but expected Float.
My Notebook: https://colab.research.google.com/drive/1Vd9fJs0bfd7IZ8D5dHS859EThz1DEB58?usp=sharing 1
#Doesn't Work
epochs=500
final_losses=[]
for i in range(epochs):
i=i+1
y_pred=model.forward(X_train)
y_pred=y_pred#.to(torch.float32)#.float()
#print(y_pred.type())
loss=loss_function(y_pred,y_train)#.float()
#print("Loss: ",loss.type())
final_losses.append(loss)
if i%10==1:
print("Epoch number: {} and the loss : {}".format(i,loss.item()))
optimizer.zero_grad()
loss.backward()
optimizer.step()
Any help would be highly appreciated.
|
st45523
|
Hi techboy,
What you should do to fix this error is to convert the tensor which is in dtype Long to float. You can figure out which tensor is causing error by looking out the line which gives error while execution.
|
st45524
|
I would like to multiply a 2D matrix by a scalar (say 0.016) and at the end have a 2D matrix as the result. What is the best way to do this? Thanks in advance!
|
st45525
|
Solved by vaisakh_m in post #2
k * X is the operation you are looking for, where, X is your 2D matrix and k is the scalar value.
|
st45526
|
k * X is the operation you are looking for, where, X is your 2D matrix and k is the scalar value.
|
st45527
|
thank you very much!
I still have one question:
if k is a scalar value and X is a 2D matrix.
Can I also use X * k (which means does the * operator work in both directions?)
|
st45528
|
I’m doing timeseries classification and i use zarr as my data storage. I have written an iterable dataset to access zarr, which works with my small test-dataset but behaves weirdly once i move to my actual (much larger) dataset. The dataloader no longer works when i use multiple workers (it hangs after the first batch) and if i use only a single thread, performance starts out okish but gradually decreases until everything grinds to a halt (and uses excessive amounts of RAM, looks like a memory leak type of issue).
I’ve added the code for my dataset, worker_init_fn, and training function below. If anybody has any ideas about what i’m doing wrong, it would be greatly appreciated. ATM i don’t even have an idea how to debug this properly. I tried iterating over the dataset in a separate script like i do in the dataset, which works perfectly fine.
class Data(IterableDataset):
def __init__(self, path, start=None, end=None):
super(Data, self).__init__()
store = zarr.DirectoryStore(path)
self.array = zarr.open(store, mode='r')
if start is None:
start = 0
if end is None:
end = self.array.shape[0]
assert end > start
self.start = start
self.end = end
def __iter__(self):
return islice(self.array, self.start, self.end)
def worker_init_fn(worker_id):
worker_info = torch.utils.data.get_worker_info()
dataset = worker_info.dataset # the dataset copy in this worker process
overall_start = dataset.start
overall_end = dataset.end
# configure the dataset to only process the split workload
per_worker = int(
math.ceil(
(overall_end - overall_start) / float(worker_info.num_workers)
)
)
worker_id = worker_info.id
dataset.start = overall_start + worker_id * per_worker
dataset.end = min(dataset.start + per_worker, overall_end)
def train(self):
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
sxnet = SXNet()
sxnet.to(device)
optimizer = optim.Adam(
sxnet.parameters(),
lr=self.learning_rate
)
criterion = nn.BCEWithLogitsLoss()
traindata = Data(os.path.join(self.store, 'trainset1'))
trainloader = DataLoader(
dataset=traindata,
batch_size=50000,
shuffle=False,
num_workers=os.cpu_count(),
pin_memory=True,
worker_init_fn=worker_init_fn
)
params = {
'desc': 'epoch progress',
'smoothing': 0.01,
'total': math.ceil(
traindata.array.shape[0] / trainloader.batch_size)
}
for e in range(self.epochs): # loop over the dataset multiple times
epoch_loss = 0
epoch_acc = 0
epoch_len = 0
for batch in tqdm(trainloader, **params):
x = batch[:, 1:].to(device)
y = batch[:, 0].unsqueeze(0).T.to(device)
optimizer.zero_grad()
# forward + backward + optimize
y_pred = sxnet(x)
loss = criterion(y_pred, y)
acc = self.binary_acc(y_pred, y)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
epoch_acc += acc.item()
epoch_len += y.shape[1]
print(f'Epoch {e+0:03}: | '
f'Loss: {epoch_loss/epoch_len:.5f} | '
f'Acc: {epoch_acc/epoch_len:.3f}')
torch.save(sxnet.state_dict(), self.model_store)
|
st45529
|
Solved by sobek in post #6
I was once again a bit hasty in my conclusion. The actual issue is in that I did not fully understand how islice works. islice takes the underlying generator and iterates it to the start index you give it without returning anything. Only after it has done that will it start actually yielding element…
|
st45530
|
Since I’ve returned working on this project, I was able to find the memory leak issue. The problem was in my validation loop:
with torch.no_grad():
for batch in tqdm(testloader, **params):
x = batch[:, 1:].to(device)
y = batch[:, 0].unsqueeze(0).T
y_test_pred = torch.sigmoid(sxnet(x))
y_pred_tag = torch.round(y_test_pred)
y_pred_list.append(y_pred_tag.cpu().numpy())
y_list.append(y.numpy())
Saving the results like this used way more memory than I originally thought. Since this is a binary classification task, my results are 1xn vectors, so I was able to use .flatten() on the numpy arrays before appending, which has solved the excessive RAM use issue.
Unfortunately I’m still facing the problem that if I use num_workers > 1 for my dataloader, it just hangs on doing the second batch. CPU usage is still there but it never finishes the second loop iteration. I have a second dataset that I created by removing the class imbalance from my original dataset, and on that data it works like a charm. From the dataloader’s perspective, the only difference between the datasets should be the number of rows.
|
st45531
|
I went ahead and compared the .zarray files of my two datasets to be sure that there wasn’t some data type nonsense going on.
{
"chunks": [
50000,
290
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "<f4",
"fill_value": 0.0,
"filters": null,
"order": "C",
"shape": [
4702488,
290
],
"zarr_format": 2
}
{
"chunks": [
50000,
290
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "<f4",
"fill_value": 0.0,
"filters": null,
"order": "C",
"shape": [
477285033,
290
],
"zarr_format": 2
Everything looks identical except for the number of rows.
|
st45532
|
This is weird, I’ve now tested the dataloader in a test function like outlined in the documentation for the iterable dataset with my data:
def test_dataloader(self):
traindata = Data(
os.path.join(self.store, 'origin'),
0,
200000
)
trainloader = DataLoader(
dataset=traindata,
batch_size=50000,
shuffle=False,
num_workers=os.cpu_count(),
worker_init_fn=worker_init_fn
)
print(list(trainloader))
This works perfectly. Inside the training function, it still hangs.
|
st45533
|
Oof, I’m a moron
Of course each worker process has to open the dataset once, which takes quite a while for a 300gb+ zarr store. Once all the workers have the store opened, everything works quite quickly. So for the first os.cpu_count() number of batches, i’m seeing terrible performance, but afterwards it works fine.
|
st45534
|
I was once again a bit hasty in my conclusion. The actual issue is in that I did not fully understand how islice works. islice takes the underlying generator and iterates it to the start index you give it without returning anything. Only after it has done that will it start actually yielding elements of the array. Naturally for large arrays this is extremely inefficient, hence the long wait times I experienced at startup. The solution was to modify the storage backend (zarr) to enable its built-in iteration to start at a custom index. I’ve submitted a pull request 26 that should get released with the next minor release of zarr.
|
st45535
|
I am contenanting three fetures who have same no of rows,
A=torch.cat(chroma_feats.T,mel_feats.T,mfcc_feats.T)
getting an error
cat() received an invalid combination of arguments - got (numpy.ndarray, numpy.ndarray, numpy.ndarray), but expected one of:
(tuple of Tensors tensors, name dim, *, Tensor out)
(tuple of Tensors tensors, int dim, *, Tensor out)
what to do?
|
st45536
|
You need to provide a tuple of tensors instead of just 3 tensors :
tuple = (tensor_1, tensor_2)
new_tensor = torch.cat(tuple)
|
st45537
|
Hello. I am trying to prepare some data for training and testing.
I am running in a problem as most of the tutorials i’ve seen are built around image datasets but i’ve got some custom data that i want to use for the Neural Network now…
Explanations
Basically, let’s say i have 5 CSV files (data1,2,3,4,5) with data and 5 CSV files (state1,2,3,4,5) with states.
The network should use the corresponding data file to guess the value that is written in the state file.
The data files contain 2 columns, X and Y (timeseries) of 100 points each.
The state files only contain 1 column and 1 data, (kept or not kept (0 or 1))
The issue i have now
I can succesfully create a dataloader and input tensors that i create after the CSV files.
I’ll get 3 tensors, 1 for DataXvalues, 1 for DataYvalues, 1 for State
I create a dataLoader like this
myDataLoader = torch.utils.data.DataLoader((myXTensor,myYTensor,myStateTensor))
And it seems to work good, but…
But i only have the stuff i need for 1 train or test pass now, and i don’t see how im supposed to fit the 4 other sets i should add next! (Data2,3,4,5 and State2,3,4,5)
When i lookup my DataLoader the data in it is somewhat like this
[0] - Data for X
[1] - Data for Y
[2] - State
Should i just add a lot of tensors and i could itterate doing jumps of 3 with other sets of data (is that a setting in the DataLoader?) (I would do one pass with Input 0,1 Output 2 - Next pass with Input 3,4 Output 5 - The next one with 6,7,8…)?
If there’s more info required i’ll give all the details i can!
|
st45538
|
Update on this -
What i am planning to do is a List for Timeseries Data and a List of States
So i would itterate over the lists to secure the proper values for each pass (1 full Timeseries X + Y and the Kept/Not Kept state)
Does this seem like a solution that would work?
Also, i would be treating the XY values of the Timeseries like this
All the X (times) first and then underneat all the Y (Values), Does this make sense?
|
st45539
|
Hello everyone,
I am saving model using:
torch.save({
'step': step,
'arch': args.net,
'G_state_dict': G.state_dict(),
'F1_state_dict': F1.state_dict(),
'best_acc_test': best_acc_test,
'optimizer_g' : optimizer_g.state_dict(),
'optimizer_f' : optimizer_f.state_dict(),
'feat_dict_target': feat_dict_target
},os.path.join(args.checkpath,"%s_%s_%s_%d.ckpt.pth.tar"%(args.net,args.source,args.target,step)))
But when I try model.load_state_dict(the_state_dict), it seems like every key of the dictionary is getting prepended by this string: module. When I iterate through this state_dict and remove this string from each of the keys, the state_dict loads just fine. I am using resnet34.
Please help.
Thanks
|
st45540
|
Solved by ptrblck in post #6
Side info: Besides the mentions possibility that you are adding the .module attribute manually, it would also be added automatically by e.g. nn.DataParallel as described here.
|
st45541
|
Hi,
This is most likely because your actual model is saved in G.model? If this is the only part you’re interested in you can save it directly by doing G.model.state_dict().
|
st45542
|
Thanks for your reply. I am using resnet34. My architecture code is:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from torch.autograd import Function
import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://s3.amazonaws.com/pytorch/models/resnet18-5c106cde.pth',
'resnet34': 'https://s3.amazonaws.com/pytorch/models/resnet34-333f7ec4.pth',
'resnet50': 'https://s3.amazonaws.com/pytorch/models/resnet50-19c8e357.pth',
'resnet101':
'https://s3.amazonaws.com/pytorch/models/resnet101-5d3b4d8f.pth',
'resnet152':
'https://s3.amazonaws.com/pytorch/models/resnet152-b121ed2d.pth',
}
def init_weights(m):
classname = m.__class__.__name__
if classname.find('Conv2d') != -1 or \
classname.find('ConvTranspose2d') != -1:
nn.init.kaiming_uniform_(m.weight)
nn.init.zeros_(m.bias)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight, 1.0, 0.02)
nn.init.zeros_(m.bias)
elif classname.find('Linear') != -1:
nn.init.xavier_normal_(m.weight)
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class GradReverse(Function):
def __init__(self, lambd):
self.lambd = lambd
def forward(self, x):
return x.view_as(x)
def backward(self, grad_output):
return (grad_output * -self.lambd)
def grad_reverse(x, lambd=1.0):
return GradReverse(lambd)(x)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, nobn=False):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3x3(planes, planes)
self.bn2 = nn.BatchNorm2d(planes)
self.downsample = downsample
self.stride = stride
self.nobn = nobn
def forward(self, x, source=True):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ScaleLayer(nn.Module):
def __init__(self, init_value=1e-3):
super(ScaleLayer, self).__init__()
self.scale = nn.Parameter(torch.FloatTensor([init_value]))
def forward(self, input):
print(self.scale)
return input * self.scale
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, nobn=False):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1,
stride=stride, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3,
stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * 4)
self.relu = nn.ReLU(inplace=True)
self.downsample = downsample
self.stride = stride
self.nobn = nobn
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000):
self.inplanes = 64
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.in1 = nn.InstanceNorm2d(64)
self.in2 = nn.InstanceNorm2d(128)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2,
padding=0, ceil_mode=True)
self.layer1 = self._make_layer(block, 64, layers[0])
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AvgPool2d(7)
self.fc = nn.Linear(512 * block.expansion, num_classes)
for m in self.modules():
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def _make_layer(self, block, planes, blocks, stride=1, nobn=False):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, nobn=nobn))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
return x
def resnet34(pretrained=True):
"""Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [3, 4, 6, 3])
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))
return model
Is there some issue with this code?
Thanks,
Megh
|
st45543
|
I don’t think there is any issue. it is just the way your Model is structured.
As I mentioned, if you don’t want to see the first level you can just get the state_dict for G.model directly.
|
st45544
|
Side info: Besides the mentions possibility that you are adding the .module attribute manually, it would also be added automatically by e.g. nn.DataParallel as described here 3.
|
st45545
|
Yes, @ptrblck! I am doing parallel training. That is why I guess it is being added.
Thank you so much!
|
st45546
|
Hi everyone,
does anyone know a solution for this Error? I am trying to switch my PyTorch network to an Federated Learning network but i always get this Error.
I’m using Google Colab an train on GPU. When I print the size of embeds I get 0, but I don’t understand why the data is not used there.
RuntimeError Traceback (most recent call last)
<ipython-input-42-fd4a5223524b> in <module>()
----> 1 model, history = train_model(net, dataloaders_dict, criterion, optimizer, num_epochs=10)
2 #model = train_model(net, dataloaders_dict, criterion, optimizer, num_epochs=10)
6 frames
<ipython-input-41-a386f044d41f> in train_model(model, dataloaders, criterion, optimizer, num_epochs, batch_size)
68 # detaching it from its history on the last instance.
69
---> 70 outputs = model(inputs)
71
72 loss = criterion(outputs, labels)
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
530 result = self._slow_forward(*input, **kwargs)
531 else:
--> 532 result = self.forward(*input, **kwargs)
533 for hook in self._forward_hooks.values():
534 hook_result = hook(self, input, result)
<ipython-input-36-64e9a7d68b11> in forward(self, sentence)
11 def forward(self, sentence):
12 embeds = self.word_embeddings(sentence)
---> 13 lstm_out, (h,t) = self.lstm(embeds)
14 lstm_out = self.dropout(lstm_out)
15 tag_space = self.output(lstm_out[:,-1,:])
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
530 result = self._slow_forward(*input, **kwargs)
531 else:
--> 532 result = self.forward(*input, **kwargs)
533 for hook in self._forward_hooks.values():
534 hook_result = hook(self, input, result)
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/rnn.py in forward(self, input, hx)
554 hx = self.permute_hidden(hx, sorted_indices)
555
--> 556 self.check_forward_args(input, hx, batch_sizes)
557 if batch_sizes is None:
558 result = _VF.lstm(input, hx, self._flat_weights, self.bias, self.num_layers,
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/rnn.py in check_forward_args(self, input, hidden, batch_sizes)
506 def check_forward_args(self, input, hidden, batch_sizes):
507 # type: (Tensor, Tuple[Tensor, Tensor], Optional[Tensor]) -> None
--> 508 self.check_input(input, batch_sizes)
509 expected_hidden_size = self.get_expected_hidden_size(input, batch_sizes)
510
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/rnn.py in check_input(self, input, batch_sizes)
157 raise RuntimeError(
158 'input.size(-1) must be equal to input_size. Expected {}, got {}'.format(
--> 159 self.input_size, input.size(-1)))
160
161 def get_expected_hidden_size(self, input, batch_sizes):
RuntimeError: input.size(-1) must be equal to input_size. Expected 200, got 0
class LSTM(nn.Module):
def __init__(self, embedding_dim, hidden_layers,vocab_size,num_layers,pretrained_weights):
super(LSTM, self).__init__()
self.word_embeddings = nn.Embedding(vocab_size, embedding_dim,_weight=pretrained_weights, padding_idx=0)
self.lstm = nn.LSTM(embedding_dim, hidden_size=hidden_layers,num_layers=num_layers, batch_first=True)
self.output = nn.Linear(hidden_layers, vocab_size, bias=False)
self.dropout = nn.Dropout(0.1)
def forward(self, sentence):
embeds = self.word_embeddings(sentence)
lstm_out, (h,t) = self.lstm(embeds)
lstm_out = self.dropout(lstm_out)
tag_space = self.output(lstm_out[:,-1,:])
return tag_space
The Error throws in this line: lstm_out, (h,t) = self.lstm(embeds)
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1))
print('-' * 10)
train_loss = 0
acc_score = 0
valid_loss = 0
acc_valid_score = 0
#Variables to store the losses temporary
train_loss_result = 0
acc_score_result = 0
valid_loss_result = 0
acc_valid_score_result = 0
valid_loss_not_decreased = 0
if valid_loss_not_decreased == 5:
break
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
for inputs,labels in dataloaders[phase]:
# Location of current batch
worker = inputs.location # <---- Where will send the model to
#model.to(device)
model = model.send(worker) # <---- for Federated Learning
inputs, labels = inputs.to(device), labels.to(device)
print("--------> INPUT: ",inputs)
print("--------> LABEL: ",labels)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
# Get model outputs and calculate loss
# backward + optimize only if in training phase
if phase == 'train':
# we need to clear out the hidden state of the LSTM,
# detaching it from its history on the last instance.
outputs = model(inputs)
loss = criterion(outputs, labels)
acc = binary_accuracy(outputs,labels)
acc_score = acc_score + acc
train_loss = train_loss + loss.item()
loss.backward()
optimizer.step()
|
st45547
|
Based on @Tudor_Cebere’s post 154 it seems you would get fast help by joining the OpenMined slack
|
st45548
|
Hello.
I think I’ve done wrong. It uses too much memory.
Before training I made sure any memory isn’t allocated,
but it dies saying
RuntimeError: CUDA out of memory. Tried to allocate 14.00 MiB (GPU 0; 7.93 GiB total capacity; 6.30 GiB already allocated; 25.75 MiB free; 6.78 GiB reserved in total by PyTorch)
I do not know why 6.3GB is alreay allocated.
Is there something I am doing wrong?
This is my training function.
‘’’
def train(input, target):
# initializing grad and hidden state
hidden = model.init_hidden()
optimizer.zero_grad()
loss = 0
for i in range(input.size()[0]):
output, hidden = model(input.data[i].unsqueeze(0), hidden)
l = criterion(output, target.data[i])
loss += l
output.detach()
# backpropagation
loss.backward()
# optimizing
optimizer.step()
# learning rate scheduling
scheduler.step()
return loss
‘’’
this is my gru unit
‘’’
import torch.nn as nn
import torch
class GRU(nn.Module):
def init(self, input_size, hidden_size, output_size, batch_size, device, num_layers):
super(GRU, self).init()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.batch_size = batch_size
self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=False, dropout=0.2)
self.elu = nn.ELU()
self.fc = nn.Linear(hidden_size, output_size)
self.device = device
self.to(device)
def forward(self, x, h):
out, h = self.gru(x, h)
out = self.elu(h[0])
out = self.fc(out)
return out, h
def init_hidden(self):
hidden = torch.zeros(self.num_layers, self.batch_size, self.hidden_size).to(self.device)
return hidden
‘’’
|
st45549
|
The losses will be accumulated to loss in the first loop and with them the complete computation graphs.
It’s thus expected that your memory usage would grow and your GPU might run out of memory.
You could have a look at this post 59 and see if another approach would be suitable for your use case.
PS: you can post code snippets by wrapping them into three backticks ```, which would make debugging easier.
|
st45550
|
Hello All,
I am trying to adapt my binary semantic segmentation code to multi-class semantic-seg.
I am having trouble figuring out how to convert my training masks to an appropriate format/shape.
My training labels are a single band image (grayscale) where unique integer (eg 1,2,3,4) values represent a label. How should this be transformed to the correct format?
Thanks
|
st45551
|
For a multi-class segmentation you would most likely use nn.CrossEntropyLoss, which expects the target masks to have the shape [batch_size, height, width] and contain the class indices in the range [0, nb_classes-1].
If your current targets are grayscale images with discrete gray values for each class, you could map these values to class indices e.g. by using a lookup table.
|
st45552
|
Hi everyone
I just noticed that when I train a network in an anaconda environment with cudatoolkit=10.2.89, I get different results to when I train the exact same network in a different environment with cudatoolkit=10.1.243 (everything else is the same). Is this behaviour to be expected?
I seed everything and I can reproduce the results within each environment, they are just different from each other…
Any help is very much appreciated!
All the best
snowe
|
st45553
|
Solved by albanD in post #2
Hi,
I am afraid this is expected. Results (especially on CUDA) are reproducible only for a fix hardware/library version and if the deterministic flag is set to true on pytorch.
If you change anything there, the floating point arithmetic order can lead to different floating point results. These dif…
|
st45554
|
Hi,
I am afraid this is expected. Results (especially on CUDA) are reproducible only for a fix hardware/library version and if the deterministic flag is set to true on pytorch.
If you change anything there, the floating point arithmetic order can lead to different floating point results. These differences then get amplified by the model depth and gradient descend, leading to a final result that is completely different (even though, if your model is stable, the final loss value should be similar).
|
st45555
|
I have a distance matrix D with 2 dimensions from which I want to calculate the norm (||D||). Is it possible to use torch.norm(D) still having the two dimensions (same shape like before calculation) after the calculation? I saw that it is possible to calculate either the norm over the rows or over the colomns.
|
st45556
|
Hi,
Which norm are you looking for here?
Depending on what you’re looking for, you’ll need to set both dim and p to the right values.
|
st45557
|
You can check the doc for details on each argument: https://pytorch.org/docs/stable/generated/torch.norm.html?highlight=norm#torch.norm 2
But as you will see there. This function can do many types of norms so you first need to know which norm you want
|
st45558
|
so p is float in my case. and I want to do the .norm() operation over the float entries of a 2d matrix (E, C) in which every entry is represening a distance. The shape (E, C) of the resulting matrix should not change.
|
st45559
|
I am not sure to follow what you mean. The norm of a matrix is a single number. Which norm are you looking for here? Euclidean, frobenius, … ?
|
st45560
|
okay thank you! I was quite unsure about that. the matrix holds euclidean distances in each entry. so you mean that I can not have a matrix as a result. the result should be a scalar value?
|
st45561
|
If these are already euclidean distances, then you don’t need the norm function?
Which value of p do you use for the distance computation?
|
st45562
|
I’ve forgotten to mention, that I took th.cdist() for the distance computation between cluster centers and data points (image patches) which is Dx-ci^dct in the following formula: -1/2h^2 * ||Dx - ci^dct||² . So you mean that I do not need to calculate the norm here in the formula with th.norm(x) where x = Dx - ci^dct because I already have the eucledian distances?
|
st45563
|
cdist already computes the p-norm distance.
Distance and norms are very similar in simple spaces.
|
st45564
|
I’ve just started using pytorch and am working on my first project. What got me confused was the eval() function. I followed a starting tutorial that showed how to use pytorch and it did not contain using eval() function for validation. So I trained a model with a satisfactory validation performance, but then came across eval and train modes when looking something up. As far as I understand, not using it would only affect how accurate my validation actually is (because dropouts and normalizations would still be used for validation), but it would not affect the training itself. However, when I added the model.eval() and model.train() lines between validation, I noticed that the training loss for the same amount of epochs is now different?
for i in range(epochs):
i += 1
start = time.time()
y_pred = model(categorical_train_data, numerical_train_data)
single_loss = loss_function(y_pred, train_outputs)
aggregated_losses.append(single_loss)
print(f'epoch: {i:3} loss: {single_loss.item():10.8f}')
optimizer.zero_grad()
single_loss.backward()
optimizer.step()
with torch.no_grad():
y_val = model(categorical_test_data, numerical_test_data)
loss = loss_function(y_val, test_outputs)
The code above produces
epoch: 1 loss: 0.80006623
epoch: 2 loss: 0.78904432
however, if I change it to
for i in range(epochs):
i += 1
start = time.time()
y_pred = model(categorical_train_data, numerical_train_data)
single_loss = loss_function(y_pred, train_outputs)
aggregated_losses.append(single_loss)
print(f'epoch: {i:3} loss: {single_loss.item():10.8f}')
optimizer.zero_grad()
single_loss.backward()
optimizer.step()
model.eval()
with torch.no_grad():
y_val = model(categorical_test_data, numerical_test_data)
loss = loss_function(y_val, test_outputs)
model.train()
I get a different output:
epoch: 1 loss: 0.80006623
epoch: 2 loss: 0.78863680
I used torch.manual_seed(0) so I know it’s not the initial distribution. I can run the code multiple times and get the same output for both these cases.
Which as far as I understand means that weights of the model were updated. Does that mean that without using eval mode I let the validation set influence the training of the actual model and therefore the validation performance is not actually validation?
|
st45565
|
unami:
Which as far as I understand means that weights of the model were updated.
No, that won’t be the case, since you are never updating the model (and the gradient calculation is also disabled via torch.no_grad()).
The difference in the losses might come from additional calls into the random number generator during the validation loop while the model is still in training mode.
As you’ve already described the dropout layers will be used, which will sample random numbers and would thus change the next call into the random number generator.
Besides that the running stats in all batchnorm layers will be updated with the validation batch statistics, which would be a data leak.
|
st45566
|
Hi All
we have dataloader and training code works like this way
for fi, batch in enumerate(my_data_loader):
train()
and in our dataloader, we have define some collate_fn to cook_data
DataLoader(my_dataset,
num_workers=config['num_dataloader_worker'],
batch_size=config['dataloader_batch_size'],
timeout=600,
collate_fn=cook_data
)
My question here is when training is running, can data loader in parallel run in background to do like cook_data, or each “process” will first load/cook data , then run training, so during training, this particular process is basically blocking waiting there?
|
st45567
|
The DataLoader will use multiprocessing to create multiple workers, which will load and process each data sample and add the batch to a queue. It should thus not be blocking the training as long as the queue is filled with batches.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.