Skip to content

Commit 2d52f60

Browse files
committed
add K-means, in progress.
add validate_shape for variable.
1 parent 8654b41 commit 2d52f60

8 files changed

Lines changed: 162 additions & 4 deletions

File tree

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace Tensorflow.Clustering
6+
{
7+
/// <summary>
8+
/// Creates the graph for k-means clustering.
9+
/// </summary>
10+
public class KMeans : Python
11+
{
12+
public const string CLUSTERS_VAR_NAME = "clusters";
13+
14+
public const string SQUARED_EUCLIDEAN_DISTANCE = "squared_euclidean";
15+
public const string COSINE_DISTANCE = "cosine";
16+
public const string RANDOM_INIT = "random";
17+
public const string KMEANS_PLUS_PLUS_INIT = "kmeans_plus_plus";
18+
public const string KMC2_INIT = "kmc2";
19+
20+
Tensor[] _inputs;
21+
int _num_clusters;
22+
IInitializer _initial_clusters;
23+
string _distance_metric;
24+
bool _use_mini_batch;
25+
int _mini_batch_steps_per_iteration;
26+
int _random_seed;
27+
int _kmeans_plus_plus_num_retries;
28+
int _kmc2_chain_length;
29+
30+
public KMeans(Tensor inputs,
31+
int num_clusters,
32+
IInitializer initial_clusters = null,
33+
string distance_metric = SQUARED_EUCLIDEAN_DISTANCE,
34+
bool use_mini_batch = false,
35+
int mini_batch_steps_per_iteration = 1,
36+
int random_seed = 0,
37+
int kmeans_plus_plus_num_retries = 2,
38+
int kmc2_chain_length = 200)
39+
{
40+
_inputs = new Tensor[] { inputs };
41+
_num_clusters = num_clusters;
42+
_initial_clusters = initial_clusters;
43+
_distance_metric = distance_metric;
44+
_use_mini_batch = use_mini_batch;
45+
_mini_batch_steps_per_iteration = mini_batch_steps_per_iteration;
46+
_random_seed = random_seed;
47+
_kmeans_plus_plus_num_retries = kmeans_plus_plus_num_retries;
48+
_kmc2_chain_length = kmc2_chain_length;
49+
}
50+
51+
public object training_graph()
52+
{
53+
var initial_clusters = _initial_clusters;
54+
var num_clusters = ops.convert_to_tensor(_num_clusters);
55+
var inputs = _inputs;
56+
_create_variables(num_clusters);
57+
58+
throw new NotImplementedException("KMeans training_graph");
59+
}
60+
61+
private RefVariable[] _create_variables(Tensor num_clusters)
62+
{
63+
var init_value = constant_op.constant(new float[0], dtype: TF_DataType.TF_FLOAT);
64+
var cluster_centers = tf.Variable(init_value, name: CLUSTERS_VAR_NAME, validate_shape: false);
65+
var cluster_centers_initialized = tf.Variable(false, dtype: TF_DataType.TF_BOOL, name: "initialized");
66+
RefVariable update_in_steps = null;
67+
if (_use_mini_batch && _mini_batch_steps_per_iteration > 1)
68+
throw new NotImplementedException("KMeans._create_variables");
69+
else
70+
{
71+
var cluster_centers_updated = cluster_centers;
72+
var cluster_counts = _use_mini_batch ?
73+
tf.Variable(array_ops.ones(new Tensor[] { num_clusters }, dtype: TF_DataType.TF_INT64)) :
74+
null;
75+
return new RefVariable[]
76+
{
77+
cluster_centers,
78+
cluster_centers_initialized,
79+
cluster_counts,
80+
cluster_centers_updated,
81+
update_in_steps
82+
};
83+
}
84+
}
85+
}
86+
}

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,18 @@ public static Tensor ones(Tensor shape, TF_DataType dtype = TF_DataType.TF_FLOAT
161161
});
162162
}
163163

