首页 > 解决方案 > ValueError: Value tf.Tensor.. shape=(), dtype=float64) has enough rank for batching.?

问题描述

我正在尝试获取数据框并将它们转换为张量以在 keras 中训练模型。

我认为当我将 Y 标签转换为张量时会触发它:

  X_train = df_train1.drop(variableToPredict, axis=1)
  y_train = df_train1[variableToPredict].copy()


X_train=tf.data.Dataset.from_tensor_slices(dict(X_train))
  y_train=tf.data.Dataset.from_tensor_slices(dict(y_train))

将 y_train 从切片转换为张量时出现以下错误:

ValueError: Value tf.Tensor(0.10559591064345274, shape=(), dtype=float64) has insufficient rank for batching.

在教程中这似乎可行,但我认为那些教程正在做多类分类,而我正在做回归,所以 y_train 是一个系列而不是多列。

关于我能做什么的任何建议?

标签: pythontensorflowkeras

解决方案


要么使用:

y = tf.data.Dataset.from_tensors(dict(y_train))

或这个:

y = tf.data.Dataset.from_tensor_slices(y_train)

或者只是使用双括号,这样您的数据框仍然是一个数据框,那么您不需要更改任何内容:

y_train = df[['height']].copy()

y = tf.data.Dataset.from_tensor_slices(dict(y_train))

重现该问题的完整代码,并提供替代方案:

import tensorflow as tf
import pandas as pd

df = pd.DataFrame(data={'integers': [1, 2, 3, 4], 'floats': [4., 3., 2., 1]})

y_train = df['floats'].copy()

y = tf.data.Dataset.from_tensor_slices(dict(y_train)) # not good

y = tf.data.Dataset.from_tensor_slices(y_train) # good
print(next(iter(y)))

y = tf.data.Dataset.from_tensors(y_train) # good
print(next(iter(y)))

y_train = df[['floats']].copy()
y = tf.data.Dataset.from_tensor_slices(dict(y_train)) # good
next(iter(y))
{'floats': <tf.Tensor: shape=(4,), dtype=float64, numpy=array([5., 4., 3., 2.])>}

推荐阅读