Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Keras多输出numpy变换_Python_Numpy_Tensorflow_Keras - Fatal编程技术网

Python Keras多输出numpy变换

Python Keras多输出numpy变换,python,numpy,tensorflow,keras,Python,Numpy,Tensorflow,Keras,我有一个y\u序列数据集,形状为(示例,9)。我的X\u列输入的形状为(示例,30,1) 这些内容贯穿于构建为以下内容的模型: def create_model(input_shape, outputs): i = Input(shape=input_shape) x = Dense(256, activation="relu")(i) x = Dropout(0.5)(x) x = Dense(128, activation="relu")(x) x

我有一个
y\u序列
数据集,形状为
(示例,9)
。我的
X\u列
输入的形状为
(示例,30,1)

这些内容贯穿于构建为以下内容的模型:

def create_model(input_shape, outputs):
    i = Input(shape=input_shape)

    x = Dense(256, activation="relu")(i)
    x = Dropout(0.5)(x)
    x = Dense(128, activation="relu")(x)
    x = Dropout(0.5)(x)
    x = Dense(64, activation="relu")(x)
    x = Dropout(0.5)(x)
    x = Flatten()(x)

    # Optimize each binary output independently.
    o = list(map(lambda _: Dense(1, activation='sigmoid')(x), range(outputs)))

    m = Model(i, o)
    m.compile('adam', loss='binary_crossentropy', metrics=['accuracy'])
    return m

model = create_model((30, 1), 9)
这会产生一个训练错误:

检查模型目标时出错:您选择的Numpy数组列表 传递给模型的大小不是模型预期的大小。预期 查看9个数组,但得到了以下1个数组的列表:


我尝试了
y\u序列
形状的变体,包括
(9,示例1)
(示例1,9)
。keras希望看到我的
(示例,9)
阵列形状如何变换?

您的模型有9个输出层,每个层都有二进制交叉熵。因此,您需要将输出作为9个输出的列表传递,其中每个输出是一个
(示例,1)
大小的数组,而不是一个包含9列的单个数组

因此,您需要执行以下操作

# Assuming your y_train is of size (samples, 9)
y_train_list = np.split(y_train, y_train.shape[1], axis=1)

model.fit(x_train, y_train_list)
下面是一个玩具数据的工作示例

x_train = np.random.normal(size=(500,30,1))
y_train = np.random.choice([0,1], size=(500, 9))
y_train_list = np.split(y_train, y_train.shape[1], axis=1)
model.fit(X_tr, y_train_list)
使用列车测试分割创建列车验证数据
这样,我得到了一个错误:
找到了样本数不一致的输入变量:[samples,9]
您的
y\u序列需要是[samples,9]。您可能通过了不同大小的
y\u列
。如果I
print(y\u train.shape)
,它将返回
(4994,9)
,其中4994是样本数。在np.split之后,
print(len(y\u train),y\u train[0].shape)
返回错误抛出的
9(4994,1)
。@iRyanBell我在我的问题中添加了一个工作示例。你能将你的数据与玩具数据进行比较,看看它们的形状是否正确吗?@thrushv89得到了。成功了!我有一个培训验证分离,这使测试复杂化。
x_train = np.random.normal(size=(500,30,1))
y_train = np.random.choice([0,1], size=(500, 9))
y_train_list = np.split(y_train, y_train.shape[1], axis=1)
model.fit(X_tr, y_train_list)
from sklearn.model_selection import train_test_split

tr_x, ts_x, tr_y, ts_y =train_test_split(X_tr, Y_tr, test_size=0.33)
tr_list_y = np.split(tr_y, tr_y.shape[1], axis=1)
ts_list_y = np.split(ts_y, ts_y.shape[1], axis=1)
model.fit(tr_x, tr_list_y, validation_data=(ts_x, ts_list_y))