TensorFlow - XOR 实现
TensorFlow - XOR 问题实现
Section titled “TensorFlow - XOR 问题实现”XOR(异或)问题是神经网络中的一个经典示例,因为它是一个线性不可分问题。这意味着简单的线性分类器无法解决它。需要一个至少包含一个隐藏层的神经网络。本章演示了如何使用 TensorFlow 及其 Keras API 实现一个神经网络来解决 XOR 问题。
| 输入 A | 输入 B | 输出 (A XOR B) |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
XOR 函数的输出是:如果输入不同则为 1,如果输入相同则为 0。我们将构建一个小型神经网络来学习这种映射。
我们将使用 tf.keras 来定义、编译和训练模型。
# 导入必要的模块import tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras import layersimport numpy as np
# 用于结果可复现性np.random.seed(42)tf.random.set_seed(42)
# 定义 XOR 输入数据(特征)和输出数据(标签)X_train = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype="float32")
y_train = np.array([[0], [1], [1], [0]], dtype="float32")
# 使用 Keras Sequential API 定义神经网络模型model = keras.Sequential([ # 输入层: 通过第一层的 input_shape 隐式定义 # 隐藏层: 8 个单元,'relu' 激活函数 layers.Dense(units=8, activation='relu', input_shape=(2,)), # 2 个输入特征 # 输出层: 1 个单元(用于二元输出),'sigmoid' 激活函数用于输出概率 layers.Dense(units=1, activation='sigmoid')])
# 编译模型# 优化器: Adam 是一个很好的通用优化器# 损失函数: 二元交叉熵 (Binary Crossentropy) 适合二元分类 (0 或 1)model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.1), loss='binary_crossentropy', metrics=['accuracy'])
# 打印模型摘要model.summary()
# 训练模型print("\n正在训练模型...")# epochs: 遍历整个数据集的次数# verbose=0 以保持教程输出整洁,设为 1 或 2 可查看更多细节history = model.fit(X_train, y_train, epochs=100, verbose=0)
# 评估模型 (可选,因为数据集非常小)loss, accuracy = model.evaluate(X_train, y_train, verbose=0)print(f"\n训练集损失: {loss:.4f}")print(f"训练集准确率: {accuracy:.4f}")
# 进行预测print("\n预测结果 (概率):")predictions_prob = model.predict(X_train)print(predictions_prob)
# 将概率转换为二元预测 (0 或 1)predictions_binary = (predictions_prob > 0.5).astype(int)print("\n二元预测结果 (0 或 1):")print(predictions_binary)
# 显示输入、真实输出和预测输出print("\n输入 | 真实输出 | 预测输出 (概率) | 预测输出 (二元)")print("------------------------------------------------------------------------")for i in range(len(X_train)): print(f"{X_train[i]} | {y_train[i][0]} | {predictions_prob[i][0]:.4f} | {predictions_binary[i][0]}")这段代码定义了一个小型神经网络,使用 Adam 优化器和二元交叉熵损失函数进行编译,在 XOR 数据上进行训练,然后打印出预测结果。具有非线性激活函数(如 ‘relu’ 或 ‘sigmoid’)的隐藏层是解决 XOR 问题的关键。
预期输出(会因随机初始化略有差异,尤其是当 epoch 较少或学习率不同时。可能需要更多 epoch 或不同的超参数才能完美解决 XOR 问题):
Model: "sequential"_________________________________________________________________ Layer (type) Output Shape Param #================================================================= dense (Dense) (None, 8) 24
dense_1 (Dense) (None, 1) 9
=================================================================Total params: 33Trainable params: 33Non-trainable params: 0_________________________________________________________________
Training the model...
Training Loss: 0.0128Training Accuracy: 1.0000
Predictions (Probabilities):1/1 [==============================] - 0s 21ms/step[[0.00621046] [0.99280304] [0.9930576 ] [0.01085009]]
Binary Predictions (0 or 1):[[0] [1] [1] [0]]
Input | True Output | Predicted Output (Prob) | Predicted Output (Binary)------------------------------------------------------------------------[0. 0.] | 0.0 | 0.0062 | 0[0. 1.] | 1.0 | 0.9928 | 1[1. 0.] | 1.0 | 0.9931 | 1[1. 1.] | 0.0 | 0.0109 | 0