神经网络(无隐藏层)与逻辑回归?

Neural Network (No hidden layers) vs Logistic Regression?

我一直在学习神经网络 class,但我真的不明白为什么我从逻辑回归和两层神经网络(输入层和输出层)的准确度得分中得到不同的结果).输出层使用 sigmoid 激活函数。根据我学到的知识,我们可以在神经网络中使用 sigmoid 激活函数来计算概率。如果不完全相同,这应该与逻辑回归试图实现的目标非常相似。然后从那里反向传播以使用梯度下降最小化错误。可能有一个简单的解释,但我不明白为什么准确性分数差异如此之大。在这个例子中,我没有使用任何训练或测试集,只是简单的数据来证明我不理解的地方。

逻辑回归的准确率为 71.4%。在下面的示例中,我刚刚为 'X' 和结果 'y' 数组创建了数字。当结果等于“1”时,我故意使 'X' 的数字更高,以便线性 classifier 可以有一定的准确性。

import numpy as np
from sklearn.linear_model import LogisticRegression
X = np.array([[200, 100], [320, 90], [150, 60], [170, 20], [169, 75], [190, 65], [212, 132]])
y = np.array([[1], [1], [0], [0], [0], [0], [1]])

clf = LogisticRegression()
clf.fit(X,y)
clf.score(X,y) ##This results in a 71.4% accuracy score for logistic regression

然而,当我实现一个没有隐藏层的神经网络时,只对单节点输出层(所以总共两层,输入和输出层)使用 sigmoid 激活函数。我的准确率大约是 42.9%?为什么这与逻辑回归准确度得分有显着差异?为什么这么低?

import keras
from keras.models import Sequential
from keras.utils.np_utils import to_categorical
from keras.layers import Dense, Dropout, Activation

model = Sequential()

#Create a neural network with 2 input nodes for the input layer and one node for the output layer. Using the sigmoid activation function
model.add(Dense(units=1, activation='sigmoid', input_dim=2))
model.summary()
model.compile(loss="binary_crossentropy", optimizer="adam", metrics = ['accuracy'])
model.fit(X,y, epochs=12)

model.evaluate(X,y) #The accuracy score will now show 42.9% for the neural network

你不是在比较同一件事。 Sklearn 的 LogisticRegression 设置了许多您在 Keras 实现中没有使用的默认值。在考虑这些差异时,我实际上得到的准确度在 1e-8 以内,主要差异是:

迭代次数

在 Keras 中,这是 epochsfit() 期间通过的。您将其设置为 12。在 Sklearn 中,这是在 LogisticRegression__init__() 期间传递的 max_iter。默认为 100。

优化器

您在 Keras 中使用 adam 优化器,而 LogisticRegression 默认使用 liblinear 优化器。 Sklearn 称之为 solver.

正则化

Sklearn 的 LogisticRegression 默认使用 L2 正则化,您没有在 Keras 中进行任何权重正则化。在 Sklearn 中,这是 penalty,在 Keras 中,您可以使用每一层的 kernel_regularizer.

来调整权重

这些实现都达到了 0.5714% 的准确率:

import numpy as np

X = np.array([
  [200, 100], 
  [320, 90], 
  [150, 60], 
  [170, 20], 
  [169, 75], 
  [190, 65], 
  [212, 132]
])
y = np.array([[1], [1], [0], [0], [0], [0], [1]])

逻辑回归

from sklearn.linear_model import LogisticRegression

# 'sag' is stochastic average gradient descent
lr = LogisticRegression(penalty='l2', solver='sag', max_iter=100)

lr.fit(X, y)
lr.score(X, y)
# 0.5714285714285714

神经网络

from keras.models import Sequential
from keras.layers import Dense
from keras.regularizers import l2

model = Sequential([
  Dense(units=1, activation='sigmoid', kernel_regularizer=l2(0.), input_shape=(2,))
])

model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])
model.fit(X, y, epochs=100)
model.evaluate(X, y)
# 0.57142859697341919