我有一个带有二进制类(对或错)的数据样本。神经网络赋予每个班级权重,最大值将决定归属的班级。但是,即使输出层没有适当数量的神经元,为什么角膜也能起作用?(在我的情况下,=类数= 2,即0或1)。
import keras
from model import *
X_train, X_test, y_train, y_test = train_test_split(df_features, df_labels, test_size=0.25, random_state=10)
model = keras.Sequential([
keras.layers.Flatten(input_shape=(len(X_test.columns),)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(128, activation='softmax') # Shouldn't be two here ?
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
# len(y_train.columns) == 1
history = model.fit(X_train, y_train, epochs=100, validation_split=0.25)
scores = model.evaluate(X_test, y_test, verbose=0)
print(model.metrics_names)
print('scores=', scores)
假设:它在末尾添加了一个隐式层,或者它忽略了某些神经元,或者完全是其他东西?
编辑:添加数据
>>> print(y_train)
[0 0 0 ... 0 1 0]
>>> print(y_test)
Class
1424 0
3150 1
2149 0
1700 0
4330 0
4200 0
# etc, ~1000 entries
>>> print('len(y_train)=', len(y_train))
len(y_train)= 2678
>>> print('len(y_test)=', len(y_test))
len(y_test)= 893
我认为问题在于您的损失如何sparse_cartegorical_crossentropy
运作。这种损失(与相对categorical_crossentropy
)假定y_actual将作为标签编码格式而不是单热编码格式提供。这意味着,如果要预测5个类别,则将提供y_actual数组,[0,2,4,1,2,2,3,3,1...]
其中1-D数组中的每个值代表5个可能类别中的一个类别编号。
让我们直接从tf2文档中查看有关此损失的独立用法的示例-
y_true = [1, 2] #class number from 0 to 2
y_pred = [[0.05, 0.95, 0], [0.1, 0.8, 0.1]] #3 class classification output
loss = tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred)
assert loss.shape == (2,)
loss.numpy()
[0.0513, 2.253]
在您的情况下,这意味着当模型返回128维输出时,它将假定此分类问题中有128个类。但是,由于损失为sparse_categorical_crossentropy
,因此它将等待接收0-127之间的单个数字,然后将其用于计算其错误。
由于在所有情况下都始终将其设置为0或1,因此假定样本所属的实际类仅是128个类中的0或1类,而其他所有类都不是。因此,它可以运行代码,但是它是有缺陷的,因为它假定它属于128个其他类中的一个,而不是作为二进制类读取y_train
(或从y_test
)获得的一位数字。
print(y_train)
[0 0 0 ... 0 1 0]
#The first 0 here, is being considered as one class out of 128 other classes.
#The code would still work if u changed that to say 105 instead of 0.
#Similarly for all the other 0s and 1s.
希望这是有道理的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句