Skip to content

Commit 9160887

Browse files
committed
VarCreation1 passed. create variable through variable_scope.
1 parent 0e80ee5 commit 9160887

10 files changed

Lines changed: 114 additions & 29 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ using(var sess = tf.Session())
6666

6767
Read the docs & book [The Definitive Guide to Tensorflow.NET](https://tensorflownet.readthedocs.io/en/latest/FrontCover.html).
6868

69-
More examples:
69+
### More examples:
7070

7171
* [Hello World](test/TensorFlowNET.Examples/HelloWorld.cs)
7272
* [Basic Operations](test/TensorFlowNET.Examples/BasicOperations.cs)

‎src/TensorFlowNET.Core/APIs/tf.init.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace Tensorflow
77
public static partial class tf
88
{
99
public static IInitializer zeros_initializer => new Zeros();
10-
public static IInitializer glorot_uniform => new GlorotUniform();
10+
public static IInitializer glorot_uniform_initializer => new GlorotUniform();
1111

1212
public static variable_scope variable_scope(string name_or_scope,
1313
string default_name = null,

‎src/TensorFlowNET.Core/Operations/gen_random_ops.py.cs‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,34 @@ public static Tensor random_standard_normal(Tensor shape, TF_DataType dtype = TF
2424
if (!seed2.HasValue)
2525
seed2 = 0;
2626

27-
var _op = _op_def_lib._apply_op_helper("RandomStandardNormal", name: name,
27+
var _op = _op_def_lib._apply_op_helper("RandomStandardNormal",
28+
name: name,
2829
args: new { shape, dtype, seed, seed2 });
2930

3031
return _op.outputs[0];
3132
}
33+
34+
/// <summary>
35+
/// Outputs random values from a uniform distribution.
36+
/// </summary>
37+
/// <param name="shape"></param>
38+
/// <param name="dtype"></param>
39+
/// <param name="seed"></param>
40+
/// <param name="seed2"></param>
41+
/// <param name="name"></param>
42+
/// <returns></returns>
43+
public static Tensor random_uniform(Tensor shape, TF_DataType dtype, int? seed = 0, int? seed2 = 0, string name = null)
44+
{
45+
if (!seed.HasValue)
46+
seed = 0;
47+
if (!seed2.HasValue)
48+
seed2 = 0;
49+
50+
var _op = _op_def_lib._apply_op_helper("RandomUniform",
51+
name: name,
52+
args: new { shape, dtype, seed, seed2});
53+
54+
return _op.outputs[0];
55+
}
3256
}
3357
}

‎src/TensorFlowNET.Core/Operations/random_ops.py.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,11 @@ public static Tensor random_uniform(int[] shape,
5656
return with<ops.name_scope, Tensor>(new ops.name_scope(name, "random_uniform", new { shape, minval, maxval }), scope =>
5757
{
5858
name = scope;
59-
return null;
59+
var tensorShape = _ShapeTensor(shape);
60+
var minTensor = ops.convert_to_tensor(minval, dtype: dtype, name: "min");
61+
var maxTensor = ops.convert_to_tensor(maxval, dtype: dtype, name: "max");
62+
var rnd = gen_random_ops.random_uniform(tensorShape, dtype);
63+
return math_ops.add(rnd * (maxTensor - minTensor), minTensor, name: name);
6064
});
6165
}
6266

‎src/TensorFlowNET.Core/Tensors/Tensor.cs‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,11 @@ public int[] _shape_tuple()
7777
return null;
7878
}
7979

80+
public TensorShape getShape()
81+
{
82+
return tensor_util.to_shape(shape);
83+
}
84+
8085
/// <summary>
8186
/// number of dimensions
8287
/// 0 Scalar (magnitude only)

‎src/TensorFlowNET.Core/Variables/RefVariable.cs‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using System;
1+
using Google.Protobuf;
2+
using Google.Protobuf.Collections;
3+
using System;
24
using System.Collections.Generic;
35
using System.Linq;
46
using System.Text;
@@ -99,7 +101,7 @@ private void _init_from_args(object initial_value,
99101
if (initial_value is null)
100102
throw new ValueError("initial_value must be specified.");
101103

102-
var init_from_fn = false;
104+
var init_from_fn = initial_value.GetType().Name == "Func`1";
103105

104106
if(collections == null)
105107
{
@@ -115,12 +117,27 @@ private void _init_from_args(object initial_value,
115117
collections.Add(ops.GraphKeys.TRAINABLE_VARIABLES);
116118

117119
ops.init_scope();
118-
var values = init_from_fn ? new List<object>() : new List<object> { initial_value };
119-
Python.with<ops.name_scope>(new ops.name_scope(name, "Variable", values), scope =>
120+
var values = init_from_fn ? new object[0] : new object[] { initial_value };
121+
with<ops.name_scope>(new ops.name_scope(name, "Variable", values), scope =>
120122
{
123+
name = scope;
121124
if (init_from_fn)
122125
{
123-
126+
// Use attr_scope and device(None) to simulate the behavior of
127+
// colocate_with when the variable we want to colocate with doesn't
128+
// yet exist.
129+
string true_name = ops._name_from_scope_name(name);
130+
var attr = new AttrValue
131+
{
132+
List = new AttrValue.Types.ListValue()
133+
};
134+
attr.List.S.Add(ByteString.CopyFromUtf8($"loc:{true_name}"));
135+
with<ops.name_scope>(new ops.name_scope("Initializer"), scope2 =>
136+
{
137+
_initial_value = (initial_value as Func<Tensor>)();
138+
_initial_value = ops.convert_to_tensor(_initial_value, name: "initial_value", dtype: dtype);
139+
_variable = state_ops.variable_op_v2(_initial_value.shape, _initial_value.dtype.as_base_dtype(), name: name);
140+
});
124141
}
125142
// Or get the initial value from a Tensor or Python object.
126143
else
@@ -135,7 +152,9 @@ private void _init_from_args(object initial_value,
135152
// Manually overrides the variable's shape with the initial value's.
136153
if (validate_shape)
137154
{
138-
var initial_value_shape = _initial_value.shape;
155+
var initial_value_shape = _initial_value.getShape();
156+
if (!initial_value_shape.is_fully_defined())
157+
throw new ValueError($"initial_value must have a shape specified: {_initial_value}");
139158
}
140159

141160
// If 'initial_value' makes use of other variables, make sure we don't

‎src/TensorFlowNET.Core/Variables/_VariableStore.cs‎

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ private RefVariable _get_single_variable(string name,
7474
VariableSynchronization synchronization = VariableSynchronization.AUTO,
7575
VariableAggregation aggregation = VariableAggregation.NONE)
7676
{
77-
bool initializing_from_value = false;
77+
bool initializing_from_value = true;
78+
if (use_resource == null)
79+
use_resource = false;
7880

7981
if (_vars.ContainsKey(name))
8082
{
@@ -86,15 +88,18 @@ private RefVariable _get_single_variable(string name,
8688
throw new NotImplementedException("_get_single_variable");
8789
}
8890

89-
Tensor init_val = null;
90-
91+
RefVariable v = null;
9192
// Create the tensor to initialize the variable with default value.
9293
if (initializer == null)
9394
{
9495
if (dtype.is_floating())
95-
initializer = tf.glorot_uniform;
96+
{
97+
initializer = tf.glorot_uniform_initializer;
98+
initializing_from_value = false;
99+
}
96100
}
97101

102+
// Create the variable.
98103
ops.init_scope();
99104
{
100105
if (initializing_from_value)
@@ -103,23 +108,19 @@ private RefVariable _get_single_variable(string name,
103108
}
104109
else
105110
{
106-
init_val = initializer.call(shape, dtype);
111+
Func<Tensor> init_val = () => initializer.call(shape, dtype);
107112
var variable_dtype = dtype.as_base_dtype();
113+
114+
v = variable_scope.default_variable_creator(init_val,
115+
name: name,
116+
trainable: trainable,
117+
dtype: TF_DataType.DtInvalid,
118+
validate_shape: validate_shape,
119+
synchronization: synchronization,
120+
aggregation: aggregation);
108121
}
109122
}
110123

111-
// Create the variable.
112-
if (use_resource == null)
113-
use_resource = false;
114-
115-
var v = variable_scope.default_variable_creator(init_val,
116-
name: name,
117-
trainable: trainable,
118-
dtype: TF_DataType.DtInvalid,
119-
validate_shape: validate_shape,
120-
synchronization: synchronization,
121-
aggregation: aggregation);
122-
123124
_vars[name] = v;
124125

125126
return v;
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Tensorflow
6+
{
7+
public class state_ops
8+
{
9+
/// <summary>
10+
/// Create a variable Operation.
11+
/// </summary>
12+
/// <param name="shape"></param>
13+
/// <param name="dtype"></param>
14+
/// <param name="name"></param>
15+
/// <param name="container"></param>
16+
/// <param name="shared_name"></param>
17+
/// <returns></returns>
18+
public static Tensor variable_op_v2(long[] shape,
19+
TF_DataType dtype,
20+
string name = "Variable",
21+
string container = "",
22+
string shared_name = "") => gen_state_ops.variable_v2(shape,
23+
dtype,
24+
name: name,
25+
container: container,
26+
shared_name: shared_name);
27+
}
28+
}

‎test/TensorFlowNET.Examples/LinearRegression.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public class LinearRegression : Python, IExample
1616

1717
// Parameters
1818
float learning_rate = 0.01f;
19-
int training_epochs = 10000;
19+
int training_epochs = 1000;
2020
int display_step = 50;
2121

2222
public void Run()

‎test/TensorFlowNET.UnitTest/VariableTest.cs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,18 @@ public void StringVar()
3030
var mammal2 = tf.Variable("Tiger");
3131
}
3232

33+
/// <summary>
34+
/// https://www.tensorflow.org/api_docs/python/tf/variable_scope
35+
/// </summary>
3336
[TestMethod]
34-
public void SimpleScope()
37+
public void VarCreation1()
3538
{
3639
with(tf.variable_scope("foo"), delegate
3740
{
3841
with(tf.variable_scope("bar"), delegate
3942
{
4043
var v = tf.get_variable("v", new TensorShape(1));
44+
Assert.AreEqual(v.name, "foo/bar/v:0");
4145
});
4246
});
4347
}

0 commit comments

Comments
 (0)