ai-04-模型训练-理解数据集-如Ant Financial
在您可以在数据集上训练模型之前,数据需要被预处理为期望的模型输入格式。无论您的数据是文本、图像还是音频,它们都需要被转换并组合成批量的张量。🤗 Transformers 提供了一组预处理类来帮助准备数据以供模型使用。在本教程中,您将了解以下内容:
- 对于文本,使用分词器(
Tokenizer
)将文本转换为一系列标记(tokens
),并创建tokens
的数字表示,将它们组合成张量。 - 对于语音和音频,使用特征提取器(
Feature extractor
)从音频波形中提取顺序特征并将其转换为张量。 - 图像输入使用图像处理器(
ImageProcessor
)将图像转换为张量。 - 多模态输入,使用处理器(
Processor
)结合了Tokenizer
和ImageProcessor
或Processor
。
数据集使用指南 · 文档中心 (modelscope.cn)
模型的训练Train · 文档中心 (modelscope.cn)
Ant Financial Question Matching Corpus(蚂蚁金服问题匹配语料库)是一个用于自然语言处理中的问答匹配任务的数据集。该数据集主要用于训练和评估模型在判断两个问题是否相似或匹配方面的性能。以下是对该数据集的详细理解:
- 数据集简介
Ant Financial Question Matching Corpus 是由蚂蚁金服(Ant Financial)提供的一个公开数据集,主要用于研究和开发自然语言处理(NLP)模型,特别是问答匹配和语义相似性任务。该数据集包含了大量的问答对,每对问答对都标注了它们是否匹配(相似)。 - 数据集结构
一个典型的问答匹配数据集通常包含以下几个部分:
问题对(Question Pairs):每一行包含两个问题,分别是question1和question2。
标签(Label):每对问题都对应一个标签,表示这两个问题是否匹配。通常标签为二值(0或1),其中1表示匹配,0表示不匹配。
示例:
question1,question2,label
"如何开通花呗?","怎么开通蚂蚁花呗?",1
"余额宝收益怎么算?","余额宝的收益如何计算?",1
"如何申请信用卡?","怎样申请贷款?",0
-
使用场景
该数据集主要用于以下几个方面:
模型训练:用于训练机器学习或深度学习模型,使其能够判断两个问题是否相似或匹配。
模型评估:用于评估模型的性能,通过计算准确率、精确率、召回率和F1分数等指标来衡量模型的效果。
研究和开发:用于学术研究和工业应用,探索和开发更好的问答匹配算法和技术。 -
数据预处理
在使用数据集之前,通常需要进行一些预处理步骤:
数据清洗:去除重复数据、处理缺失值等。
文本处理:分词、去停用词、词干提取等。
特征工程:将文本转换为模型可接受的特征形式,如TF-IDF、词向量(Word2Vec)、句向量(Sentence Embeddings)等。 -
模型选择
常用的模型包括:
传统机器学习模型:如逻辑回归、支持向量机(SVM)、随机森林等。
深度学习模型:如卷积神经网络(CNN)、循环神经网络(RNN)、长短期记忆网络(LSTM)等。
预训练语言模型:如BERT、RoBERTa、GPT等,这些模型在处理自然语言理解任务时表现出色。 -
示例代码
以下是一个简单的示例代码,展示如何加载和使用该数据集:
import pandas as pd
from sklearn.model_selection import train_test_split //用于将数据集分割为训练集和测试集
from sklearn.feature_extraction.text import TfidfVectorizer //用于将文本数据转换为TF-IDF特征向量
from sklearn.linear_model import LogisticRegression // 逻辑回归模型,用于分类任务
from sklearn.metrics import accuracy_score // 用于评估模型的准确性
# 加载数据集
data = pd.read_csv('ant_financial_question_matching.csv')
# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(
data[['question1', 'question2']], data['label'], test_size=0.2, random_state=42)
# data[['question1', 'question2']]: 选择数据集中的问题对作为特征。
# data['label']: 选择标签列作为目标变量。
# train_test_split: 将数据集分割为训练集和测试集,其中20%的数据用于测试,80%的数据用于训练。random_state=42确保分割的可重复性。
# 特征提取
vectorizer = TfidfVectorizer() //初始化TF-IDF向量化器
X_train_tfidf = vectorizer.fit_transform(X_train['question1'] + ' ' + X_train['question2']) // 对训练集进行拟合并转换,将文本数据转换为TF-IDF特征向量
X_test_tfidf = vectorizer.transform(X_test['question1'] + ' ' + X_test['question2']) //对测试集进行转换(使用训练集的拟合结果)
# 训练模型
model = LogisticRegression() //初始化逻辑回归模型
model.fit(X_train_tfidf, y_train) //使用训练集的特征和标签来训练模型
# 预测
y_pred = model.predict(X_test_tfidf) // 使用训练好的模型对测试集进行预测,得到预测的标签
# 评估
accuracy = accuracy_score(y_test, y_pred) //计算模型的准确性,即预测正确的比例
print(f'Accuracy: {accuracy}')
训练后数据存放在哪里? 及各个文件数据格式
训练后数据存放在哪里:
在当前代码中,训练后的数据(例如模型权重、特征向量等)都存储在内存中,并没有写入到磁盘文件中。
如果你想将训练后的数据存储到文件中,可以使用Python的文件操作或相应的库函数进行保存。
各个文件和数据格式:
模型权重文件:可以使用joblib或pickle库将训练好的模型保存为文件,通常是.pkl或.joblib格式。
特征向量文件:可以将TF-IDF特征向量保存为CSV文件或其他格式。
评估结果文件:可以将评估结果(如准确性)保存到文本文件或CSV文件中。
示例:保存训练后的数据
以下是如何修改代码以保存训练后的模型和其他相关数据:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import joblib # 用于保存和加载模型
# 加载数据集
data = pd.read_csv('ant_financial_question_matching.csv')
# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(
data[['question1', 'question2']], data['label'], test_size=0.2, random_state=42)
# 特征提取
vectorizer = TfidfVectorizer()
X_train_tfidf = vectorizer.fit_transform(X_train['question1'] + ' ' + X_train['question2'])
X_test_tfidf = vectorizer.transform(X_test['question1'] + ' ' + X_test['question2'])
# 训练模型
model = LogisticRegression()
model.fit(X_train_tfidf, y_train)
# 保存模型和向量化器
joblib.dump(model, 'logistic_regression_model.pkl')
joblib.dump(vectorizer, 'tfidf_vectorizer.pkl')
# 预测
y_pred = model.predict(X_test_tfidf)
# 评估
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')
# 保存评估结果
with open('evaluation_results.txt', 'w') as f:
f.write(f'Accuracy: {accuracy}\n')
# 示例:保存特征向量
import numpy as np
np.savetxt('X_train_tfidf.csv', X_train_tfidf.toarray(), delimiter=',')
np.savetxt('X_test_tfidf.csv', X_test_tfidf.toarray(), delimiter=',')
文件说明
1:模型文件(logistic_regression_model.pkl):
格式:.pkl
内容:保存了训练后的逻辑回归模型的权重和参数。
加载方法:
model = joblib.load('logistic_regression_model.pkl')
2:向量化器文件(tfidf_vectorizer.pkl):
格式:.pkl
内容:保存了TF-IDF向量化器的拟合结果。
加载方法:
vectorizer = joblib.load('tfidf_vectorizer.pkl')
3:评估结果文件(evaluation_results.txt):
格式:.txt
内容:保存了模型的评估结果(如准确性)。
查看方法:
cat X_train_tfidf.csv
cat X_test_tfidf.csv
通过这些步骤,你可以将训练后的数据存储到文件中,便于后续的加载和分析。
音频数据集结构
对于音频任务,您需要feature extractor来准备您的数据集以供模型使用。feature extractor
旨在从原始音频数据中提取特征,并将它们转换为张量。
加载MInDS-14数据集(有关如何加载数据集的更多详细信息,请参阅🤗 Datasets教程)以了解如何在音频数据集中使用feature extractor
:
from datasets import load_dataset, Audio
dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
访问 audio 列的第一个元素以查看输入。调用 audio 列会自动加载和重新采样音频文件:
>>>from datasets import load_dataset, Audio
>>>dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")
>>>dataset[0]["audio"] # 返回的是一个包含音频数据的字典
{'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414,
0. , 0. ], dtype=float32),
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
'sampling_rate': 8000}
{
'array': array([ # array 键对应的值是一个 NumPy 数组,代表音频信号的采样数据。音频信号在数字化时,通过采样将连续的声音波形转换为一系列离散的数值,这些数值就是 array 中的元素。
0.,
0.00024414, # 数组中的每个值代表在特定时间点上音频信号的幅度。例如,0.00024414 表示某个时间点上的音频信号幅度。幅度值通常在 -1 到 1 之间,表示音频信号的相对强度。
-0.00024414,
...,
-0.00024414,
0.,
0.
],
dtype=float32), # 表示数组中的元素是 32 位浮点数。这种数据类型可以精确表示音频信号的幅度。
'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav',
'sampling_rate': 8000
}
这会返回三个对象:
array 是加载的语音信号 - 并在必要时重新采为1D array。
path 指向音频文件的位置。
sampling_rate 是每秒测量的语音信号数据点数量。
图片数据集的情况
from datasets import load_dataset
import json
# 加载 food101 数据集的前 100 个训练样本
dataset = load_dataset("food101", split="train[:100]")
# 获取第一个样本的 image 字段
image_data = dataset[0]["image"] # image_data 对象是一个复杂的类型(例如 PIL.Image 或类似的对象)
# 提取可序列化的信息
image_info = {
"format": image_data.format, # 图像格式
"mode": image_data.mode, # 图像模式
"width": image_data.width, # 图像宽度
"height": image_data.height # 图像高度
}
# 打印 image 字段的 JSON 表示
print(json.dumps(image_info, indent=4))
from datasets import load_dataset
import json
# 加载 food101 数据集的前 100 个训练样本
dataset = load_dataset("food101", split="train[:100]")
# 获取第一个样本的 image 字段
image_data = dataset[0]["image"] # image_data 对象是一个复杂的类型(例如 PIL.Image 或类似的对象)
# 提取可序列化的信息
image_info = {
"format": image_data.format, # 图像格式
"mode": image_data.mode, # 图像模式
"width": image_data.width, # 图像宽度
"height": image_data.height # 图像高度
}
# 打印 image 字段的 JSON 表示
print(json.dumps(image_info, indent=4))
print(dir(image_data)) # 检查属性和方法
print(dir(dataset[0])) # 检查属性和方法
dataset[0].keys()
dataset[0]["label"] # dict_keys(['image', 'label'])
<class 'dict'>
<class 'PIL.Image.Image'>
{
"format": null,
"mode": "RGB",
"width": 384,
"height": 512
}
['_Image__transformer', '__array_interface__', '__class__', '__copy__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_category', '_close_exclusive_fp_after_loading', '_copy', '_crop', '_dump', '_ensure_mutable', '_exif', '_expand', '_get_safe_box', '_getxmp', '_new', '_reload_exif', '_repr_png_', '_repr_pretty_', '_size', 'alpha_composite', 'apply_transparency', 'close', 'convert', 'copy', 'crop', 'draft', 'effect_spread', 'entropy', 'filter', 'format', 'format_description', 'frombytes', 'get_child_images', 'getbands', 'getbbox', 'getchannel', 'getcolors', 'getdata', 'getexif', 'getextrema', 'getim', 'getpalette', 'getpixel', 'getprojection', 'height', 'histogram', 'im', 'info', 'load', 'mode', 'palette', 'paste', 'point', 'putalpha', 'putdata', 'putpalette', 'putpixel', 'pyaccess', 'quantize', 'readonly', 'reduce', 'remap_palette', 'resize', 'rotate', 'save', 'seek', 'show', 'size', 'split', 'tell', 'thumbnail', 'tobitmap', 'tobytes', 'toqimage', 'toqpixmap', 'transform', 'transpose', 'verify', 'width']
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
dict_keys(['image', 'label'])
url图片转转张量,打印查看 -使用 PIL、requests 和 torchvision.transforms
import requests
from PIL import Image
from io import BytesIO
from torchvision import transforms
import torch
# 定义图像预处理管道
preprocess = transforms.Compose([ # 使用torchvision.transforms定义图像预处理管道,包括调整大小、转换为张量和归一化。
transforms.Resize((224, 224)), # 调整图像大小
transforms.ToTensor(), # 将图像转换为张量
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # 归一化
])
# 从URL读取图像
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
response = requests.get(url)
image = Image.open(BytesIO(response.content))
# 预处理并转换为张量
image_tensor = preprocess(image)
print(image_tensor.shape) # 输出张量的形状---描述了张量的维度和每个维度的大小。对于图像数据,张量通常是一个三维或四维的结构,具体取决于批次的使用情况。
image_tensor
torch.Size([3, 224, 224]) # 第一个维度 3 表示图像的通道数。对于彩色图像,通常有三个通道:红色(Red)、绿色(Green)和蓝色(Blue),简称RGB。; 高度(Height):第二个维度 224 表示图像的高度,单位是像素。 第三个维度 224 表示图像的宽度,单位是像素。
tensor([[[-0.0629, -0.1657, -0.4054, ..., 0.4851, 0.4337, 0.2796],
[ 0.0056, -0.0972, -0.3198, ..., 0.5707, 0.5022, 0.3481], # 每个值表示一个像素在某个颜色通道的强度,范围在 [0, 1] 之间,已经进行了归一化处理。
[ 0.0398, -0.0801, -0.3198, ..., 0.6392, 0.5536, 0.4166],
...,
[ 1.8037, 1.8037, 1.8208, ..., -1.8268, -1.8268, -1.7583],
[ 1.8208, 1.8208, 1.8208, ..., -1.6042, -1.7069, -1.7069],
[ 1.8379, 1.8550, 1.8379, ..., -1.5014, -1.6727, -1.7069]],
[[ 0.1176, 0.0126, -0.2325, ..., 0.5378, 0.4853, 0.3277],
[ 0.1877, 0.0826, -0.1450, ..., 0.6254, 0.5553, 0.3978],
[ 0.2227, 0.1001, -0.1450, ..., 0.6954, 0.6078, 0.4678],
...,
[ 2.0784, 2.0784, 2.0959, ..., -1.8256, -1.8256, -1.7556],
[ 2.0959, 2.0959, 2.0959, ..., -1.5980, -1.7031, -1.7031],
[ 2.1134, 2.1310, 2.1134, ..., -1.4930, -1.6681, -1.7031]],
[[ 0.4962, 0.3916, 0.1476, ..., 0.6879, 0.6356, 0.4788],
[ 0.5659, 0.4614, 0.2348, ..., 0.7751, 0.7054, 0.5485],
[ 0.6008, 0.4788, 0.2348, ..., 0.8448, 0.7576, 0.6182],
...,
[ 2.5006, 2.5006, 2.5180, ..., -1.6476, -1.6476, -1.5779],
[ 2.5180, 2.5180, 2.5180, ..., -1.4210, -1.5256, -1.5256],
[ 2.5354, 2.5529, 2.5354, ..., -1.3164, -1.4907, -1.5256]]])
url图片转转张量,打印查看 -使用 使用 TensorFlow 和 Keras
import tensorflow as tf
import requests
from io import BytesIO
# 从URL读取图像
url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
response = requests.get(url)
image = tf.image.decode_image(BytesIO(response.content).getvalue(), channels=3)
# 调整大小
image = tf.image.resize(image, [224, 224])
# 归一化
image = image / 255.0 # 将像素值归一化到 [0, 1]
# 增加批次维度
image = tf.expand_dims(image, axis=0)
print(image.shape) # 输出张量的形状
(1, 224, 224, 3)
在TensorFlow和Keras中,张量的形状(shape)描述了张量的维度和每个维度的大小。你提到的输出 (1, 224, 224, 3) 表示一个四维张量,其含义如下:
各个维度的含义
批次大小(Batch Size):第一个维度 1 表示批次的大小,即这个张量包含1个图像。如果你有多个图像,这个值会大于1。
高度(Height):第二个维度 224 表示图像的高度,单位是像素。
宽度(Width):第三个维度 224 表示图像的宽度,单位是像素。
通道数(Channels):第四个维度 3 表示图像的通道数。对于彩色图像,通常有三个通道:红色(Red)、绿色(Green)和蓝色(Blue),简称RGB。
<tf.Tensor: shape=(1, 224, 224, 3), dtype=float32, numpy=
array([[[[0.46311274, 0.48272058, 0.50625 ], # 每个值表示一个像素在某个颜色通道的强度,范围在 [0, 1] 之间,已经进行了归一化处理。
[0.436222 , 0.45582986, 0.47935927],
[0.3865459 , 0.40615374, 0.42968315],
...,
[0.59013486, 0.570527 , 0.5469976 ],
[0.584165 , 0.56455714, 0.5410277 ],
[0.5396625 , 0.52005464, 0.4965253 ]],
总结
Ant Financial Question Matching Corpus 数据集是一个非常有价值的资源,特别适用于研究问答匹配和语义相似性任务。通过理解数据集的结构、使用场景和预处理步骤,你可以更好地利用该数据集来训练和评估你的模型。