如何拼接”锯齿状”张量

我在尝试用TensorFlow实现这篇论文时遇到了一些问题。在我的池化层中,我需要将所有内容拼接在一起。这是我使用的代码:

    pooled_outputs = []    for i, filter_size in enumerate(filter_sizes):        with tf.name_scope("conv-maxpool-%s" % filter_size):            # 卷积层            filter_shape = [filter_size, embedding_size, 1, num_filters]            # W 是滤波器矩阵            W = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="W")            b = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="b")            conv = tf.nn.conv2d(                self.embedded_chars_expanded,                W,                strides=[1, 1, 1, 1],                padding="VALID",                name="conv"            )            # 应用非线性            h = tf.nn.relu(tf.nn.bias_add(conv, b), name="relu")            # 在输出上进行最大池化层            pooled = tf.nn.max_pool(                h,                ksize=[1, sequence_lengths[i] - filter_size + 1, 1, 1],                strides=[1, 1, 1, 1],                padding="VALID",                name="pool"            )            pooled_outputs.append(pooled)    # 组合所有池化特征    num_filters_total = num_filters * len(filter_sizes)    print(pooled_outputs)    pooled_outputs = [tf.reshape(out, ["?", 94, 1, self.max_length]) for out in pooled_outputs] # 问题行    self.h_pool = tf.concat(3, pooled_outputs)

当我运行这段代码时,它为 pooled_outputs 打印出以下内容:

[<tf.Tensor 'conv-maxpool-3/pool:0' shape=(?, 94, 1, 128) dtype=float32>, <tf.Tensor 'conv-maxpool-4/pool:0' shape=(?, 51, 1, 128) dtype=float32>, <tf.Tensor 'conv-maxpool-5/pool:0' shape=(?, 237, 1, 128) dtype=float32>]

我最初尝试没有 pooled_outputs = [tf.reshape(out, ["?", 94, 1, self.max_length]) for out in pooled_outputs] 这行代码,结果得到了以下错误:

ValueError: Dimension 1 in both shapes must be equal, but are 51 and 237

当我添加了reshape这行后,我得到了以下错误:

TypeError: Expected binary or unicode string, got 94

我知道第二个错误是因为我为新大小传递了”?”,而第一个错误我想是因为张量的大小不一致。我应该如何正确地填充这些张量,以便无障碍地拼接它们?


回答:

你可以将 -1 作为形状的一个组件传递给 tf.reshape 方法;它会根据你的张量的形状自动推断,这样总大小将保持不变。

所以,尝试将问题行更改为

pooled_outputs = [tf.reshape(out, [-1, 94, 1, self.max_length]) for out in pooled_outputs]

有关详细信息,请参阅文档

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注