为什么sklearn的MLPClassifier无法预测异或?

理论上,一个具有单隐藏层且仅有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使用的是什么。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注