Skip to content

Commit 4c814d6

Browse files
committed
Add imdb sample data.
1 parent 0316fde commit 4c814d6

File tree

11 files changed

+124
-88
lines changed

11 files changed

+124
-88
lines changed

data/imdb.zip

15.2 MB
Binary file not shown.

src/TensorFlowNET.Examples/ImageProcessing/ImageClassificationKeras.cs

+7-13
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ public override void PrepareData()
7676
{
7777
string fileName = "flower_photos.tgz";
7878
string url = $"https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz";
79-
string data_dir = Path.GetTempPath();
79+
string data_dir = Path.Combine(Path.GetTempPath(), "flower_photos");
8080
Web.Download(url, data_dir, fileName);
8181
Compress.ExtractTGZ(Path.Join(data_dir, fileName), data_dir);
8282
data_dir = Path.Combine(data_dir, "flower_photos");
@@ -90,25 +90,19 @@ public override void PrepareData()
9090
batch_size: batch_size);
9191

9292
val_ds = keras.preprocessing.image_dataset_from_directory(data_dir,
93-
validation_split: 0.2f,
94-
subset: "validation",
95-
seed: 123,
96-
image_size: img_dim,
97-
batch_size: batch_size);
93+
validation_split: 0.2f,
94+
subset: "validation",
95+
seed: 123,
96+
image_size: img_dim,
97+
batch_size: batch_size);
9898

9999
train_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size: -1);
100100
val_ds = val_ds.cache().prefetch(buffer_size: -1);
101101

102102
foreach (var (img, label) in train_ds)
103103
{
104104
print($"images: {img.TensorShape}");
105-
var nd = label.numpy();
106-
print($"labels: {nd}");
107-
var data = nd.Data<int>();
108-
if (data.Max() > 4 || data.Min() < 0)
109-
{
110-
// exception
111-
}
105+
print($"labels: {label.numpy()}");
112106
}
113107
}
114108
}

src/TensorFlowNET.Examples/ImageProcessing/ToyResNet.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ public ExampleConfig InitConfig()
4343
public bool Run()
4444
{
4545
tf.enable_eager_execution();
46-
46+
4747
BuildModel();
4848
PrepareData();
4949
Train();

src/TensorFlowNET.Examples/Program.cs

+2
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ limitations under the License.
2222
using System.Reflection;
2323
using Tensorflow;
2424
using static Tensorflow.Binding;
25+
using static Tensorflow.KerasApi;
2526
using Console = Colorful.Console;
2627

2728
namespace TensorFlowNET.Examples
@@ -100,6 +101,7 @@ private static void RunExamples(string key, IExample[] examples)
100101
}
101102

102103
finished++;
104+
keras.backend.clear_session();
103105
Console.WriteLine($"{DateTime.UtcNow} Completed {example.Config.Name}", Color.White);
104106
}
105107

src/TensorFlowNET.Examples/TensorFlowNET.Examples.csproj

+1
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
<PackageReference Include="SciSharp.TensorFlow.Redist" Version="2.3.1" />
4545
<PackageReference Include="SharpCV" Version="0.6.0" />
4646
<PackageReference Include="System.Drawing.Common" Version="5.0.0" />
47+
<PackageReference Include="TensorFlow.Keras" Version="0.3.0" />
4748
</ItemGroup>
4849

4950
<ItemGroup>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.IO;
4+
using System.Text;
5+
using Tensorflow.Keras.Utils;
6+
using static Tensorflow.KerasApi;
7+
8+
namespace TensorFlowNET.Examples
9+
{
10+
/// <summary>
11+
/// https://colab.research.google.com/github/keras-team/keras-io/blob/master/examples/nlp/ipynb/text_classification_from_scratch.ipynb#scrollTo=qqTCrB7SmJv9
12+
/// </summary>
13+
public class CnnTextClassificationKeras : SciSharpExample, IExample
14+
{
15+
public ExampleConfig InitConfig()
16+
=> Config = new ExampleConfig
17+
{
18+
Name = "CNN Text Classification (Keras)",
19+
Enabled = false
20+
};
21+
22+
public bool Run()
23+
{
24+
return true;
25+
}
26+
27+
public override void PrepareData()
28+
{
29+
string fileName = "aclImdb_v1.tar.gz";
30+
string url = $"https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz";
31+
string data_dir = Path.GetTempPath();
32+
Web.Download(url, data_dir, fileName);
33+
Compress.ExtractGZip(Path.Join(data_dir, fileName), data_dir);
34+
data_dir = Path.Combine(data_dir, "aclImdb_v1");
35+
}
36+
}
37+
}

