File size: 9,950 Bytes
476d115 |
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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from datasets import load_dataset\n",
"df_raw = load_dataset('Ezi/medical_and_legislators_synthetic')\n",
"df_pandas = df_raw['train'].to_pandas()\n",
"df_pandas.columns"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df_raw = pd.read_csv('/Users/nullzero/Documents/repos/github.com/privacy-identity/vda-simulation-medical/vda-sim-medical/data/raw/marketing_campaign.csv', sep='\\t')\n",
"df_raw.shape\n",
"df_raw[\"Response\"].unique()\n",
"df_raw.rename(columns={'Reponse': 'target'}, inplace=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = df_raw.copy()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(df.describe) "
]
},
{
"cell_type": "code",
"execution_count": 122,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"shape is (2240, 29) and there are ID 0\n",
"Year_Birth 0\n",
"Education 0\n",
"Marital_Status 0\n",
"Income 24\n",
"Kidhome 0\n",
"Teenhome 0\n",
"Dt_Customer 0\n",
"Recency 0\n",
"MntWines 0\n",
"MntFruits 0\n",
"MntMeatProducts 0\n",
"MntFishProducts 0\n",
"MntSweetProducts 0\n",
"MntGoldProds 0\n",
"NumDealsPurchases 0\n",
"NumWebPurchases 0\n",
"NumCatalogPurchases 0\n",
"NumStorePurchases 0\n",
"NumWebVisitsMonth 0\n",
"AcceptedCmp3 0\n",
"AcceptedCmp4 0\n",
"AcceptedCmp5 0\n",
"AcceptedCmp1 0\n",
"AcceptedCmp2 0\n",
"Complain 0\n",
"Z_CostContact 0\n",
"Z_Revenue 0\n",
"Response 0\n",
"dtype: int64 NAs\n",
"Index(['ID', 'Year_Birth', 'Education', 'Marital_Status', 'Income', 'Kidhome',\n",
" 'Teenhome', 'Dt_Customer', 'Recency', 'MntWines', 'MntFruits',\n",
" 'MntMeatProducts', 'MntFishProducts', 'MntSweetProducts',\n",
" 'MntGoldProds', 'NumDealsPurchases', 'NumWebPurchases',\n",
" 'NumCatalogPurchases', 'NumStorePurchases', 'NumWebVisitsMonth',\n",
" 'AcceptedCmp3', 'AcceptedCmp4', 'AcceptedCmp5', 'AcceptedCmp1',\n",
" 'AcceptedCmp2', 'Complain', 'Z_CostContact', 'Z_Revenue', 'Response'],\n",
" dtype='object')\n"
]
}
],
"source": [
"print(f\"shape is {df.shape} and there are {df.isna().sum()} NAs\")\n",
"print(df.columns)\n",
"#columns = [\"Unnamed: 0\", \"suffix\", \"nickname, \"]"
]
},
{
"cell_type": "code",
"execution_count": 124,
"metadata": {},
"outputs": [],
"source": [
"df.to_csv(\"./customer_profile_marketing.csv\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df.head(10)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from sklearn.model_selection import train_test_split\n",
"from sklearn.cluster import KMeans, AgglomerativeClustering\n",
"from sklearn.feature_extraction.text import TfidfVectorizer\n",
"from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
"import seaborn as sns\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"import seaborn as sns\n",
"import matplotlib.pyplot as plt\n",
"from datetime import datetime\n",
"\n",
"# Drop irrelevant columns\n",
"df_bak = df.copy()\n",
"df = df_bak\n",
"\n",
"# Handle missing values\n",
"df['middle_name'].fillna('None', inplace=True)\n",
"df['suffix'].fillna('None', inplace=True)\n",
"\n",
"# Feature engineering - calculate age\n",
"df['birthday'] = pd.to_datetime(df['birthday'])\n",
"#df['age'] = (pd.Timestamp.now() - df['birthday']).astype('<m8[ns]')\n",
"\n",
"# Categorical encoding\n",
"df = pd.get_dummies(df, columns=['gender', 'party', 'state', 'type'])\n",
"\n",
"# Drop columns with all missing values (like washington_post_id.1)\n",
"df.dropna(axis=1, how='all', inplace=True)\n",
"\n",
"# Chart age before normalization\n",
"sns.boxplot(x=df['age'])\n",
"plt.title('Boxplot of Age to Detect Outliers')\n",
"plt.show()\n",
"\n",
"# Remove outliers for the age column (optional, if outliers are detected)\n",
"q_low = df['age'].quantile(0.1)\n",
"q_high = df['age'].quantile(0.90)\n",
"#df_filtered = df[(df['age'] > q_low) & (df['age'] < q_high)]\n",
"\n",
"# Visualization - Distribution of Age with limited bins\n",
"sns.histplot(df['age']) # Reduced bins for better performance\n",
"plt.title('Distribution of Age')\n",
"plt.xlabel('Age')\n",
"plt.ylabel('Frequency')\n",
"plt.show()\n",
"\n",
"\n",
"# Normalize continuous variables\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import numpy as np\n",
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
"from datetime import datetime\n",
"\n",
"# Drop irrelevant columns and duplicates\n",
"critical_columns = ['last_name', 'first_name', 'age', 'gender', 'state', 'district', \\\n",
" 'party', 'twitter', 'facebook', 'youtube']\n",
"\n",
"# Handle missing values\n",
"df['middle_name'].fillna('None', inplace=True)\n",
"df['suffix'].fillna('None', inplace=True)\n",
"print(\"Suffix and middle name filled with 'None'\")\n",
"\n",
"# Feature engineering - calculate age\n",
"\n",
"# Ensure 'birthday' is in datetime format\n",
"df['birthday'] = pd.to_datetime(df['birthday']).dt.floor('D')\n",
"\n",
"# Calculate the current date\n",
"today = pd.Timestamp.now().normalize()\n",
"\n",
"# Calculate age in years\n",
"df['age'] = today.year - df['birthday'].dt.year\n",
"print(df['age'][0:3])\n",
"# Select only critical columns\n",
"df_reduced = df.copy()\n",
"df_reduced = df[critical_columns]\n",
"print(df_reduced.columns)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# Categorical encoding with LabelEncoder for binary categories\n",
"label_encoder = LabelEncoder()\n",
"df_reduced['gender'] = label_encoder.fit_transform(df_reduced['gender'])\n",
"\n",
"# Categorical encoding with OneHotEncoder for multi-class categories\n",
"df_reduced = pd.get_dummies(df_reduced, columns=['state', 'party', 'district'])\n",
"\n",
"# Handle online presence as binary features (e.g., presence/absence of account)\n",
"df_reduced['twitter'] = df_reduced['twitter'].notna().astype(int)\n",
"df_reduced['facebook'] = df_reduced['facebook'].notna().astype(int)\n",
"df_reduced['youtube'] = df_reduced['youtube'].notna().astype(int)\n",
"\n",
"# Normalize continuous variables\n",
"scaler = StandardScaler()\n",
"df_reduced[['age']] = scaler.fit_transform(df_reduced[['age']])\n",
"\n",
"# Visualization of the reduced dataframe\n",
"print(\"Reduced DataFrame:\")\n",
"print(df_reduced.head())\n",
"\n",
"# Correlation matrix to understand the relationship between features\n",
"import seaborn as sns\n",
"import matplotlib.pyplot as plt\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"# Missing data visualization\n",
"plt.figure(figsize=(12,8))\n",
"sns.heatmap(df.isnull(), cbar=False, cmap='viridis')\n",
"plt.title('Missing Data Heatmap')\n",
"plt.show()\n",
"\n",
"# Categorical distribution of gender\n",
"sns.countplot(x='gender_M', data=df)\n",
"plt.title('Distribution of Gender')\n",
"plt.xlabel('Gender (1 = Male, 0 = Female)')\n",
"plt.ylabel('Count')\n",
"plt.show()\n",
"\n",
"# Distribution by Party\n",
"sns.countplot(x='party', data=df)\n",
"plt.title('Distribution by Party')\n",
"plt.xlabel('Party')\n",
"plt.ylabel('Count')\n",
"plt.show()\n",
"\n",
"plt.figure(figsize=(12,8))\n",
"sns.heatmap(df.corr(), annot=True, fmt='.2f', cmap='coolwarm')\n",
"plt.title('Correlation Matrix')\n",
"plt.show()\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|