【问题标题】:Using Random search in keras_tuner在 keras_tuner 中使用随机搜索
【发布时间】:2021-10-26 13:00:26
【问题描述】:

当我运行 RandomSearch.search 时,我收到 logits 形状和标签形状不同的错误消息。我不明白错误是什么。有什么帮助吗? 按照错误消息:

tensorflow.python.framework.errors_impl.InvalidArgumentError: logits 并且标签必须具有相同的第一维,得到 logits 形状 [32,15] 和标签形状 [480] [[节点 sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits (定义在 ProgramData\Anaconda3\envs\tf\lib\site-packages\keras_tuner\engine\tuner.py:147) ]] [Op:__inference_train_function_828] 函数调用堆栈: train_function

以下是我的代码:

import tensorflow as tf
import keras_tuner as kt
from tensorflow import keras
from keras_tuner import RandomSearch
from keras_tuner.engine.hyperparameters import HyperParameters
import os
import cv2
import pandas as pd
import numpy as np
from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split


f= pd.read_csv('CELLS_ALL.csv')
Labels= f['labels']
path_dir = 'C:\\Users\\Tusneem\\PycharmProjects\\imageDataGen\\images\\'
img_all = []
for i in os.listdir(path_dir):
   img_sig = cv2.imread(path_dir+i)
   img_sig = cv2.resize(img_sig, (50, 50))
   img_all.append(img_sig)
x = np.array(img_all, dtype="float") / 255.0
y = Labels
le = LabelEncoder()
y = le.fit_transform(y)
y = to_categorical(y)
#print(labels)


(trainX, testX, trainY, testY) = train_test_split(x, y, test_size=0.25, random_state=42)

# for cnn images should me of shape (len(training,size,size, channel)

trainX= trainX.reshape(len(trainX),50,50,3)
testX = testX.reshape(len(testX),50,50,3)


def build_model(hp):
    model = keras.Sequential([
        keras.layers.Conv2D(
            filters=hp.Int('conv_1_filter', min_value=32, max_value=128, step=20),
            kernel_size=hp.Choice('conv_1_kernel', values=[3, 5]),
            activation='relu',
            input_shape=(50, 50, 3)
        ),
        keras.layers.Conv2D(
            filters=hp.Int('conv_2_filter', min_value=32, max_value=64, step=20),
            kernel_size=hp.Choice('conv_2_kernel', values=[3, 5]),
            activation='relu'
        ),
        keras.layers.Flatten(),
        keras.layers.Dense(
            units=hp.Int('dense_1_units', min_value=32, max_value=128, step=20),
            activation='relu'
        ),
        keras.layers.Dense(15, activation='softmax')
    ])

    model.compile(optimizer=keras.optimizers.Adam(hp.Choice('learning_rate', values=[1e-2, 1e-3])),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    return model
    model.compile(optimizer=keras.optimizers.Adam(hp.Choice('learning_rate', values=[1e-2, 1e-3])),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])
    model.summary()

    return model

tuner_search= kt.RandomSearch(build_model,
                          objective='val_accuracy',
                          max_trials=5) #,directory='tune',project_name="cnn model tunning"

tuner_search.search(trainX,trainY,epochs=5,validation_split=0.1)
model=tuner_search.get_best_models()[0]

问题出在这一行:

tuner_search.search(trainX,trainY,epochs=5,validation_split=0.1)

我的问题是如何解决这个错误?

【问题讨论】:

    标签: tensorflow hyperparameters keras-tuner


    【解决方案1】:

    我认为问题在于不应该使用我的“y”变量作为热编码。 它应该是 1 到 15 的形式,这是我的目标变量“y”中的类别数。

    【讨论】:

    • 您可以将sparse_categorical_crossentropy 更改为categorical_crossentropy,而不是更改标签格式。
    猜你喜欢
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 2019-07-13
    相关资源
    最近更新 更多