|
| 1 | +/***************************************************************************** |
| 2 | + Copyright 2021 Haiping Chen. All Rights Reserved. |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +******************************************************************************/ |
| 16 | + |
| 17 | +using System; |
| 18 | +using System.Linq; |
| 19 | +using Tensorflow.Framework; |
| 20 | +using static Tensorflow.Binding; |
| 21 | + |
| 22 | +namespace Tensorflow |
| 23 | +{ |
| 24 | + /// <summary> |
| 25 | + /// Represents a sparse tensor. |
| 26 | + /// </summary> |
| 27 | + public class SparseTensor : CompositeTensor |
| 28 | + { |
| 29 | + public Tensor indices; |
| 30 | + |
| 31 | + public Tensor values; |
| 32 | + |
| 33 | + public Tensor dense_shape; |
| 34 | + |
| 35 | + public SparseTensor(Tensor indices, Tensor values, Tensor dense_shape) |
| 36 | + { |
| 37 | + this.indices = indices; |
| 38 | + this.values = values; |
| 39 | + this.dense_shape = dense_shape; |
| 40 | + _init(); |
| 41 | + } |
| 42 | + |
| 43 | + public SparseTensor(long[,] indices_, Array values_, long[] dense_shape_) |
| 44 | + { |
| 45 | + tf_with(ops.name_scope(null, "SparseTensor", new { }), delegate |
| 46 | + { |
| 47 | + indices = ops.convert_to_tensor( |
| 48 | + indices_, name: "indices", dtype: dtypes.int64); |
| 49 | + values = ops.convert_to_tensor(values_, name: "values"); |
| 50 | + dense_shape = ops.convert_to_tensor( |
| 51 | + dense_shape_, name: "dense_shape", dtype: dtypes.int64); |
| 52 | + }); |
| 53 | + _init(); |
| 54 | + } |
| 55 | + |
| 56 | + void _init() |
| 57 | + { |
| 58 | + var indices_shape = indices.TensorShape.with_rank(2); |
| 59 | + var values_shape = values.TensorShape.with_rank(1); |
| 60 | + var dense_shape_shape = dense_shape.TensorShape.with_rank(1); |
| 61 | + |
| 62 | + indices_shape["0"].merge_with(values_shape[0]); |
| 63 | + indices_shape["1"].merge_with(dense_shape_shape[0]); |
| 64 | + } |
| 65 | + |
| 66 | + public static implicit operator Tensor(SparseTensor indexedSlices) |
| 67 | + { |
| 68 | + return indexedSlices.values; |
| 69 | + } |
| 70 | + |
| 71 | + public static implicit operator SparseTensor(Tensor tensor) |
| 72 | + { |
| 73 | + return tensor.Tag as SparseTensor; |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments