|
|
|
@ -17,7 +17,8 @@ from mindspore.ops import operations as P
|
|
|
|
|
import mindspore.nn as nn
|
|
|
|
|
from mindspore.common import dtype as mstype
|
|
|
|
|
from .distribution import Distribution
|
|
|
|
|
from ._utils.utils import logits_to_probs, probs_to_logits, check_type, check_tensor_type, cast_to_tensor, raise_probs_logits_error
|
|
|
|
|
from ._utils.utils import logits_to_probs, probs_to_logits, check_type, cast_to_tensor, \
|
|
|
|
|
raise_probs_logits_error
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Categorical(Distribution):
|
|
|
|
@ -25,7 +26,7 @@ class Categorical(Distribution):
|
|
|
|
|
Creates a categorical distribution parameterized by either probs or logits (but not both).
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
probs (Tensor, list, numpy.ndarray, Parameter, float): event probabilities.
|
|
|
|
|
probs (Tensor, list, numpy.ndarray, Parameter): event probabilities.
|
|
|
|
|
logits (Tensor, list, numpy.ndarray, Parameter, float): event log-odds.
|
|
|
|
|
seed (int): seed to use in sampling. Default: 0.
|
|
|
|
|
dtype (mindspore.dtype): type of the distribution. Default: mstype.int32.
|
|
|
|
@ -77,6 +78,7 @@ class Categorical(Distribution):
|
|
|
|
|
if (probs is None) == (logits is None):
|
|
|
|
|
raise_probs_logits_error()
|
|
|
|
|
self.reduce_sum = P.ReduceSum(keep_dims=True)
|
|
|
|
|
self.reduce_sum1 = P.ReduceSum(keep_dims=False)
|
|
|
|
|
self.log = P.Log()
|
|
|
|
|
self.exp = P.Exp()
|
|
|
|
|
self.shape = P.Shape()
|
|
|
|
@ -88,6 +90,7 @@ class Categorical(Distribution):
|
|
|
|
|
self.expandim = P.ExpandDims()
|
|
|
|
|
self.gather = P.GatherNd()
|
|
|
|
|
self.concat = P.Concat(-1)
|
|
|
|
|
self.transpose = P.Transpose()
|
|
|
|
|
if probs is not None:
|
|
|
|
|
self._probs = cast_to_tensor(probs, mstype.float32)
|
|
|
|
|
input_sum = self.reduce_sum(self._probs, -1)
|
|
|
|
@ -102,8 +105,8 @@ class Categorical(Distribution):
|
|
|
|
|
self._param = self._logits
|
|
|
|
|
self._num_events = self.shape(self._param)[-1]
|
|
|
|
|
self._param2d = self.reshape(self._param, (-1, self._num_events))
|
|
|
|
|
self._batch_shape = self.shape(self._param2d)[0]
|
|
|
|
|
|
|
|
|
|
self._batch_shape = self.shape(self._param)[:-1]
|
|
|
|
|
self._batch_shape_n = (1,) * len(self._batch_shape)
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def logits(self):
|
|
|
|
@ -130,72 +133,35 @@ class Categorical(Distribution):
|
|
|
|
|
Tensor, shape is shape(probs)[:-1] + sample_shape
|
|
|
|
|
"""
|
|
|
|
|
self.checktuple(sample_shape, 'shape')
|
|
|
|
|
if sample_shape == ():
|
|
|
|
|
sample_shape = (1,)
|
|
|
|
|
num_sample = 1
|
|
|
|
|
for i in sample_shape:
|
|
|
|
|
num_sample *= i
|
|
|
|
|
probs_2d = self.reshape(self._probs, (-1, self._num_events))
|
|
|
|
|
samples = self.mutinomial(probs_2d, num_sample)
|
|
|
|
|
samples = self.transpose(samples, (1, 0))
|
|
|
|
|
extend_shape = sample_shape
|
|
|
|
|
if len(self.shape(self._probs)) > 1:
|
|
|
|
|
extend_shape = sample_shape + self.shape(self._probs)[:-1]
|
|
|
|
|
return self.cast(self.reshape(samples, extend_shape), self.dtype)
|
|
|
|
|
|
|
|
|
|
def _broad_cast_shape(self, a, b):
|
|
|
|
|
"""
|
|
|
|
|
Broadcast Tensor shape.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
a (Tensor): A Tensor need to Broadcast.
|
|
|
|
|
b (Tensor): Another Tensor need to Broadcast.
|
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
Tuple, Broadcast shape.
|
|
|
|
|
"""
|
|
|
|
|
shape_a = self.shape(a)
|
|
|
|
|
shape_b = self.shape(b)
|
|
|
|
|
size_a = len(shape_a)
|
|
|
|
|
size_b = len(shape_b)
|
|
|
|
|
if size_a > size_b:
|
|
|
|
|
size = size_a
|
|
|
|
|
shape_out = list(shape_a)
|
|
|
|
|
shape_short = list(shape_b)
|
|
|
|
|
diff_size = size_a - size_b
|
|
|
|
|
else:
|
|
|
|
|
size = size_b
|
|
|
|
|
shape_out = list(shape_b)
|
|
|
|
|
shape_short = list(shape_a)
|
|
|
|
|
diff_size = size_b - size_a
|
|
|
|
|
for i in range(diff_size, size):
|
|
|
|
|
if shape_out[i] == shape_short[i - diff_size]:
|
|
|
|
|
continue
|
|
|
|
|
if shape_out[i] == 1 or shape_short[i - diff_size] == 1:
|
|
|
|
|
shape_out[i] = shape_out[i] * shape_short[i - diff_size]
|
|
|
|
|
else:
|
|
|
|
|
raise ValueError(f"Shape {shape_a} and {shape_b} is not broadcastable.")
|
|
|
|
|
return tuple(shape_out)
|
|
|
|
|
|
|
|
|
|
def _log_prob(self, value):
|
|
|
|
|
r"""
|
|
|
|
|
Evaluate log probability.
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
value (Tensor): value to be evaluated. The dtype could be mstype.float32, bool, mstype.int32.
|
|
|
|
|
value (Tensor): value to be evaluated.
|
|
|
|
|
"""
|
|
|
|
|
if value is not None:
|
|
|
|
|
check_tensor_type("value", value, [mstype.float32, bool, mstype.int32])
|
|
|
|
|
value = self.expandim(self.cast(value, mstype.float32), -1)
|
|
|
|
|
broad_shape = self._broad_cast_shape(value, self._logits)
|
|
|
|
|
broad = P.BroadcastTo(broad_shape)
|
|
|
|
|
logits_pmf = self.reshape(broad(self._logits), (-1, broad_shape[-1]))
|
|
|
|
|
value = self.reshape(broad(value)[..., :1], (-1, 1))
|
|
|
|
|
index = nn.Range(0., self.shape(value)[0], 1)()
|
|
|
|
|
index = self.reshape(index, (-1, 1))
|
|
|
|
|
value = self.concat((index, value))
|
|
|
|
|
value = self.cast(value, mstype.int32)
|
|
|
|
|
return self.reshape(self.gather(logits_pmf, value), broad_shape[:-1])
|
|
|
|
|
return None
|
|
|
|
|
value = self._check_value(value, 'value')
|
|
|
|
|
value = self.expandim(self.cast(value, mstype.float32), -1)
|
|
|
|
|
broad_shape = self.shape(value + self._logits)
|
|
|
|
|
broad = P.BroadcastTo(broad_shape)
|
|
|
|
|
logits_pmf = self.reshape(broad(self._logits), (-1, broad_shape[-1]))
|
|
|
|
|
value = self.reshape(broad(value)[..., :1], (-1, 1))
|
|
|
|
|
index = nn.Range(0., self.shape(value)[0], 1)()
|
|
|
|
|
index = self.reshape(index, (-1, 1))
|
|
|
|
|
value = self.concat((index, value))
|
|
|
|
|
value = self.cast(value, mstype.int32)
|
|
|
|
|
return self.reshape(self.gather(logits_pmf, value), broad_shape[:-1])
|
|
|
|
|
|
|
|
|
|
def _entropy(self):
|
|
|
|
|
r"""
|
|
|
|
@ -205,7 +171,7 @@ class Categorical(Distribution):
|
|
|
|
|
H(X) = -\sum(logits * probs)
|
|
|
|
|
"""
|
|
|
|
|
p_log_p = self._logits * self._probs
|
|
|
|
|
return self.reduce_sum(-p_log_p, -1)
|
|
|
|
|
return self.reduce_sum1(-p_log_p, -1)
|
|
|
|
|
|
|
|
|
|
def enumerate_support(self, expand=True):
|
|
|
|
|
r"""
|
|
|
|
@ -213,8 +179,8 @@ class Categorical(Distribution):
|
|
|
|
|
"""
|
|
|
|
|
num_events = self._num_events
|
|
|
|
|
values = nn.Range(0., num_events, 1)()
|
|
|
|
|
values = self.reshape(values, (num_events, 1))
|
|
|
|
|
values = self.reshape(values, (num_events,) + self._batch_shape_n)
|
|
|
|
|
if expand:
|
|
|
|
|
values = P.BroadcastTo((num_events, self._batch_shape))(values)
|
|
|
|
|
values = P.BroadcastTo((num_events,) + self._batch_shape)(values)
|
|
|
|
|
values = self.cast(values, mstype.int32)
|
|
|
|
|
return values
|
|
|
|
|