Skip to content
This repository has been archived by the owner on Nov 17, 2023. It is now read-only.

[Numpy] Random.gamma() implemented #16152

Merged
merged 8 commits into from
Jan 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 58 additions & 1 deletion python/mxnet/ndarray/numpy/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from ..ndarray import NDArray


__all__ = ['randint', 'uniform', 'normal', "choice", "rand", "multinomial", "shuffle"]
__all__ = ['randint', 'uniform', 'normal', "choice", "rand", "multinomial", "shuffle", 'gamma']


def randint(low, high=None, size=None, dtype=None, ctx=None, out=None):
Expand Down Expand Up @@ -319,6 +319,63 @@ def choice(a, size=None, replace=True, p=None, ctx=None, out=None):
return _npi.choice(p, a=a, size=size, replace=replace, ctx=ctx, weighted=True, out=out)


def gamma(shape, scale=1.0, size=None, dtype=None, ctx=None, out=None):
"""Draw samples from a Gamma distribution.

Samples are drawn from a Gamma distribution with specified parameters,
`shape` (sometimes designated "k") and `scale` (sometimes designated
"theta"), where both parameters are > 0.

Parameters
----------
shape : float or array_like of floats
The shape of the gamma distribution. Should be greater than zero.
scale : float or array_like of floats, optional
The scale of the gamma distribution. Should be greater than zero.
Default is equal to 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``shape`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(shape, scale).size`` samples are drawn.
ctx : Context, optional
Device context of output. Default is current context.

Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized gamma distribution.

The Gamma distribution is often used to model the times to failure of
electronic components, and arises naturally in processes for which the
waiting times between Poisson distributed events are relevant.
"""
from ...numpy import ndarray as np_ndarray
input_type = (isinstance(shape, np_ndarray), isinstance(scale, np_ndarray))
if dtype is None:
dtype = 'float32'
xidulu marked this conversation as resolved.
Show resolved Hide resolved
if ctx is None:
ctx = current_context()
if out is not None:
size = out.shape
if size == ():
size = None
if input_type == (True, True):
return _npi.gamma(shape, scale, shape=None, scale=None, size=size,
ctx=ctx, dtype=dtype, out=out)
elif input_type == (False, True):
return _npi.gamma(scale, shape=shape, scale=None, size=size,
ctx=ctx, dtype=dtype, out=out)
elif input_type == (True, False):
return _npi.gamma(shape, shape=None, scale=scale, size=size,
ctx=ctx, dtype=dtype, out=out)
else:
return _npi.gamma(shape=shape, scale=scale, size=size,
ctx=ctx, dtype=dtype, out=out)

raise ValueError("Distribution parameters must be either mxnet.numpy.ndarray or numbers")


def rand(*size, **kwargs):
r"""Random values in a given shape.

Expand Down
37 changes: 36 additions & 1 deletion python/mxnet/numpy/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
from __future__ import absolute_import
from ..ndarray import numpy as _mx_nd_np

__all__ = ["randint", "uniform", "normal", "choice", "rand", "multinomial", "shuffle", "randn"]
__all__ = ["randint", "uniform", "normal", "choice", "rand", "multinomial", "shuffle", "randn",
"gamma"]


def randint(low, high=None, size=None, dtype=None, ctx=None, out=None):
Expand Down Expand Up @@ -359,6 +360,40 @@ def shuffle(x):
_mx_nd_np.random.shuffle(x)


def gamma(shape, scale=1.0, size=None, dtype=None, ctx=None, out=None):
"""Draw samples from a Gamma distribution.

Samples are drawn from a Gamma distribution with specified parameters,
`shape` (sometimes designated "k") and `scale` (sometimes designated
"theta"), where both parameters are > 0.

