- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想从输入文本中预测 8 个类。这是我用于预处理数据的代码:
num_max = 1000
tok = Tokenizer(num_words=num_max)
tok.fit_on_texts(x_train)
mat_texts = tok.texts_to_matrix(x_train,mode='count')
num_max = 1000
tok = Tokenizer(num_words=num_max)
tok.fit_on_texts(x_train)
max_len = 100
cnn_texts_seq = tok.texts_to_sequences(x_train)
print(cnn_texts_seq[0])
[12, 4, 303]
# padding the sequences
cnn_texts_mat = sequence.pad_sequences(cnn_texts_seq,maxlen=max_len)
print(cnn_texts_mat[0])
print(cnn_texts_mat.shape)
[ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 12 4 303]
(301390, 100)
下面是我的模型的结构,其中包含嵌入层:
max_features = 20000
max_features = cnn_texts_mat.shape[1]
maxlen = 100
embedding_size = 128
model = Sequential()
model.add(Embedding(max_features, embedding_size, input_length=maxlen))
model.add(Dropout(0.2))
model.add(Dense(5000, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(600, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(units=y_train.shape[1], activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy',
optimizer=sgd)
以下是模型摘要:
model.summary()
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding_5 (Embedding) (None, 100, 128) 12800
_________________________________________________________________
dropout_13 (Dropout) (None, 100, 128) 0
_________________________________________________________________
dense_13 (Dense) (None, 100, 5000) 645000
_________________________________________________________________
dropout_14 (Dropout) (None, 100, 5000) 0
_________________________________________________________________
dense_14 (Dense) (None, 100, 600) 3000600
_________________________________________________________________
dropout_15 (Dropout) (None, 100, 600) 0
_________________________________________________________________
dense_15 (Dense) (None, 100, 8) 4808
=================================================================
Total params: 3,663,208
Trainable params: 3,663,208
Non-trainable params: 0
此后,当我尝试运行模型时出现以下错误:
model.fit(x=cnn_texts_mat, y=y_train, epochs=2, batch_size=100)
ValueError Traceback (most recent call last)
<ipython-input-41-4b9da9914e7e> in <module>
----> 1 model.fit(x=cnn_texts_mat, y=y_train, epochs=2, batch_size=100)
~/.local/lib/python3.5/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, **kwargs)
950 sample_weight=sample_weight,
951 class_weight=class_weight,
--> 952 batch_size=batch_size)
953 # Prepare validation data.
954 do_validation = False
~/.local/lib/python3.5/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)
787 feed_output_shapes,
788 check_batch_axis=False, # Don't enforce the batch size.
--> 789 exception_prefix='target')
790
791 # Generate sample-wise weight values given the `sample_weight` and
~/.local/lib/python3.5/site-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
126 ': expected ' + names[i] + ' to have ' +
127 str(len(shape)) + ' dimensions, but got array '
--> 128 'with shape ' + str(data_shape))
129 if not check_batch_axis:
130 data_shape = data_shape[1:]
ValueError: Error when checking target: expected dense_15 to have 3 dimensions, but got array with shape (301390, 8)
最佳答案
查看模型摘要中最后一层的输出形状:它是(None, 100, 8)
。这不是您要找的。每个样本的标签形状为 (8,)
而不是 (100,8)
。为什么会发生这样的事?那是因为the Dense layer is applied on the last axis of its input因此,由于 Embedding 层的输出是 3D,因此所有后续 Dense 层的输出也将具有 3 维。
如何解决这个问题?一种方法是在模型中的某个位置使用Flatten
层(可能就在嵌入层之后)。这样,您将获得形状 (None, 8)
的 2D 输出,这就是您想要的并且与标签的形状一致。
但是,请注意,您最终可能会得到一个非常大的模型(即参数太多),这很容易出现过度拟合。要么减少密集层中的单元数量,要么使用 Conv1D 和 MaxPooling1D 层甚至 RNN 层来处理嵌入并减少结果张量的维度(这也是使用它们可能也会提高模型的准确性)。
关于python - Keras ValueError : Error when checking target: expected dense_15 to have 3 dimensions, 但得到了形状为 (301390, 8) 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53443475/
我正在尝试并行运行具有循环返回值的函数。但它似乎停留在 results = pool.map(algorithm_file.foo, population) 在 for 循环的第二次迭代中 r
Serving Flask 应用程序“服务器”(延迟加载) 环境:生产警告:这是一个开发服务器。不要在生产部署中使用它。请改用生产 WSGI 服务器。 Debug模式:开启 在 http://0.0.
我使用“product.pricelist”模型中的 get_product_price_rule() 函数。我的代码是: price = self._get_display_price(produ
我收到以下错误: Traceback (most recent call last): File "/home/odroid/trackAndFollow/getPositions.py", line
我正在尝试采用机器学习方法,但遇到了一些问题。这是我的代码: import sys import scipy import numpy import matplotlib import pandas
我尝试使用 tensorflow 1.4.0 对我的原始记录进行分类。过程如下。 拳头:读取图片和标签,输出“tfrecord”格式的文件。第二:读取tf记录和训练 编写tfrecord脚本是 !/u
我是新手,所以需要任何帮助,当我要求一个例子时,我的教授给我了这段代码,我希望有一个工作模型...... from numpy import loadtxt import numpy as np fr
我无法弄清楚为什么会出现此 ValueError...为了提供一些上下文,我正在使用 requests、BeautifulSoup 和 json 与 python 来抓取站点 json 数据。 我不确
我已经尝试使用这两个循环以及列表理解。即使我正在尝试将数字转换为列表中的整型,两者都无法解析整数。
我已经尝试使用这两个循环以及列表理解。即使我正在尝试将数字转换为列表中的整型,两者都无法解析整数。
我只有四个星期的 Python 经验。使用 Tkinter 创建一个工具,将新的公司 Logo 粘贴到现有图像之上。 下面的方法是获取给定目录中的所有图像并将新 Logo 粘贴到初始级别。现有图像、编
我只有四个星期的 Python 经验。使用 Tkinter 创建一个工具,将新的公司 Logo 粘贴到现有图像之上。 下面的方法是获取给定目录中的所有图像并将新 Logo 粘贴到初始级别。现有图像、编
我在尝试在 Keras 2.0.8、Python 3.6.1 和 Tensorflow 后端中训练模型时遇到问题。 错误消息: ValueError: Error when checking targ
我已经尝试使用这两个循环以及列表理解。即使我正在尝试将数字转换为列表中的整型,两者都无法解析整数。
我有这段代码: while True: try: start = int(input("Starting number: ")) fin = int(i
我是 python 的初学者编码员,试图制作一个“模具滚筒”,您可以在其中选择模具的大小,它在我的代码的第 20 行返回此错误 import sys import random import geto
我有以下代码: import fxcmpy import pandas as pd from pandas import datetime from pandas import DataFrame a
我正在尝试使用 django 和 python 制作一个博客应用程序。我也在尝试使用 s3 存储桶进行存储,使用 heroku 进行部署。我正在学习 coreymschafer 的在线教程。我正在按照
我创建了一个 numpy 数组(考虑输入数据)并想更改顺序(一些数值运算后的输出数据)。在使用转换后的数组时,我遇到错误并找到了根本原因。请在下面找到详细信息并使用 numpy 版本 1.19.1 i
我已经引用了之前的查询 All arguments should have the same length plotly但仍然没有得到我的问题的答案。 我有一个黄金价格数据集。 Date
我是一名优秀的程序员,十分优秀!