无法使用VGG16预训练模型实施多班制转移学习

时间:2019-08-07 16:38:25

标签: python keras deep-learning transfer-learning vgg-net

我正在尝试重新实现迁移学习from this link,我想重新实现用于数据的多类分类的代码。

我的示例数据位于https://www.dropbox.com/s/esirpr6q1lsdsms/ricetransfer1.zip?dl=0

我尝试了StackOverflow上提供的其他建议,但这不起作用。

# Extract features
import os, shutil
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
train_size, validation_size, test_size = 148, 27, 31

datagen = ImageDataGenerator(rescale=1./255)
batch_size = 16
train_dir = "ricetransfer1/train"
validation_dir = "ricetransfer1/validation"
test_dir="ricetransfer1/test"
#indices = np.random.choice(range(len(X_train)))

def extract_features(directory, sample_count):
   #sample_count= X_train.ravel()

    features = np.zeros(shape=(sample_count, 7, 7, 512))  # Must be 
    equal to the output of the convolutional base
    labels = np.zeros(shape=(sample_count))
    # Preprocess data
    generator = datagen.flow_from_directory(directory,
                                        target_size=(img_width,img_height),
                                        batch_size = batch_size,
                                        class_mode='binary')
    # Pass data through convolutional base
    i = 0
    for inputs_batch, labels_batch in generator:
        features_batch = conv_base.predict(inputs_batch)
        features[i * batch_size: (i + 1) * batch_size] = features_batch
        labels[i * batch_size: (i + 1) * batch_size] = labels_batch
        i += 1
        if i * batch_size >= sample_count:
            break
return features, labels

train_features, train_labels = extract_features(train_dir, train_size)  # Agree with our small dataset size
validation_features, validation_labels = extract_features(validation_dir, validation_size)
test_features, test_labels = extract_features(test_dir, test_size)
  

ValueError:无法将输入数组从形状(16,4)广播到形状(16)

我想将转移学习用于图像的多类分类。

1 个答案:

答案 0 :(得分:0)

您需要用labels = np.zeros(shape=(sample_count))修复labels = np.zeros(shape=(sample_count, 4)),其中四个代表四个类,现在它将正确广播。

相关问题