TensorFlow2.0读取csv文件,划分训练测试集,并训练

本教程展示了如何对结构化数据进行分类(例如CSV中的表格数据)。我们使用Keras定义模型,并将csv中各列的特征转化为训练的输入。 本教程包含以下功能代码:

  • 使用Pandas加载CSV文件。
  • 构建一个输入的pipeline,使用tf.data批处理和打乱数据。
  • 从CSV中的列映射到用于训练模型的输入要素。
  • 使用Keras构建,训练和评估模型。

1、导包,查看tensorflow版本

from __future__ import absolute_import, division, print_function
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import feature_column
from tensorflow.keras import layers,Sequential
from tensorflow.keras.layers import DenseFeatures,Dense
from sklearn.model_selection import train_test_split
print(tf.__version__)   # 2.4.1

2、使用Pandas加载CSV文件

通过read.csv读取文件,然后通过shape方法查看行列,通过head方法查看数据

dataframe = pd.read_csv('/root/anaconda3/envs/rlink/lyz/tensorflow_incremental_training/test_data.csv')
print(dataframe.shape)  # (250, 20)
dataframe.head(5)

image.png

3、通过sklearn - train_test_split划分数据集和测试集

 通过train_test_split 将数据集按照6:2:2的比例划分成训练集、验证集、测试集数据,但是划分完的数据格式依旧还是pandas.core.frame.DataFrame 格式

train, test = train_test_split(dataframe, test_size=0.2)
train, val = train_test_split(train, test_size=0.2)
print(len(train), '训练数据')   # 160 训练数据 
print(len(val), '验证数据 ')    # 40 验证数据 
print(len(test), '测试数据')    # 50 测试数据 
print(type(train))    # <class 'pandas.core.frame.DataFrame'>

4、将dataframe格式转为tensorflow能识别的 dataset格式

自定义df_to_dataset 方法,将dataframe格式转为tensorflow能识别的 dataset格式

def df_to_dataset(dataframe, shuffle=True, batch_size=32):
    dataframe = dataframe.copy()
    labels = dataframe.pop('fare_amount') #label为目标值字段,可以根据要求更换列名
    ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
    if shuffle:
        ds = ds.shuffle(buffer_size=len(dataframe))
    ds = ds.batch(batch_size)
    return ds
batch_size = 5
train_ds = df_to_dataset(train, batch_size=batch_size)
val_ds = df_to_dataset(val, shuffle=False, batch_size=batch_size)
test_ds = df_to_dataset(test, shuffle=False, batch_size=batch_size)
print(type(train_ds))   # <class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'>
通过自定义方法,我们可以看到数据变为dataset_ops.BatchDataset方式。

5 、从CSV中的列映射到用于训练模型的输入要素。

通过遍历train_ds.take(1),我们拿到训练数据集的第一行,所有特征值的标签名,将他定义为feature,该feature 即为需要训练的特征。

for feature_batch, label_batch in train_ds.take(1):
    feature = list(feature_batch.keys())
    print('feature list:', feature)
    print('A batch of targets:', label_batch )
# 可以打印出来,看看特征值如下:
# feature list: ['day1', 'hour_of_day', 'day_of_week', 'week_of_year', 'month_of_year', 'quarter_of_year', 'year1', 'night', 'late_night', 'abs_diff_longitude', 'abs_diff_latitude', 'pickup_distance_jfk', 'dropoff_distance_jfk', 'pickup_distance_ewr', 'dropoff_distance_ewr', 'pickup_distance_lgr', 'pickup_distance_downtown', 'dropoff_distance_downtown', 'manhattan']

6、 构建Dense类型输入层

深度模型的输入必须是Dense类型,所有输出是categorical类型需要经过indicator或者embedding的转换才可以,如果输出为Dense类型的,就可以使用。

可以通过看下面两个文档了解更多

https://blog.csdn.net/u014021893/article/details/80423112

https://blog.csdn.net/htbeker/article/details/112266784

遍历特征列表feature,拿到每一个特征值,使用feature_column.numeric_column(header)将所有类型转为数值类型,在通过DenseFeatures()转为Dense类型,作为输入层

feature_columns = []
# 遍历特征列表feature
for header in feature:
    feature_columns.append(feature_column.numeric_column(header))
feature_layer = DenseFeatures(feature_columns)
print(feature_layer(next(iter(train_ds))[0]).numpy())
#
print(type(feature_column.numeric_column(header)))  #可以看到转换类型
#<class 'tensorflow.python.feature_column.feature_column_v2.NumericColumn'>
print(type(feature_layer))
#<class 'tensorflow.python.keras.feature_column.dense_features_v2.DenseFeatures'>

7、使用keras进行模型训练

model = Sequential([
    feature_layer,
    Dense(128, activation='relu'),
    Dense(128, activation='relu'),
    Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam',
             loss='binary_crossentropy',
             metrics=['accuracy'])
model.fit(train_ds, validation_data=val_ds,epochs=5)
  • 11
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

3分钟秒懂大数据

你的打赏就是对我最大的鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值