python - 在 Keras 或 Tensorflow 中,如何在模型中输入不同的样本大小和成对连接嵌入?
问题描述
在 [this question] 的后续行动中,关于我们希望完成的工作的一些说明:
- 我们有两个不同样本大小的输入
X
和,以及一个大小为 的布尔向量。的每个元素表示和中的两项是否匹配Y
n
m
z
nm
z
X
Y
- 我们希望在成对连接这些嵌入层的输出以将输入导出到输出层之前
X
和之前使用嵌入层(可能相同,也可能不同)。Y
下面是一个简单网络的示例:
链接的答案和其他一些资源帮助达到了这个例子,它建立了一个模型,但在合适的时候抛出了这个错误: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)
解决方案
推荐阅读
- java - 已声明的变量无法解析
- python - 将 JSON 分页响应与 python 请求连接起来
- python - 使用小部件更新 Gmaps + Jupyter 中的标记
- php - Sinch Voice Callback REST API - 使用 PHP 作为电话会议的回调 URL
- c++ - 确保删除链表的所有元素
- javascript - 如何匹配 dropzone 表单上的文件名?
- php - woocommerce-如何仅在商店页面上显示子类别?
- javascript - 如何防止用户两次问同一个问题?
- linux - Linux Perf_Events 中的 LLC-Miss 报告
- javascript - javascript代码没有检测到值的变化