【问题标题】:ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray) in TensorflowValueError:无法在 Tensorflow 中将 NumPy 数组转换为张量(不支持的对象类型 numpy.ndarray)
【发布时间】:2020-10-15 15:36:21
【问题描述】:

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

下面是列的结构,作用在上面。

创建的新列如下所示。

我写的函数如下:

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])

但是在尝试训练模型时出现以下错误。

虽然 StackOverflow 中有几个类似的问题,但建议的解决方案对我不起作用。

如果有人能弄清楚我哪里出错了,那将不胜感激。谢谢。

【问题讨论】:

标签: python pandas numpy tensorflow machine-learning


【解决方案1】:

我可以弄清楚我的代码出了什么问题。在这里为将来可能受益的人发帖。

在上面的代码中,我提供了一个 Pandas Series 对象作为 X_train_credit_balanceX_test_credit_balance 的数据类型,其中 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 对象。

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 2020-11-22
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 2020-12-08
    • 2021-07-25
    • 2020-02-26
    • 2021-04-25
    相关资源
    最近更新 更多