> ## Documentation Index
> Fetch the complete documentation index at: https://khaos-ml.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Tabular

> Messy tables: typing, joins, deduplication, anomalies.

## Clean up a messy CSV

**Problem:** load an export whose columns are all strings and give each a proper
type. **Uses:** Khaos and pandas.

```python theme={null}
import khaos
import pandas as pd

df = pd.read_csv("export.csv", dtype=str)
types = khaos.load("tab_column_types")(df).column_types
print(types)
# {'signup': 'date', 'email': 'email', 'zip': 'postal_code', 'spend': 'currency'}

for col, kind in types.items():
    if kind == "date":
        df[col] = pd.to_datetime(df[col], errors="coerce")
    elif kind == "currency":
        df[col] = pd.to_numeric(df[col].str.replace(r"[^\d.\-]", "", regex=True))
print(df.dtypes)
```

## Join two exports with no documentation

**Problem:** two systems export tables and nobody knows which columns link them.
**Uses:** Khaos and pandas.

```python theme={null}
import khaos
import pandas as pd

orders = pd.read_csv("orders.csv")
customers = pd.read_csv("customers.csv")

matches = khaos.load("tab_key_matching")(orders, customers).matches
left, right, score = max(matches, key=lambda m: m[2])
print(left, "->", right, round(score, 2))
# customer_ref -> id 0.97

joined = orders.merge(customers, left_on=left, right_on=right, how="left")
print(len(orders), len(joined))
# 18420 18420
```

## Deduplicate customer records

**Problem:** the same person appears under slightly different names and emails.
**Uses:** Khaos and pandas.

```python theme={null}
import khaos
import pandas as pd

df = pd.read_csv("customers.csv")
clusters = khaos.load("tab_entity_dedupe")(df).clusters
print(clusters[:2])
# [[0, 14], [3, 9, 27]]

keep = {c[0] for c in clusters}
drop = {i for c in clusters for i in c[1:]}
clean = df.drop(index=sorted(drop))
print(len(df), "->", len(clean))
# 5000 -> 4631
```

## Flag unusual transactions

**Problem:** surface the handful of rows worth a human look. **Uses:** Khaos alone.

```python theme={null}
import khaos

scores = khaos.load("tab_anomaly_scoring")("transactions.csv").scores
top = scores.argsort()[-10:][::-1]
print(top)
# [812 455 12 903 77 641 230 18 504 366]
```

## Inputs and outputs for each model

These are real outputs of the v1 models, run through their exported ONNX files on held-out examples. The shapes listed are the exact ONNX inputs and outputs; `batch` and other named sizes are dynamic.

### `tab_column_types`

Up to 24 sampled cells of a column in (encoded as byte ids with `encode_column`, shape (1, 24, 40)), a probability for each of 91 semantic types out. Six held-out columns of different types are shown with the model's top two guesses.

**Model inputs:** `chars int64 [batch, cells, 40]`\
**Model outputs:** `logits float32 [batch, 91]; vector float32 [batch, 256]`

**Input**

```python theme={null}
chars.shape = (1, 24, 40)   # one column of up to 24 cells; six columns shown below
```

**Output**

```json theme={null}
{
  "columns": [
    {
      "cells": [
        "2153455550",
        "2153455550",
        "2153455550"
      ],
      "true_type": "telephone",
      "top_1": {
        "type": "postalCode",
        "probability": 0.458
      },
      "top_2": {
        "type": "telephone",
        "probability": 0.157
      }
    },
    {
      "cells": [
        "1.0",
        "1.0",
        "1.0"
      ],
      "true_type": "Number",
      "top_1": {
        "type": "Number",
        "probability": 0.556
      },
      "top_2": {
        "type": "Integer",
        "probability": 0.304
      }
    },
    {
      "cells": [
        "Vitamin Supreme 50ml Code: 558 Protecting night cream for all skin conditions. E",
        "Night Cream Rich, essential night cream for every skin type, well suited even fo",
        "Eye Balm Supreme 15ml Code: 226 Special balm for the delicate, sensitive eye are"
      ],
      "true_type": "Text",
      "top_1": {
        "type": "CreativeWork/name",
        "probability": 0.35
      },
      "top_2": {
        "type": "Text",
        "probability": 0.173
      }
    },
    {
      "cells": [
        "postmaster@humblekro.dk",
        "info@sukkerfabrikken.dk",
        "post@kaedebycafeen.dk"
      ],
      "true_type": "email",
      "top_1": {
        "type": "email",
        "probability": 0.971
      },
      "top_2": {
        "type": "price",
        "probability": 0.006
      }
    },
    {
      "cells": [
        "/us/community/forums/users/1641",
        "/us/community/forums/users/1047",
        "/us/community/forums/users/5231"
      ],
      "true_type": "URL",
      "top_1": {
        "type": "URL",
        "probability": 0.862
      },
      "top_2": {
        "type": "IdentifierAT",
        "probability": 0.078
      }
    },
    {
      "cells": [
        "ES",
        "ES",
        "ES"
      ],
      "true_type": "Country",
      "top_1": {
        "type": "addressRegion",
        "probability": 0.84
      },
      "top_2": {
        "type": "Country",
        "probability": 0.039
      }
    }
  ],
  "top_1_correct": "3 of 6"
}
```

