mood.mood_modeling¶
Mood Modeling Module
This module provides tools for modeling semantic attributes (or “moods”) based on text embeddings. It allows for different modeling approaches: numerical regression, ordinal regression, and binary classification.
The main class, MoodModelingManager, handles the entire process:
Preparing different (X, y) pairs from input dataframes
Training and evaluating multiple modeling pipelines
Gathering comprehensive validation statistics
Providing a final model that outputs mood scores in the [0, 1] range
These mood scores are ordinally aligned with training scores, where higher values indicate stronger presence of the target semantic attribute.
Functions
|
Convert an object to a string path. |
|
Convert a string path to an object. |
|
Get the x and y values from a dataframe, converting y to binary values. |
Classes
|
Transformer to reduce dimensionality by selecting first n dimensions. |
|
Custom estimator that wraps an underlying model and provides methods to transform predictions to mood scores in the [0, 1] range. |
|
Manager class for building and evaluating mood models. |
|
Random Forest customized for ordinal regression. |
- class mood.mood_modeling.DimensionReducer(max_dims=None)[source]¶
Bases:
BaseEstimator,TransformerMixinTransformer to reduce dimensionality by selecting first n dimensions.
This is useful for embedding vectors where the first dimensions typically contain the most important information.
- class mood.mood_modeling.MoodEstimator(model, max_dims=None, output_transform='sigmoid', threshold=None, data_type='numerical')[source]¶
Bases:
BaseEstimator,TransformerMixinCustom estimator that wraps an underlying model and provides methods to transform predictions to mood scores in the [0, 1] range.
- fit(X, y)[source]¶
Fit the model to the data.
- Parameters:
X (
ndarray) – Input featuresy (
ndarray) – Target values
- Return type:
- Returns:
Self
- predict(X)[source]¶
Make predictions using the underlying model.
- Parameters:
X (
ndarray) – Input features- Return type:
ndarray- Returns:
Raw model predictions
- class mood.mood_modeling.MoodModelingManager(df, embedding_col='embedding', score_col='score', test_size=0.2, random_state=42, models=None, verbose=1)[source]¶
Bases:
objectManager class for building and evaluating mood models.
This class handles:
Data preparation for different model types
Training and evaluation of multiple modeling pipelines
Collection of validation statistics
Final model selection and fitting
- cross_validate_models(n_splits=5, metrics=None)[source]¶
Perform cross-validation on all models to get more stable performance metrics.
- fit_final_models()[source]¶
Fit final models on the entire dataset.
- Return type:
- Returns:
Dictionary of fitted models
- classmethod from_arrays(X, y, test_size=0.2, random_state=42, models=None, verbose=1)[source]¶
Create a MoodModelingManager directly from numpy arrays.
- Parameters:
X (
ndarray) – Array of embeddings, shape (n_samples, n_features)y (
ndarray) – Array of scores, shape (n_samples,)test_size (
float) – Proportion of data to use for testingrandom_state (
int) – Random seed for reproducibilitymodels (
dict|None) – Dictionary of modeling pipelines (uses default_models if None)verbose (
int) – Level of verbosity
- Return type:
- Returns:
MoodModelingManager instance
Example
>>> manager = MoodModelingManager.from_arrays(X, y, verbose=2) >>> results = manager.train_and_evaluate()
- get_best_model(metric='spearman', data_type=None, use_cv=False)[source]¶
Get the best model based on a specific metric.
- get_model_summary(use_cv=False, *, egress=<class 'pandas.DataFrame'>)[source]¶
Get a summary of all models and their performance.
- Parameters:
use_cv (
bool) – Whether to use cross-validation results (if available)- Returns:
DataFrame summarizing model performance
- prepare_binary_data(threshold=None, positive_labels=None, negative_labels=None)[source]¶
Prepare binary data from the dataframe.
- Parameters:
- Return type:
tuple[ndarray,ndarray]- Returns:
Tuple of (X, y) for binary classification
- class mood.mood_modeling.OrdinalRandomForest(ordinal_classes=None, **kwargs)[source]¶
Bases:
RandomForestRegressorRandom Forest customized for ordinal regression.
Predicts continuous values first, then maps them to the closest ordinal class.
- fit(X, y)[source]¶
Build a forest of trees from the training set (X, y).
- Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The training input samples. Internally, its dtype will be converted to
dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparsecsc_matrix.y (array-like of shape (n_samples,) or (n_samples, n_outputs)) – The target values (class labels in classification, real numbers in regression).
sample_weight (array-like of shape (n_samples,), default=None) – Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node.
- Returns:
self – Fitted estimator.
- Return type:
- predict(X)[source]¶
Predict regression target for X.
The predicted regression target of an input sample is computed as the mean predicted regression targets of the trees in the forest.
- Parameters:
X ({array-like, sparse matrix} of shape (n_samples, n_features)) – The input samples. Internally, its dtype will be converted to
dtype=np.float32. If a sparse matrix is provided, it will be converted into a sparsecsr_matrix.- Returns:
y – The predicted values.
- Return type:
ndarray of shape (n_samples,) or (n_samples, n_outputs)
- set_fit_request()¶
No-op.
Calling this method has no effect.
- Returns:
self – The updated object.
- Return type:
- set_score_request(*, sample_weight='$UNCHANGED$')¶
Configure whether metadata should be requested to be passed to the
scoremethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed toscoreif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it toscore.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- mood.mood_modeling.class_to_path(obj)[source]¶
Convert an object to a string path. This is useful for serialization and deserialization of objects.
>>> from sklearn.linear_model import LogisticRegression >>> path = class_to_path(LogisticRegression) >>> path 'sklearn.linear_model._logistic.LogisticRegression' >>> path_to_class(path) == LogisticRegression True
- mood.mood_modeling.x_and_y_with_boolean_y(data, x_col, y_col, y_is_true_vals, y_is_false_vals=None)[source]¶
Get the x and y values from a dataframe, converting y to binary values. The output y elements will be 1 if and only if the y_col value is in y_is_true_vals.
- Parameters:
data (
DataFrame) – The dataframe to get the x and y values fromx_col (
str) – The name of the column to use as xy_col (
str) – The name of the column to use as yy_is_true_vals (
list|str) – The values in y_col that are considered 1y_is_false_vals (
list|str|None) – The values in y_col that are considered 0 (optional)
- Return type:
tuple[ndarray,ndarray]- Returns:
Tuple of (X, y) where X contains features and y contains binary labels