tf.data.TextLineDataset 解析csv

TextLineDataset的读取机制:读取文本中数据,一行代表一组数据,一般再按照filter、map、shuffle、batch、repeat、prefetch的顺序获得可用数据。
在csv中,因存在头部行,使用filter对数据进行筛选,去掉不符合数据结构的行。

from six.moves.urllib.request import urlopen
import os
 
import numpy as np
import tensorflow as tf
 
IRIS_TRAINING = "iris_training.csv"
IRIS_TRAINING_URL = "http://download.tensorflow.org/data/iris_training.csv"
 
IRIS_TEST = "iris_test.csv"
IRIS_TEST_URL = "http://download.tensorflow.org/data/iris_test.csv"
 
if not os.path.exists(IRIS_TRAINING):
   raw = urlopen(IRIS_TRAINING_URL).read()
   with open(IRIS_TRAINING, "wb") as f:
       f.write(raw)
 
if not os.path.exists(IRIS_TEST):
   raw = urlopen(IRIS_TEST_URL).read()
   with open(IRIS_TEST, "wb") as f:
       f.write(raw)
 
fun = lambda x1: not tf.strings.regex_full_match(x1, '.*[a-z|A-Z].*')  # 判断是否存在字母
 
def funStringSplit(x):
   #对每行特征进行处理,这里可能会报错,需要更改这里的 x 为 [x] 
   split_strings = tf.strings.to_number(tf.strings.split(x, ','))  # 分割字符串
   features, target = tf.split(split_strings, [4, 1], axis=0)
   return features, target
# 很多csv有表头,那么我们这里需要使用
# trainSet = tf.data.TextLineDataset([IRIS_TRAINING]).skip(1)
# 这里[IRIS_TRAINING],表示一个列表,TextLineDataset可以读取多个文件,这里只有一个文件所以可以去掉中括号
trainSet = tf.data.TextLineDataset([IRIS_TRAINING])
testSet = tf.data.TextLineDataset([IRIS_TEST])
 
trainSet = trainSet.filter(fun)
testSet = testSet.filter(fun)
 
trainSet = trainSet.map(funStringSplit,num_parallel_calls=4)
testSet = testSet.map(funStringSplit,num_parallel_calls=4)

我们可能在tensorflow 1.x的一些版本遇到这样的情况,运行上面的代码出现以下错误

AttributeError: 'Tensor' object has no attribute 'to_sparse'

需要更改

split_strings = tf.strings.to_number(tf.strings.split(x, ','))
#改为
split_strings = tf.strings.to_number(tf.strings.split([x], ','))
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值