gpt4 book ai didi

python-3.x - 如何预处理数据并将其输入keras模型?

转载 作者:行者123 更新时间:2023-11-30 08:52:51 25 4
gpt4 key购买 nike

我有一个包含两列的数据集:路径和类。我想用它来微调 VGGface。

dataset.head(5):


path class
0 /f3_224x224.jpg red
1 /bc_224x224.jpg orange
2 /1c_224x224.jpg brown
3 /4b_224x224.jpg red
4 /0c_224x224.jpg yellow

我想使用这些路径来预处理图像并提供给 keras。我的预处理函数如下:

from keras.preprocessing.image import img_to_array, load_img

def prep_image(photo):
img = image.load_img(path + photo, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = utils.preprocess_input(x, version=1)
return x

我使用以下代码准备数据集:

from sklearn.model_selection import train_test_split

path = list(dataset.columns.values)
path.remove('class')
X = dataset[path]
y = dataset['class']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

我使用以下代码训练我的模型:

nb_class = 4
hidden_dim = 512

vgg_model = VGGFace(include_top=False, input_shape=(224, 224, 3))
last_layer = vgg_model.get_layer('pool5').output
x = Flatten(name='flatten')(last_layer)
x = Dense(hidden_dim, activation='relu', name='fc6')(x)
x = Dense(hidden_dim, activation='relu', name='fc7')(x)
out = Dense(nb_class, activation='softmax', name='fc8')(x)
custom_vgg_model = Model(vgg_model.input, out)
custom_vgg_model.compile(

optimizer="adam",
loss="categorical_crossentropy"
)

custom_vgg_model.fit(X_train, y_train, epochs=50, batch_size=16)
test_loss, test_acc = model.evaluate(X_test, y_test)

但是我得到了值错误,因为我无法弄清楚如何预处理图像并提供数组。我如何转换 X_train/test 数据帧的路径并将其替换为 prep_image 函数的输出?

ValueError: Error when checking input: expected input_2 to have 4 dimensions, but got array with shape (50297, 1)

所以形状应该是 (50297, 224, 224, 3)。

最佳答案

X_train、X_test 看起来基本上只是路径名。在数据准备步骤中,您只需修改代码,例如添加最后两行。

from sklearn.model_selection import train_test_split

path = list(dataset.columns.values)
path.remove('class')
X = dataset[path]
y = dataset['class']

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
X_train = np.array([prep_image(path)[0] for path in X_train])
X_test = np.array([prep_image(path)[0] for path in X_test])

关于python-3.x - 如何预处理数据并将其输入keras模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58527815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com