164+
public static Tensor ones(Tensor[] shape, TF_DataType dtype = TF_DataType.TF_FLOAT, string name = null)
165+
{
166+
dtype = dtype.as_base_dtype();
167+
return with(ops.name_scope(name, "ones", new { shape }), scope =>
168+
{
169+
name = scope;
170+
var shape1 = ops.convert_to_tensor(shape, dtype: TF_DataType.TF_INT32);
171+
var output = gen_array_ops.fill(shape1, constant_op.constant(1, dtype: dtype), name: name);
172+
return output;
173+
});
174+
}
175+
164176
public static Tensor ones(int[] dims, TF_DataType dtype = TF_DataType.TF_FLOAT, string name = null)
165177
{
166178
dtype = dtype.as_base_dtype();

‎src/TensorFlowNET.Core/TensorFlowNET.Core.csproj‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
<TargetFramework>netstandard2.0</TargetFramework>
55
<AssemblyName>TensorFlow.NET</AssemblyName>
66
<RootNamespace>Tensorflow</RootNamespace>
7-
<Version>0.5.1</Version>
7+
<Version>0.6.0</Version>
88
<Authors>Haiping Chen</Authors>
99
<Company>SciSharp STACK</Company>
1010
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
@@ -16,13 +16,14 @@
1616
<PackageTags>TensorFlow, NumSharp, SciSharp, MachineLearning, TensorFlow.NET, C#</PackageTags>
1717
<Description>Google's TensorFlow binding in .NET Standard.
1818
Docs: https://tensorflownet.readthedocs.io</Description>
19-
<AssemblyVersion>0.5.1.0</AssemblyVersion>
19+
<AssemblyVersion>0.6.0.0</AssemblyVersion>
2020
<PackageReleaseNotes>Changes since v0.5:
21+
Added K-means Clustering.
2122
Added Nearest Neighbor.
22-
Add a lot of APIs to build neural networks model.
23+
Added a lot of APIs to build neural networks model.
2324
Bug fix.</PackageReleaseNotes>
2425
<LangVersion>7.2</LangVersion>
25-
<FileVersion>0.5.1.0</FileVersion>
26+
<FileVersion>0.6.0.0</FileVersion>
2627
</PropertyGroup>
2728

2829
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ public static TF_DataType as_dtype(Type type)
3131

3232
switch (type.Name)
3333
{
34+
case "Boolean":
35+
dtype = TF_DataType.TF_BOOL;
36+
break;
3437
case "Int32":
3538
dtype = TF_DataType.TF_INT32;
3639
break;

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ public static TensorProto make_tensor_proto(object values, TF_DataType dtype = T
229229
switch (nparray.dtype.Name)
230230
{
231231
case "Bool":
232+
case "Boolean":
232233
tensor_proto.BoolVal.AddRange(proto_values.Data<bool>());
233234
break;
234235
case "Int32":

‎src/TensorFlowNET.Core/Variables/variable_scope.py.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ public static RefVariable default_variable_creator(object initial_value,
156156
{
157157
return new RefVariable(initial_value,
158158
trainable: trainable.Value,
159+
validate_shape: validate_shape,
159160
name: name,
160161
dtype: dtype);
161162
}

‎src/TensorFlowNET.Core/tf.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,13 @@ public static partial class tf
2222

2323
public static RefVariable Variable<T>(T data,
2424
bool trainable = true,
25+
bool validate_shape = true,
2526
string name = null,
2627
TF_DataType dtype = TF_DataType.DtInvalid)
2728
{
2829
return Tensorflow.variable_scope.default_variable_creator(data,
2930
trainable: trainable,
31+
validate_shape: validate_shape,
3032
name: name,
3133
dtype: TF_DataType.DtInvalid);
3234
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
using NumSharp.Core;
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Text;
5+
using Tensorflow;
6+
using Tensorflow.Clustering;
7+
using TensorFlowNET.Examples.Utility;
8+
9+
namespace TensorFlowNET.Examples
10+
{
11+
/// <summary>
12+
/// Implement K-Means algorithm with TensorFlow.NET, and apply it to classify
13+
/// handwritten digit images.
14+
/// https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/kmeans.py
15+
/// </summary>
16+
public class KMeansClustering : Python, IExample
17+
{
18+
public int Priority => 7;
19+
public bool Enabled => true;
20+
public string Name => "K-means Clustering";
21+
22+
Datasets mnist;
23+
NDArray full_data_x;
24+
int num_steps = 50; // Total steps to train
25+
int batch_size = 1024; // The number of samples per batch
26+
int k = 25; // The number of clusters
27+
int num_classes = 10; // The 10 digits
28+
int num_features = 784; // Each image is 28x28 pixels
29+
30+
public bool Run()
31+
{
32+
// Input images
33+
var X = tf.placeholder(tf.float32, shape: new TensorShape(-1, num_features));
34+
// Labels (for assigning a label to a centroid and testing)
35+
var Y = tf.placeholder(tf.float32, shape: new TensorShape(-1, num_classes));
36+
37+
// K-Means Parameters
38+
var kmeans = new KMeans(X, k, distance_metric: KMeans.COSINE_DISTANCE, use_mini_batch: true);
39+
40+
// Build KMeans graph
41+
var training_graph = kmeans.training_graph();
42+
43+
return false;
44+
}
45+
46+
public void PrepareData()
47+
{
48+
mnist = MnistDataSet.read_data_sets("mnist", one_hot: true);
49+
full_data_x = mnist.train.images;
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)