- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在尝试使用 Keras 为文本序列构建字符级自动编码器。当我编译模型时,出现有关张量形状的错误,如下所示。我打印出层规范以检查张量形状是否匹配,我发现问题可能出在最后一个 Lambda 层没有正确指定输出张量形状,但我想不通为什么不或如何指定它,但在 Keras 的文档或 Google 上没有找到任何关于它的信息。
错误输出下面也是代码的一部分,我在这里定义了我的模型。如果需要,用于澄清的整个脚本在这里:PasteBin .
(注意最后一层。)
0 <keras.engine.topology.InputLayer object at 0x7f5d290eb588> Input shape (None, 80) Output shape (None, 80)
1 <keras.layers.core.Lambda object at 0x7f5d35f25a20> Input shape (None, 80) Output shape (None, 80, 99)
2 <keras.layers.core.Dense object at 0x7f5d2dda52e8> Input shape (None, 80, 99) Output shape (None, 80, 256)
3 <keras.layers.core.Dropout object at 0x7f5d25004da0> Input shape (None, 80, 256) Output shape (None, 80, 256)
4 <keras.layers.core.Dense object at 0x7f5d2501ac18> Input shape (None, 80, 256) Output shape (None, 80, 128)
5 <keras.layers.core.Dense object at 0x7f5d24dc6cc0> Input shape (None, 80, 128) Output shape (None, 80, 64)
6 <keras.layers.core.Dense object at 0x7f5d24de1fd0> Input shape (None, 80, 64) Output shape (None, 80, 128)
7 <keras.layers.core.Dropout object at 0x7f5d24df4a20> Input shape (None, 80, 128) Output shape (None, 80, 128)
8 <keras.layers.core.Dense object at 0x7f5d24dfeb38> Input shape (None, 80, 128) Output shape (None, 80, 256)
9 <keras.layers.core.Lambda object at 0x7f5d24da6a20> Input shape (None, 80, 256) Output shape (None, 80)
----------------
0 Input Tensor("input_1:0", shape=(?, 80), dtype=int64) Output Tensor("input_1:0", shape=(?, 80), dtype=int64)
1 Input Tensor("input_1:0", shape=(?, 80), dtype=int64) Output Tensor("ToFloat:0", shape=(?, 80, 99), dtype=float32)
2 Input Tensor("ToFloat:0", shape=(?, 80, 99), dtype=float32) Output Tensor("Relu:0", shape=(?, 80, 256), dtype=float32)
3 Input Tensor("Relu:0", shape=(?, 80, 256), dtype=float32) Output Tensor("cond/Merge:0", shape=(?, 80, 256), dtype=float32)
4 Input Tensor("cond/Merge:0", shape=(?, 80, 256), dtype=float32) Output Tensor("Relu_1:0", shape=(?, 80, 128), dtype=float32)
5 Input Tensor("Relu_1:0", shape=(?, 80, 128), dtype=float32) Output Tensor("Relu_2:0", shape=(?, 80, 64), dtype=float32)
6 Input Tensor("Relu_2:0", shape=(?, 80, 64), dtype=float32) Output Tensor("Relu_3:0", shape=(?, 80, 128), dtype=float32)
7 Input Tensor("Relu_3:0", shape=(?, 80, 128), dtype=float32) Output Tensor("cond_1/Merge:0", shape=(?, 80, 128), dtype=float32)
8 Input Tensor("cond_1/Merge:0", shape=(?, 80, 128), dtype=float32) Output Tensor("truediv:0", shape=(?, 80, 256), dtype=float32)
9 Input Tensor("truediv:0", shape=(?, 80, 256), dtype=float32) Output Tensor("ToFloat_1:0", shape=(), dtype=float32)
----------------
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/tensor_shape.py", line 578, in merge_with
self.assert_same_rank(other)
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/tensor_shape.py", line 624, in assert_same_rank
"Shapes %s and %s must have the same rank" % (self, other))
ValueError: Shapes (?, ?) and () must have the same rank
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/ops/nn_impl.py", line 153, in sigmoid_cross_entropy_with_logits
labels.get_shape().merge_with(logits.get_shape())
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/tensor_shape.py", line 585, in merge_with
(self, other))
ValueError: Shapes (?, ?) and () are not compatible
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "lstm.py", line 97, in <module>
autoencoder.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
File "/usr/local/lib/python3.4/dist-packages/keras/engine/training.py", line 667, in compile
sample_weight, mask)
File "/usr/local/lib/python3.4/dist-packages/keras/engine/training.py", line 318, in weighted
score_array = fn(y_true, y_pred)
File "/usr/local/lib/python3.4/dist-packages/keras/objectives.py", line 45, in binary_crossentropy
return K.mean(K.binary_crossentropy(y_pred, y_true), axis=-1)
File "/usr/local/lib/python3.4/dist-packages/keras/backend/tensorflow_backend.py", line 2449, in binary_crossentropy
logits=output)
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/ops/nn_impl.py", line 156, in sigmoid_cross_entropy_with_logits
% (logits.get_shape(), labels.get_shape()))
ValueError: logits and labels must have the same shape (() vs (?, ?))
我使用这段代码构建了我的模型:
def binarize(x, sz):
return tf.to_float(tf.one_hot(x, sz, on_value=1, off_value=0, axis=-1))
def binarize_outputshape(in_shape):
return in_shape[0], in_shape[1], len(chars)
def debinarize(x):
return tf.to_float(np.argmax(x)) # get the character with most probability
def debinarize_outputshape(in_shape):
return in_shape[0], in_shape[1]
input_sentence = Input(shape=(max_title_len,), dtype='int64')
# make one-hot vectors out of sentences
one_hot = Lambda(binarize, output_shape=binarize_outputshape, arguments={'sz': len(chars)})(input_sentence)
# shape: max_title_len * chars = 80 * 55 = 4400
encoder = Dense(256, activation='relu')(one_hot)
encoder = Dropout(0.1)(encoder)
encoder = Dense(128, activation='relu')(encoder)
encoder = Dense(64, activation='relu')(encoder)
decoder = Dense(128, activation='relu')(encoder)
encoder = Dropout(0.1)(encoder)
decoder = Dense(256, activation='softmax')(decoder)
# transform back from one-hot vectors
decoder = Lambda(debinarize, output_shape=debinarize_outputshape)(decoder)
autoencoder = Model(input=input_sentence, output=decoder)
首先,我输入一个最多 80 个字符的文本序列,Lambda 层将每个字符转换为一个单热向量。最后,我想将单热向量转换回来,同时只取最大值作为解码字符。
作为Nassim Ben指出,问题出在函数 debinarize 上。将其更改为:
def debinarize(x):
return tf.to_float(tf.argmax(x, axis=0))
至少某种值被设置为输出张量的形状。虽然这个值有点奇怪,因为它是 (80, 256) 并且与输出形状 (None, 80) 不同。所有其他输出张量形状和输出形状相应地匹配(我想'?'和None或多或少意味着相同......)。更具体地说,Lambda 层现在看起来像这样:
<keras.layers.core.Lambda object at 0x7fafcc5a59b0> Input shape (None, 80, 256) Output shape (None, 80)
...
...
Input Tensor("truediv:0", shape=(?, 80, 256), dtype=float32) Output Tensor("ToFloat_1:0", shape=(80, 256), dtype=float32)
问题是,我希望输出张量形状为 (?, 80) 作为第一层的输入。除了 argmax 之外,我没有更改任何其他代码。
现在给出的错误是:
Traceback (most recent call last):
File "lstm.py", line 122, in <module>
callbacks=[earlystop_cb, check_cb, keras.callbacks.TensorBoard(log_dir='/tmp/autoencoder')])
File "/usr/local/lib/python3.4/dist-packages/keras/engine/training.py", line 1168, in fit
self._make_train_function()
File "/usr/local/lib/python3.4/dist-packages/keras/engine/training.py", line 760, in _make_train_function
self.total_loss)
File "/usr/local/lib/python3.4/dist-packages/keras/optimizers.py", line 433, in get_updates
m_t = (self.beta_1 * m) + (1. - self.beta_1) * g
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/ops/math_ops.py", line 883, in binary_op_wrapper
y = ops.convert_to_tensor(y, dtype=x.dtype.base_dtype, name="y")
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 651, in convert_to_tensor
as_ref=False)
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/ops.py", line 716, in internal_convert_to_tensor
ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/constant_op.py", line 176, in _constant_tensor_conversion_function
return constant(v, dtype=dtype, name=name)
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/constant_op.py", line 165, in constant
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
File "/usr/local/lib/python3.4/dist-packages/tensorflow/python/framework/tensor_util.py", line 360, in make_tensor_proto
raise ValueError("None values not supported.")
ValueError: None values not supported.
最佳答案
我认为它来自在张量上使用 numpy 函数。尝试使用 tf argmax 函数(我认为你要减少的轴是 1,不确定)
def debinarize(x):
return tf.to_float(tf.argmax(x,axis=2)) # get the character with most probability
这个有用吗?
关于python - Keras Lambda层没有输出张量形状,编译模型时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42630504/
我有兴趣在 tf.keras 中训练一个模型,然后用 keras 加载它。我知道这不是高度建议,但我对使用 tf.keras 来训练模型很感兴趣,因为 tf.keras 更容易构建输入管道 我想利用
我进行了大量搜索,但仍然无法弄清楚如何编写具有多个交互输出的自定义损失函数。 我有一个神经网络定义为: def NeuralNetwork(): inLayer = Input((2,));
我正在阅读一篇名为 Differential Learning Rates 的文章在 Medium 上,想知道这是否可以应用于 Keras。我能够找到在 pytorch 中实现的这项技术。这可以在 K
我正在实现一个神经网络分类器,以打印我正在使用的这个神经网络的损失和准确性: score = model.evaluate(x_test, y_test, verbose=False) model.m
我最近在查看模型摘要时遇到了这个问题。 我想知道,[(None, 16)] 和有什么区别?和 (None, 16) ?为什么输入层有这样的输入形状? 来源:model.summary() can't
我正在尝试使用 Keras 创建自定义损失函数。我想根据输入计算损失函数并预测神经网络的输出。 我尝试在 Keras 中使用 customloss 函数。我认为 y_true 是我们为训练提供的输出,
我有一组样本,每个样本都是一组属性的序列(例如,一个样本可以包含 10 个序列,每个序列具有 5 个属性)。属性的数量总是固定的,但序列的数量(时间戳)可能因样本而异。我想使用这个样本集在 Keras
Keras 在训练集和测试集文件夹中发现了错误数量的类。我有 3 节课,但它一直说有 4 节课。有人可以帮我吗? 这里的代码: cnn = Sequential() cnn.add(Conv2D(32
我想编写一个自定义层,在其中我可以在两次运行之间将变量保存在内存中。例如, class MyLayer(Layer): def __init__(self, out_dim = 51, **kwarg
我添加了一个回调来降低学习速度: keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=100,
在 https://keras.io/layers/recurrent/我看到 LSTM 层有一个 kernel和一个 recurrent_kernel .它们的含义是什么?根据我的理解,我们需要 L
问题与标题相同。 我不想打开 Python,而是使用 MacOS 或 Ubuntu。 最佳答案 Python 库作者将版本号放入 .__version__ 。您可以通过在命令行上运行以下命令来打印它:
Keras 文档并不清楚这实际上是什么。我知道我们可以用它来将输入特征空间压缩成更小的空间。但从神经设计的角度来看,这是如何完成的呢?它是一个自动编码器,RBM吗? 最佳答案 据我所知,嵌入层是一个简
我想实现[http://ydwen.github.io/papers/WenECCV16.pdf]中解释的中心损失]在喀拉斯 我开始创建一个具有 2 个输出的网络,例如: inputs = Input
我正在尝试实现多对一模型,其中输入是大小为 的词向量d .我需要输出一个大小为 的向量d 在 LSTM 结束时。 在此 question ,提到使用(对于多对一模型) model = Sequenti
我有不平衡的训练数据集,这就是我构建自定义加权分类交叉熵损失函数的原因。但问题是我的验证集是平衡的,我想使用常规的分类交叉熵损失。那么我可以在 Keras 中为验证集传递不同的损失函数吗?我的意思是用
DL 中的一项常见任务是将输入样本归一化为零均值和单位方差。可以使用如下代码“手动”执行规范化: mean = np.mean(X, axis = 0) std = np.std(X, axis =
我正在尝试学习 Keras 并使用 LSTM 解决分类问题。我希望能够绘制 准确率和损失,并在训练期间更新图。为此,我正在使用 callback function . 由于某种原因,我在回调中收到的准
在 Keras 内置函数中嵌入使用哪种算法?Word2vec?手套?其他? https://keras.io/layers/embeddings/ 最佳答案 简短的回答是都不是。本质上,GloVe 的
我有一个使用 Keras 完全实现的 LSTM RNN,我想使用梯度剪裁,梯度范数限制为 5(我正在尝试复制一篇研究论文)。在实现神经网络方面,我是一个初学者,我将如何实现? 是否只是(我正在使用 r
我是一名优秀的程序员,十分优秀!