ValueError: 无法将NumPy数组转换为Tensor(不支持的对象类型numpy.ndarray)在Tensorflow

我正在使用其他4个列创建一个新的Pandas数据框架列,并逐行应用自定义定义的函数。

下面是函数所应用的列的结构。

enter image description here

新创建的列看起来像这样。

enter image description here

我编写的函数如下:

def convert_credit_rows(row):  return np.asarray([row['A'], row['B'], row['C'], row['D']], dtype=np.float32)X_train['credit_balance'] = X_train.apply(convert_credit_rows, axis=1)X_test['credit_balance'] = X_test.apply(convert_credit_rows, axis=1)

我将这个数据集提供给一个简单的神经网络,如下所示:

def CreditBalanceDetector():  X_train_credit_balance = X_train['credit_balance']  X_test_credit_balance = X_test['credit_balance']  model = Sequential()  model.add(Dense(20, activation='relu'))  model.add(Dense(10, activation='relu'))  model.add(Dense(6, activation='softmax'))  model.compile(loss='categorical_crossentropy', optimizer=Adam(learning_rate=0.0005),   metrics=['accuracy'])  early_stop = EarlyStopping(monitor='val_loss',patience=3)  model.fit(X_train_credit_balance, y_train, epochs=50, validation_data=  (X_test_credit_balance, y_test), callbacks=[early_stop])

但在尝试训练模型时,我得到了以下错误。

enter image description here

虽然在StackOverflow上有一些类似的提问,但那里建议的解决方案对我不起作用。

如果有人能找出我哪里做错了,我将不胜感激。谢谢你。


回答:

我已经弄清楚了我的代码中出了什么问题。这里发布是为了将来可能受益的人。

在上面的代码中,我为X_train_credit_balanceX_test_credit_balance提供了Pandas Series对象作为数据类型,而model.fit()函数期望的是一个数组。如果我们按以下方式检查X_train_credit_balance的一个元素,

print(X_train_credit_balance[0])

它将给出以下输出,这不是所需的:

array([30., 30.], dtype=float32)

正确的代码

可以通过如下修改convert_credit_rows(row)函数来纠正上述行为:

credit_list = []def convert_credit_rows(row):  credit_list.append(np.asarray([row['A'], row['B'], row['C'], row['D']], dtype=np.float32)) X_train_credit_balance = np.array(credit_list)

convert_credit_rows函数将应用于每一行,创建一个(m,n)维数组列表——在本例中为credit_list。接下来,我们可以使用np.array(credit_list)credit_list转换为ndarray。如果我们在操作结束时打印出credit_list,我们可以看到如下正确格式的数组:

[[1. 2. 3.] [1. 2. 3.] [1. 2. 3.] [1. 2. 3.] [1. 2. 3.] [1. 2. 3.]]

现在,如果我们打印出X_train_credit_balance的类型,它将是<class 'numpy.ndarray'>,而不是Pandas Series对象。

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

发表回复

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