使用Keras进行布尔标签训练时出现错误“请提供共享相同第一维度的数据”

所以,这是我正在尝试做的事情。我的模型需要接收一系列训练样本,每个样本都是布尔字面量的合取(即由0或1组成的向量),并分配一个真值。通过学习这些样本,模型必须能够接收一些测试向量并确定其真值。

更具体地说,像V = [1,0,0,…,0,1]这样的由0和1组成的向量可能是可接受的或不可接受的(标记为1或0)。我的训练样本数组包含15202个这样的向量。它是一个大小为(15202, 20)的数组,而训练标签数组的大小为(15202, 1)。然后有一个训练标签数组,包含每个样本的标签。也就是说,以下代码片段

print(np.shape(train_samples))print(type(train_samples))print(np.shape(train_labels))print(type(train_labels))

给出的结果是:

(15202, 20)<class 'numpy.ndarray'>(15202, 1)<class 'numpy.ndarray'>

其余代码如下:

import numpy as npfrom random import randintfrom sklearn.utils import shufflefrom sklearn.preprocessing import MinMaxScalerimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras.models import Sequentialfrom tensorflow.keras.layers import Activation, Densefrom tensorflow.keras.optimizers import Adamfrom tensorflow.keras.metrics import categorical_crossentropy#Main Code# 随机生成的样本和标签,仅供说明train_samples = np.random.randint(2, size=(15202,20))train_labels = np.random.randint(2, size=(15202,1))#--------train_labels, train_samples = shuffle(train_labels, train_samples)scaler = MinMaxScaler(feature_range=(0,1))scaled_train_samples = scaler.fit_transform(train_samples.reshape(-1,1))model = Sequential([    Dense(units=16, input_shape=(1,), activation='relu'),    Dense(units=32, activation='relu'),    Dense(units=2, activation='softmax')])model.compile(optimizer=Adam(learning_rate=0.0001), loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(x=scaled_train_samples, y=train_labels, batch_size=10, epochs=30, verbose=2)

最后一行导致了错误:

ValueError: Data cardinality is ambiguous:  x sizes: 304040  y sizes: 15202Please provide data which shares the same first dimension.

我注意到报告的x大小(304040)实际上是15202乘以20。那么我在这里做错了什么,我该如何修复它?谢谢。


回答:

你必须这样做:

scaled_train_samples = scaler.fit_transform(train_samples)

不使用 reshape(-1,1)

现在,维度是(15202, 20),标签维度是(15202, 1)

另外,你必须将 input_shape=(train_samples.shape[1],) 改为 input_shape=(1,)

input_shape 必须有维度 (batch_size, input_dim)

在你的情况下,我们使用 (input_dim, ),因此维数是2(2列)。

查看这里

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中创建了一个多类分类项目。该项目可以对…

发表回复

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