File size: 6,029 Bytes
5e17172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
"""
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()