理论上,一个具有单隐藏层且仅有3个神经元的多层感知器就足以正确预测异或。虽然有时可能无法正确收敛,但4个神经元是更为保险的选择。
这里有一个示例
我尝试使用sklearn.neural_network.MLPClassifier来复制这个结果:
from sklearn import neural_networkfrom sklearn.metrics import accuracy_score, precision_score, recall_scoreimport numpy as npx_train = np.random.uniform(-1, 1, (10000, 2))tmp = x_train > 0y_train = 2 * (tmp[:, 0] ^ tmp[:, 1]) - 1model = neural_network.MLPClassifier( hidden_layer_sizes=(3,), n_iter_no_change=100, learning_rate_init=0.01, max_iter=1000).fit(x_train, y_train)x_test = np.random.uniform(-1, 1, (1000, 2))tmp = x_test > 0y_test = 2 * (tmp[:, 0] ^ tmp[:, 1]) - 1prediction = model.predict(x_test)print(f'Accuracy: {accuracy_score(y_pred=prediction, y_true=y_test)}')print(f'recall: {recall_score(y_pred=prediction, y_true=y_test)}')print(f'precision: {precision_score(y_pred=prediction, y_true=y_test)}')
我的准确率仅约为0.75,而tensorflow playground的模型是完美的,有人知道是什么造成了差异吗?
我也尝试使用tensorflow:
model = tf.keras.Sequential(layers=[ tf.keras.layers.Input(shape=(2,)), tf.keras.layers.Dense(4, activation='relu'), tf.keras.layers.Dense(1)])model.compile(loss=tf.keras.losses.binary_crossentropy)x_train = np.random.uniform(-1, 1, (10000, 2))tmp = x_train > 0y_train = (tmp[:, 0] ^ tmp[:, 1])model.fit(x=x_train, y=y_train)x_test = np.random.uniform(-1, 1, (1000, 2))tmp = x_test > 0y_test = (tmp[:, 0] ^ tmp[:, 1])prediction = model.predict(x_test) > 0.5print(f'Accuracy: {accuracy_score(y_pred=prediction, y_true=y_test)}')print(f'recall: {recall_score(y_pred=prediction, y_true=y_test)}')print(f'precision: {precision_score(y_pred=prediction, y_true=y_test)}')
使用这个模型,我得到了与scikit-learn模型相似的结果…所以这不仅仅是scikit-learn的问题 – 我是否遗漏了一些重要的超参数?
编辑
好的,我将损失函数从交叉熵改为均方误差,现在tensorflow示例的准确率达到了0.92。我猜这就是MLPClassifier的问题所在?
回答:
增加学习率和/或最大迭代次数似乎能使sklearn版本工作。可能不同的求解器需要这些参数的不同值,我不清楚tf playground使用的是什么。