Skip to content

Commit a53908d

Browse files
committed
implemented math_ops: 1) reduce_logsumexp, 2) reduce_max, 3) log, 4) square
1 parent 115d489 commit a53908d

File tree

6 files changed

+136
-4
lines changed

6 files changed

+136
-4
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Tensorflow
6+
{
7+
public static partial class tf
8+
{
9+
public static Tensor reshape(Tensor tensor,
10+
Tensor shape,
11+
string name = null) => gen_array_ops.reshape(tensor, shape, name);
12+
13+
}
14+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Tensorflow
6+
{
7+
public static partial class tf
8+
{
9+
public static Tensor tile(Tensor input,
10+
Tensor multiples,
11+
string name = null) => gen_array_ops.tile(input, multiples, name);
12+
13+
}
14+
}

src/TensorFlowNET.Core/Operations/array_ops.py.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ public static Tensor rank(Tensor input, string name = null)
6666
public static Tensor ones_like<T>(T tensor, TF_DataType dtype = TF_DataType.DtInvalid, string name = null, bool optimize = true)
6767
=> ones_like_impl(tensor, dtype, name, optimize);
6868

69+
public static Tensor reshape(Tensor tensor, Tensor shape, string name = null)
70+
{
71+
return gen_array_ops.reshape(tensor, shape, null);
72+
}
73+
6974
private static Tensor ones_like_impl<T>(T tensor, TF_DataType dtype, string name, bool optimize = true)
7075
{
7176
return with(ops.name_scope(name, "ones_like", new { tensor }), scope =>

src/TensorFlowNET.Core/Operations/gen_math_ops.cs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,32 @@ public static Tensor square(Tensor x, string name = null)
6161
return _op.outputs[0];
6262
}
6363

64+
/// <summary>
65+
/// Returns which elements of x are finite.
66+
/// </summary>
67+
/// <param name="x"> A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`.</param>
68+
/// <param name="name"> A name for the operation (optional).</param>
69+
/// <returns> A `Tensor` of type `bool`.</returns>
70+
public static Tensor is_finite(Tensor x, string name = null)
71+
{
72+
var _op = _op_def_lib._apply_op_helper("IsFinite", name, args: new { x });
73+
74+
return _op.outputs[0];
75+
}
76+
77+
/// <summary>
78+
/// Computes exponential of x element-wise. \\(y = e^x\\).
79+
/// </summary>
80+
/// <param name="x"> A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `complex64`, `complex128`.</param>
81+
/// <param name="name"> A name for the operation (optional).</param>
82+
/// <returns> A `Tensor`. Has the same type as `x`.</returns>
83+
public static Tensor exp(Tensor x, string name = null)
84+
{
85+
var _op = _op_def_lib._apply_op_helper("Exp", name, args: new { x });
86+
87+
return _op.outputs[0];
88+
}
89+
6490
/// <summary>
6591
/// Computes natural logarithm of x element-wise.
6692
/// </summary>
@@ -160,6 +186,13 @@ public static Tensor maximum<T1, T2>(T1 x, T2 y, string name = null)
160186
return _op.outputs[0];
161187
}
162188

189+
public static Tensor _max(Tensor input, int[] axis, bool keep_dims=false, string name = null)
190+
{
191+
var _op = _op_def_lib._apply_op_helper("Max", name, new { input, reduction_indices = axis, keep_dims });
192+
193+
return _op.outputs[0];
194+
}
195+
163196
public static Tensor pow<Tx, Ty>(Tx x, Ty y, string name = null)
164197
{
165198
var _op = _op_def_lib._apply_op_helper("Pow", name, args: new { x, y });

src/TensorFlowNET.Core/Operations/math_ops.py.cs

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,51 @@ public static Tensor reduced_shape(Tensor input_shape, Tensor axes)
8787
return gen_data_flow_ops.dynamic_stitch(a1, a2);
8888
}
8989

90+
/// <summary>
91+
/// Computes log(sum(exp(elements across dimensions of a tensor))).
92+
/// Reduces `input_tensor` along the dimensions given in `axis`.
93+
/// Unless `keepdims` is true, the rank of the tensor is reduced by 1 for each
94+
/// entry in `axis`. If `keepdims` is true, the reduced dimensions
95+
/// are retained with length 1.
96+
97+
/// If `axis` has no entries, all dimensions are reduced, and a
98+
/// tensor with a single element is returned.
99+
100+
/// This function is more numerically stable than log(sum(exp(input))). It avoids
101+
/// overflows caused by taking the exp of large inputs and underflows caused by
102+
/// taking the log of small inputs.
103+
/// </summary>
104+
/// <param name="input_tensor"> The tensor to reduce. Should have numeric type.</param>
105+
/// <param name="axis"> The dimensions to reduce. If `None` (the default), reduces all
106+
/// dimensions.Must be in the range `[-rank(input_tensor), rank(input_tensor))`.</param>
107+
/// <param name="keepdims"></param>
108+
/// <returns> The reduced tensor.</returns>
109+
public static Tensor reduce_logsumexp(Tensor input_tensor, int[] axis = null, bool keepdims = false, string name = null)
110+
{
111+
with(ops.name_scope(name, "ReduceLogSumExp", new { input_tensor }), scope =>
112+
{
113+
var raw_max = reduce_max(input_tensor, axis, true);
114+
var my_max = array_ops.stop_gradient(array_ops.where(gen_math_ops.is_finite(raw_max), raw_max, array_ops.zeros_like(raw_max)));
115+
var result = gen_math_ops.log(
116+
reduce_sum(
117+
gen_math_ops.exp(gen_math_ops.sub(input_tensor, my_max)),
118+
new Tensor(axis),
119+
keepdims));
120+
if (!keepdims)
121+
{
122+
my_max = array_ops.reshape(my_max, array_ops.shape(result));
123+
}
124+
result = gen_math_ops.add(result, my_max);
125+
return _may_reduce_to_scalar(keepdims, axis, result);
126+
});
127+
return null;
128+
}
129+
130+
public static Tensor reduce_max(Tensor input_tensor, int[] axis = null, bool keepdims = false, string name = null)
131+
{
132+
return _may_reduce_to_scalar(keepdims, axis, gen_math_ops._max(input_tensor, (int[])_ReductionDims(input_tensor, axis), keepdims, name));
133+
}
134+
90135
/// <summary>
91136
/// Casts a tensor to type `int32`.
92137
/// </summary>

test/TensorFlowNET.Examples/NaiveBayesClassifier.cs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ namespace TensorFlowNET.Examples
1212
/// </summary>
1313
public class NaiveBayesClassifier : Python, IExample
1414
{
15+
public Normal dist { get; set; }
1516
public void Run()
1617
{
1718
np.array<float>(1.0f, 1.0f);
@@ -72,16 +73,36 @@ public void fit(NDArray X, NDArray y)
7273
// Create a 3x2 univariate normal distribution with the
7374
// Known mean and variance
7475
var dist = tf.distributions.Normal(mean, tf.sqrt(variance));
75-
76+
this.dist = dist;
7677
}
7778

7879
public void predict (NDArray X)
7980
{
80-
// assert self.dist is not None
81-
// nb_classes, nb_features = map(int, self.dist.scale.shape)
81+
if (dist == null)
82+
{
83+
throw new ArgumentNullException("cant not find the model (normal distribution)!");
84+
}
85+
int nb_classes = (int) dist.scale().shape[0];
86+
int nb_features = (int)dist.scale().shape[1];
8287

88+
// Conditional probabilities log P(x|c) with shape
89+
// (nb_samples, nb_classes)
90+
Tensor tile = tf.tile(new Tensor(X), new Tensor(new int[] { -1, nb_classes, nb_features }));
91+
Tensor r = tf.reshape(tile, new Tensor(new int[] { -1, nb_classes, nb_features }));
92+
var cond_probs = tf.reduce_sum(dist.log_prob(r));
93+
// uniform priors
94+
var priors = np.log(np.array<double>((1.0 / nb_classes) * nb_classes));
8395

84-
throw new NotFiniteNumberException();
96+
// posterior log probability, log P(c) + log P(x|c)
97+
var joint_likelihood = tf.add(new Tensor(priors), cond_probs);
98+
// normalize to get (log)-probabilities
99+
/*
100+
var norm_factor = tf.reduce_logsumexp(joint_likelihood, axis = 1, keep_dims = True)
101+
var log_prob = joint_likelihood - norm_factor;
102+
// exp to get the actual probabilities
103+
return tf.exp(log_prob)
104+
*/
105+
throw new NotImplementedException();
85106
}
86107
}
87108
}

0 commit comments

Comments
 (0)