首页 > 解决方案 > 在 Keras 或 Tensorflow 中,如何在模型中输入不同的样本大小和成对连接嵌入?

问题描述

在 [this question] 的后续行动中,关于我们希望完成的工作的一些说明:

下面是一个简单网络的示例:

在此处输入图像描述

链接的答案和其他一些资源帮助达到了这个例子,它建立了一个模型,但在合适的时候抛出了这个错误:ValueError: All input arrays (x) should have the same number of samples. Got array shapes: [(10, 2), (12, 2)].

最近版本的 Keras允许跳过维度检查,在 Tensorflow 中可以跳过这个检查吗?我也很乐意使用 Keras,但我不确定如何在模型中间的 Keras 中执行重塑和连接。

或者,这根本不可能吗?是在输入之前扩展和成对连接的唯一选择吗?

import tensorflow as tf
from tensorflow import keras 
from tensorflow.keras import layers
import numpy as np

k = 2
N = 10
M = 12

x = np.random.randint(2, size = 2 * N).reshape((-1,2))
y = np.random.randint(2, size = 2 * M).reshape((-1,2))

x_rep = np.tile(x, (1, M)).reshape((-1,2))
y_rep = np.tile(y, (N, 1))

xy = np.concatenate((x_rep, y_rep), axis=1)
xy = xy.astype(bool)
z = (xy[:,0] == xy[:,2]) * (xy[:,1] ^ xy[:,3])

print(z[:20])
xy = xy.astype(int)
z = z.astype(int)


first = keras.Input(shape=(k,))
second = keras.Input(shape=(k,))

shared_dense = layers.Dense(k)

first_dense = shared_dense(first)
second_dense = shared_dense(second)

first_tiled = layers.Lambda(tf.tile, arguments={'multiples':[1, M]}, name='first_expanded' )(first_dense) #keras.backend.tile(first_dense, [1, M])
second_tiled = layers.Lambda(tf.tile, arguments={'multiples':[N,1]}, name='second_expanded')(second_dense) #keras.backend.tile(first_dense, [1, M])

first_reshaped = layers.Reshape((k,))(first_tiled)
concatenated = layers.Concatenate()([first_reshaped, second_tiled])
out = layers.Dense(1)(concatenated)
model = keras.Model([first, second], out)

keras.utils.plot_model(model, 'tf_nw.png', show_shapes=True)
model.compile('Adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit([x, y], z)

标签: pythontensorflowkerasdeep-learning

解决方案


推荐阅读