Coding01

Coding 点滴

0%

Swift for TensorFlow (2) 之训练和识别 MNIST

引入 Python:

Swift For TensorFlow supports Python interoperability.

You can import Python modules from Swift, call Python functions, and convert values between Swift and Python.

1
2
import PythonKit
print(Python.version)

MNIST 数据集识别

本文主要学习如何利用 S4TF 训练和识别 MNIST。

读取数据集

在 Swift 版本里:

先引入组件:

1
2
3
4
5
6
7
import TensorFlow
import PythonKit
import Foundation

let os = Python.import("os")
let np = Python.import("numpy")
let metrics = Python.import("sklearn.metrics")

在之前的文章使用 MNIST 集入门 Tensoflow 中 Python 版本读数据集:

1
2
3
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(
path = os.path.join(os.getcwd(), "data/mnist.npz")
)

在 Swift 版本调入数据集:

1
2
3
4
5
if !Bool(os.path.exists("mnist.npz"))! {
os.popen("wget https://s3.amazonaws.com/img-datasets/mnist.npz").read()
}

let mnist = np.load("mnist.npz")

Python 数据初始化:

1
2
3
4
5
6
7
8
9
10
11
12
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')

x_train /= 255
x_test /= 255

print('x_train shape: ', x_train.shape)
print('Number of images in x_train', x_train.shape[0])
print('Number of images in x_test', x_test.shape[0])

Swift 中:

1
2
3
4
5
let xTrain = Tensor<Float>(numpy: mnist["x_train"].astype("float32").reshape([60000, 28, 28, 1]) / 255.0)!
let xTest = Tensor<Float>(numpy: mnist["x_test"].astype("float32").reshape([10000, 28, 28, 1]) / 255.0)!

let yTrain = Tensor<Int32>(numpy: mnist["y_train"].astype("int32"))!
let yTest = Tensor<Int32>(numpy: mnist["y_test"].astype("int32"))!

模型

在 python 中:

1
2
3
4
5
6
7
model = Sequential()
model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) # Flattening the 2D arrays for fully connected layers
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dropout(0.2))
model.add(Dense(10,activation=tf.nn.softmax))

在 Swift 中,我们先简单的用其中几个人 Layers:

1
2
3
4
5
var model = Sequential {
Flatten<Float>()
Dense<Float>(inputSize: 784, outputSize: 100, activation: relu)
Dense<Float>(inputSize: 100, outputSize: 10, activation: softmax)
}

编译和优化模型

在 Python 中:

1
2
3
4
5
6
model.compile(optimizer='adam', 
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x=x_train,y=y_train, epochs=10)

model.evaluate(x_test, y_test)

在 Swift 中:

1
2
3
4
5
6
7
8
9
10
11
12
let optimizer = Adam(for: model, learningRate: 0.02)
Context.local.learningPhase = .training

for _ in 1...5 {
let 𝛁model = gradient(at: model) { model -> Tensor<Float> in
let ŷ = model(xTrain)
let loss = softmaxCrossEntropy(logits: ŷ, labels: yTrain)
// print("Loss: \(loss)")
return loss
}
optimizer.update(&model, along: 𝛁model)
}

测试

在 Python 中:

1
2
3
4
image_index = 5555
plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
print(pred.argmax())

在 Swift 中我们看看正确率:

1
2
3
4
5
6
7
// 在测试数据集上进行检查,得到模型的准度
let logits = model(xTest)
let sparseLogits = logits.makeNumpyArray().argmax(axis: -1)

let sparseLabels = yTest.makeNumpyArray()

print(Float(metrics.accuracy_score(sparseLabels, sparseLogits))!)

运行:

1
swift -O mnist_1.swift

正确率在: 80%左右,基本跑通 Swift For Tensorflow 流程。

总结

在接下来的学习过程中,不断了解 Python 的代码,也可以在 Swift 版本中同步学习,加深了解 TensorFlow!

Welcome to my other publishing channels