おめでとう!通常のKerasでモデルをトレーニングし、Syft Kerasでモデルを保護した後、プライバシーを配慮した予測を行う準備が整いました。
In [1]:
import numpy as np
import tensorflow as tf
from tensorflow.keras.datasets import mnist
import syft as sy
ここでは、MNISTデータを前処理します。これは、トレーニング中に前処理した方法と同じです。
In [2]:
#画像の次元の入力
img_rows, img_cols = 28, 28
# データを学習用とテスト用に分解
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
モデル照会の前に、モデルに接続する必要があります。そのために、クライアントを作成する必要があります。この時、まったく同じ3つのTFEWorker( alice、bob、および carol)とクラスターを定義します。最後に「connect_to_model」を呼び出します。これにより、クライアント側にTFEキューサーバーが作成され、Part 13b. の model.serve()で設定されたキューサーバーに接続することが可能です。キューは、予測リクエストで共有を送信する前に、プレーンテキストデータを秘密に共有します。
In [3]:
num_classes = 10
input_shape = (1, 28, 28, 1)
output_shape = (1, num_classes)
In [4]:
client = sy.TFEWorker()
alice = sy.TFEWorker(host='localhost:4000')
bob = sy.TFEWorker(host='localhost:4001')
carol = sy.TFEWorker(host='localhost:4002')
cluster = sy.TFECluster(alice, bob, carol)
client.connect_to_model(input_shape, output_shape, cluster)
いくつかのプライバシーに配慮した予測を取得する準備ができました! query_modelを呼び出すと、上記で作成したキューにimageを挿入し、データをローカルで秘密共有し、Part 13bでモデルサーバーに共有を送信できます。
In [5]:
# ユーザーの入力
num_tests = 3
images, expected_labels = x_test[:num_tests], y_test[:num_tests]
In [6]:
for image, expected_label in zip(images, expected_labels):
res = client.query_model(image.reshape(1, 28, 28, 1))
predicted_label = np.argmax(res)
print("The image had label {} and was {} classified as {}".format(
expected_label,
"correctly" if expected_label == predicted_label else "wrongly",
predicted_label))
素晴らしいですね!これら3つの画像を正しく分類することができます!しかし、これらの予測の特別な点は、このサービスを利用するための個人情報を明らかにしていないことです。モデルホストは入力データや予測を見たことはなく、モデルをダウンロードしたこともありません。暗号化されたモデルを使用して、暗号化されたデータのプライベートな予測を取得できました!
これを自身のアプリケーションに適用する前に、Part 13b に戻ってあたなの学習モデルをクリーンにしましょう.