3

我一直在学习神经网络的课程,并不真正理解为什么我从逻辑回归的准确性分数和两层神经网络(输入层和输出层)中获得不同的结果。输出层使用sigmoid激活函数。根据我所了解的,我们可以在神经网络中使用S形激活函数来计算概率。如果逻辑回归试图完成的话,这应该是非常相似的。然后从那里backpropogate使用梯度下降最小化错误。可能有一个简单的解释,但我不明白为什么准确度分数变化如此之大。在这个例子中,我没有使用任何训练或测试集,只是简单的数据来展示我不明白的东西。神经网络(无隐藏层)vs Logistic回归?

逻辑回归的准确性达到了71.4%。在下面的例子中,我只是为'X'和结果'y'数组创建了数字。当结果等于'1'时,我故意让'X'的数字更高,这样线性分类器就可以具有一些准确性。

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 

然而,当我实现一个神经网络,没有隐藏层,只是用S形的激活函数的单个节点的输出层(总共,输入和输出层这样两层)。我的准确性分数大概是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 

回答

4

你没有比较相同的东西。 Sklearn的LogisticRegression设置了很多您在Keras实现中未使用的默认值。

迭代

数在Keras这是epochs期间fit()过去了:我其实考虑这些差别,其中主要是当对方的1E-8中得到的准确度。您将它设置为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]]) 

Logistic回归

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 
+1

太谢谢你了!我没有意识到这些参数会产生很大的差异。我们了解了这两种模型,并且我认为精确度得分几乎相同。我真的想了解神经网络如何工作,这真的有助于澄清事情。看起来我仍然需要花几个小时来查看神经网络的参数,以充分和真实地理解一切。再次感谢! – James