src/tensorflow2.x-python-tutorial/.vscode/launch.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
"name": "Python: Current File",
99
"type": "python",
1010
"request": "launch",
11-
"program": "${workspaceFolder}/image_classification.py",
11+
"program": "${workspaceFolder}/keras_mnist.py",
1212
"console": "integratedTerminal",
1313
"cwd": "${workspaceFolder}",
1414
"justMyCode": false

src/tensorflow2.x-python-tutorial/keras-basic.py

-34
This file was deleted.

src/tensorflow2.x-python-tutorial/keras_basic.py

-39
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import numpy as np
2+
import tensorflow as tf
3+
from tensorflow import keras
4+
from tensorflow.keras import layers
5+
6+
from tensorflow.python.platform import gfile
7+
# GRAPH_PB_PATH = 'D:/tmp/TensorflowIssue/TensorflowIssue/model/saved_model.pb'
8+
GRAPH_PB_PATH = 'D:/tmp/TensorFlow.NET/data/saved_model.pb'
9+
with tf.compat.v1.Session() as sess:
10+
print("load graph")
11+
with tf.io.gfile.GFile(GRAPH_PB_PATH,'rb') as f:
12+
graph_def = tf.compat.v1.GraphDef()
13+
graph_def.ParseFromString(f.read())
14+
sess.graph.as_default()
15+
tf.import_graph_def(graph_def, name='')
16+
graph_nodes=[n for n in graph_def.node]
17+
names = []
18+
for t in graph_nodes:
19+
names.append(t.name)
20+
print(names)
21+
22+
inputs = keras.Input(shape=(784,))
23+
24+
dense = layers.Dense(64, activation="relu")
25+
x = dense(inputs)
26+
27+
dense = layers.Dense(64, activation="relu")
28+
x = dense(x)
29+
30+
dense = layers.Dense(10)
31+
outputs = dense(x)
32+
33+
model = keras.Model(inputs=inputs, outputs=outputs, name="mnist_model")
34+
model.summary();
35+
36+
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
37+
38+
x_train = x_train.reshape(60000, 784).astype("float32") / 255
39+
x_test = x_test.reshape(10000, 784).astype("float32") / 255
40+
41+
model.compile(
42+
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
43+
optimizer=keras.optimizers.RMSprop(),
44+
metrics=["accuracy"],
45+
)
46+
47+
history = model.fit(x_train, y_train, batch_size=64, epochs=2, validation_split=0.2)
48+
49+
test_scores = model.evaluate(x_test, y_test, verbose=2)
50+
print("Test loss:", test_scores[0])
51+
print("Test accuracy:", test_scores[1])
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import tensorflow as tf
2+
from tensorflow import keras
3+
from tensorflow.keras import layers
4+
5+
physical_devices = tf.config.list_physical_devices('CPU')
6+
tf.config.experimental.set_memory_growth(physical_devices[0], True)
7+
8+
tf.config.run_functions_eagerly(True)
9+
tf.debugging.set_log_device_placement(True)
10+
11+
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
12+
print(a)
13+
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
14+
print(b)
15+
c = tf.matmul(a, b)
16+
print(c)
17+
18+
vocab_size = 20000 # Only consider the top 20k words
19+
maxlen = 200 # Only consider the first 200 words of each movie review
20+
(x_train, y_train), (x_val, y_val) = keras.datasets.imdb.load_data(num_words=vocab_size)
21+
print(len(x_train), "Training sequences")
22+
print(len(x_val), "Validation sequences")
23+
x_train = keras.preprocessing.sequence.pad_sequences(x_train, maxlen=maxlen)
24+
x_val = keras.preprocessing.sequence.pad_sequences(x_val, maxlen=maxlen)

0 commit comments

Comments
 (0)