Parameters
----------
shape : float or array_like of floats
The shape of the gamma distribution. Should be greater than zero.
scale : float or array_like of floats, optional
The scale of the gamma distribution. Should be greater than zero.
Default is equal to 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``shape`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(shape, scale).size`` samples are drawn.
ctx : Context, optional
Device context of output. Default is current context.

Returns
-------
out : ndarray or scalar
Drawn samples from the parameterized gamma distribution.

The Gamma distribution is often used to model the times to failure of
electronic components, and arises naturally in processes for which the
waiting times between Poisson distributed events are relevant.
"""
return _mx_nd_np.random.gamma(shape, scale, size, dtype, ctx, out)


def randn(*size, **kwargs):
r"""Return a sample (or samples) from the "standard normal" distribution.
If positive, int_like or int-convertible arguments are provided,
Expand Down
59 changes: 58 additions & 1 deletion python/mxnet/symbol/numpy/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from ...context import current_context
from . import _internal as _npi

__all__ = ['randint', 'uniform', 'normal', 'rand', 'shuffle']
__all__ = ['randint', 'uniform', 'normal', 'rand', 'shuffle', 'gamma']


def randint(low, high=None, size=None, dtype=None, ctx=None, out=None):
Expand Down Expand Up @@ -290,6 +290,63 @@ def choice(a, size=None, replace=True, p=None, ctx=None, out=None):
return _npi.choice(p, a=a, size=size, replace=replace, ctx=ctx, weighted=True, out=out)


def gamma(shape, scale=1.0, size=None, dtype=None, ctx=None, out=None):
"""Draw samples from a Gamma distribution.

Samples are drawn from a Gamma distribution with specified parameters,
`shape` (sometimes designated "k") and `scale` (sometimes designated
"theta"), where both parameters are > 0.

Parameters
----------
shape : float or array_like of floats
The shape of the gamma distribution. Should be greater than zero.
scale : float or array_like of floats, optional
The scale of the gamma distribution. Should be greater than zero.
Default is equal to 1.
size : int or tuple of ints, optional
Output shape. If the given shape is, e.g., ``(m, n, k)``, then
``m * n * k`` samples are drawn. If size is ``None`` (default),
a single value is returned if ``shape`` and ``scale`` are both scalars.
Otherwise, ``np.broadcast(shape, scale).size`` samples are drawn.
ctx : Context, optional
Device context of output. Default is current context.

Returns
-------
out : _Symbol
Drawn samples from the parameterized gamma distribution.

The Gamma distribution is often used to model the times to failure of
electronic components, and arises naturally in processes for which the
waiting times between Poisson distributed events are relevant.
"""
from ._symbol import _Symbol as np_symbol
input_type = (isinstance(shape, np_symbol), isinstance(scale, np_symbol))
if dtype is None:
dtype = 'float32'
if ctx is None:
ctx = current_context()
if out is not None:
size = out.shape
if size == ():
size = None
if input_type == (True, True):
return _npi.gamma(shape, scale, shape=None, scale=None, size=size,
ctx=ctx, dtype=dtype, out=out)
elif input_type == (False, True):
return _npi.gamma(scale, shape=shape, scale=None, size=size,
ctx=ctx, dtype=dtype, out=out)
elif input_type == (True, False):
return _npi.gamma(shape, shape=None, scale=scale, size=size,
ctx=ctx, dtype=dtype, out=out)
else:
return _npi.gamma(shape=shape, scale=scale, size=size,
ctx=ctx, dtype=dtype, out=out)

raise ValueError("Distribution parameters must be either _Symbol or numbers")


def shuffle(x):
"""
Modify a sequence in-place by shuffling its contents.
Expand Down
84 changes: 84 additions & 0 deletions src/operator/numpy/random/np_gamma_op.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

/*!
* Copyright (c) 2019 by Contributors
* \file np_gamma_op.cc
* \brief Operator for random sampling from gamma distribution
*/

#include "./np_gamma_op.h"

namespace mxnet {
namespace op {

DMLC_REGISTER_PARAMETER(NumpyGammaParam);

inline bool NumpyGammaOpType(const nnvm::NodeAttrs& attrs,
std::vector<int>* in_attrs,
std::vector<int>* out_attrs) {
const NumpyGammaParam& param = nnvm::get<NumpyGammaParam>(attrs.parsed);
int otype = param.dtype;
if (otype != -1) {
(*out_attrs)[0] = otype;
} else {
(*out_attrs)[0] = mshadow::kFloat32;
}
return true;
}

NNVM_REGISTER_OP(_npi_gamma)
.describe("Numpy behavior gamma")
.set_num_inputs(
[](const nnvm::NodeAttrs& attrs) {
const NumpyGammaParam& param = nnvm::get<NumpyGammaParam>(attrs.parsed);
int num_inputs = 2;
if (param.shape.has_value()) num_inputs -= 1;
if (param.scale.has_value()) num_inputs -= 1;
return num_inputs;
}
)
.set_num_outputs(1)
.set_attr<nnvm::FListInputNames>("FListInputNames",
[](const NodeAttrs& attrs) {
const NumpyGammaParam& param = nnvm::get<NumpyGammaParam>(attrs.parsed);
int num_inputs = 2;
if (param.scale.has_value()) num_inputs -= 1;
if (param.shape.has_value()) num_inputs -= 1;
if (num_inputs == 0) return std::vector<std::string>();
if (num_inputs == 1) return std::vector<std::string>{"input1"};
return std::vector<std::string>{"input1", "input2"};
})
.set_attr_parser(ParamParser<NumpyGammaParam>)
.set_attr<mxnet::FInferShape>("FInferShape", TwoparamsDistOpShape<NumpyGammaParam>)
.set_attr<nnvm::FInferType>("FInferType", NumpyGammaOpType)
.set_attr<FResourceRequest>("FResourceRequest",
[](const nnvm::NodeAttrs& attrs) {
return std::vector<ResourceRequest>{
ResourceRequest::kRandom,
ResourceRequest::kTempSpace};
})
.set_attr<FCompute>("FCompute<cpu>", NumpyGammaForward<cpu, double>)
.set_attr<nnvm::FGradient>("FGradient", MakeZeroGradNodes)
.add_argument("input1", "NDArray-or-Symbol", "Source input")
.add_argument("input2", "NDArray-or-Symbol", "Source input")
.add_arguments(NumpyGammaParam::__FIELDS__());

} // namespace op
} // namespace mxnet
36 changes: 36 additions & 0 deletions src/operator/numpy/random/np_gamma_op.cu
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

/*!
* Copyright (c) 2019 by Contributors
* \file np_gamma_op.cu
* \brief Operator for random sampling from gamma distribution
*/

#include "./np_gamma_op.h"
#include <iostream>

namespace mxnet {
namespace op {

NNVM_REGISTER_OP(_npi_gamma)
.set_attr<FCompute>("FCompute<gpu>", NumpyGammaForward<gpu, double>);

} // namespace op
} // namespace mxnet
Loading