为什么我无法在 Python 中打印 Tensor 对象的内容?

Why can't I print the contents from a Tensor object in Python?

我正在尝试将 pandas 数据帧加载到 Tensorflow 数据集中。我是否缺少诸如 Tensor 对象的属性之类的东西?或者可能是导入问题?

我一直在尝试根据以下示例执行此操作: https://www.tensorflow.org/beta/tutorials/load_data/pandas

我没有得到预期的输出。

我之前尝试过这个更复杂的例子,它给了我类似的结果: https://www.tensorflow.org/beta/tutorials/keras/feature_columns

即使在终端中完全复制第一个提到的示例,它也不会像所示那样运行。

代码如下:

URL = 'https://storage.googleapis.com/applied-dl/heart.csv'
df = pd.read_csv(URL)

df['thal'] = pd.Categorical(df['thal'])
df['thal'] = df.thal.cat.codes

target = df.pop('target')

dataset = tf.data.Dataset.from_tensor_slices((df.values, target.values))

for feat, targ in dataset.take(5):
    print('Features: {}, Target: {}'.format(feat, targ))

预期输出:

Features: [ 63.   1.   1. 145. 233.   1.   2. 150.   0.   2.3  3.   0.   2. ], Target: 0
Features: [ 67.   1.   4. 160. 286.   0.   2. 108.   1.   1.5  2.   3.   3. ], Target: 1
Features: [ 67.   1.   4. 120. 229.   0.   2. 129.   1.   2.6  2.   2.   4. ], Target: 0
Features: [ 37.   1.   3. 130. 250.   0.   0. 187.   0.   3.5  3.   0.   3. ], Target: 0
Features: [ 41.   0.   2. 130. 204.   0.   2. 172.   0.   1.4  1.   0.   3. ], Target: 0

实际输出:

Features: Tensor("IteratorGetNext:0", shape=(13,), dtype=float64), Target: Tensor("IteratorGetNext:1", shape=(), dtype=int64)
Features: Tensor("IteratorGetNext_1:0", shape=(13,), dtype=float64), Target: Tensor("IteratorGetNext_1:1", shape=(), dtype=int64)
Features: Tensor("IteratorGetNext_2:0", shape=(13,), dtype=float64), Target: Tensor("IteratorGetNext_2:1", shape=(), dtype=int64)
Features: Tensor("IteratorGetNext_3:0", shape=(13,), dtype=float64), Target: Tensor("IteratorGetNext_3:1", shape=(), dtype=int64)
Features: Tensor("IteratorGetNext_4:0", shape=(13,), dtype=float64), Target: Tensor("IteratorGetNext_4:1", shape=(), dtype=int64)
Features: Tensor("IteratorGetNext_5:0", shape=(13,), dtype=float64), Target: Tensor("IteratorGetNext_5:1", shape=(), dtype=int64)
Features: Tensor("IteratorGetNext_6:0", shape=(13,), dtype=float64), Target: Tensor("IteratorGetNext_6:1", shape=(), dtype=int64)
Features: Tensor("IteratorGetNext_7:0", shape=(13,), dtype=float64), Target: Tensor("IteratorGetNext_7:1", shape=(), dtype=int64)
...

编辑: 我尝试在导入后添加:

tf.enable_eager_execution()

现在可以使用了!

这对我有用:

import tensorflow as tf
import pandas as pd
tf.enable_eager_execution()

URL = 'https://storage.googleapis.com/applied-dl/heart.csv'
df = pd.read_csv(URL)

df['thal'] = pd.Categorical(df['thal'])
df['thal'] = df.thal.cat.codes

target = df.pop('target')

dataset = tf.data.Dataset.from_tensor_slices((df.values, target.values))

for feat, targ in dataset.take(5):
    print('Features: {}, Target: {}'.format(feat, targ))

试试看然后告诉我。