misery-index / load_dataset.py
bansalaman18's picture
Upload load_dataset.py
5e17172 verified
raw
history blame
6.03 kB
"""
Simple script to load the Misery Index Dataset using pandas or datasets library.
"""
import pandas as pd
from typing import Dict, List, Optional
def load_misery_dataset(file_path: str = "Misery_Data.csv") -> pd.DataFrame:
"""
Load the Misery Index Dataset from CSV file.
Args:
file_path: Path to the CSV file (default: "Misery_Data.csv")
Returns:
pandas.DataFrame with cleaned column names and proper data types
"""
df = pd.read_csv(file_path)
# Rename columns to be more user-friendly
column_mapping = {
"Ep #": "episode",
"Misery": "scenario",
"Score": "misery_score",
"VNTO": "vnto",
"Reward": "reward",
"Win": "win",
"Comments": "comments",
"question_tag": "question_tag",
"level": "level"
}
df = df.rename(columns=column_mapping)
# Convert misery_score to numeric
df["misery_score"] = pd.to_numeric(df["misery_score"], errors="coerce")
# Convert reward to numeric, handling empty values
df["reward"] = pd.to_numeric(df["reward"], errors="coerce").fillna(0).astype(int)
# Clean up string columns
string_columns = ["episode", "scenario", "vnto", "win", "comments", "question_tag", "level"]
for col in string_columns:
if col in df.columns:
df[col] = df[col].astype(str).str.strip()
df[col] = df[col].replace("nan", "")
return df
def get_dataset_statistics(df: pd.DataFrame) -> Dict:
"""
Get basic statistics about the dataset.
Args:
df: DataFrame containing the dataset
Returns:
Dictionary with dataset statistics
"""
stats = {
"total_samples": len(df),
"mean_misery": df["misery_score"].mean(),
"std_misery": df["misery_score"].std(),
"min_misery": df["misery_score"].min(),
"max_misery": df["misery_score"].max(),
"percentiles": {
"25th": df["misery_score"].quantile(0.25),
"50th": df["misery_score"].quantile(0.50),
"75th": df["misery_score"].quantile(0.75),
},
"vnto_types": df["vnto"].value_counts().to_dict() if "vnto" in df.columns else {},
"episodes": df["episode"].nunique(),
"question_tags": df["question_tag"].value_counts().to_dict() if "question_tag" in df.columns else {},
}
return stats
def filter_by_vnto(df: pd.DataFrame, vnto_type: str) -> pd.DataFrame:
"""
Filter dataset by VNTO type.
Args:
df: DataFrame containing the dataset
vnto_type: VNTO type to filter by (T, V, N, O, P)
Returns:
Filtered DataFrame
"""
return df[df["vnto"] == vnto_type].copy()
def filter_by_misery_range(df: pd.DataFrame, min_score: float = 0, max_score: float = 100) -> pd.DataFrame:
"""
Filter dataset by misery score range.
Args:
df: DataFrame containing the dataset
min_score: Minimum misery score (inclusive)
max_score: Maximum misery score (inclusive)
Returns:
Filtered DataFrame
"""
return df[(df["misery_score"] >= min_score) & (df["misery_score"] <= max_score)].copy()
def get_sample_scenarios(df: pd.DataFrame, vnto_type: Optional[str] = None, n: int = 5) -> List[Dict]:
"""
Get sample scenarios from the dataset.
Args:
df: DataFrame containing the dataset
vnto_type: Optional VNTO type to filter by
n: Number of samples to return
Returns:
List of dictionaries with scenario information
"""
if vnto_type:
df_filtered = filter_by_vnto(df, vnto_type)
else:
df_filtered = df
samples = df_filtered.sample(n=min(n, len(df_filtered)))
return [
{
"scenario": row["scenario"],
"misery_score": row["misery_score"],
"vnto": row["vnto"],
"episode": row["episode"]
}
for _, row in samples.iterrows()
]
def main():
"""Example usage of the dataset loading functions."""
# Load the dataset
print("Loading Misery Index Dataset...")
df = load_misery_dataset()
# Get basic statistics
stats = get_dataset_statistics(df)
print(f"\nDataset Statistics:")
print(f"Total samples: {stats['total_samples']}")
print(f"Mean misery score: {stats['mean_misery']:.2f}")
print(f"Standard deviation: {stats['std_misery']:.2f}")
print(f"Score range: {stats['min_misery']}-{stats['max_misery']}")
print(f"Number of episodes: {stats['episodes']}")
print(f"\nPercentiles:")
for p, value in stats['percentiles'].items():
print(f" {p}: {value:.2f}")
print(f"\nVNTO Types distribution:")
for vnto_type, count in stats['vnto_types'].items():
percentage = (count / stats['total_samples']) * 100
print(f" {vnto_type}: {count} ({percentage:.1f}%)")
print(f"\nTop Question Tags:")
for tag, count in list(stats['question_tags'].items())[:5]:
percentage = (count / stats['total_samples']) * 100
print(f" {tag}: {count} ({percentage:.1f}%)")
# Show some examples
print(f"\nSample low misery scenarios (< 30):")
low_misery = filter_by_misery_range(df, 0, 30)
samples = get_sample_scenarios(low_misery, n=3)
for sample in samples:
print(f" Score {sample['misery_score']}: {sample['scenario']}")
print(f"\nSample high misery scenarios (> 80):")
high_misery = filter_by_misery_range(df, 80, 100)
samples = get_sample_scenarios(high_misery, n=3)
for sample in samples:
print(f" Score {sample['misery_score']}: {sample['scenario']}")
print(f"\nSample Video scenarios (VNTO=V):")
video_scenarios = filter_by_vnto(df, "V")
samples = get_sample_scenarios(video_scenarios, n=3)
for sample in samples:
print(f" Score {sample['misery_score']}: {sample['scenario']}")
if __name__ == "__main__":
main()