我试图从使用https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map处理的张量对象中访问numpy数组。
我得到了错误: AttributeError:‘张量’对象没有属性'numpy‘
当我尝试访问张量时,如: np_array = tensor.numpy()
如果使用: dataset.take(n),则可以访问numpy数组。
为了更清楚地了解我所面临的情况,下面是google中错误的一个可复制的简短示例:
https://colab.research.google.com/drive/13ectGEMDSygcyuW4ip9zrWaHO3pSxc3p?usp=sharing
Tensorflow版本: 2.4.1
更新:在上面的colab之外添加代码:
import os
import numpy as np
import tensorflow as tf
# This works
def get_spectrogram_and_label_id(file_path):
spectrogram, label = get_spectrogram(audio) # not showing the function here since it is irrelevant
return spectrogram, label
# This doesn't!
def get_spec_and_label_time(spectrogram, label):
time_step_spectrogram = generate_time_step_samples(spectrogram)
return time_step_spectrogram, label
# I want to manipulate the Tensor by extracting the numpy array as part of the map function
def generate_time_step_samples(tensor):
np_array = tensor.numpy() # ERROR: AttributeError: 'Tensor' object has no attribute 'numpy'
# Do something with the numpy array
return np_array
filenames = ['file1.wav', 'file2.wav', ...]
files_ds = tf.data.Dataset.from_tensor_slices(filenames)
spectrogram_ds = files_ds.map(get_spectrogram_and_label_id) # this works
spectrogram_time_ds = spectrogram_ds.map(get_spec_and_label_time) # this doesn't更多的细节在谷歌colab。
发布于 2021-04-28 19:02:39
不能在.numpy()函数中访问.map()。
这不是一个bug,它是TensorFlow如何在幕后处理静态图形的。
在这里阅读我的答案,以获得更全面的解释。
AttributeError: 'Tensor' object has no attribute 'numpy' in Tensorflow 2.1
https://stackoverflow.com/questions/67304198
复制相似问题