Jam*_*mes 7 python machine-learning neural-network logistic-regression keras
我一直在上神经网络课,并不真正理解为什么我从逻辑回归和两层神经网络(输入层和输出层)的准确度得分得到不同的结果.输出层使用sigmoid激活功能.根据我的学习,我们可以使用神经网络中的sigmoid激活函数来计算概率.如果与逻辑回归试图完成的内容完全相同,这应该非常相似.然后从那里backpropogate使用梯度下降最小化错误.可能有一个简单的解释,但我不明白为什么准确性得分变化如此之大.在这个例子中,我没有使用任何训练或测试集,只是简单的数据来演示我不理解的东西.
逻辑回归的准确率为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
Run Code Online (Sandbox Code Playgroud)
然而,当我实现一个没有隐藏层的神经网络时,只需对单节点输出层使用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
Run Code Online (Sandbox Code Playgroud)
你不是在比较同样的事情.Sklearn的LogisticRegression设置了许多你在Keras实现中没有使用的默认值.在考虑到这些差异时,我实际上得到的精度在1e-8之内,主要是:
迭代次数
在Keras,这是epochs在期间通过fit().你将它设置为12.在Sklearn中,这是max_iter在期间传递LogisticRegression的__init__().它默认为100.
优化
您正在使用adamKeras中的优化程序,而默认情况下LogisticRegression使用liblinear优化程序.Sklearn称之为solver.
正则
LogisticRegression默认情况下,Sklearn 使用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]])
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
神经网络
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2530 次 |
| 最近记录: |