使用Keras预处理层进行结构化数据分类

使用Keras预处理层进行结构化数据分类

概述

本文将介绍如何使用TensorFlow Keras预处理层来处理结构化数据(如CSV表格数据)并进行分类任务。我们将基于一个简化的宠物领养预测数据集,演示完整的机器学习工作流程。

数据集介绍

我们使用的是PetFinder数据集的简化版本,包含以下特征:

| 特征名称 | 描述 | 类型 | 数据类型 | |---------|------|------|---------| | Type | 动物类型(猫/狗) | 分类 | 字符串 | | Age | 宠物年龄 | 数值 | 整数 | | Breed1 | 主要品种 | 分类 | 字符串 | | Color1 | 主要颜色 | 分类 | 字符串 | | Color2 | 次要颜色 | 分类 | 字符串 | | MaturitySize | 成熟体型 | 分类 | 字符串 | | FurLength | 毛发长度 | 分类 | 字符串 | | Vaccinated | 是否接种疫苗 | 分类 | 字符串 | | Sterilized | 是否绝育 | 分类 | 字符串 | | Health | 健康状况 | 分类 | 字符串 | | Fee | 领养费用 | 数值 | 整数 | | PhotoAmt | 照片数量 | 数值 | 整数 |

目标变量是二元分类标签:1表示宠物被领养,0表示未被领养。

技术栈

我们将使用以下工具和技术:

  1. Pandas:用于数据加载和初步处理
  2. TensorFlow tf.data:构建高效的数据输入管道
  3. Keras预处理层:特征工程和预处理
  4. Keras API:构建和训练深度学习模型

实现步骤

1. 环境准备

首先确保安装了必要的库:

!pip install -U scikit-learn

然后导入所需的库:

import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers
from tensorflow.keras.layers.experimental import preprocessing

2. 数据加载与预处理

使用Pandas加载CSV数据:

dataset_url = 'http://storage.googleapis.com/download.tensorflow.org/data/petfinder-mini.zip'
csv_file = 'petfinder-mini_toy.csv'

tf.keras.utils.get_file('petfinder_mini.zip', dataset_url, extract=True, cache_dir='.')
dataframe = pd.read_csv(csv_file)

查看数据前几行:

dataframe.head()

3. 目标变量处理

将原始的多分类问题转换为二元分类问题:

dataframe['target'] = np.where(dataframe['AdoptionSpeed']==4, 0, 1)
dataframe = dataframe.drop(columns=['AdoptionSpeed', 'Description'])

4. 数据分割

将数据分为训练集、验证集和测试集:

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')

5. 构建输入管道

使用tf.data创建高效的数据输入管道:

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 shuffle:
        ds = ds.shuffle(buffer_size=len(dataframe))
    ds = ds.batch(batch_size)
    ds = ds.prefetch(batch_size)
    return ds

创建训练数据集:

batch_size = 5
train_ds = df_to_dataset(train, batch_size=batch_size)

6. 特征工程与预处理

Keras预处理层允许我们将特征工程直接集成到模型中,这简化了部署流程。我们将为不同类型的特征创建不同的预处理层:

  • 数值特征:标准化
  • 分类特征:字符串索引和独热编码
# 数值特征预处理
numeric_features = ['Age', 'Fee', 'PhotoAmt']
numeric_layers = []
for feature in numeric_features:
    normalizer = preprocessing.Normalization()
    normalizer.adapt(train_ds.map(lambda x, y: x[feature]))
    numeric_layers.append(normalizer)

# 分类特征预处理
categorical_features = ['Type', 'Breed1', 'Color1', 'Color2', 
                       'MaturitySize', 'FurLength', 'Vaccinated',
                       'Sterilized', 'Health']
categorical_layers = []
for feature in categorical_features:
    indexer = preprocessing.StringLookup()
    indexer.adapt(train_ds.map(lambda x, y: x[feature]))
    encoder = preprocessing.CategoryEncoding(max_tokens=indexer.vocabulary_size())
    categorical_layers.append((indexer, encoder))

7. 模型构建

将预处理层与模型层结合:

# 数值特征输入
numeric_inputs = []
for feature in numeric_features:
    input_layer = layers.Input(shape=(1,), name=feature)
    numeric_inputs.append(input_layer)

# 分类特征输入
categorical_inputs = []
for feature in categorical_features:
    input_layer = layers.Input(shape=(1,), name=feature, dtype=tf.string)
    categorical_inputs.append(input_layer)

# 数值特征处理
numeric_processed = []
for i, feature in enumerate(numeric_features):
    processed = numeric_layers[i](numeric_inputs[i])
    numeric_processed.append(processed)

# 分类特征处理
categorical_processed = []
for i, feature in enumerate(categorical_features):
    indexed = categorical_layers[i][0](categorical_inputs[i])
    encoded = categorical_layers[i][1](indexed)
    categorical_processed.append(encoded)

# 合并所有特征
all_features = layers.concatenate(numeric_processed + categorical_processed)

# 添加隐藏层
x = layers.Dense(32, activation='relu')(all_features)
x = layers.Dropout(0.5)(x)
output = layers.Dense(1, activation='sigmoid')(x)

# 创建模型
model = tf.keras.Model(
    inputs=numeric_inputs + categorical_inputs,
    outputs=output)

model.compile(
    optimizer='adam',
    loss='binary_crossentropy',
    metrics=['accuracy'])

8. 模型训练与评估

# 准备完整的数据集
batch_size = 32
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)

# 训练模型
history = model.fit(
    train_ds,
    validation_data=val_ds,
    epochs=10)

# 评估模型
loss, accuracy = model.evaluate(test_ds)
print(f"Test accuracy: {accuracy:.4f}")

关键优势

使用Keras预处理层的主要优势包括:

  1. 端到端模型:预处理逻辑成为模型的一部分,简化了部署
  2. 一致性:训练和推理时使用相同的预处理逻辑
  3. 灵活性:可以轻松调整预处理策略
  4. 性能优化:预处理在GPU上并行执行

总结

本文展示了如何使用Keras预处理层处理结构化数据并构建分类模型。这种方法特别适合生产环境,因为它将整个数据处理流程封装在模型中,确保了训练和推理时的一致性。通过合理设计特征预处理和模型架构,我们能够有效地从表格数据中学习并做出准确的预测。

对于更复杂的场景,您可以考虑:

  • 添加更多隐藏层或调整层大小
  • 尝试不同的特征组合方式
  • 使用更复杂的预处理策略
  • 添加正则化技术防止过拟合

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

段钰榕Hugo

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值