在 TensorFlow.org 上查看
|
在 Google Colab 运行
|
在 Github 上查看源代码 |
下载笔记本
|
警告:不推荐为新代码使用本教程中介绍的
tf.feature_columns模块。Keras 预处理层介绍了此功能,有关迁移说明,请参阅迁移特征列指南。tf.feature_columns模块旨在与 TF1Estimators结合使用。它不在我们的兼容性保证范围内,除了安全漏洞修正外,不会获得其他修正。
我们将使用一个小型 数据集,该数据集由克利夫兰心脏病诊所基金会(Cleveland Clinic Foundation for Heart Disease)提供。CSV 中有几百行数据。每行描述了一个病人(patient),每列描述了一个属性(attribute)。我们将使用这些信息来预测一位病人是否患有心脏病,这是在该数据集上的二分类任务。
- 用 Pandas 导入 CSV 文件。
- 用 tf.data 建立了一个输入流水线(pipeline),用于对行进行分批(batch)和随机排序(shuffle)。
- 用特征列将 CSV 中的列映射到用于训练模型的特征。
- 用 Keras 构建,训练并评估模型。
数据集
下面是该数据集的描述。 请注意,有数值(numeric)和类别(categorical)类型的列。
Following is a description of this dataset. Notice there are both numeric and categorical columns. There is a free text column which we will not use in this tutorial.
| 列 | 描述 | 特征类型 | 数据类型 |
|---|---|---|---|
| Type | 动物类型(狗、猫) | 分类 | 字符串 |
| Age | 宠物年龄 | 数值 | 整数 |
| Breed1 | 宠物的主要品种 | 分类 | 字符串 |
| Color1 | 宠物的颜色 1 | 分类 | 字符串 |
| Color2 | 宠物的颜色 2 | 分类 | 字符串 |
| MaturitySize | 成年个体大小 | 分类 | 字符串 |
| FurLength | 毛发长度 | 分类 | 字符串 |
| Vaccinated | 宠物已接种疫苗 | 分类 | 字符串 |
| Sterilized | 宠物已绝育 | 分类 | 字符串 |
| Health | 健康状况 | 分类 | 字符串 |
| Fee | 领养费 | 数值 | 整数 |
| Description | 关于此宠物的简介 | 文本 | 字符串 |
| PhotoAmt | 为该宠物上传的照片总数 | 数值 | 整数 |
| AdoptionSpeed | 领养速度 | 分类 | 整数 |
导入 TensorFlow 和其他库
pip install sklearnimport numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import feature_column
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split
2023-11-08 00:50:39.060981: E external/local_xla/xla/stream_executor/cuda/cuda_dnn.cc:9261] Unable to register cuDNN factory: Attempting to register factory for plugin cuDNN when one has already been registered 2023-11-08 00:50:39.061041: E external/local_xla/xla/stream_executor/cuda/cuda_fft.cc:607] Unable to register cuFFT factory: Attempting to register factory for plugin cuFFT when one has already been registered 2023-11-08 00:50:39.062610: E external/local_xla/xla/stream_executor/cuda/cuda_blas.cc:1515] Unable to register cuBLAS factory: Attempting to register factory for plugin cuBLAS when one has already been registered
使用 Pandas 创建一个 dataframe
Pandas 是一个 Python 库,它有许多有用的实用程序,用于加载和处理结构化数据。我们将使用 Pandas 从 URL下载数据集,并将其加载到 dataframe 中。
import pathlib
dataset_url = 'http://storage.googleapis.com/download.tensorflow.org/data/petfinder-mini.zip'
csv_file = 'datasets/petfinder-mini/petfinder-mini.csv'
tf.keras.utils.get_file('petfinder_mini.zip', dataset_url,
extract=True, cache_dir='.')
dataframe = pd.read_csv(csv_file)
Downloading data from http://storage.googleapis.com/download.tensorflow.org/data/petfinder-mini.zip 1668792/1668792 [==============================] - 0s 0us/step
dataframe.head()
创建目标变量
原始数据集中的任务是预测宠物被领养的速度(例如,在第一周、第一个月、前三个月等)。我们针对教程进行一下简化。在这里,我们将把它转化为一个二元分类问题,并简单地预测宠物是否被领养。
修改标签列后,0 表示宠物未被领养,1 表示宠物已被领养。
# In the original dataset "4" indicates the pet was not adopted.
dataframe['target'] = np.where(dataframe['AdoptionSpeed']==4, 0, 1)
# Drop un-used columns.
dataframe = dataframe.drop(columns=['AdoptionSpeed', 'Description'])
将 dataframe 拆分为训练、验证和测试集
我们下载的数据集是一个 CSV 文件。 我们将其拆分为训练、验证和测试集。
train, test = train_test_split(dataframe, test_size=0.2)
train, val = train_test_split(train, test_size=0.2)
print(len(train), 'train examples')
print(len(val), 'validation examples')
print(len(test), 'test examples')
7383 train examples 1846 validation examples 2308 test examples
用 tf.data 创建输入流水线
接下来,我们将使用 tf.data 包装 dataframe。这让我们能将特征列作为一座桥梁,该桥梁将 Pandas dataframe 中的列映射到用于训练模型的特征。如果我们使用一个非常大的 CSV 文件(非常大以至于它不能放入内存),我们将使用 tf.data 直接从磁盘读取它。本教程不涉及这一点。
# A utility method to create a tf.data dataset from a Pandas Dataframe
def df_to_dataset(dataframe, shuffle=True, batch_size=32):
dataframe = dataframe.copy()
labels = dataframe.pop('target')
ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
if
在 TensorFlow.org 上查看
在 Google Colab 运行
在 Github 上查看源代码
下载笔记本