python - 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 是一个系列而不是多列。
关于我能做什么的任何建议?
解决方案
要么使用:
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.])>}
推荐阅读
- javascript - 如何将 mp3 文件从 Java 后端发送到前端并在 Vue.js 前端播放文件
- php - 在结帐重定向到错误的 URL 之前检查并重定向以登录
- python - 如何使用 Tkinter 使用下拉菜单打开文件夹中的文件
- ios - 安装新的 iOS 应用后接收相同的 FCM 令牌
- amazon-web-services - Gitlab runner 使用 IAM ROLE 在 Spot 实例中自动扩展
- javascript - 基于 XHR 的 ajax 无法上传文件
- sas - 将行转换为数据集中的变量
- asp.net-mvc - 如何在对 ASP.NET 核心服务器的 POST 请求正文中使用字符串化枚举?
- java - 为本地环境禁用 @SqsListener
- sql - Postgres & Rust R2D2:如何在没有转义双引号的情况下将 array_to_json 作为文本/字符串?