将TensorFlow数据集转换为Pandas数据框。

5

我对深度学习和计算机视觉非常陌生。我想做一些人脸识别项目。为此,我从互联网上下载了一些图像,并在tensorflow文档的帮助下将其转换为Tensorflow数据集。现在我想将该数据集转换为pandas数据框以便将其转换为csv文件。我尝试了很多次,但无法完成。 请有人帮助我。 以下是创建数据集的代码,以及我尝试的一些错误代码。

import tensorflow as tf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


filenames = tf.constant(['al.jpg', 'al2.jpg', 'al3.jpg', 'al4.jpeg','al5.jpeg', 'al6.jpeg','al7.jpg','al8.jpeg', '5.jpg', 'hrit8.jpeg', 'Hrithik-Roshan.jpg', 'Hrithik.jpg', 'hriti1.jpeg', 'hriti2.jpg', 'hriti3.jpeg', 'hritik4.jpeg', 'hritik5.jpg', 'hritk9.jpeg', 'index.jpeg', 'sah.jpeg', 'sah1.jpeg', 'sah3.jpeg', 'sah4.jpg', 'sah5.jpg','sah6.jpg','sah7.jpg'])
labels = tf.constant([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2, 2, 2, 2])
dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))


def _parse_function(filename, label):
     image_string = tf.read_file(filename)
     image_decoded = tf.image.decode_jpeg(image_string,channels=3)
     image_resized = tf.image.resize_images(image_decoded, [28, 28])
     return image_resized, label
dataset = dataset.map(_parse_function)
dataset = dataset.shuffle(buffer_size=100)
dataset = dataset.batch(26)
iterator = dataset.make_one_shot_iterator()
image,labels = iterator.get_next()

sess = tf.Session()

print(sess.run([image, labels]))

最初我尝试使用df = pd.DataFrame(dataset)

然后我遇到了以下错误:

enter code here
ValueError                                Traceback (most recent call last)
<ipython-input-15-d5503ae4603d> in <module>()
----> 1 df = pd.DataFrame((dataset))

 ~/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
402                                          dtype=values.dtype, copy=False)
403             else:
--> 404                 raise ValueError('DataFrame constructor not properly called!')
405 
406         NDFrame.__init__(self, mgr, fastpath=True)

ValueError: DataFrame constructor not properly called!

后来我看到了这篇文章,我明白了在tensorflow中任何东西都只存在于session之内。所以我尝试了以下代码:

with tf.Session() as sess:
df = pd.DataFrame(sess.run(dataset))

如果我写的代码有最愚蠢的错误,请原谅,因为我是从这段类似代码中编写的:print(sess.run(dataset)),但是出现了一个更严重的错误:

 TypeError: Fetch argument <BatchDataset shapes: ((?, 28, 28, 3), (?,)), types: (tf.float32, tf.int32)> has invalid type <class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'>, must be a string or Tensor. (Can not convert a BatchDataset into a Tensor or Operation.)

1
你可以分享一下你自己尝试过的代码吗? - sdcbr
我编辑了我的问题。 - Mukul
3个回答

2

我认为你可以像这样使用map。我假设你想像这里描述的那样将一个numpy数组添加到数据框中。但是,你必须逐个附加并确定整个数组如何适配数据框的一列。

import tensorflow as tf
import pandas as pd


filenames = tf.constant(['C:/Machine Learning/sunflower/50987813_7484bfbcdf.jpg'])
labels = tf.constant([1])
dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))

sess = tf.Session()

def convert_to_dataframe(filename, label):
    print ( pd.DataFrame.from_records(filename))
    return filename, label


def _parse_function(filename, label):
     image_string = tf.read_file(filename)
     image_decoded = tf.image.decode_jpeg(image_string,channels=3)
     image_resized = tf.image.resize_images(image_decoded, [28, 28])
     return image_resized, label

dataset = dataset.map(_parse_function)
dataset = dataset.map( lambda filename, label: tf.py_func(convert_to_dataframe,
                                                          [filename, label],
                                                          [tf.float32,tf.int32]))

dataset = dataset.shuffle(buffer_size=100)
dataset = dataset.batch(26)
iterator = dataset.make_one_shot_iterator()
image,labels = iterator.get_next()


sess.run([image, labels])

0

一种简单的方法是将数据集保存为普通的csv文件,然后直接将csv文件读入pandas dataframe。

import tensorflow_datasets as tfds

# Construct a tf.data.Dataset
ds = tfds.load('civil_comments/CivilCommentsCovert', split='train')
#read the dataset into a tensorflow styled_dataframe
df = tfds.as_dataframe(ds)
#save the dataframe into csv file
df.to_csv("/.../.../Desktop/covert_toxicity.csv")

#read the csv file as normal, then you have the df you need
import pandas as pd
file_path = "/.../.../Desktop/covert_toxicity.csv"
df = pd.read_csv(file_path, header = 0, sep=",")
df

使用这种方法时,您仍然需要解析解决方案,因为输出列将是字节而不是字符串类型(即使源类型是字符串)。 - letsBeePolite

0
将TensorFlow对象转换为数据帧的更简单方法是将TensorFlow对象转换为NumPy数组,然后传递给pandas DataFrame类。
import pandas as pd

dataset = pd.DataFrame(labels.numpy(), columns=filenames)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接