Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Fix training with pandas DataFrames, closes #1265 (#1266)

Jin47d3e657561e
diff --git a/src/python/txtai/data/base.py b/src/python/txtai/data/base.py
index 5a98c6d2..c1de9366 100644
--- a/src/python/txtai/data/base.py
+++ b/src/python/txtai/data/base.py
@@ -38,7 +38,10 @@ class Data:
(train, validation)
"""
- return (self.prepare(train, self.process, workers, batch), self.prepare(validation, self.process, workers, batch) if validation else None)
+ return (
+ self.prepare(train, self.process, workers, batch),
+ self.prepare(validation, self.process, workers, batch) if validation is not None else None,
+ )
def prepare(self, data, fn, workers, batch):
"""
@@ -54,7 +57,8 @@ class Data:
tokens
"""
- if hasattr(data, "map"):
+ # Check for column_names, pandas DataFrames also have a map method
+ if hasattr(data, "column_names"):
# Hugging Face dataset
tokens = data.map(fn, batched=True, batch_size=batch, num_proc=workers, remove_columns=data.column_names)
else:
@@ -93,11 +97,11 @@ class Data:
column = self.columns[-1]
# Return length of labels if it's an array
- length = self.length(data[column][0] if hasattr(data, "columns") else data[0][column])
+ length = self.length(next(iter(data[column])) if hasattr(data, "columns") else data[0][column])
if length:
return length
- if hasattr(data, "map"):
+ if hasattr(data, "column_names"):
# Hugging Face dataset
labels = sorted(data.unique(self.columns[-1]))
elif hasattr(data, "columns"):
diff --git a/test/python/testpipeline/testtrain/testtrainer.py b/test/python/testpipeline/testtrain/testtrainer.py
index 638f81ea..8441c91d 100644
--- a/test/python/testpipeline/testtrain/testtrainer.py
+++ b/test/python/testpipeline/testtrain/testtrainer.py
@@ -11,6 +11,7 @@ import unittest
from unittest.mock import patch
import numpy as np
+import pandas as pd
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
@@ -691,6 +692,27 @@ class TestTrainer(unittest.TestCase):
labels = Labels((model, tokenizer), dynamic=False)
self.assertEqual(labels("cat")[0][0], 1)
+ def testPandas(self):
+ """
+ Test training a model with a pandas DataFrame
+ """
+
+ df = pd.DataFrame(self.data)
+
+ # Split into train and validation sets, the train index doesn't start at 0
+ train, validation = df.iloc[4:], df.iloc[:4]
+
+ trainer = HFTrainer()
+ model, tokenizer = trainer(
+ "google/bert_uncased_L-2_H-128_A-2",
+ train,
+ validation=validation,
+ do_eval=True,
+ output_dir=os.path.join(tempfile.gettempdir(), "trainer"),
+ )
+
+ labels = Labels((model, tokenizer), dynamic=False)
+ self.assertEqual(labels("cat")[0][0], 1)
def testPack(self):
"""
Test packing rows into chunks up to maxlength