61607


## 質問

Kerasに実装されているVGG16を転移学習して画像の2クラス分類をしようと考えております。  
[参考サイト](https://qiita.com/yottyann1221/items/20a9c8a7a02edc7cd3d1)のコードを一部修正して実行すると、下記エラーが発生して学習できません。

[code]

    ValueError: Error when checking target: expected sequential_1 to have shape (2,) but got array with shape (1,)
    
[/code]

どのようにコードを修正すればよいでしょうか?  
もしくは、教師データの数量が原因でしょうか?

## 現状

### コード

[code]

    from keras.applications.vgg16 import VGG16
    from keras.preprocessing.image import ImageDataGenerator
    from keras.optimizers import SGD
    from keras.models import Sequential, Model
    from keras.layers import Input, Activation, Dropout, Flatten, Dense
    
    
    n_categories = 2
    batch_size = 2
    train_data_dir = './images/train'
    validation_data_dir = './images/validation'
    file_name = 'vgg16_ano_fine'
    image_size = 224
    
    #画像データの水増しはしない
    train_datagen = ImageDataGenerator(
        rescale=1. / 255,
        horizontal_flip=False)
    
    
    test_datagen = ImageDataGenerator(rescale=1. / 255)
    
    train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size=(image_size, image_size),
        batch_size=batch_size,
        class_mode='binary')
    
    #2クラス分類のため'binary'を指定
    validation_generator = test_datagen.flow_from_directory(
        validation_data_dir,
        target_size=(image_size, image_size),
        batch_size=batch_size,
        class_mode='binary')
    
    
    # VGG16のロード。FC層は不要なので include_top=False
    input_tensor = Input(shape=(image_size, image_size, 3))
    vgg16 = VGG16(include_top=False, weights='imagenet', input_tensor=input_tensor)
    
    # VGG16の図の緑色の部分（FC層）の作成
    top_model = Sequential()
    top_model.add(Flatten(input_shape=vgg16.output_shape[1:]))
    top_model.add(Dense(256, activation='relu'))
    top_model.add(Dropout(0.5))
    top_model.add(Dense(n_categories, activation='softmax'))
    
    # VGG16とFC層を結合してモデルを作成（完成図が上の図）
    model = Model(input=vgg16.input, output=top_model(vgg16.output))
    
    # VGG16の図の青色の部分は重みを固定（frozen）
    for layer in model.layers[:15]:
        layer.trainable = False
    model.summary()
    # 多クラス分類を指定
    model.compile(loss='binary_crossentropy',
                  optimizer=optimizers.SGD(lr=1e-5, momentum=0.9),
                  metrics=['accuracy'])
    
    model.fit_generator(
        train_generator,
        steps_per_epoch=10 // batch_size,
        epochs=20,
        validation_data=validation_generator,
        validation_steps=6 // batch_size)
    
[/code]

### 環境

  * Windows10 1903
  * python v3.7.5
  * keras-gpu v2.2.4
  * keras v2.2.4
  * tensorflow v1.15.0
  * cuddn v10.0

### 学習画像

クラスAとクラスBで、教師データがそれぞれ10枚、バリデーションデータがそれぞれ6枚。  
画像サイズは224x224  
実行時に下記のメッセージが出力されるため、画像読み込みはできていると思います。

[code]

    Found 20 images belonging to 2 classes.
    Found 12 images belonging to 2 classes.
    
[/code]

### ネットワーク図

[code]

    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    input_1 (InputLayer)         (None, 224, 224, 3)       0
    _________________________________________________________________
    block1_conv1 (Conv2D)        (None, 224, 224, 64)      1792      
    _________________________________________________________________
    block1_conv2 (Conv2D)        (None, 224, 224, 64)      36928
    _________________________________________________________________
    block1_pool (MaxPooling2D)   (None, 112, 112, 64)      0
    _________________________________________________________________
    block2_conv1 (Conv2D)        (None, 112, 112, 128)     73856
    _________________________________________________________________
    block2_conv2 (Conv2D)        (None, 112, 112, 128)     147584
    _________________________________________________________________
    block2_pool (MaxPooling2D)   (None, 56, 56, 128)       0
    _________________________________________________________________
    block3_conv1 (Conv2D)        (None, 56, 56, 256)       295168
    _________________________________________________________________
    block3_conv2 (Conv2D)        (None, 56, 56, 256)       590080
    _________________________________________________________________
    block3_conv3 (Conv2D)        (None, 56, 56, 256)       590080
    _________________________________________________________________
    block3_pool (MaxPooling2D)   (None, 28, 28, 256)       0
    _________________________________________________________________
    block4_conv1 (Conv2D)        (None, 28, 28, 512)       1180160
    _________________________________________________________________
    block4_conv2 (Conv2D)        (None, 28, 28, 512)       2359808
    _________________________________________________________________
    block4_conv3 (Conv2D)        (None, 28, 28, 512)       2359808
    _________________________________________________________________
    block4_pool (MaxPooling2D)   (None, 14, 14, 512)       0
    _________________________________________________________________
    block5_conv1 (Conv2D)        (None, 14, 14, 512)       2359808
    _________________________________________________________________
    block5_conv2 (Conv2D)        (None, 14, 14, 512)       2359808
    _________________________________________________________________
    block5_conv3 (Conv2D)        (None, 14, 14, 512)       2359808
    _________________________________________________________________
    block5_pool (MaxPooling2D)   (None, 7, 7, 512)         0
    _________________________________________________________________
    sequential_1 (Sequential)    (None, 2)                 6423298
    =================================================================
    Total params: 21,137,986
    Trainable params: 13,502,722
    Non-trainable params: 7,635,264
    _________________________________________________________________
    
[/code]


CC BY-SA 4.0
2019-12-19T06:46:52.030
61573
2019-12-20T12:11:59.967
2019-12-20T12:11:59.967
32986
19500
question
python python3 機械学習 深層学習 keras
KerasでVGG16の転移学習をするときにValueErrorが発生する


2クラス分類なら

[code]

    n_categories = 2
    ・・・
    top_model.add(Dense(n_categories, activation='softmax'))
    
[/code]

ではなく、

[code]

    n_categories = 1
    ・・・
    top_model.add(Dense(n_categories, activation='softmax'))
    
[/code]

では。


CC BY-SA 4.0
2019-12-20T03:53:30.177
61607
2019-12-20T03:53:30.177
21092
61573
answer