Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 6 additions & 18 deletions TensorFlow.NET.sln
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TensorFlowNET.Core", "src\T
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Keras.Core", "src\KerasNET.Core\Keras.Core.csproj", "{902E188F-A953-43B4-9991-72BAB1697BC3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Keras.Example", "test\KerasNET.Example\Keras.Example.csproj", "{17E1AC16-9E0E-4545-905A-E92C6300C7AF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Keras.UnitTest", "test\KerasNET.Test\Keras.UnitTest.csproj", "{A5839A45-A117-4BEA-898B-DE1ED6E0D58F}"
EndProject
Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "TensorFlowNET.Examples.FSharp", "test\TensorFlowNET.Examples.FSharp\TensorFlowNET.Examples.FSharp.fsproj", "{62BC3801-F0D3-44A9-A0AC-712F40C8F961}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TensorFlowBenchmark", "src\TensorFlowNet.Benchmarks\TensorFlowBenchmark.csproj", "{68861442-971A-4196-876E-C9330F0B3C54}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TensorFlowHub", "src\TensorFlowHub\TensorFlowHub.csproj", "{8FD59A5A-97EB-457E-B9F1-D88B0C822C6E}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TensorFlowHub", "src\TensorFlowHub\TensorFlowHub.csproj", "{8FD59A5A-97EB-457E-B9F1-D88B0C822C6E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TensorFlowHub.Examples", "test\TensorFlowHub.Examples\TensorFlowHub.Examples.csproj", "{5FF6CB67-DC99-4741-9545-E803DFCE5CDC}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TensorFlowText", "src\TensorFlowText\TensorFlowText.csproj", "{B598E5D5-BD2D-4191-8532-F2FBAC31AB81}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand All @@ -45,14 +41,6 @@ Global
{902E188F-A953-43B4-9991-72BAB1697BC3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{902E188F-A953-43B4-9991-72BAB1697BC3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{902E188F-A953-43B4-9991-72BAB1697BC3}.Release|Any CPU.Build.0 = Release|Any CPU
{17E1AC16-9E0E-4545-905A-E92C6300C7AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{17E1AC16-9E0E-4545-905A-E92C6300C7AF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{17E1AC16-9E0E-4545-905A-E92C6300C7AF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{17E1AC16-9E0E-4545-905A-E92C6300C7AF}.Release|Any CPU.Build.0 = Release|Any CPU
{A5839A45-A117-4BEA-898B-DE1ED6E0D58F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A5839A45-A117-4BEA-898B-DE1ED6E0D58F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A5839A45-A117-4BEA-898B-DE1ED6E0D58F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A5839A45-A117-4BEA-898B-DE1ED6E0D58F}.Release|Any CPU.Build.0 = Release|Any CPU
{62BC3801-F0D3-44A9-A0AC-712F40C8F961}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{62BC3801-F0D3-44A9-A0AC-712F40C8F961}.Debug|Any CPU.Build.0 = Debug|Any CPU
{62BC3801-F0D3-44A9-A0AC-712F40C8F961}.Release|Any CPU.ActiveCfg = Release|Any CPU
Expand All @@ -65,10 +53,10 @@ Global
{8FD59A5A-97EB-457E-B9F1-D88B0C822C6E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8FD59A5A-97EB-457E-B9F1-D88B0C822C6E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8FD59A5A-97EB-457E-B9F1-D88B0C822C6E}.Release|Any CPU.Build.0 = Release|Any CPU
{5FF6CB67-DC99-4741-9545-E803DFCE5CDC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5FF6CB67-DC99-4741-9545-E803DFCE5CDC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5FF6CB67-DC99-4741-9545-E803DFCE5CDC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5FF6CB67-DC99-4741-9545-E803DFCE5CDC}.Release|Any CPU.Build.0 = Release|Any CPU
{B598E5D5-BD2D-4191-8532-F2FBAC31AB81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B598E5D5-BD2D-4191-8532-F2FBAC31AB81}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B598E5D5-BD2D-4191-8532-F2FBAC31AB81}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B598E5D5-BD2D-4191-8532-F2FBAC31AB81}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
6 changes: 3 additions & 3 deletions src/TensorFlowHub/MnistDataSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,19 @@ public class MnistDataSet : DataSetBase
public int EpochsCompleted { get; private set; }
public int IndexInEpoch { get; private set; }

public MnistDataSet(NDArray images, NDArray labels, TF_DataType dtype, bool reshape)
public MnistDataSet(NDArray images, NDArray labels, Type dataType, bool reshape)
{
EpochsCompleted = 0;
IndexInEpoch = 0;

NumOfExamples = images.shape[0];

images = images.reshape(images.shape[0], images.shape[1] * images.shape[2]);
images.astype(dtype.as_numpy_datatype());
images.astype(dataType);
images = np.multiply(images, 1.0f / 255.0f);
Data = images;

labels.astype(dtype.as_numpy_datatype());
labels.astype(dataType);
Labels = labels;
}
}
Expand Down
22 changes: 19 additions & 3 deletions src/TensorFlowHub/MnistModelLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ public class MnistModelLoader : IModelLoader<MnistDataSet>
private const string TEST_IMAGES = "t10k-images-idx3-ubyte.gz";
private const string TEST_LABELS = "t10k-labels-idx1-ubyte.gz";

public static async Task<Datasets<MnistDataSet>> LoadAsync(string trainDir, bool oneHot = false)
{
var loader = new MnistModelLoader();
return await loader.LoadAsync(new ModelLoadSetting
{
TrainDir = trainDir,
OneHot = oneHot
});
}

public async Task<Datasets<MnistDataSet>> LoadAsync(ModelLoadSetting setting)
{
if (setting.TrainSize.HasValue && setting.ValidationSize >= setting.TrainSize.Value)
Expand Down Expand Up @@ -71,7 +81,7 @@ await this.UnzipAsync(Path.Combine(setting.TrainDir, TEST_LABELS), setting.Train
trainImages = trainImages[np.arange(validationSize, end)];
trainLabels = trainLabels[np.arange(validationSize, end)];

var dtype = setting.DtType;
var dtype = setting.DataType;
var reshape = setting.ReShape;

var train = new MnistDataSet(trainImages, trainLabels, dtype, reshape);
Expand All @@ -83,11 +93,14 @@ await this.UnzipAsync(Path.Combine(setting.TrainDir, TEST_LABELS), setting.Train

private NDArray ExtractImages(string file, int? limit = null)
{
if (!Path.IsPathRooted(file))
file = Path.Combine(AppContext.BaseDirectory, file);

using (var bytestream = new FileStream(file, FileMode.Open))
{
var magic = Read32(bytestream);
if (magic != 2051)
throw new ValueError($"Invalid magic number {magic} in MNIST image file: {file}");
throw new Exception($"Invalid magic number {magic} in MNIST image file: {file}");

var num_images = Read32(bytestream);
num_images = limit == null ? num_images : Math.Min(num_images, (uint)limit);
Expand All @@ -108,11 +121,14 @@ private NDArray ExtractImages(string file, int? limit = null)

private NDArray ExtractLabels(string file, bool one_hot = false, int num_classes = 10, int? limit = null)
{
if (!Path.IsPathRooted(file))
file = Path.Combine(AppContext.BaseDirectory, file);

using (var bytestream = new FileStream(file, FileMode.Open))
{
var magic = Read32(bytestream);
if (magic != 2049)
throw new ValueError($"Invalid magic number {magic} in MNIST label file: {file}");
throw new Exception($"Invalid magic number {magic} in MNIST label file: {file}");

var num_items = Read32(bytestream);
num_items = limit == null ? num_items : Math.Min(num_items, (uint)limit);
Expand Down
2 changes: 1 addition & 1 deletion src/TensorFlowHub/ModelLoadSetting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class ModelLoadSetting
{
public string TrainDir { get; set; }
public bool OneHot { get; set; }
public TF_DataType DtType { get; set; } = TF_DataType.TF_FLOAT;
public Type DataType { get; set; } = typeof(float);
public bool ReShape { get; set; }
public int ValidationSize { get; set; } = 5000;
public int? TrainSize { get; set; }
Expand Down
18 changes: 11 additions & 7 deletions src/TensorFlowHub/TensorFlowHub.csproj
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<AssemblyName>TensorFlow.Net.Hub</AssemblyName>
<RootNamespace>Tensorflow.Hub</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
<Version>0.0.1</Version>
<Authors>SciSharp</Authors>
<Company>SciSharp STACK</Company>
<Copyright>Apache 2.0</Copyright>
<RepositoryUrl>https://github.com/SciSharp/TensorFlow.NET</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageProjectUrl>http://scisharpstack.org</PackageProjectUrl>
<PackageTags>TensorFlow, Training model</PackageTags>
<Description>TensorFlow Hub is a library to foster the publication, discovery, and consumption of reusable parts of machine learning models.</Description>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\TensorFlowNET.Core\TensorFlowNET.Core.csproj" />
<PackageReference Include="NumSharp" Version="0.10.6" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NumSharp" Version="0.10.5" />
<PackageReference Include="sharpcompress" Version="0.23.0" />
</ItemGroup>
</Project>
</Project>
39 changes: 17 additions & 22 deletions src/TensorFlowHub/Utils.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
using System;
using System.IO;
using System.IO.Compression;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NumSharp;
using SharpCompress;
using SharpCompress.Common;
using SharpCompress.Readers;

namespace Tensorflow.Hub
{
Expand Down Expand Up @@ -37,36 +34,34 @@ public static async Task DownloadAsync<TDataSet>(this IModelLoader<TDataSet> mod
}
}

public static void Unzip<TDataSet>(this IModelLoader<TDataSet> modelLoader, string zipFile, string saveTo)
public static async Task UnzipAsync<TDataSet>(this IModelLoader<TDataSet> modelLoader, string zipFile, string saveTo)
where TDataSet : IDataSet
{
if (!Path.IsPathRooted(saveTo))
saveTo = Path.Combine(AppContext.BaseDirectory, saveTo);

if (!Directory.Exists(saveTo))
Directory.CreateDirectory(saveTo);

if (!Path.IsPathRooted(zipFile))
zipFile = Path.Combine(AppContext.BaseDirectory, zipFile);

var destFilePath = Path.Combine(saveTo, Path.GetFileNameWithoutExtension(zipFile));

using (var stream = File.OpenRead(zipFile))
using (var reader = ReaderFactory.Open(stream))
if (File.Exists(destFilePath))
File.Delete(destFilePath);

using (GZipStream unzipStream = new GZipStream(File.OpenRead(zipFile), CompressionMode.Decompress))
{
while (reader.MoveToNextEntry())
using (var destStream = File.Create(destFilePath))
{
if (!reader.Entry.IsDirectory)
{
reader.WriteEntryToDirectory(saveTo, new ExtractionOptions()
{
ExtractFullPath = true,
Overwrite = true
});
}
await unzipStream.CopyToAsync(destStream);
await destStream.FlushAsync();
destStream.Close();
}
}
}

public static async Task UnzipAsync<TDataSet>(this IModelLoader<TDataSet> modelLoader, string zipFile, string saveTo)
where TDataSet : IDataSet
{
await Task.Run(() => modelLoader.Unzip(zipFile, saveTo));
unzipStream.Close();
}
}

public static async Task ShowProgressInConsole(this Task task)
Expand Down
4 changes: 2 additions & 2 deletions src/TensorFlowNET.Core/APIs/tf.graph.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static Graph get_default_graph()
return ops.get_default_graph();
}

public static Graph Graph() => new Graph();

public static Graph Graph()
=> new Graph();
}
}
9 changes: 9 additions & 0 deletions src/TensorFlowNET.Core/APIs/tf.math.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ public static Tensor arg_max(Tensor input, int dimension, TF_DataType output_typ
public static Tensor arg_min(Tensor input, int dimension, TF_DataType output_type = TF_DataType.TF_INT64, string name = null)
=> gen_math_ops.arg_min(input, dimension, output_type: output_type, name: name);

public static Tensor is_finite(Tensor input, string name = null)
=> gen_math_ops.is_finite(input, name);

public static Tensor is_nan(Tensor input, string name = null)
=> gen_math_ops.is_nan(input, name);

/// <summary>
/// Returns element-wise smallest integer not less than x.
/// </summary>
Expand Down Expand Up @@ -203,6 +209,9 @@ public static Tensor divide(Tensor a, Tensor b)
public static Tensor sqrt(Tensor a, string name = null)
=> gen_math_ops.sqrt(a, name);

public static Tensor sign(Tensor a, string name = null)
=> gen_math_ops.sign(a, name);

public static Tensor subtract<T>(Tensor x, T[] y, string name = null) where T : struct
=> gen_math_ops.sub(x, ops.convert_to_tensor(y, dtype: x.dtype.as_base_dtype(), name: "y"), name);

Expand Down
12 changes: 7 additions & 5 deletions src/TensorFlowNET.Core/APIs/tf.ops.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,11 @@ namespace Tensorflow
{
public static partial class tf
{
public static object get_collection(string key, string scope = "") => get_default_graph()
.get_collection(key, scope: scope);
public static Tensor assign(Tensor @ref, object value, bool validate_shape = true, bool use_locking = true, string name = null)
=> state_ops.assign(@ref, value, validate_shape, use_locking, name);

public static object get_collection(string key, string scope = "")
=> get_default_graph().get_collection(key, scope: scope);

/// <summary>
/// Returns a context manager that creates hierarchical names for operations.
Expand All @@ -28,8 +31,7 @@ public static object get_collection(string key, string scope = "") => get_defaul
/// <param name="default_name">The default name to use if the name argument is None.</param>
/// <param name="values">The list of Tensor arguments that are passed to the op function.</param>
/// <returns>The scope name.</returns>
public static ops.NameScope name_scope(string name,
string default_name = "",
object values = null) => new ops.NameScope(name, default_name, values);
public static ops.NameScope name_scope(string name, string default_name = "", object values = null)
=> new ops.NameScope(name, default_name, values);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Linq;
using NumSharp;
using Tensorflow.Framework;

namespace Tensorflow.Contrib.Learn.Estimators
{
public static class tensor_signature
{
public static bool is_compatible_with(this Tensor self, Tensor other)
{
bool _shape_is_compatible_0dim(Shape _this, Shape _other)
{
var __other = tensor_shape.as_shape(_other);
if (_this.Dimensions == null || __other.Dimensions == null)
return true;

if (_this.NDim != __other.NDim)
return false;

foreach (var (x_dim, y_dim) in _this.Dimensions.Zip(__other.Dimensions, (x_dim, y_dim) => (x_dim, y_dim)))
{
if (x_dim != y_dim)
return false;
}

return true;
}

if (other.is_sparse())
{
return self.dtype.is_compatible_with(other.dtype);
}

return self.dtype.is_compatible_with(other.dtype) &&
_shape_is_compatible_0dim(self.shape, other.shape) &&
!self.is_sparse();
}
}
}
13 changes: 12 additions & 1 deletion src/TensorFlowNET.Core/Framework/sparse_tensor.py.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
namespace Tensorflow.Framework
{
public static class SparseTensor
public interface _TensorLike
{ }

public class SparseTensor : CompositeTensor, _TensorLike
{
private static Tensor _dense_shape { get; set; }

}

public static class sparse_tensor
{
public static bool is_sparse(this _TensorLike x)
{
return x is SparseTensor;
}
}
}
34 changes: 34 additions & 0 deletions src/TensorFlowNET.Core/Framework/tensor_shape.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System;
using System.Linq;
using System.Text;
using NumSharp;
using Tensorflow.Contrib.Learn.Estimators;

namespace Tensorflow.Framework
{
public static class tensor_shape
{
public static void assert_is_compatible_with(this Tensor self, Tensor other)
{
if (!self.is_compatible_with(other))
{
var selfDim = self.shape
.Aggregate(new StringBuilder("{"), (sb, i) => sb.Append(i).Append(", "), sb => sb.ToString())
.Replace(", }", "}");

var otherDim = other.shape
.Aggregate(new StringBuilder("{"), (sb, i) => sb.Append(i).Append(", "), sb => sb.ToString())
.Replace(", }", "}");

throw new ArgumentException($"Dimensions {selfDim} and {otherDim} are not compatible");
}
}

public static TensorShape as_shape(this Shape shape)
{
if (shape is TensorShape tshape)
return tshape;
return new TensorShape(shape);
}
}
}
Loading