Skip to content

Commit

Permalink
fix: πŸ› Enhance Models code snippets
Browse files Browse the repository at this point in the history
βœ… Closes: #361
  • Loading branch information
yashksaini-coder committed Nov 7, 2024
1 parent 9411066 commit ef7014c
Show file tree
Hide file tree
Showing 10 changed files with 352 additions and 49 deletions.
14 changes: 12 additions & 2 deletions pysnippets/models/CV_means.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression
import logging

class CVMeansModel:
"""Model to compute cross-validation mean score for Linear Regression."""

def __init__(self):
self.model = LinearRegression()
self.logger = logging.getLogger(__name__)
self.logger.info("Initialized LinearRegression model.")

def cross_val_mean(self, X, y, cv=5):
return np.mean(cross_val_score(self.model, X, y, cv=cv))
def cross_val_mean(self, X: np.ndarray, y: np.ndarray, cv: int = 5) -> float:
"""Compute the mean cross-validation score."""
try:
return np.mean(cross_val_score(self.model, X, y, cv=cv))
except Exception as e:
self.logger.error(f"Error during cross-validation: {e}")
raise
40 changes: 34 additions & 6 deletions pysnippets/models/Catboost.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,43 @@
import numpy as np
from catboost import CatBoostRegressor
import logging

class CatBoostModel:
"""
CatBoost regression model.
"""
def __init__(self):
self.model = CatBoostRegressor(silent=True)
self.logger = logging.getLogger(__name__)
self.logger.info("Initialized CatBoostRegressor.")

def fit(self, X, y):
self.model.fit(X, y)
def fit(self, X: np.ndarray, y: np.ndarray) -> None:
"""
Fit the CatBoost model to the data.
"""
try:
self.model.fit(X, y)
self.logger.info("Model fitting successful.")
except Exception as e:
self.logger.error(f"Error during model fitting: {e}")
raise

def predict(self, X):
return self.model.predict(X)
def predict(self, X: np.ndarray) -> np.ndarray:
"""
Predict using the CatBoost model.
"""
try:
return self.model.predict(X)
except Exception as e:
self.logger.error(f"Error during prediction: {e}")
raise

def score(self, X, y):
return self.model.score(X, y)
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""
Score the CatBoost model.
"""
try:
return self.model.score(X, y)
except Exception as e:
self.logger.error(f"Error during scoring: {e}")
raise
61 changes: 55 additions & 6 deletions pysnippets/models/Ensemble.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,64 @@
import numpy as np
from sklearn.ensemble import RandomForestClassifier
import logging

class EnsembleModel:
"""
Ensemble model using RandomForestClassifier.
"""

def __init__(self):
"""
Initialize the EnsembleModel with a RandomForestClassifier.
"""
self.model = RandomForestClassifier()
self.logger = logging.getLogger(__name__)
self.logger.info("Initialized RandomForestClassifier.")

def fit(self, X: np.ndarray, y: np.ndarray) -> None:
"""
Fit the RandomForestClassifier model to the data.
Parameters:
X (np.ndarray): The feature matrix.
y (np.ndarray): The target vector.
"""
try:
self.model.fit(X, y)
self.logger.info("Model fitting successful.")
except Exception as e:
self.logger.error(f"Error during model fitting: {e}")
raise

def predict(self, X: np.ndarray) -> np.ndarray:
"""
Predict using the RandomForestClassifier model.
Parameters:
X (np.ndarray): The feature matrix.
Returns:
np.ndarray: The predicted values.
"""
try:
return self.model.predict(X)
except Exception as e:
self.logger.error(f"Error during prediction: {e}")
raise

def fit(self, X, y):
self.model.fit(X, y)
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""
Score the RandomForestClassifier model.
def predict(self, X):
return self.model.predict(X)
Parameters:
X (np.ndarray): The feature matrix.
y (np.ndarray): The target vector.
def score(self, X, y):
return self.model.score(X, y)
Returns:
float: The model's score.
"""
try:
return self.model.score(X, y)
except Exception as e:
self.logger.error(f"Error during scoring: {e}")
raise
42 changes: 37 additions & 5 deletions pysnippets/models/Grid_search.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,47 @@
import numpy as np
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
import logging

class GridSearchModel:
"""
Grid search model for Logistic Regression.
"""

def __init__(self):
"""
Initialize the GridSearchModel with a LogisticRegression model and a parameter grid.
"""
self.model = LogisticRegression()
self.param_grid = {'C': [0.1, 1, 10]}
self.grid_search = GridSearchCV(self.model, self.param_grid)
self.logger = logging.getLogger(__name__)
self.logger.info("Initialized LogisticRegression model with GridSearchCV.")

def fit(self, X: np.ndarray, y: np.ndarray) -> None:
"""
Fit the GridSearchCV to the data.
Parameters:
X (np.ndarray): The feature matrix.
y (np.ndarray): The target vector.
"""
try:
self.grid_search.fit(X, y)
self.logger.info("Grid search fitting successful.")
except Exception as e:
self.logger.error(f"Error during grid search fitting: {e}")
raise