### `tab_key_matching`

Two columns in (sampled cells of each plus 11 overlap features from `pair_features`), the probability that column A is a foreign key of column B out.

**Model inputs:** `chars_a int64 [batch, cells, 40]; chars_b int64 [batch, cells, 40]; features float32 [batch, 11]`\
**Model outputs:** `logit float32 [batch]`

**Input**

```python theme={null}
values_a = ['515', '332', '1040', '1010', '76']  # ...
values_b = ['446', '920', '244', '322', '639']  # ...
features = [1.0, 0.209, 0.209, 0.935, 1.0, 1.0, 1.0, 0.061, 0.06, 0.976, 1.0]
```

**Output**

```json theme={null}
{
  "a_real_foreign_key": {
    "column_a": "constructor_results.raceId",
    "column_b": "races.raceId",
    "probability_foreign_key": 0.748,
    "true_label": 1
  },
  "a_non_key_pair": {
    "column_a": "standings.raceId",
    "column_b": "standings.driverStandingsId",
    "probability_foreign_key": 0.076,
    "true_label": 0
  }
}
```

### `tab_entity_dedupe`

Two records in, each written as `column: value | column: value` and tokenized as a pair, the probability that they describe the same entity out. Three duplicate and three non-duplicate bibliographic pairs from the held-out DBLP-ACM benchmark are shown.

**Model inputs:** `input_ids int64 [batch, seq]; attention_mask int64 [batch, seq]`\
**Model outputs:** `logit float32 [batch]`

**Input**

```python theme={null}
# each pair: text_a, text_b  (tokenized together as [CLS] A [SEP] B [SEP])
```

**Output**

```json theme={null}
{
  "pairs": [
    {
      "text_a": "title: reducing the braking distance of an sql query engine | authors: donald kossmann , m",
      "text_b": "title: reducing the braking distance of an sql query engine | authors: michael j. carey , ",
      "probability_same_entity": 0.999,
      "true_label": 1
    },
    {
      "text_a": "title: dynamic memory adjustment for external mergesort | authors: weiye zhang , per-åke l",
      "text_b": "title: dynamic memory adjustment for external mergesort | authors: weiye zhang , per - &#1",
      "probability_same_entity": 0.999,
      "true_label": 1
    },
    {
      "text_a": "title: bulk loading into an oodb : a performance study | authors: jeffrey f. naughton , ja",
      "text_b": "title: bulk loading into an oodb : a performance study | authors: janet l. wiener , jeffre",
      "probability_same_entity": 0.999,
      "true_label": 1
    },
    {
      "text_a": "title: research directions in biodiversity informatics | authors: john l. schnase | venue:",
      "text_b": "title: work and information practices in the sciences of biodiversity | authors: geoffrey ",
      "probability_same_entity": 0.0,
      "true_label": 0
    },
    {
      "text_a": "title: query processing techniques for arrays | authors: kenneth salem , arunprasad p. mar",
      "text_b": "title: data mining techniques | authors: jiawei han | venue: international conference on m",
      "probability_same_entity": 0.0,
      "true_label": 0
    },
    {
      "text_a": "title: integrating reliable memory in databases | authors: peter m. chen , wee teck ng | v",
      "text_b": "title: query processing in tertiary memory databases | authors: sunita sarawagi | venue: v",
      "probability_same_entity": 0.0,
      "true_label": 0
    }
  ],
  "correct_at_0.5": "6 of 6"
}
```

### `tab_anomaly_scoring`

A row of up to 64 scaled numeric cells in. Hide 25% of the cells at random, let the model predict them, and repeat 24 times: the average error on the hidden cells is the row's anomaly score (higher is more unusual). Scores vary a lot from row to row, so 60 normal and 60 anomalous rows of the held-out `6_cardio` table are summarized.

**Model inputs:** `values float32 [batch, 64]; visible float32 [batch, 64]; present float32 [batch, 64]; col_ids int64 [batch, 64]`\
**Model outputs:** `recon float32 [batch, 64]`

**Input**

```python theme={null}
# ... 21 values, one row of the held-out 6_cardio table
row = [0.08, 0.09, 0.0, 0.33, 0.0, 0.0]
visible = a random 75% of the cells, repeated 24 times
```

**Output**

```json theme={null}
{
  "normal_rows": {
    "count": 60,
    "mean_score": 0.708,
    "median_score": 0.553
  },
  "anomalous_rows": {
    "count": 60,
    "mean_score": 2.051,
    "median_score": 1.776
  },
  "auroc_on_these_rows": 0.932
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.