I am going through Pytorch and want to create a random tensor of shape 5X3 in the interval [3,7)
torch.rand(5,3) will return a random tensor of shape 5 X 3, however, I could not figure to set the given interval.
Please guide.
You can map U ~ [0, 1] to U ~ [a, b] with u -> (a - b)*u + b:
(a - b)*torch.rand(5, 3) + b
Define the minimum and maximum value and use the code below:
import torch
max = 7
min = 3
rand_tensor = (max-min)*torch.rand((5, 3)) + min
Related
I have a tensor A with the shape BxWxH (B=Batch size, W=Width, H=Height) and want to change it to a tensor B of shape BxNx3 (B=Batch size, N=Number of points=W*H).
Tensor A represents a depth map, e.g. tensor[0,1,2] => gives the depth value for the pixel (1,2) in batch 0.
Tensor B also represents a depth map but in a different format. Each point in tensor B has the following three dimensions: (x coord, y coord, depth value).
How can I transform tensor A into tensor B?
You are looking for meshgrid to give you the x and y coordinates of each pixel:
b, w, h = A.shape
x, y = torch.meshgrid(torch.arange(w), torch.arange(h))
B = torch.cat((x[None, ...], y[None, ...], A), dim=0)
B = B.reshape(b, w*h, 3)
i'm trying to write a python code to calculate the distance between two 3D points. Those points are listed as follows:
Timestamp, X, Y, Z, Distance
2613, 4.35715, 5.302030, -0.447308
2614, 7.88429, -8.401940, -0.484432
2615, 4.08796, 2.213850, -0.515359
2616, 4.35715, 5.302030, -0.447308
2617, 7.88429, -8.401940, -0.484432
i know the formula but I'm not sure how to list the column to run the formula for 3D point distance!
This is essentially the same question as How can the Euclidean distance be calculated with NumPy?
you can use numpy/scipy.linalg.norm
E.g.
scipy.lingalg.norm(2613-2614)
can you try this code and see if you can get some ideas to start:
# distance between 2 points in 3D
from math import pow, sqrt
from functools import reduce
def calculate_dist(point1, point2):
x, y, z = point1
a, b, c = point2
distance = sqrt(pow(a - x, 2) +
pow(b - y, 2) +
pow(c - z, 2)* 1.0)
return distance
point1 = (2, 3, 4) # tuple
point2 = (1, 5, 7)
print(calculate_dist(point1, point2))
# reduce(calcuate_dist(oint1, point2)) # apply to your data
Assuming that I have defined 2 probability variables in SymPy:
x = Normal('x', 0, 2)
y = 2*x + Normal('0', 3)
Now given evidence that y = 4, is it possible to define a new probability variable that follow the posterior distribution P(x | y=4)?
It is easy to simply multiply the probability distribution function of 2, however I wonder whether sympy has the feature to yield a probability variable directly.
The typical way is to pass conditions as the second argument without creating a new random symbol: for example,
density(x, Eq(y, 4)) # Lambda(x, 5*sqrt(2)*exp(8/25)*exp(-x**2/8)*exp(-2*(-x + 2)**2/9)/(12*sqrt(pi)))
P(x > 0, Eq(y, 4)) # -erfc(8*sqrt(2)/15)/2 + 1
But it's also possible to create a random variable with a custom density using ContinuousRV:
from sympy.stats import ContinuousRV
x_post = Symbol("x_post")
X_post = ContinuousRV(x_post, density(x, Eq(y, 4))(x_post))
For example, simplify(E(X_post)) returns 16*erf(3*sqrt(2)/10)/25 + 16*erfc(3*sqrt(2)/10)/25 + 16/25.
The data is from a measurement. The picture of the plotted data
I tried using trapz twice, but I get and error code: "ValueError: operands could not be broadcast together with shapes (1,255) (256,531)"
The x has 256 points and y has 532 points, also the Z is a 2d array that has a 256 by 532 lenght. The code is below:
import numpy as np
img=np.loadtxt('focus_x.txt')
m=0
m=np.max(img)
Z=img/m
X=np.loadtxt("pixelx.txt",float)
Y=np.loadtxt("pixely.txt",float)
[X, Y] = np.meshgrid(X, Y)
volume=np.trapz(X,np.trapz(Y,Z))
The docs state that trapz should be used like this
intermediate = np.trapz(Z, x)
result = np.trapz(intermediate, y)
trapz is reducing the dimensionality of its operand (by default on the last axis) using optionally a 1D array of abscissae to determine the sub intervals of integration; it is not using a mesh grid for its operation.
A complete example.
First we compute, using sympy, the integral of a simple bilinear function over a rectangular domain (0, 5) × (0, 7)
In [1]: import sympy as sp, numpy as np
In [2]: x, y = sp.symbols('x y')
In [3]: f = 1 + 2*x + y + x*y
In [4]: f.integrate((x, 0, 5)).integrate((y, 0, 7))
Out[4]: 2555/4
Now we compute the trapezoidal approximation to the integral (as it happens, the approximation is exact for a bilinear function) — we need coordinates arrays
In [5]: x, y = np.linspace(0, 5, 11), np.linspace(0, 7, 22)
(note that the sampling is different in the two directions and different from the defalt value used by trapz) — we need a mesh grid to compute the integrand and we need to compute the integrand
In [6]: X, Y = np.meshgrid(x, y)
In [7]: z = 1 + 2*X + Y + X*Y
and eventually we compute the integral
In [8]: 4*np.trapz(np.trapz(z, x), y)
Out[8]: 2555.0
PyTorch's torch.transpose function only transposes 2D inputs. Documentation is here.
On the other hand, Tensorflow's tf.transpose function allows you to transpose a tensor of N arbitrary dimensions.
Can someone please explain why PyTorch does not/cannot have N-dimension transpose functionality? Is this due to the dynamic nature of the computation graph construction in PyTorch versus Tensorflow's Define-then-Run paradigm?
It's simply called differently in pytorch. torch.Tensor.permute will allow you to swap dimensions in pytorch like tf.transpose does in TensorFlow.
As an example of how you'd convert a 4D image tensor from NHWC to NCHW (not tested, so might contain bugs):
>>> img_nhwc = torch.randn(10, 480, 640, 3)
>>> img_nhwc.size()
torch.Size([10, 480, 640, 3])
>>> img_nchw = img_nhwc.permute(0, 3, 1, 2)
>>> img_nchw.size()
torch.Size([10, 3, 480, 640])
Einops supports verbose transpositions for arbitrary number of dimensions:
from einops import rearrange
x = torch.zeros(10, 3, 100, 100)
y = rearrange(x, 'b c h w -> b h w c')
x2 = rearrange(y, 'b h w c -> b c h w') # inverse to the first
(and the same code works for tensorfow as well)