forked from SciSharp/TensorFlow.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTensor.cs
More file actions
383 lines (325 loc) · 12.1 KB
/
Copy pathTensor.cs
File metadata and controls
383 lines (325 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/*****************************************************************************
Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
Licensed 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.
******************************************************************************/
using NumSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using static Tensorflow.Python;
namespace Tensorflow
{
/// <summary>
/// A tensor is a generalization of vectors and matrices to potentially higher dimensions.
/// Internally, TensorFlow represents tensors as n-dimensional arrays of base datatypes.
/// </summary>
public partial class Tensor : IDisposable, ITensorOrOperation
{
private IntPtr _handle;
private int _id;
private Operation _op;
public int Id => _id;
public Graph graph => op?.graph;
public Operation op => _op;
public Tensor[] outputs => op.outputs;
/// <summary>
/// The string name of this tensor.
/// </summary>
public string name => $"{(op == null ? "<unnamed Operation>" : $"{op.name}:{_value_index}")}";
private int _value_index;
public int value_index => _value_index;
private Status status = new Status();
private TF_DataType _dtype = TF_DataType.DtInvalid;
public TF_DataType dtype => _handle == IntPtr.Zero ? _dtype : c_api.TF_TensorType(_handle);
public ulong bytesize => _handle == IntPtr.Zero ? 0 : c_api.TF_TensorByteSize(_handle);
public ulong itemsize => _handle == IntPtr.Zero ? 0 : c_api.TF_DataTypeSize(dtype);
public ulong size => _handle == IntPtr.Zero ? 0 : bytesize / itemsize;
public IntPtr buffer => _handle == IntPtr.Zero ? IntPtr.Zero : c_api.TF_TensorData(_handle);
public int num_consumers(TF_Output oper_out) => _handle == IntPtr.Zero ? 0 : c_api.TF_OperationOutputNumConsumers(oper_out);
private TF_Output? _tf_output;
/// <summary>
/// used for keep other pointer when do implicit operating
/// </summary>
public object Tag { get; set; }
public int[] shape
{
get
{
var dims = new long[rank < 0 ? 0 : rank];
if (_handle == IntPtr.Zero)
{
c_api.TF_GraphGetTensorShape(op.graph, _as_tf_output(), dims, rank, status);
status.Check();
}
else
{
for (int i = 0; i < rank; i++)
dims[i] = c_api.TF_Dim(_handle, i);
}
return dims.Select(x => Convert.ToInt32(x)).ToArray();
}
set
{
if (value == null)
c_api.TF_GraphSetTensorShape(this.graph, this._as_tf_output(), null, -1, status);
else
c_api.TF_GraphSetTensorShape(this.graph, this._as_tf_output(), value.Select(x => Convert.ToInt64(x)).ToArray(), value.Length, status);
}
}
public int[] _shape_tuple()
{
if (shape == null) return null;
return shape.Select(x => (int)x).ToArray();
}
public TensorShape TensorShape => tensor_util.to_shape(shape);
public void SetShape(Shape shape)
{
this.shape = shape.Dimensions;
}
/// <summary>
/// number of dimensions
/// 0 Scalar (magnitude only)
/// 1 Vector (magnitude and direction)
/// 2 Matrix (table of numbers)
/// 3 3-Tensor (cube of numbers)
/// n n-Tensor (you get the idea)
/// </summary>
public int rank
{
get
{
if (_handle == IntPtr.Zero)
{
var output = _as_tf_output();
return c_api.TF_GraphGetTensorNumDims(op.graph, output, status);
}
else
{
return c_api.TF_NumDims(_handle);
}
}
}
public int NDims => rank;
public string Device => op.Device;
public Operation[] consumers()
{
var output = _as_tf_output();
var consumer_names = c_api.TF_OperationOutputConsumers_wrapper(output);
return consumer_names.Select(x => graph.OperationByName(x)).ToArray();
}
public TF_Output _as_tf_output()
{
if(!_tf_output.HasValue)
_tf_output = new TF_Output(op, value_index);
return _tf_output.Value;
}
public T[] Data<T>()
{
// Column major order
// https://en.wikipedia.org/wiki/File:Row_and_column_major_order.svg
// matrix:[[1, 2, 3], [4, 5, 6]]
// index: 0 2 4 1 3 5
// result: 1 4 2 5 3 6
var data = new T[size];
for (ulong i = 0; i < size; i++)
{
data[i] = Marshal.PtrToStructure<T>(buffer + (int)(i * itemsize));
}
return data;
}
public byte[] Data()
{
var data = new byte[bytesize];
Marshal.Copy(buffer, data, 0, (int)bytesize);
return data;
}
public Tensor MaybeMove()
{
var tensor = c_api.TF_TensorMaybeMove(_handle);
return tensor;
}
/// <summary>
/// Evaluates this tensor in a `Session`.
/// </summary>
/// <param name="feed_dict">A dictionary that maps `Tensor` objects to feed values.</param>
/// <param name="session">The `Session` to be used to evaluate this tensor.</param>
/// <returns></returns>
public NDArray eval(params FeedItem[] feed_dict)
{
return ops._eval_using_default_session(this, feed_dict, graph);
}
public NDArray eval(Session session, FeedItem[] feed_dict = null)
{
return ops._eval_using_default_session(this, feed_dict, graph, session);
}
public TF_DataType ToTFDataType(Type type)
{
switch (type.Name)
{
case "Char":
return TF_DataType.TF_UINT8;
case "Int16":
return TF_DataType.TF_INT16;
case "Int32":
return TF_DataType.TF_INT32;
case "Int64":
return TF_DataType.TF_INT64;
case "Single":
return TF_DataType.TF_FLOAT;
case "Double":
return TF_DataType.TF_DOUBLE;
case "Byte":
return TF_DataType.TF_UINT8;
case "String":
return TF_DataType.TF_STRING;
case "Boolean":
return TF_DataType.TF_BOOL;
default:
throw new NotImplementedException("ToTFDataType error");
}
}
public Tensor slice(Slice slice)
{
var slice_spec = new int[] { slice.Start.Value };
var begin = new List<int>();
var end = new List<int>();
var strides = new List<int>();
var index = 0;
var (new_axis_mask, shrink_axis_mask) = (0, 0);
var (begin_mask, end_mask) = (0, 0);
var ellipsis_mask = 0;
foreach (var s in slice_spec)
{
begin.Add(s);
if (slice.Stop.HasValue)
{
end.Add(slice.Stop.Value);
}
else
{
end.Add(0);
end_mask |= (1 << index);
}
strides.Add(slice.Step);
index += 1;
}
return with(ops.name_scope(null, "strided_slice", new { begin, end, strides }), scope =>
{
string name = scope;
if (begin != null)
{
var (packed_begin, packed_end, packed_strides) =
(array_ops.stack(begin.ToArray()),
array_ops.stack(end.ToArray()),
array_ops.stack(strides.ToArray()));
return gen_array_ops.strided_slice(
this,
packed_begin,
packed_end,
packed_strides,
begin_mask: begin_mask,
end_mask: end_mask,
shrink_axis_mask: shrink_axis_mask,
new_axis_mask: new_axis_mask,
ellipsis_mask: ellipsis_mask,
name: name);
}
throw new NotImplementedException("");
});
}
public Tensor slice(int start)
{
var slice_spec = new int[] { start };
var begin = new List<int>();
var end = new List<int>();
var strides = new List<int>();
var index = 0;
var (new_axis_mask, shrink_axis_mask) = (0, 0);
var (begin_mask, end_mask) = (0, 0);
var ellipsis_mask = 0;
foreach (var s in slice_spec)
{
begin.Add(s);
end.Add(s + 1);
strides.Add(1);
shrink_axis_mask |= (1 << index);
index += 1;
}
return with(ops.name_scope(null, "strided_slice", new { begin, end, strides }), scope =>
{
string name = scope;
if (begin != null)
{
var (packed_begin, packed_end, packed_strides) =
(array_ops.stack(begin.ToArray()),
array_ops.stack(end.ToArray()),
array_ops.stack(strides.ToArray()));
return gen_array_ops.strided_slice(
this,
packed_begin,
packed_end,
packed_strides,
begin_mask: begin_mask,
end_mask: end_mask,
shrink_axis_mask: shrink_axis_mask,
new_axis_mask: new_axis_mask,
ellipsis_mask: ellipsis_mask,
name: name);
}
throw new NotImplementedException("");
});
}
public override string ToString()
{
// this can throw IndexOutOfRangeException
//if(NDims == 0)
//{
// switch (dtype)
// {
// case TF_DataType.TF_INT32:
// return Data<int>()[0].ToString();
// }
//}
return $"tf.Tensor '{name}' shape=({string.Join(",", shape)}) dtype={dtype}";
}
public void Dispose()
{
IntPtr h=IntPtr.Zero;
lock (this)
{
h = _handle;
_handle=IntPtr.Zero;
}
if (h != IntPtr.Zero)
c_api.TF_DeleteTensor(_handle);
status.Dispose();
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose the tensor when it gets garbage collected
/// </summary>
~Tensor()
{
Dispose();
}
public bool IsDisposed
{
get
{
lock (this)
{
return _handle == IntPtr.Zero;
}
}
}
}
}