💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 用于 MNIST 分类的基于 TFLearn 的 MLP 现在让我们看看如何使用 TFLearn 实现相同的 MLP,TFLearn 是 TensorFlow 的另一个高级库: 1. 导入 TFLearn 库: ```py import tflearn ``` 1. 定义超参数(我们假设数据集已经加载到`X_train`,`Y_train`,`X_test`和`Y_test`变量): ```py num_layers = 2 num_neurons = [] for i in range(num_layers): num_neurons.append(256) learning_rate = 0.01 n_epochs = 50 batch_size = 100 ``` 1. 构建输入层,两个隐藏层和输出层(与 TensorFlow 和 Keras 部分中的示例相同) ```py # Build deep neural network input_layer = tflearn.input_data(shape=[None, num_inputs]) dense1 = tflearn.fully_connected(input_layer, num_neurons[0], activation='relu') dense2 = tflearn.fully_connected(dense1, num_neurons[1], activation='relu') softmax = tflearn.fully_connected(dense2, num_outputs, activation='softmax') ``` 1. 使用最后一步中构建的 DNN(在变量`softmax`中)定义优化器函数,神经网络和 MLP 模型(在 TFLearn 中称为 DNN): ```py optimizer = tflearn.SGD(learning_rate=learning_rate) net = tflearn.regression(softmax, optimizer=optimizer, metric=tflearn.metrics.Accuracy(), loss='categorical_crossentropy') model = tflearn.DNN(net) ``` 1. 训练模型: ```py model.fit(X_train, Y_train, n_epoch=n_epochs, batch_size=batch_size, show_metric=True, run_id="dense_model") ``` 训练结束后,我们得到以下输出: ```py Training Step: 27499 | total loss: 0.11236 | time: 5.853s | SGD | epoch: 050 | loss: 0.11236 - acc: 0.9687 -- iter: 54900/55000 Training Step: 27500 | total loss: 0.11836 | time: 5.863s | SGD | epoch: 050 | loss: 0.11836 - acc: 0.9658 -- iter: 55000/55000 -- ``` 1. 评估模型并打印准确率分数: ```py score = model.evaluate(X_test, Y_test) print('Test accuracy:', score[0]) ``` 我们得到以下输出: ```py Test accuracy: 0.9637 ``` 与使用 TFLearn 相比,我们获得了相当的精确度。 在笔记本 `ch-05_MLP` 中提供了使用 TFLearn 进行 MNIST 分类的 MLP 的完整代码。