File size: 12,283 Bytes
31d3380 | 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 | # import pandas as pd
# import numpy as np
# from PIL import Image
# from pathlib import Path
# from typing import List, Dict, Any, Union, Tuple, Optional
# import os
# import json
# class DataLoader:
# def __init__(self):
# self.supported_image_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']
# self.supported_text_formats = ['.txt', '.csv', '.json', '.xlsx', '.xls']
# def load_csv(self, file_path: Union[str, Path]) -> pd.DataFrame:
# return pd.read_csv(file_path)
# def load_excel(self, file_path: Union[str, Path], sheet_name: Union[str, int] = 0) -> pd.DataFrame:
# return pd.read_excel(file_path, sheet_name=sheet_name)
# def load_json(self, file_path: Union[str, Path]) -> pd.DataFrame:
# return pd.read_json(file_path)
# def load_image(self, file_path: Union[str, Path]) -> Image.Image:
# return Image.open(file_path).convert('RGB')
# def load_images_from_folder(self, folder_path: Union[str, Path]) -> List[Tuple[str, Image.Image]]:
# folder = Path(folder_path)
# images = []
# for ext in self.supported_image_formats:
# for file_path in folder.glob(f"*{ext}"):
# try:
# img = Image.open(file_path).convert('RGB')
# images.append((str(file_path), img))
# except Exception as e:
# print(f"Error loading {file_path}: {e}")
# return images
# def load_text_file(self, file_path: Union[str, Path]) -> str:
# with open(file_path, 'r', encoding='utf-8') as f:
# return f.read()
# def detect_file_type(self, file_path: Union[str, Path]) -> str:
# path = Path(file_path)
# suffix = path.suffix.lower()
# if suffix in self.supported_image_formats:
# return "image"
# elif suffix == '.csv':
# return "csv"
# elif suffix in ['.xlsx', '.xls']:
# return "excel"
# elif suffix == '.json':
# return "json"
# elif suffix == '.txt':
# return "text"
# else:
# return "unknown"
# def auto_load(self, file_path: Union[str, Path]) -> Tuple[Any, str]:
# file_type = self.detect_file_type(file_path)
# if file_type == "csv":
# return self.load_csv(file_path), "dataframe"
# elif file_type == "excel":
# return self.load_excel(file_path), "dataframe"
# elif file_type == "json":
# return self.load_json(file_path), "dataframe"
# elif file_type == "image":
# return self.load_image(file_path), "image"
# elif file_type == "text":
# return self.load_text_file(file_path), "text"
# else:
# raise ValueError(f"Unsupported file type: {file_type}")
# def get_data_summary(self, df: pd.DataFrame) -> Dict[str, Any]:
# summary = {
# "row_count": int(len(df)),
# "columns": df.columns.tolist(),
# "features": int(len(df.columns)),
# "dtypes": df.dtypes.astype(str).to_dict(),
# "missing_values": df.isnull().sum().to_dict(),
# "missing_percent": (df.isnull().sum() / len(df) * 100).round(2).to_dict(),
# "numeric_columns": df.select_dtypes(include=[np.number]).columns.tolist(),
# "categorical_columns": df.select_dtypes(include=['object', 'category']).columns.tolist(),
# "duplicate_rows": int(df.duplicated().sum()),
# }
# numeric_df = df.select_dtypes(include=[np.number])
# if not numeric_df.empty:
# summary["numeric_summary"] = {
# "mean": numeric_df.mean().round(4).to_dict(),
# "std": numeric_df.std().round(4).to_dict(),
# "min": numeric_df.min().to_dict(),
# "max": numeric_df.max().to_dict(),
# "median": numeric_df.median().to_dict(),
# }
# return summary
# def preprocess_dataframe(
# self,
# df: pd.DataFrame,
# drop_non_numeric: bool = True,
# fill_strategy: str = "median"
# ) -> pd.DataFrame:
# df = df.copy()
# df = df.dropna(axis=1, how='all')
# for col in df.columns:
# if df[col].dtype == 'object':
# try:
# df[col] = pd.to_numeric(df[col])
# except (ValueError, TypeError):
# if drop_non_numeric:
# df = df.drop(columns=[col])
# else:
# df = pd.get_dummies(df, columns=[col], drop_first=True)
# for col in df.columns:
# if df[col].isnull().any():
# if df[col].dtype in ['int64', 'float64', 'int32', 'float32']:
# if fill_strategy == "median":
# df[col] = df[col].fillna(df[col].median())
# elif fill_strategy == "mean":
# df[col] = df[col].fillna(df[col].mean())
# else:
# df[col] = df[col].fillna(0)
# elif df[col].dtype == 'bool':
# df[col] = df[col].fillna(False)
# else:
# mode_val = df[col].mode()
# df[col] = df[col].fillna(mode_val.iloc[0] if not mode_val.empty else "unknown")
# return df
# def split_features_target(
# self, df: pd.DataFrame, target_column: str
# ) -> Tuple[pd.DataFrame, pd.Series]:
# if target_column not in df.columns:
# raise ValueError(f"Target column '{target_column}' not found in dataframe")
# X = df.drop(columns=[target_column])
# y = df[target_column]
# return X, y
# def get_class_distribution(self, series: pd.Series) -> Dict[str, int]:
# return series.value_counts().to_dict()
# def detect_task_type(self, series: pd.Series) -> str:
# """Auto-detect whether classification or regression is appropriate."""
# if series.dtype == 'object' or series.nunique() <= 20:
# return "classification"
# return "regression"
import pandas as pd
import numpy as np
from PIL import Image
from pathlib import Path
from typing import List, Dict, Any, Union, Tuple, Optional
import os
import json
class DataLoader:
def __init__(self):
self.supported_image_formats = ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']
self.supported_text_formats = ['.txt', '.csv', '.json', '.xlsx', '.xls']
def load_csv(self, file_path: Union[str, Path]) -> pd.DataFrame:
return pd.read_csv(file_path)
def load_excel(self, file_path: Union[str, Path], sheet_name: Union[str, int] = 0) -> pd.DataFrame:
return pd.read_excel(file_path, sheet_name=sheet_name)
def load_json(self, file_path: Union[str, Path]) -> pd.DataFrame:
return pd.read_json(file_path)
def load_image(self, file_path: Union[str, Path]) -> Image.Image:
return Image.open(file_path).convert('RGB')
def load_images_from_folder(self, folder_path: Union[str, Path]) -> List[Tuple[str, Image.Image]]:
folder = Path(folder_path)
images = []
for ext in self.supported_image_formats:
for file_path in folder.glob(f"*{ext}"):
try:
img = Image.open(file_path).convert('RGB')
images.append((str(file_path), img))
except Exception as e:
print(f"Error loading {file_path}: {e}")
return images
def load_text_file(self, file_path: Union[str, Path]) -> str:
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()
def detect_file_type(self, file_path: Union[str, Path]) -> str:
path = Path(file_path)
suffix = path.suffix.lower()
if suffix in self.supported_image_formats:
return "image"
elif suffix == '.csv':
return "csv"
elif suffix in ['.xlsx', '.xls']:
return "excel"
elif suffix == '.json':
return "json"
elif suffix == '.txt':
return "text"
else:
return "unknown"
def auto_load(self, file_path: Union[str, Path]) -> Tuple[Any, str]:
file_type = self.detect_file_type(file_path)
if file_type == "csv":
return self.load_csv(file_path), "dataframe"
elif file_type == "excel":
return self.load_excel(file_path), "dataframe"
elif file_type == "json":
return self.load_json(file_path), "dataframe"
elif file_type == "image":
return self.load_image(file_path), "image"
elif file_type == "text":
return self.load_text_file(file_path), "text"
else:
raise ValueError(f"Unsupported file type: {file_type}")
def get_data_summary(self, df: pd.DataFrame) -> Dict[str, Any]:
summary = {
"row_count": int(len(df)),
"columns": df.columns.tolist(),
"features": int(len(df.columns)),
"dtypes": df.dtypes.astype(str).to_dict(),
"missing_values": df.isnull().sum().to_dict(),
"missing_percent": (df.isnull().sum() / len(df) * 100).round(2).to_dict(),
"numeric_columns": df.select_dtypes(include=[np.number]).columns.tolist(),
"categorical_columns": df.select_dtypes(include=['object', 'category']).columns.tolist(),
"duplicate_rows": int(df.duplicated().sum()),
}
numeric_df = df.select_dtypes(include=[np.number])
if not numeric_df.empty:
summary["numeric_summary"] = {
"mean": numeric_df.mean().round(4).to_dict(),
"std": numeric_df.std().round(4).to_dict(),
"min": numeric_df.min().to_dict(),
"max": numeric_df.max().to_dict(),
"median": numeric_df.median().to_dict(),
}
return summary
def preprocess_dataframe(
self,
df: pd.DataFrame,
drop_non_numeric: bool = True,
fill_strategy: str = "median"
) -> pd.DataFrame:
df = df.copy()
# Drop fully empty columns
df = df.dropna(axis=1, how='all')
for col in df.columns:
if df[col].dtype == 'object':
try:
df[col] = pd.to_numeric(df[col])
except (ValueError, TypeError):
if drop_non_numeric:
df = df.drop(columns=[col])
else:
df = pd.get_dummies(df, columns=[col], drop_first=True)
# Fill missing values
for col in df.columns:
if df[col].isnull().any():
if df[col].dtype in ['int64', 'float64', 'int32', 'float32']:
if fill_strategy == "median":
df[col] = df[col].fillna(df[col].median())
elif fill_strategy == "mean":
df[col] = df[col].fillna(df[col].mean())
else:
df[col] = df[col].fillna(0)
elif df[col].dtype == 'bool':
df[col] = df[col].fillna(False)
else:
mode_val = df[col].mode()
df[col] = df[col].fillna(mode_val.iloc[0] if not mode_val.empty else "unknown")
return df
def split_features_target(
self, df: pd.DataFrame, target_column: str
) -> Tuple[pd.DataFrame, pd.Series]:
if target_column not in df.columns:
raise ValueError(f"Target column '{target_column}' not found in dataframe")
X = df.drop(columns=[target_column])
y = df[target_column]
return X, y
def get_class_distribution(self, series: pd.Series) -> Dict[str, int]:
return series.value_counts().to_dict()
def detect_task_type(self, series: pd.Series) -> str:
"""Auto-detect whether classification or regression is appropriate."""
if series.dtype == 'object' or series.nunique() <= 20:
return "classification"
return "regression" |