PyTorch — это открытая библиотека машинного обучения с открытым исходным кодом, используемая для глубокого обучения с большей гибкостью и осуществимостью. Это расширение NumPy.
Что касается статистических функций для случайной выборки, давайте посмотрим, что они из себя представляют, а также их простые реализации. Чтобы запустить все это, сначала нужно импортировать Pytorch с помощью импортного факела. Есть 5 функций:
- torch.bernoulli()
- torch.normal()
- torch.poisson()
- torch.randn()
- torch.randperm()
1) функция torch.bernoulli()
Эта функция просто преобразует все входные данные в двоичные случайные числа (0 или 1) из распределения Бернулли. Форма вывода такая же, как данные, введенные в код.
Syntax-
torch.bernoulli(input, *, generator=None, out=None) → Tensor
Parameters-
input (Tensor) – the input tensor of probability values for the Bernoulli distribution
Key Argument-
- generator (torch.Generator, optional) – a pseudorandom number generator for sampling
- out (Tensor, optional) – the output tensor.
Пример:
В этом примере давайте рассмотрим базовую простую случайно сгенерированную форму и выведем ее в распределении Бернулли.
Python3
import
torch
# this function will make a
# tensor of 5X5 array with
# random numbers
rand_matrix
=
torch.rand(
5
,
5
)
(rand_matrix)
# Bernoulli distribution
# this function will do the bernoulli
# distrobution on the given matrix and
# form the new tensor
torch.bernoulli(rand_matrix)
Выход:
tensor([[0.5010, 0.0622, 0.3710, 0.3325, 0.5136],
[0.0790, 0.6433, 0.8819, 0.3770, 0.8236],
[0.3458, 0.9933, 0.2282, 0.6544, 0.6823],
[0.5454, 0.5916, 0.2471, 0.6174, 0.1676],
[0.8980, 0.4162, 0.8114, 0.3744, 0.9957]])
tensor([[0., 0., 0., 0., 0.],
[0., 1., 1., 0., 0.],
[0., 1., 0., 0., 0.],
[1., 0., 0., 0., 1.],
[1., 1., 1., 0., 1.]])
2) функция torch.normal()
Эта функция работает по теории нормального распределения. Функция возвращает тензор случайных чисел, в котором задано среднее значение и стандартное отклонение. В этом есть 2 параметра — а) среднее значение — это тензор со средним значением нормального распределения каждого выходного элемента. б) std- тензор со стандартным отклонением
Примечание. Форма среднего и стандартного не обязательно должна быть одинаковой, но общее количество элементов в тензоре одинаково.
Syntax-
torch.normal(mean, std, *, generator=None, out=None) → Tensor
Parameters-
- mean (Tensor) – the tensor of per-element means
- std (Tensor) – the tensor of per-element standard deviations
Key Argument-
- generator (torch.Generator, optional) – a pseudorandom number generator for sampling
- out (Tensor, optional) – the output tensor.
Пример:
В этом примере мы будем генерировать случайные числа с указанным средним значением и стандартным отклонением в функции torch.normal().
Python3
# this function have 2 parameters,
# and will form the tensor of
# normal distribution
# normal(mean,std)
# mean, giving a range of mean
# std,dive the standard in the given range
torch.normal(mean
=
torch.arange(
12.
,
22.
),
std
=
torch.arange(
1
,
0
,
-
0.1
))
Выход:
tensor([12.2238, 12.8651, 15.5746, 14.7285, 16.3280, 17.4913, 17.8418, 19.5997,
19.8890, 21.0208])
3) функция torch.poisson():
Выход этой функции имеет тот же размер, что и вход с каждым элементом, полученным из распределения Пуассона. Это распределение показывает, сколько раз событие может произойти в данный период времени.
Syntax:
torch.poisson(input, generator=None) → Tensor
Parameters:
input (Tensor) – the input tensor containing the rates of the Poisson distribution
Key Arguments:
generator (torch.Generator, optional) – a pseudorandom number generator for sampling
Пример:
В этом примере мы будем генерировать случайную тензорную матрицу 4 × 4, используя функцию torch.poisson() в python.
Python3
# generating the random tensor
# matrix of 4X4
rates_torch
=
torch.rand(
4
,
4
)
*
10
(rates_torch)
# this function will do the poisson
# distribution od the given tensor
# and will give new tensor
# poisson(param),this param is the
# tensor matrix of 4X4
torch.poisson(rates_torch)
Выход:
tensor([[7.5055, 6.9471, 7.9227, 2.2798], [5.0238, 9.1469, 5.4483, 0.1173], [1.3271, 0.0355, 5.4621, 1.8165], [5.1992, 2.9028, 0.2533, 3.8208]]) tensor([[ 8., 11., 10., 5.], [ 6., 12., 5., 0.], [ 2., 0., 5., 0.], [ 4., 2., 0., 2.]])
4) функция torch.randn()
Эта функция возвращает тензор со случайными числами из нормального распределения со средним значением 0 и дисперсией 1 (стандартное нормальное распределение).
Syntax:
torch.randn(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False) → Tensor
Returns a tensor filled with random numbers from a normal distribution with mean 0 and variance 1 (also called the standard normal distribution)
Parameters:
size (int…) – a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple.
Key Arguments:
- generator (torch.Generator, optional) – a pseudorandom number generator for sampling
- out (Tensor, optional) – the output tensor.
- dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: if None, uses a global default (see torch.set_default_tensor_type()).
- layout (torch.layout, optional) – the desired layout of returned Tensor. Default: torch.strided.
- device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.
- requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False.
Пример:
В этом примере мы будем использовать функцию torch.randn() для создания матрицы 4 × 4, передав 4 и 4 функции в python.
Python3
# randn function has two parameters
# for making 2X2 matrix,
# it can have 1 parameter also for
# 1-D matrix the below function
# will five a tensor of the random
# generated matrix
torch.randn(
4
,
4
)
#2-D matrix
Выход:
tensor([[ 0.1073, 0.8425, -0.4281, 0.2010], [ 1.3098, -0.0065, -1.9434, 0.1854], [-0.9948, 0.5385, -0.7217, -0.4963], [ 2.8455, -0.2791, -0.1963, 1.4643]])
5) функция torch.randperm()
Эта функция возвращает случайную перестановку целых чисел.
Syntax:
torch.randperm(n, *, generator=None, out=None, dtype=torch.int64, layout=torch.strided, device=None, requires_grad=False, pin_memory=False) → Tensor
Returns a random permutation of integers from 0 to n – 1.
Parameters:
n (int) – the upper bound (exclusive)
Key Arguments:
- generator (torch.Generator, optional) – a pseudorandom number generator for sampling
- out (Tensor, optional) – the output tensor.
- dtype (torch.dtype, optional) – the desired data type of returned tensor. Default: torch.int64.
- layout (torch.layout, optional) – the desired layout of returned Tensor. Default: torch.strided.
- device (torch.device, optional) – the desired device of returned tensor. Default: if None, uses the current device for the default tensor type (see torch.set_default_tensor_type()). device will be the CPU for CPU tensor types and the current CUDA device for CUDA tensor types.
- requires_grad (bool, optional) – If autograd should record operations on the returned tensor. Default: False.
- pin_memory (bool, optional) – If set, returned tensor would be allocated in the pinned memory. Works only for CPU tensors. Default: False.
Пример:
В этом примере мы генерируем случайные числа от 0 до 5, просто передавая 6 в качестве параметра функции torch.randperm() в Python.
Python3
# this function will give the
# random permutation of the
# given range,
# if randperm(n), then it will
# give 0 to n-1 random permutated
# sequence
torch.randperm(
6
)
Выход:
tensor([4, 1, 0, 2, 3, 5])