为什么mnist fasion keras代码中的softmax可以正常工作,但不能产生S形?

时间:2019-05-07 11:15:00

标签: machine-learning keras deep-learning

我有用于多标签分类的简单Keras代码,

from keras.models import Sequential
from keras.layers import Conv2D, GlobalAveragePooling2D, Dense, MaxPooling2D, Flatten
from keras.callbacks import EarlyStopping
import keras

(x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()
model = Sequential()

model.add(Conv2D(64, (3,3), activation='relu', padding='same', input_shape=(x_train.shape[1],x_train.shape[2],1)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
#model.add(Dense(128, activation='relu'))

model.add(Dense(10, activation='softmax'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.summary()

摘要, enter image description here

现在,正如您在最后一层中看到的那样,我使用了“ sigmoid”,但是由于它是多标签分类,因此我想使用sigmoid。但是,如果执行相同的操作,则会出现以下错误。

  

ValueError:检查目标时出错:预期density_2具有形状   (10,)但形状为(1,)的数组

这里的解决办法是什么?

1 个答案:

答案 0 :(得分:0)

loss='binary_crossentropy'更改为loss='sparse_categorical_crossentropy'

当标签为one-hot encoded时,请使用categorical_crossentropy。否则,请使用sparse_categorical_crossentropy

binary_crossentropy用于两类,并且输出一个神经元(或者在多输出分类的情况下,它可以输出多个神经元)。例如,如果神经元的值大于0.5而不是您选择的类1,则选择了0的类(或者如果该值小于keras,则不选择任何类一些阈值)。

另外,在某些tf.keras / x_train, x_test = np.expand_dims(x_train, -1), np.expand_dims(x_test, -1) 版本中,MNIST时尚没有渠道维度,因此您应该手动添加它:

<script>
//random video only desktop
var isMobile = 
/Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ? 
true : false;
jQuery(document).ready(function($){
  if(!isMobile) {
        var video = new Array ();
        video[0] = "/anek-ferry-traghetti-grecia-low.mp4";
        video[1] = "/anek-ferry-traghetti-grecia-v2-low.mp4";
        var randomvideo = Math.floor(Math.random() * video.length);
        $('#random-clip video').attr('src', '/wp-        
 content/uploads/media' + video[randomvideo]);
        $('#random-clip source').attr('src', '/wp- 
content/uploads/media' + video[randomvideo]);
    }
});
</script>
<script>
//random background only mobile
jQuery(document).ready(function($){

 var background = new Array ();
 background[0] = "/traghetti-italia-grecia-anek-fallback1.jpg";
 background[1] = "/traghetti-italia-grecia-anek-fallback5.jpg";
 background[2] = "/traghetti-italia-grecia-anek-fallback2.jpg";
 var randombackground = Math.floor(Math.random() * background.length); 

$("#random-clip.et_pb_fullwidth_header.et_pb_fullwidth_header_0").css({
  'background-image': 'url(/wp-content/uploads/media' + 
background[randombackground] + ')',
    'background-position-y': '35%' });
});
</script>