Spaces:
Sleeping
Sleeping
Commit ·
35a6d7e
1
Parent(s): 722cfc4
Oracle
Browse files60 unmodified lines616263646566671 unmodified line6970717273747576777879808182838485868788899091929394959697989910010110210310410510610725 unmodified lines13313413513613713818 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713722 unmodified lines3753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354361 unmodified line4384394404414424434444454464474484494504514524534544554564574584594604614624634644654662 unmodified lines4694704714724734744752 unmodified lines4784794804814824834844854864874883 unmodified lines49249349449549649749849910 unmodified lines51051151251351451551651751851952052160 unmodified lines# Configure logging to file and consolelogging.basicConfig(handlers=[logging.FileHandler("deepfundingoracle.log"),logging.StreamHandler(sys.stdout)],level=logging.INFO,1 unmodified line)def add_temporal_and_ratio_features(df):"""Adds:- days_since_update: days between last GitHub update and today- closed_issue_ratio: ratio of closed to total issues- (Optional) merged_pull_ratio: if you have merged_pulls count"""df['activity'] = pd.to_datetime(df['activity'], errors='coerce')today = pd.to_datetime('today')df['days_since_update'] = (today - df['activity']).dt.days.fillna((today - df['activity'].median()).days)# closed_issue_ratio: assuming open_issues includes all and closed = total - opendf['closed_issue_ratio']= 0total_issues = (df['open_issues']/ (1- 0.5)).replace([np.inf, -np.inf], np.nan)df['closed_issue_ratio'] = ((total_issues - df['open_issues']).fillna(0)/ total_issues.fillna(1))df['closed_issue_ratio'] = df['closed_issue_ratio'].clip(0, 1)# merged_pull_ratio: if you have merged_pulls countdf['merged_pull_ratio'] = df['merged_pulls'].clip(lower=0)/ df['pulls'].clip(lower=1)return df############################### GitHub API helper: Fetch repository metrics##############################def fetch_repo_metrics(repo_url):"""RATIONALE (Recommendation 2): Fetches GitHub metrics, handling API pagination to get accuratecontributor and pull request counts instead of the default cap of 30. This provides muchmore accurate features for popular repositories."""default_metrics = {"stars": 0, "forks": 0, "watchers": 0, "open_issues": 0, "pulls": 0, "activity": pd.NaT,"contributors": 0}try:m = re.search(r"github\.com/([^/]+)/([^/]+)", repo_url)if not m:logging.warning(f"Malformed GitHub URL: {repo_url}")return default_metrics25 unmodified lines"watchers": data.get("subscribers_count", 0), # subscribers_count is a better 'watch' metric"open_issues": data.get("open_issues_count", 0),"activity": pd.to_datetime(data.get("updated_at")),"contributors": get_count_from_pagination(data['contributors_url'], headers),"pulls": get_count_from_pagination(data['pulls_url'].replace('{/number}', ''), headers)}18 unmodified linesand 'stars_per_contributor' to give the model more powerful signals to learn from."""logging.info("Engineering derived features...")df['activity'] = pd.to_datetime(df['activity'], errors='coerce')df['days_since_update'] = (pd.Timestamp.now(tz='UTC') - df['activity']).dt.daysdf['days_since_update'].fillna(df['days_since_update'].median(), inplace=True)df['stars_per_contributor'] = df['stars'] / df['contributors'].clip(lower=1)df['forks_per_star'] = df['forks'] / df['stars'].clip(lower=1)numeric_cols = df.select_dtypes(include=np.number).columnsdf[numeric_cols] = df[numeric_cols].fillna(0)return dfdef calculate_fallback_weights(df):"""Dynamically calculate fallback feature weights based on feature variance."""print("[INFO] Calculating fallback feature weights...")numeric_cols = ['stars', 'forks', 'watchers', 'open_issues', 'pulls', 'contributors', 'dependencies_count']# Filter to only include columns that exist in the DataFramevalid_cols = [col for col in numeric_cols if col in df.columns]# Create default weightsdefault_weights = {'stars': 0.3,'forks': 0.2,'watchers': 0.2,'open_issues': 0.1,'pulls': 0.1,'contributors': 0.05,'dependencies_count': 0.05}# If any data exists, calculate variance-based weightsif len(valid_cols) > 0 and df[valid_cols].sum().sum() > 0:# Calculate variance for each featurefeature_variances = df[valid_cols].var()total_variance = feature_variances.sum()# If meaningful variance exists, use it for weightsif total_variance > 0:weights = {col: var / total_variance for col, var in feature_variances.items()}# Normalize to ensure sum is 1.0sum_weights = sum(weights.values())if sum_weights > 0:weights = {k: v / sum_weights for k, v in weights.items()}return weights# Return default weights if we couldn't calculate meaningful onesprint("[INFO] Using default fallback weights")return default_weights############################### Feature Extraction##############################def load_data(file):"""Dynamically load the dependency data CSV from the uploaded file.Expects at least "repo" and "parent" columns."""try:print("[INFO] Loading data from uploaded file...")start_time = time.time()# Read the uploaded file directly into a DataFramedf = pd.read_csv(file)end_time = time.time()print(f"[INFO] Data loaded successfully in {end_time - start_time:.2f} seconds.")return dfexcept Exception as e:print("[ERROR] Error loading data:", e)return Nonedef timeout_handler(signum, frame):raise TimeoutError("LLama model prediction timed out.")def assign_base_weight(df):"""Assigns a robust `base_weight` using an LLM with a specific persona and JSON output,then applies log transformation before normalization."""logging.info("Assigning robust base weights using LLM...")oracle = SmolLM()# RATIONALE (Recommendation 1): This prompt is highly specific. It sets a persona (VC), defines# the goal (assess health), prioritizes metrics, and demands a strict JSON output. This# leads to a much higher quality and more reliable response from the LLM.prompt = ("As an expert venture capitalist specializing in open-source software, your goal is to assess a project's ""overall health, community engagement, and development velocity. Based on this, assign a numeric importance ""weight to each of the following GitHub metrics: 'stars', 'forks', 'watchers', 'open_issues', 'pulls', ""'contributors', and 'days_since_update'. ""Prioritize metrics indicating active, collaborative development (like contributors, pulls, recent updates) ""over simple popularity metrics (like stars). The 'days_since_update' metric is inverse; lower is better, so it should have a negative weight. ""The absolute values of the weights should sum to approximately 1. ""Provide your answer ONLY in a strict JSON format. Example: "'{"stars": 0.2, "forks": 0.1, "watchers": 0.05, "pulls": 0.2, "open_issues": 0.1, "contributors": 0.25, "days_since_update": -0.1}')feature_weights = Nonetry:response_text = oracle.predict(prompt)json_match = re.search(r'\{.*\}', response_text, re.DOTALL)if not json_match: raise ValueError("No JSON object found in the LLM response.")feature_weights = json.loads(json_match.group(0))logging.info(f"Successfully parsed feature weights from LLM: {feature_weights}")except Exception as e:logging.error(f"Failed to parse LLM response, using fallback weights. Error: {e}")feature_weights = {'stars': 0.15, 'forks': 0.1, 'watchers': 0.05, 'pulls': 0.25, 'open_issues': 0.1,'contributors': 0.25, 'days_since_update': -0.1}df["base_weight_raw"] = sum(df[feature] * weight for feature, weight in feature_weights.items() if feature in df)# RATIONALE (Recommendation 1): Log-transforming the raw score before scaling prevents extreme# outliers from dominating the normalization process, creating a more stable target variable.df['base_weight_log'] = np.log1p(df['base_weight_raw'] - df['base_weight_raw'].min())df['base_weight'] = df.groupby("parent")["base_weight_log"].transform(lambda s: (s - s.min()) / (s.max() - s.min() if s.max() > s.min() else 1)).fillna(0.5)return dfdef sanity_check_weights(df):"""Sanity-checks LLM weights by comparing them with other metrics."""print("[INFO] Performing sanity check on LLM weights...")df["sanity_check_weight"] = (df["stars"] + df["forks"] + df["watchers"]) / 3df["ensemble_weight"] = (df["base_weight"] + df["sanity_check_weight"]) / 2print("[INFO] Sanity check and ensemble weights added.")return dfdef visualize_feature_distributions(df):"""Visualizes feature distributions and correlations."""print("[INFO] Visualizing feature distributions and correlations...")if not plt or not sns:print("[ERROR] Matplotlib or Seaborn not available for visualization.")returnnumeric_cols = df.select_dtypes(include=[np.number]).columns# Plot feature distributionsdf[numeric_cols].hist(bins=20, figsize=(15, 10), color="skyblue", edgecolor="black")plt.suptitle("Feature Distributions", fontsize=16)plt.show()# Plot feature correlationscorrelation_matrix = df[numeric_cols].corr()plt.figure(figsize=(12, 8))sns.heatmap(correlation_matrix, annot=True, cmap="coolwarm", fmt=".2f", linewidths=0.5)plt.title("Feature Correlation Matrix", fontsize=16)plt.show()def normalize_and_clip_weights(df, group_col="parent", weight_col="final_weight"):"""Ensures weights are non-negative and sum to 1 per group."""if df is None:raise ValueError("DataFrame is None, cannot normalize weights.")if weight_col not in df.columns:raise KeyError(f"`{weight_col}` column not found in DataFrame.")# Clip negativesdf[weight_col] = df[weight_col].clip(lower=0)# Normalize within each groupdef normalize_group(x):total = x.sum()if total > 0:return x / totalreturn np.ones_like(x) / len(x)df[weight_col] = df.groupby(group_col)[weight_col].transform(normalize_group)return dfdef normalize_funding(df):"""Normalize funding weights for child repositories grouped by parent."""print("[INFO] Normalizing funding weights...", flush=True)if df is None or df.empty:print("[WARN] Skipping normalization: DataFrame is None or empty.", flush=True)return dfdf = normalize_and_clip_weights(df)print("[INFO] Funding weights normalized successfully.", flush=True)return dfdef prepare_dataset(file):print("[INFO] Starting dataset preparation...")start_time = time.time()df = load_data(file)if df is None:raise ValueError("Failed to load data.")if not {"repo", "parent"}.issubset(df.columns):raise ValueError("Input CSV must contain 'repo' and 'parent' columns.")print("[INFO] Fetching GitHub features...")df = fetch_github_features(df)print("[INFO] GitHub features fetched successfully.")print("[INFO] Cleaning data...")df = clean_data(df)print("[INFO] Data cleaned successfully.")print("[INFO] Assigning base weights using LLama model...")df = assign_base_weight(df)df = sanity_check_weights(df) # Add sanity-check and ensemble weightsdf = train_predict_weight(df)if df is not None and not df.empty:visualize_feature_distributions(df)else:print("[WARN] DataFrame is empty after processing. Skipping visualization.")df = normalize_funding(df)end_time = time.time()print(f"[INFO] Dataset preparation completed in {end_time - start_time:.2f} seconds.")return df2 unmodified lines##############################def clean_data(df):"""Cleans the input DataFrame by handling missing values and removing outliers."""# Impute missing valuesdf.fillna(df.median(numeric_only=True), inplace=True)# Remove extreme outliers using quantilesfor col in df.select_dtypes(include=[np.number]).columns:q1 = df[col].quantile(0.25)q3 = df[col].quantile(0.75)iqr = q3 - q1lower_bound = q1 - 1.5 * iqrupper_bound = q3 + 1.5 * iqrdf[col] = df[col].clip(lower=lower_bound, upper=upper_bound)return df############################### Feature Validation and Scaling##############################def validate_features(df):"""Validates and scales features to ensure they are meaningful for model training."""print("[INFO] Validating and scaling features...")numeric_cols = df.select_dtypes(include=[np.number]).columnsfor col in numeric_cols:df[col]= log1p(df[col].clip(lower=0))scaler = StandardScaler()# Scale numeric featuresdf[numeric_cols] = scaler.fit_transform(df[numeric_cols])print("[INFO] Features scaled successfully.")return dfdef validate_target(df):"""Validates the target variable to ensure it has sufficient variance.If variance is insufficient, adds small random noise to create variance."""print("[INFO] Validating target variable 'base_weight'...")target = "base_weight"if target not in df.columns:raise ValueError(f"Target variable '{target}' not found in DataFrame.")variance = df[target].var()print(f"[DEBUG] Target variable variance: {variance}")if variance < 1e-6:print("[WARN] Target variable has insufficient variance. Adding small random noise...")# Add small random noise to introduce variancenp.random.seed(42) # For reproducibilitynoise = np.random.normal(0.5, 0.1, size=len(df))df[target] = noiseprint(f"[INFO] New target variable variance: {df[target].var()}")return df############################### Model Training and Prediction##############################1 unmodified line"""Trains an XGBoost Regressor with GroupKFold cross-validation and extensive hyperparameter tuning."""logging.info("Starting model training with GroupKFold validation...")target_col = 'base_weight'drop_cols = ["repo", "parent", "activity", "base_weight_raw", "base_weight_log", target_col]feature_cols = [col for col in df.select_dtypes(include=np.number).columns if col not in drop_cols]X = df[feature_cols].copy()y = df[target_col]groups = df['parent']# RATIONALE (Recommendation 2): Log-transforming skewed input features helps the model by# making their distributions more normal, improving the performance of the regressor.skewed_features = ['stars', 'forks', 'watchers', 'open_issues', 'pulls', 'contributors', 'stars_per_contributor']for col in skewed_features:if col in X.columns:X[col] = np.log1p(X[col])pipeline = Pipeline([("scaler", RobustScaler()),("xgb", XGBRegressor(objective="reg:squarederror", n_jobs=-1, random_state=42, verbosity=0))])param_dist = {'xgb__n_estimators': [100, 300, 500, 700], 'xgb__max_depth': [3, 5, 7, 9],'xgb__learning_rate': [0.01, 0.02, 0.05, 0.1], 'xgb__subsample': [0.6, 0.7, 0.8, 0.9],'xgb__colsample_bytree': [0.6, 0.7, 0.8, 0.9]}# RATIONALE (Recommendation 3): GroupKFold ensures that all repos from the same parent are in the# same fold. This prevents data leakage and gives a realistic measure of true performance.2 unmodified lines# RATIONALE (Recommendation 4): Increasing n_iter explores more hyperparameter combinations,# increasing the chance of finding a better-performing model.search = RandomizedSearchCV(pipeline, param_distributions=param_dist, n_iter=50, cv=cv.split(X, y, groups),scoring="neg_root_mean_squared_error", verbose=1, n_jobs=-1, random_state=42)search.fit(X, y)2 unmodified lineslogging.info(f"Best CV score (neg RMSE): {search.best_score_:.4f}")logging.info(f"Best parameters found: {search.best_params_}")df['final_weight'] = best_model.predict(X)df['final_weight'] = df['final_weight'].clip(lower=0)df['final_weight'] = df.groupby("parent")['final_weight'].transform(lambda w: w / w.sum() if w.sum() > 0 else np.ones_like(w) / len(w))return df3 unmodified lines##############################def create_submission_csv(df, output_filename="submission.csv"):"""Saves the final predictions to a CSV file."""logging.info(f"Writing final results to {output_filename}...")df[["repo", "parent", "final_weight"]].to_csv(output_filename, index=False)logging.info(f"Successfully created {output_filename}.")10 unmodified lineslogging.info("--- Starting DeepFunding Oracle - Enhanced Process ---")# Execute the full pipelinemain_df = pd.read_csv(input_file)main_df = fetch_github_features(main_df)main_df = add_derived_features(main_df)main_df = assign_base_weight(main_df)main_df = train_predict_weight(main_df)create_submission_csv(main_df, output_file)logging.info("--- Process Completed Successfully ---")60 unmodified lines616263646566671 unmodified line697071727374757677787980818283848586878889909192939425 unmodified lines12012112212312412512618 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522 unmodified lines2552562572582592602612622632642652662672682692702712722732742752762771 unmodified line2792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143152 unmodified lines3183193203213223233242 unmodified lines3273283293303313323333343353363 unmodified lines34034134234334434534634734834910 unmodified lines36036136236336436536636736836937037137260 unmodified lines# Configure logging to file and consolelogging.basicConfig(handlers=[logging.FileHandler("deepfundingoracle.log", mode='w'),logging.StreamHandler(sys.stdout)],level=logging.INFO,1 unmodified line)############################### GitHub API helper: Fetch repository metrics##############################def fetch_repo_metrics(repo_url):"""Fetches GitHub metrics, handling API pagination to get accuratecontributor and pull request counts."""default_metrics = {"stars": 0,"forks": 0,"watchers": 0,"open_issues": 0,"pulls": 0,"activity": pd.NaT,"created_at":pd.NaT,"contributors": 0}try:m = re.search(r"github.com/([^/]+)/([^/]+)", repo_url)if not m:logging.warning(f"Malformed GitHub URL: {repo_url}")return default_metrics25 unmodified lines"watchers": data.get("subscribers_count", 0), # subscribers_count is a better 'watch' metric"open_issues": data.get("open_issues_count", 0),"activity": pd.to_datetime(data.get("updated_at")),"created_at": pd.to_datetime(data.get("created_at")),"contributors": get_count_from_pagination(data['contributors_url'], headers),"pulls": get_count_from_pagination(data['pulls_url'].replace('{/number}', ''), headers)}18 unmodified linesand 'stars_per_contributor' to give the model more powerful signals to learn from."""logging.info("Engineering derived features...")# Handle timestampdf['activity'] = pd.to_datetime(df['activity'], errors='coerce',utc=True)df['created_at'] = pd.to_datetime(df['created_at'], errors='coerce', utc=True)# Temporal featuresnow = pd.Timestamp.now(tz='UTC')df['days_since_update'] = (now - df['activity']).dt.daysdf['repo_age_days'] = (now - df['created_at']).dt.days#Interactions and Ratio Featuresdf['stars_per_contributor'] = df['stars'] / df['contributors'].clip(lower=1)df['forks_per_star'] = df['forks'] / df['stars'].clip(lower=1)df ['pulls_per_contributor'] = df['pulls'] / df['contributors'].clip(lower=1)df['stars_per_day'] = df['stars']/df['repo_age_days'].clip(lower=1)#Dependency featuresdf['dependencies_count']= df.groupby('parent')['repo'].transform('count')numeric_cols = df.select_dtypes(include=np.number).columnsdf[numeric_cols] = df[numeric_cols].fillna(df[numeric_cols].median())return df############################### Feature Extraction##############################def assign_base_weight_per_row(row, oracle):"""RATIONALE: Asks the LLM to score each repo individually on a 0-1 scale based on its specific stats.This creates a much more accurate and nuanced target variable `base_weight` for the XGBoost model."""stats = (f"Stars: {int(row.get('stars', 0))}, "f"Contributors: {int(row.get('contributors', 0))}, "f"Pull Requests: {int(row.get('pulls', 0))}, "f"Days Since Last Update: {int(row.get('days_since_update', 0))}, "f"Repo Age (Days): {int(row.get('repo_age_days', 0))}")# <<< UPDATED: The prompt now asks for a score on a 0.0 to 1.0 scale. >>>prompt = ("You are a venture capitalist analyzing open-source projects for the Ethereum ecosystem. "f"A project named '{row['repo'].split('/')[-1]}' is a dependency of '{row['parent'].split('/')[-1]}'. ""Here are its key metrics: "f"[{stats}]. ""Based on these metrics, evaluate its standalone importance, community health, and development velocity. ""On a scale of 0.0 (minor, easily replaceable utility) to 1.0 (critical, foundational dependency), how would you score this project's value to its parent? ""Provide ONLY the numeric score in your answer. Example: 0.8")try:response = oracle.predict(prompt, max_new_tokens=10)match = re.search(r"(\d+(\.\d+)?)", response)if match:return max(0.0, min(1.0, float(match.group(1))))logging.warning(f"Could not parse score from LLM for {row['repo']}. Defaulting.")return 0.4except Exception as e:logging.error(f"LLM prediction failed for {row['repo']}: {e}. Defaulting.")return 0.4def generate_all_base_weights(df):"""Applies the per-row LLM evaluation to the entire dataframe."""logging.info("Assigning robust base weights using per-row LLM evaluation...")oracle = SmolLM()if not oracle.available:logging.error("Oracle (LLM) is not available. Falling back to composite score.")df['base_weight'] = (np.log1p(df['stars']) * 0.4 +np.log1p(df['contributors']) * 0.4 +np.log1p(df['pulls']) * 0.2)return dfdf['base_weight'] = df.progress_apply(lambda row: assign_base_weight_per_row(row, oracle), axis=1)# This normalization step is kept as a crucial safeguard. It ensures the final `base_weight`# is scaled relative to its siblings, even if the LLM isn't perfectly calibrated.df['base_weight'] = df.groupby("parent")["base_weight"].transform(lambda s: (s - s.min()) / (s.max() - s.min() if s.max() > s.min() else 0.0)).fillna(0.5)return dfdef normalize_and_clip_weights(df, group_col="parent", weight_col="final_weight"):"""Ensures final weights are non-negative and sum to 1 per group."""logging.info("Normalizing final weights...")df[weight_col] = df[weight_col].clip(lower=0)group_sums = df.groupby(group_col)[weight_col].transform('sum')# Normalize where sum > 0df[weight_col] = np.where(group_sums > 0, df[weight_col] / group_sums, 0)# Handle groups where the sum was 0 by distributing weight equallyzero_sum_parents = df[group_sums == 0][group_col].unique()for parent in zero_sum_parents:mask = df[group_col] == parentcount = mask.sum()if count > 0:df.loc[mask, weight_col] = 1 / countreturn df2 unmodified lines##############################def clean_data(df):"""INTEGRATED: Cleans the DataFrame by imputing missing values and clipping extremeoutliers, which helps stabilize the model."""logging.info("Cleaning data and handling outliers...")numeric_cols = df.select_dtypes(include=np.number).columnsfor col in numeric_cols:df[col].fillna(df[col].median(), inplace=True)# REFINED: Clip outliers using a wider percentile range (5% and 95%) which is often# more suitable for heavily skewed data like GitHub stats.for col in numeric_cols:if col not in ['repo_age_days', 'days_since_update']: # Don't clip age featuresq_low = df[col].quantile(0.05)q_high = df[col].quantile(0.95)df[col] = df[col].clip(q_low, q_high)return df############################### Model Training and Prediction##############################1 unmodified line"""Trains an XGBoost Regressor with GroupKFold cross-validation and extensive hyperparameter tuning."""logging.info("Starting model training...")target_col = 'base_weight'if target_col not in df.columns or df[target_col].isnull().all():logging.error("Target column 'base_weight' is missing or all null. Aborting training.")df['final_weight'] = df['stars']return dfdrop_cols = ["repo", "parent", "activity", "created_at", target_col]feature_cols = [col for col in df.select_dtypes(include=np.number).columns if col not in drop_cols]X = df[feature_cols].copy().fillna(0)y = df[target_col]groups = df['parent']# RATIONALE (Recommendation 2): Log-transforming skewed input features helps the model by# making their distributions more normal, improving the performance of the regressor.for col in X.columns:if 'ratio' not in col and 'per' not in col and 'day' not in col:X[col] = np.log1p(X[col])pipeline = Pipeline([("scaler", RobustScaler()),("xgb", XGBRegressor(objective="reg:squarederror", n_jobs=-1, random_state=42, base_score=y.mean()))])param_dist = {'xgb__n_estimators': [100, 200, 300, 500],'xgb__max_depth': [3, 5, 7],'xgb__learning_rate': [0.01, 0.05, 0.1],'xgb__subsample': [0.7, 0.8, 0.9],'xgb__colsample_bytree': [0.7, 0.8, 0.9]}# RATIONALE (Recommendation 3): GroupKFold ensures that all repos from the same parent are in the# same fold. This prevents data leakage and gives a realistic measure of true performance.2 unmodified lines# RATIONALE (Recommendation 4): Increasing n_iter explores more hyperparameter combinations,# increasing the chance of finding a better-performing model.search = RandomizedSearchCV(pipeline, param_distributions=param_dist, n_iter=25, cv=cv.split(X, y, groups),scoring="neg_root_mean_squared_error", verbose=1, n_jobs=-1, random_state=42)search.fit(X, y)2 unmodified lineslogging.info(f"Best CV score (neg RMSE): {search.best_score_:.4f}")logging.info(f"Best parameters found: {search.best_params_}")raw_predictions = best_model.predict(X)# Apply a log transformation to raw predictions to stabilize variance before normalization.df['final_weight'] = np.log1p(raw_predictions - raw_predictions.min())return df3 unmodified lines##############################def create_submission_csv(df, output_filename="submission.csv"):"""Saves the final predictions to a CSV file."""# FIXED: Changed "weight" to "final_weight" to match the calculated column.submission_df = df[["repo", "parent", "final_weight"]]logging.info(f"Writing final results to {output_filename}...")submission_df.to_csv(output_filename, index=False)logging.info(f"Successfully created {output_filename}.")10 unmodified lineslogging.info("--- Starting DeepFunding Oracle - Enhanced Process ---")main_df = pd.read_csv(input_file)main_df = fetch_github_features(main_df)main_df = add_derived_features(main_df)main_df = generate_all_base_weights(main_df) # New LLM step with corrected promptmain_df = train_predict_weight(main_df)main_df = normalize_and_clip_weights(main_df) # Final normalization stepcreate_submission_csv(main_df, output_file)logging.info("--- Process Completed Successfully ---")
Oracle/deepfundingoracle.py+127-276