AttributeError: 'NoneType' object has no attribute 'SerializeToString'

AttributeError: 'NoneType' object has no attribute 'SerializeToString'

我想将数据帧转换为 TFRecordf 格式的张量流数据集。这是我写的:

import pandas as pd
import tensorflow as tf
from pandas_tfrecords import pd2tf, tf2pd
import pandas_tfrecords

df = pd.read_csv('data.csv')
print(df)
output_file = 'data.tfrecord'
writer = tf.compat.v1.python_io.TFRecordWriter(output_file)
rec = df.to_records(index=False)
print(repr(rec))

s = rec.tobytes()
def _bytes_feature(value):
    if isinstance(value, type(tf.constant(0))):
        value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
        return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
print(_bytes_feature(s))
a=_bytes_feature(s)
a=a.SerializeToString()
writer.write(a)

writer.close()

这些行主要由字符串组成。但中间也有一些空行。因此,并非所有行都是字符串类型。

这是我得到的输出:

[65422771 rows x 1 columns]
rec.array([('method apparatus facilitating attention task disclosed',),
           ('method include detecting sensor movement estimating task attention state based movement determining workload based estimated attention state determining based workload optimal format relay operational information best facilitates attention task increased ease task performance',),
           ('\n',), ..., ('\n',),
           ('system method apparatus provided implementation motorized tricycle includes lean mechanism active system operably coupled lean mechanism receives signal indicative interaction human operable detect lean body human operable receive sensed movement seat multisensory device generate send signal lean mechanism signal lean sensed movement',),
           ('\n',)],
          dtype=[('text', 'O')])

None
Traceback (most recent call last):
  File "/dfgd.py", line 20, in <module>
    a=a.SerializeToString()
AttributeError: 'NoneType' object has no attribute 'SerializeToString'

如何解决这个问题并将我的数据帧写入 tenesorflow 数据集?

您有一个缩进错误。使用以下内容。

def _bytes_feature(value):
    if isinstance(value, type(tf.constant(0))):
        value = value.numpy() # BytesList won't unpack a string from an EagerTensor.
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

在您的原始代码中,return 语句位于 if 语句中。因此,如果代码从未进入 if,函数将 return None.