使用Syft Keras进行隐私预测

步骤3:使用Syft Keras进行隐私预测-服务(客户端)

恭喜你! 用普通的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

连接模型

在查询模型之前,您只需连接到它。 为此,您可以创建一个客户端。 然后定义完全相同的三个TFEWorkers(alicebobcarol)并进行聚类。最后调用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)


INFO:tf_encrypted:Starting session on target 'grpc://localhost:4000' using config graph_options {
}

查询模型

您已准备好进行一些隐私预测!调用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))


The image had label 7 and was correctly classified as 7
The image had label 2 and was correctly classified as 2
The image had label 1 and was correctly classified as 1

这很棒。您可以正确分类这三个图像!但是,这些预测的特别之处在于您尚未透露任何隐私信息来获取此服务。模型主机从未看到您的输入数据或预测,也从未下载过模型。您可以使用加密模型获得对加密数据的隐私预测!

在我们急于将其应用到自己的应用程序中之前,让我们快速回到Part 13b来清理我们提供的模型!