lawlevisan commited on
Commit
644e2d5
·
verified ·
1 Parent(s): 355a907

Delete src/evaluate.py

Browse files
Files changed (1) hide show
  1. src/evaluate.py +0 -143
src/evaluate.py DELETED
@@ -1,143 +0,0 @@
1
- # evaluate.py
2
- import pandas as pd
3
- import os
4
- from collections import Counter
5
- import re
6
- from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score, classification_report
7
-
8
- SCRAPER_FOLDER = "drug_analysis_data_3months" # Folder where scraper saves CSVs
9
-
10
- # -----------------------------
11
- # Load CSVs
12
- # -----------------------------
13
- csv_files = [f for f in os.listdir(SCRAPER_FOLDER) if f.endswith(".csv")]
14
- if not csv_files:
15
- print("❌ No CSV files found in scraper folder!")
16
- exit()
17
-
18
- dfs = [pd.read_csv(os.path.join(SCRAPER_FOLDER, f)) for f in csv_files]
19
- df = pd.concat(dfs, ignore_index=True)
20
- print(f"✅ Loaded {len(df)} rows from {len(csv_files)} CSV files.\n")
21
-
22
- # -----------------------------
23
- # General Stats
24
- # -----------------------------
25
- print("=== General Stats ===")
26
- print("Columns:", df.columns.tolist())
27
- print("Total rows:", len(df))
28
- print("Missing values per column:\n", df.isna().sum())
29
- print("\nDuplicate rows:", df.duplicated().sum())
30
-
31
- # Sample rows with missing data
32
- missing_rows = df[df.isna().any(axis=1)]
33
- if not missing_rows.empty:
34
- print("\nSample rows with missing values:\n", missing_rows.head())
35
-
36
- # Sample duplicate rows
37
- duplicates = df[df.duplicated(keep=False)]
38
- if not duplicates.empty:
39
- print("\nSample duplicate rows:\n", duplicates.head())
40
-
41
- # -----------------------------
42
- # Drug/Crime-related stats
43
- # -----------------------------
44
- for col in ["is_drug_related", "is_crime_related", "risk_level"]:
45
- if col in df.columns:
46
- print(f"\n=== {col} Distribution ===")
47
- print(df[col].value_counts())
48
- print("Proportion:\n", round(df[col].value_counts(normalize=True), 4))
49
-
50
- # Risk level numeric analysis
51
- if "risk_level" in df.columns and pd.api.types.is_numeric_dtype(df["risk_level"]):
52
- print("\n=== Risk Level Stats ===")
53
- print("Average risk:", round(df["risk_level"].mean(), 2))
54
- print("Max risk:", df["risk_level"].max())
55
- high_risk_count = (df["risk_level"] >= 0.7).sum() # Threshold
56
- print("Number of high-risk items (risk >= 0.7):", high_risk_count)
57
-
58
- # -----------------------------
59
- # Time coverage
60
- # -----------------------------
61
- if "datetime" in df.columns:
62
- df["datetime"] = pd.to_datetime(df["datetime"], errors="coerce")
63
- print("\n=== Date Range ===")
64
- print("Earliest:", df["datetime"].min())
65
- print("Latest:", df["datetime"].max())
66
-
67
- # Daily counts
68
- df["date"] = df["datetime"].dt.date
69
- daily_counts = df.groupby("date").size()
70
- print("\n=== Daily Counts of Posts ===")
71
- print(daily_counts)
72
-
73
- # -----------------------------
74
- # Text Analysis
75
- # -----------------------------
76
- if "text" in df.columns:
77
- df["text"] = df["text"].astype(str)
78
- df["text_length"] = df["text"].apply(len)
79
- print("\n=== Text Length Stats ===")
80
- print("Average length:", round(df["text_length"].mean(), 2))
81
- print("Min length:", df["text_length"].min())
82
- print("Max length:", df["text_length"].max())
83
-
84
- # Top 10 most common words
85
- words = Counter()
86
- for t in df["text"]:
87
- words.update(re.findall(r"\w+", t.lower()))
88
- print("\nTop 10 common words:", words.most_common(10))
89
-
90
- # -----------------------------
91
- # User / Source Analysis
92
- # -----------------------------
93
- if "username" in df.columns:
94
- print("\n=== User Analysis ===")
95
- print("Total unique users:", df["username"].nunique())
96
- top_users = df["username"].value_counts().head(10)
97
- print("Top 10 users by post count:\n", top_users)
98
-
99
- # -----------------------------
100
- # Scraper Evaluation Metrics
101
- # -----------------------------
102
- print("\n=== Scraper Evaluation Metrics ===")
103
-
104
- # 1. Completeness (% of filled cells)
105
- completeness = 1 - df.isna().mean().mean()
106
- print(f"Completeness (all columns filled): {round(completeness*100, 2)}%")
107
-
108
- # 2. Duplicate rate (% of duplicate rows)
109
- duplicate_rate = df.duplicated().mean()
110
- print(f"Duplicate rows rate: {round(duplicate_rate*100, 2)}%")
111
-
112
- # 3. Drug/Crime relevance (if available)
113
- for col in ["is_drug_related", "is_crime_related"]:
114
- if col in df.columns:
115
- relevance = df[col].sum() / len(df)
116
- print(f"{col} relevance rate: {round(relevance*100,2)}%")
117
-
118
- # 4. Time coverage (active days vs total days)
119
- if "datetime" in df.columns:
120
- total_days = (df["datetime"].max() - df["datetime"].min()).days + 1
121
- active_days = df["date"].nunique()
122
- coverage_ratio = active_days / total_days
123
- print(f"Time coverage ratio (active days / total days): {round(coverage_ratio*100,2)}%")
124
-
125
- # 5. Average text length (proxy for content richness)
126
- if "text" in df.columns:
127
- print(f"Average text length: {round(df['text_length'].mean(),2)} characters")
128
-
129
- # 6. Classification Metrics (using scraper labels as pseudo-ground truth)
130
- # If multiple columns available (e.g., is_drug_related vs is_crime_related), compute metrics
131
- if "is_drug_related" in df.columns and "is_crime_related" in df.columns:
132
- y_true = df["is_crime_related"]
133
- y_pred = df["is_drug_related"]
134
- print("\n=== Classification Metrics (is_drug_related vs is_crime_related) ===")
135
- print("Accuracy:", round(accuracy_score(y_true, y_pred), 4))
136
- print("Precision:", round(precision_score(y_true, y_pred), 4))
137
- print("Recall:", round(recall_score(y_true, y_pred), 4))
138
- print("F1-score:", round(f1_score(y_true, y_pred), 4))
139
- print("\nClassification Report:\n", classification_report(y_true, y_pred))
140
- else:
141
- print("\n⚠️ Skipping classification metrics: Not enough columns for evaluation.")
142
-
143
- print("\n✅ Data evaluation + metrics complete!")