def fit(self, X, y):
self.grid_search.fit(X, y)
def best_params(self) -> dict:
"""
Retrieve the best parameters found by grid search.
def best_params(self):
return self.grid_search.best_params_
Returns:
dict: A dictionary containing the best parameters.
"""
try:
return self.grid_search.best_params_
except Exception as e:
self.logger.error(f"Error retrieving best parameters: {e}")
raise
47 changes: 42 additions & 5 deletions pysnippets/models/KMeans.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,49 @@
import numpy as np
from sklearn.cluster import KMeans
import logging

class KMeansModel:
def __init__(self, n_clusters=3):
"""
KMeans clustering model.
"""

def __init__(self, n_clusters: int = 3):
"""
Initialize the KMeansModel with a specified number of clusters.
Parameters:
n_clusters (int): The number of clusters to form and the number of centroids to generate.
"""
self.model = KMeans(n_clusters=n_clusters)
self.logger = logging.getLogger(__name__)
self.logger.info(f"Initialized KMeans with n_clusters={n_clusters}.")

def fit(self, X: np.ndarray) -> None:
"""
Fit the KMeans model to the data.
Parameters:
X (np.ndarray): The feature matrix.
"""
try:
self.model.fit(X)
self.logger.info("Model fitting successful.")
except Exception as e:
self.logger.error(f"Error during model fitting: {e}")
raise

def predict(self, X: np.ndarray) -> np.ndarray:
"""
Predict cluster indices for samples.
def fit(self, X):
self.model.fit(X)
Parameters:
X (np.ndarray): The feature matrix.
def predict(self, X):
return self.model.predict(X)
Returns:
np.ndarray: The predicted cluster indices.
"""
try:
return self.model.predict(X)
except Exception as e:
self.logger.error(f"Error during prediction: {e}")
raise
32 changes: 26 additions & 6 deletions pysnippets/models/LightGBM.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,35 @@
import numpy as np
import lightgbm as lgb
import logging

class LightGBMModel:
"""LightGBM regression model."""
def __init__(self):
self.model = lgb.LGBMRegressor()
self.logger = logging.getLogger(__name__)
self.logger.info("Initialized LGBMRegressor.")

def fit(self, X, y):
self.model.fit(X, y)
def fit(self, X: np.ndarray, y: np.ndarray) -> None:
"""Fit the LightGBM model to the data."""
try:
self.model.fit(X, y)
self.logger.info("Model fitting successful.")
except Exception as e:
self.logger.error(f"Error during model fitting: {e}")
raise

def predict(self, X):
return self.model.predict(X)
def predict(self, X: np.ndarray) -> np.ndarray:
"""Predict using the LightGBM model."""
try:
return self.model.predict(X)
except Exception as e:
self.logger.error(f"Error during prediction: {e}")
raise

def score(self, X, y):
return self.model.score(X, y)
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""Score the LightGBM model."""
try:
return self.model.score(X, y)
except Exception as e:
self.logger.error(f"Error during scoring: {e}")
raise
61 changes: 55 additions & 6 deletions pysnippets/models/Linear_regression.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,64 @@
import numpy as np
from sklearn.linear_model import LinearRegression
import logging

class LinearModel:
"""
Linear Regression model.
"""

def __init__(self):
"""
Initialize the LinearModel with a LinearRegression model.
"""
self.model = LinearRegression()
self.logger = logging.getLogger(__name__)
self.logger.info("Initialized LinearRegression model.")

def fit(self, X: np.ndarray, y: np.ndarray) -> None:
"""
Fit the Linear Regression model to the data.
Parameters:
X (np.ndarray): The feature matrix.
y (np.ndarray): The target vector.
"""
try:
self.model.fit(X, y)
self.logger.info("Model fitting successful.")
except Exception as e:
self.logger.error(f"Error during model fitting: {e}")
raise

def predict(self, X: np.ndarray) -> np.ndarray:
"""
Predict using the Linear Regression model.
Parameters:
X (np.ndarray): The feature matrix.
Returns:
np.ndarray: The predicted values.
"""
try:
return self.model.predict(X)
except Exception as e:
self.logger.error(f"Error during prediction: {e}")
raise

def fit(self, X, y):
self.model.fit(X, y)
def score(self, X: np.ndarray, y: np.ndarray) -> float:
"""
Score the Linear Regression model.
def predict(self, X):
return self.model.predict(X)
Parameters:
X (np.ndarray): The feature matrix.
y (np.ndarray): The target vector.
def score(self, X, y):
return self.model.score(X, y)
Returns:
float: The model's score.
"""
try:
return self.model.score(X, y)
except Exception as e:
self.logger.error(f"Error during scoring: {e}")
raise
Loading

0 comments on commit ef7014c

Please sign in to comment.