Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random vectors of Euclidean norm <= 1 in Python?

More specifically, given a natural number d, how can I generate random vectors in R^d such that each vector x has Euclidean norm <= 1?

Generating random vectors via numpy.random.rand(1,d) is no problem, but the likelihood of such a random vector having norm <= 1 is predictably bad for even not-small d. For example, even for d = 10 about 0.2% percent of such random vectors have appropriately small norm. So that seems like a silly solution.

EDIT: Re: Walter's comment, yes, I'm looking for a uniform distribution over vectors in the unit ball in R^d.

like image 635
lamb_da_calculus Avatar asked Jun 01 '16 20:06

lamb_da_calculus


People also ask

How do you find the Euclidean norm of a vector in Python?

To calculate the L2 norm of a vector, take the square root of the sum of the squared vector values. Another name for L2 norm of a vector is Euclidean distance. This is often used for calculating the error in machine learning models.

What does norm () do in Python?

The norm is what is generally used to evaluate the error of a model. For instance it is used to calculate the error between the output of a neural network and what is expected (the actual label or value). You can think of the norm as the length of a vector. It is a function that maps a vector to a positive value.

How do you find the norm of an array in Python?

To find a matrix or vector norm we use function numpy. linalg. norm() of Python library Numpy. This function returns one of the seven matrix norms or one of the infinite vector norms depending upon the value of its parameters.

Does Numpy have random?

NumPy offers the random module to work with random numbers.


1 Answers

Based on the Wolfram Mathworld article on hypersphere point picking and Nate Eldredge's answer to a similar question on math.stackexchange.com, you can generate such a vector by generating a vector of d independent Gaussian random variables and a random number U uniformly distributed over the closed interval [0, 1], then normalizing the vector to norm U^(1/d).

like image 132
user2357112 supports Monica Avatar answered Oct 15 '22 09:10

user2357112 supports Monica