### Install ASV and Virtualenv Source: https://github.com/online-ml/river/blob/main/benchmarks/README.md Install the necessary tools for running benchmarks. ```bash pip install asv virtualenv ``` -------------------------------- ### Install uv Package Manager Source: https://github.com/online-ml/river/blob/main/CONTRIBUTING.md Install the uv package manager by downloading and executing the official installation script. ```sh curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/online-ml/river/blob/main/CONTRIBUTING.md Install additional dependencies required for building the project documentation. ```sh uv sync --group docs ``` -------------------------------- ### Install and Sync Dependencies Source: https://github.com/online-ml/river/blob/main/CLAUDE.md Use this command to install or synchronize project dependencies, which also builds Cython and Rust extensions. ```sh uv sync ``` -------------------------------- ### Install River using uv Source: https://github.com/online-ml/river/blob/main/docs/introduction/installation.md Install River using the uv package installer. This is an alternative to pip for managing Python packages. ```sh uv add river ``` -------------------------------- ### Install pre-commit Hooks Source: https://github.com/online-ml/river/blob/main/CONTRIBUTING.md Install pre-commit hooks for automated code quality checks before pushing to GitHub. ```sh uv run pre-commit install --hook-type pre-push ``` -------------------------------- ### Install River from GitHub (HTTPS) Source: https://github.com/online-ml/river/blob/main/docs/introduction/installation.md Install the latest development version directly from the GitHub repository using HTTPS. This method requires Cython and Rust. ```sh pip install git+https://github.com/online-ml/river --upgrade ``` -------------------------------- ### Install River using pip Source: https://github.com/online-ml/river/blob/main/README.md Installs the River library using pip. Ensure Python 3.11 or higher is used. ```sh pip install river ``` -------------------------------- ### Get First Sample from Dataset Source: https://github.com/online-ml/river/blob/main/docs/introduction/getting-started/regression.ipynb Retrieves and displays the first sample (features and target) from the TrumpApproval dataset. ```python x, y = next(iter(dataset)) x ``` -------------------------------- ### Install Python Version Source: https://github.com/online-ml/river/blob/main/CONTRIBUTING.md Install the specific Python version required by River using pyenv, as defined in the .python-version file. ```sh pyenv install -v $(cat .python-version) ``` -------------------------------- ### Install River Development Version from GitHub (HTTPS) Source: https://github.com/online-ml/river/blob/main/README.md Installs the latest development version of River from GitHub using HTTPS. This requires Cython and Rust. ```sh pip install git+https://github.com/online-ml/river --upgrade ``` -------------------------------- ### Install River Development Version from GitHub (SSH) Source: https://github.com/online-ml/river/blob/main/README.md Installs the latest development version of River from GitHub using SSH. This requires Cython and Rust. ```sh pip install git+ssh://git@github.com/online-ml/river.git --upgrade # using SSH ``` -------------------------------- ### Initialize and Predict with Logistic Regression Source: https://github.com/online-ml/river/blob/main/docs/introduction/getting-started/binary-classification.ipynb Initializes a Logistic Regression model and demonstrates how to get a probability distribution for a given sample before training. ```python from river import linear_model model = linear_model.LogisticRegression() model.predict_proba_one(x) ``` -------------------------------- ### Download and Inspect the Higgs Dataset Source: https://github.com/online-ml/river/blob/main/docs/recipes/mini-batching.ipynb Download the Higgs dataset if it's not already present and display its metadata. This dataset is used for the mini-batch learning example. ```python from river import datasets dataset = datasets.Higgs() if not dataset.is_downloaded: dataset.download() dataset ``` -------------------------------- ### List Available River Bandit Environments Source: https://github.com/online-ml/river/blob/main/docs/recipes/bandits-101.ipynb Iterates through the Gym registry to find and print all available bandit environments provided by River. This requires the `gymnasium` library to be installed. ```python import gymnasium as gym for k in gym.envs.registry: if k.startswith('river_bandits'): print(k) ``` -------------------------------- ### Measuring Time and Memory in Progressive Validation Source: https://github.com/online-ml/river/blob/main/docs/recipes/model-evaluation.ipynb This example demonstrates how to track resource usage during progressive validation by setting `show_time=True` and `show_memory=True`. It uses a Logistic Regression model and Accuracy metric. ```python from river import preprocessing from river import linear_model from river import evaluate from river import datasets from river import metrics model = preprocessing.StandardScaler() | linear_model.LogisticRegression() evaluate.progressive_val_score( dataset=datasets.Phishing(), model=model, metric=metrics.Accuracy(), print_every=500, show_time=True, show_memory=True, ) ``` -------------------------------- ### FFMRegressor Model Setup and Evaluation Source: https://github.com/online-ml/river/blob/main/docs/examples/matrix-factorization-for-recommender-systems/part-2.ipynb Sets up and evaluates a Field-aware Factorization Machines (FFM) regressor. This model is suitable for learning specific interaction effects between features from different fields. Ensure necessary imports for optimizers, compose, and facto are available. ```python ffm_params = { 'n_factors': 8, 'weight_optimizer': optim.SGD(0.01), 'latent_optimizer': optim.SGD(0.025), 'intercept': 3, 'latent_initializer': optim.initializers.Normal(mu=0., sigma=0.05, seed=73), } regressor = compose.Select('user', 'item') regressor += ( compose.Select('genres') | compose.FuncTransformer(split_genres) ) regressor += ( compose.Select('age') | compose.FuncTransformer(bin_age) ) regressor |= facto.FFMRegressor(**ffm_params) model = preprocessing.PredClipper( regressor=regressor, y_min=1, y_max=5 ) evaluate(model) ``` -------------------------------- ### Train a Linear Regression Model Source: https://github.com/online-ml/river/blob/main/docs/recipes/cloning-and-mutating.ipynb Initializes and trains a LinearRegression model using the TrumpApproval dataset. This serves as the base model for cloning examples. ```python from river import datasets, linear_model, optim, preprocessing model = ( preprocessing.StandardScaler() | linear_model.LinearRegression( optimizer=optim.SGD(3e-2) ) ) for x, y in datasets.TrumpApproval(): model.predict_one(x) model.learn_one(x, y) model[-1].weights ``` -------------------------------- ### FwFMRegressor Model Setup and Evaluation Source: https://github.com/online-ml/river/blob/main/docs/examples/matrix-factorization-for-recommender-systems/part-2.ipynb Sets up and evaluates a Field-weighted Factorization Machines (FwFM) regressor. This model addresses memory issues in FFM by learning interaction strengths between fields. Ensure necessary imports for optimizers, compose, and facto are available. ```python fwfm_params = { 'n_factors': 10, 'weight_optimizer': optim.SGD(0.01), 'latent_optimizer': optim.SGD(0.025), 'intercept': 3, 'seed': 73, } regressor = compose.Select('user', 'item') regressor += ( compose.Select('genres') | compose.FuncTransformer(split_genres) ) regressor += ( compose.Select('age') | compose.FuncTransformer(bin_age) ) regressor |= facto.FwFMRegressor(**fwfm_params) model = preprocessing.PredClipper( regressor=regressor, y_min=1, y_max=5 ) evaluate(model) ``` -------------------------------- ### Biased Matrix Factorization (BiasedMF) Implementation Source: https://github.com/online-ml/river/blob/main/docs/examples/matrix-factorization-for-recommender-systems/part-1.ipynb This snippet demonstrates the setup and evaluation of the BiasedMF model, which includes user and item biases along with latent factors. It requires specific parameter configurations for bias and latent optimizers, initializers, and regularization terms. The model is also evaluated using a prediction clipper. ```python biased_mf_params = { 'n_factors': 10, 'bias_optimizer': optim.SGD(0.025), 'latent_optimizer': optim.SGD(0.05), 'weight_initializer': optim.initializers.Zeros(), 'latent_initializer': optim.initializers.Normal(mu=0., sigma=0.1, seed=73), 'l2_bias': 0., 'l2_latent': 0. } model = preprocessing.PredClipper( regressor=reco.BiasedMF(**biased_mf_params), y_min=1, y_max=5 ) evaluate(model) ``` -------------------------------- ### Sampling with RandomSampler Source: https://github.com/online-ml/river/blob/main/docs/examples/imbalanced-learning.ipynb Use RandomSampler to control both class distribution and the total amount of data for training. This example sets the training data to 1 percent of the total dataset. ```python model = ( preprocessing.StandardScaler() | imblearn.RandomSampler( classifier=linear_model.LogisticRegression(), desired_dist={0: .8, 1: .2}, sampling_rate=.01, seed=42 ) ) metric = metrics.ROCAUC() evaluate.progressive_val_score(X_y, model, metric) ``` -------------------------------- ### Implement Naive Baseline Model (Running Mean) Source: https://github.com/online-ml/river/blob/main/docs/examples/matrix-factorization-for-recommender-systems/part-1.ipynb Implements a naive baseline model that predicts the running mean of the target variable. This serves as a starting point for comparison with more complex models. ```python from river import dummy from river import stats model = dummy.StatisticRegressor(stats.Mean()) evaluate(model, unpack_user_and_item=False) ``` -------------------------------- ### Hybrid Approach with RandomUnderSampler and Weighted Loss Source: https://github.com/online-ml/river/blob/main/docs/examples/imbalanced-learning.ipynb Combine RandomUnderSampler with a weighted loss function to address class imbalance. This example uses RandomUnderSampler and sets a weight for the positive class in the Log loss. ```python model = ( preprocessing.StandardScaler() | imblearn.RandomUnderSampler( classifier=linear_model.LogisticRegression( loss=optim.losses.Log(weight_pos=5) ), desired_dist={0: .8, 1: .2}, seed=42 ) ) metric = metrics.ROCAUC() evaluate.progressive_val_score(X_y, model, metric) ``` -------------------------------- ### Build and Serve Docs Locally Source: https://github.com/online-ml/river/blob/main/CLAUDE.md Synchronize documentation dependencies and serve the documentation locally for live preview. ```sh uv sync --group docs make livedoc ``` -------------------------------- ### Publish and Preview Benchmark Results Source: https://github.com/online-ml/river/blob/main/benchmarks/README.md Generate a static website of benchmark results and serve it locally for review. ```bash asv publish ``` ```bash asv preview ``` -------------------------------- ### Initialize and Simulate FunkMF Recommender Source: https://github.com/online-ml/river/blob/main/docs/examples/content-personalization.ipynb Initializes Simon Funk's Matrix Factorization (FunkMF) recommender model and simulates its performance. ```python model = reco.FunkMF(seed=10) simulate(5_000, get_reward, model, seed=42) ``` -------------------------------- ### Initialize and Simulate Baseline Recommender Source: https://github.com/online-ml/river/blob/main/docs/examples/content-personalization.ipynb Initializes a baseline recommender model and simulates its performance over 5,000 steps using a predefined reward function and seed. ```python model = reco.Baseline(seed=10) simulate(5_000, get_reward, model, seed=42) ``` -------------------------------- ### Initialize a Pipeline for Mini-batch Learning Source: https://github.com/online-ml/river/blob/main/docs/recipes/mini-batching.ipynb Create a pipeline with preprocessing and a linear model. This pipeline can be used with mini-batches as long as each step supports it. ```python from river import compose from river import linear_model from river import preprocessing model = compose.Pipeline( preprocessing.StandardScaler(), linear_model.LogisticRegression() ) ``` -------------------------------- ### Quick Benchmark Run Source: https://github.com/online-ml/river/blob/main/benchmarks/README.md Execute benchmarks quickly using the current Python environment without setting up new virtual environments. ```bash asv run --python=same --quick --show-stderr ``` -------------------------------- ### Creating Pipelines Sequentially Source: https://github.com/online-ml/river/blob/main/docs/recipes/pipelines.ipynb Demonstrates three equivalent ways to create a sequential pipeline: using the constructor, the `|` operator, and incremental assignment with `|=`. ```python from river import compose, feature_extraction, linear_model, preprocessing # Using the constructor model = compose.Pipeline( preprocessing.StandardScaler(), feature_extraction.PolynomialExtender(), linear_model.LinearRegression(), ) # Using the | operator model = ( preprocessing.StandardScaler() | feature_extraction.PolynomialExtender() | linear_model.LinearRegression() ) # Using |= incrementally model = preprocessing.StandardScaler() model |= feature_extraction.PolynomialExtender() model |= linear_model.LinearRegression() ``` -------------------------------- ### Get River Version Source: https://github.com/online-ml/river/blob/main/CONTRIBUTING.md Retrieve the current version of the River library. This is used to tag releases. ```sh RIVER_VERSION=$(uv run python -c "import river; print(river.__version__)") echo $RIVER_VERSION ``` -------------------------------- ### Funk Matrix Factorization (FunkMF) Implementation Source: https://github.com/online-ml/river/blob/main/docs/examples/matrix-factorization-for-recommender-systems/part-1.ipynb This snippet shows how to set up and evaluate the FunkMF model. It requires importing necessary modules and defining parameters such as the number of factors, optimizer, and regularization. The model is then wrapped with a prediction clipper for bounding. ```python funk_mf_params = { 'n_factors': 10, 'optimizer': optim.SGD(0.05), 'l2': 0.1, 'initializer': optim.initializers.Normal(mu=0., sigma=0.1, seed=73) } model = preprocessing.PredClipper( regressor=reco.FunkMF(**funk_mf_params), y_min=1, y_max=5 ) evaluate(model) ``` -------------------------------- ### Predict the Most Likely Class Source: https://github.com/online-ml/river/blob/main/docs/introduction/getting-started/binary-classification.ipynb Uses the predict_one method to get the single most likely class prediction for a sample, instead of a probability distribution. ```python model.predict_one(x) ``` -------------------------------- ### Setting up Bandit Policies and Environment Source: https://github.com/online-ml/river/blob/main/docs/recipes/bandits-101.ipynb Initializes a list of bandit policies, including EpsilonGreedy with different epsilon values and a rolling average reward object, and ThompsonSampling. It also sets up the 'CandyCaneContest-v0' environment from gym. ```python from river import proba, utils policies=[ bandit.EpsilonGreedy( epsilon=0.1, seed=42 ), bandit.EpsilonGreedy( epsilon=0.3, reward_obj=utils.Rolling(stats.Mean(), window_size=50), seed=42 ), bandit.ThompsonSampling( reward_obj=proba.Beta(), seed=42 ) ] env = gym.make('river_bandits/CandyCaneContest-v0') ``` -------------------------------- ### Get the First Sample from the Dataset Source: https://github.com/online-ml/river/blob/main/docs/introduction/getting-started/binary-classification.ipynb Retrieves the first feature-label pair (x, y) from the streaming dataset. Useful for inspecting individual samples. ```python x, y = next(iter(dataset)) ``` ```python x ``` ```python y ``` -------------------------------- ### Tqdm Progress Bar (Initial State) Source: https://github.com/online-ml/river/blob/main/docs/recipes/bandits-101.ipynb This represents the initial state of a tqdm progress bar, indicating that the process has started but no iterations have been completed. ```text Output: 0%| | 0/6000000 [00:00= 30000 and i % 30000 == 0: print(i, metric) ``` -------------------------------- ### Draw Hoeffding Tree Structure Source: https://github.com/online-ml/river/blob/main/docs/examples/on-hoeffding-trees.ipynb Visualizes the structure of the trained Hoeffding Tree. Requires Graphviz to be installed and its executables to be in the system's PATH. If 'dot' is not found, an ExecutableNotFound error will be raised. ```python model.draw() ``` -------------------------------- ### Process Benchmark Results into DataFrame Source: https://github.com/online-ml/river/blob/main/docs/recipes/bandits-101.ipynb Converts the generator output from `bandit.evaluate` into a pandas DataFrame for easier analysis. `tqdm` is used to display a progress bar during the conversion. Ensure `pandas` and `tqdm` are installed. ```python trace_df = pd.DataFrame(tqdm( trace, position=0, total=( n_episodes * len(policies) * env._max_episode_steps ) )) trace_df.sample(5, random_state=42) ``` -------------------------------- ### Instantiate and use TALibFeatures transformer Source: https://github.com/online-ml/river/blob/main/docs/recipes/feature-extraction.ipynb Demonstrates how to instantiate the TALibFeatures transformer, feed it historical data using `learn_one`, and then transform a new sample using `transform_one`. This is useful for testing the transformer's behavior with a limited dataset. ```python ta = TALibFeatures(buffer_size=50) # Feed some history for _, row in df.head(20).iterrows(): x = row.to_dict() ta.learn_one(x) # Now transform the next sample x = df.iloc[20].to_dict() ta.transform_one(x) ``` -------------------------------- ### Get Hoeffding Tree Summary Statistics Source: https://github.com/online-ml/river/blob/main/docs/examples/on-hoeffding-trees.ipynb Retrieves summary statistics of the trained Hoeffding Tree model, including node counts, branch counts, leaf information, and total observed weight. ```python model.summary ``` -------------------------------- ### Plotting Performance with Limited Tree Depth Source: https://github.com/online-ml/river/blob/main/docs/examples/on-hoeffding-trees.ipynb This example visualizes the performance of a Hoeffding Tree Regressor with a maximum depth of 5, using EBSTSplitter. It's useful for comparing memory-bound tree behavior. ```python plot_performance( synth.Friedman(seed=42).take(10_000), metrics.MAE(), { "HTR with at most 5 levels": ( preprocessing.StandardScaler() | tree.HoeffdingTreeRegressor( splitter=tree.splitter.EBSTSplitter(), max_depth=5 ) ) } ) ``` -------------------------------- ### Execute Notebooks Source: https://github.com/online-ml/river/blob/main/CONTRIBUTING.md Run the project's notebooks. This command is typically used to ensure notebooks are up-to-date before a release. ```sh uv run make execute-notebooks ``` -------------------------------- ### Apply Binary Focal Loss to Logistic Regression Source: https://github.com/online-ml/river/blob/main/docs/examples/imbalanced-learning.ipynb Utilize the binary version of Focal Loss for logistic regression to address class imbalance. This loss function is designed to down-weight easy examples and focus on hard ones. ```python model = ( preprocessing.StandardScaler() | linear_model.LogisticRegression(loss=optim.losses.BinaryFocalLoss(2, 1)) ) metric = metrics.ROCAUC() evaluate.progressive_val_score(X_y, model, metric) ``` -------------------------------- ### Tag and Push Release Source: https://github.com/online-ml/river/blob/main/CONTRIBUTING.md Create a Git tag for the new release version and push it to the origin. ```sh git tag $RIVER_VERSION -m "Release $RIVER_VERSION" git push origin $RIVER_VERSION ``` -------------------------------- ### Visualize Learned Preferences Source: https://github.com/online-ml/river/blob/main/docs/examples/content-personalization.ipynb Use pandas to create a DataFrame of predicted preferences for all user-item pairs. This helps in verifying the model's learned preferences by highlighting the maximum preference for each user across items. Requires the 'pandas' library to be installed. ```python import pandas as pd ( pd.DataFrame( { 'user': user, 'item': item, 'preference': model.predict_one(user, item) } for user in model.u_latents for item in model.i_latents ) .pivot(index='user', columns='item') .style.highlight_max(color='lightgreen', axis='columns') ) ``` -------------------------------- ### Including Custom Functions in Pipelines Source: https://github.com/online-ml/river/blob/main/docs/recipes/pipelines.ipynb Demonstrates how to integrate arbitrary Python functions as pipeline steps using `compose.FuncTransformer` or by passing functions directly to the `|` operator. ```python def add_interaction(x): x["interaction"] = x["gallup"] * x["ipsos"] return x model = ( add_interaction | preprocessing.StandardScaler() | linear_model.LinearRegression() ) model ``` -------------------------------- ### Iterate Through Dataset Samples Source: https://github.com/online-ml/river/blob/main/docs/recipes/reading-data.ipynb Demonstrates iterating through a dataset to access individual samples. This is equivalent to using `next(iter(dataset))` in a loop. ```python for x, y in dataset: break x ``` -------------------------------- ### Compare Regression Tree Splitters Performance Source: https://github.com/online-ml/river/blob/main/docs/examples/on-hoeffding-trees.ipynb Compares the performance of Hoeffding Tree Regressors with different splitters (E-BST, TE-BST, QO) on the Friedman synthetic dataset. Requires importing necessary modules from `river.preprocessing`, `river.tree`, `river.synth`, and `river.metrics`. ```python plot_performance( synth.Friedman(seed=42).take(10_000), metrics.MAE(), { "HTR + E-BST": ( preprocessing.StandardScaler() | tree.HoeffdingTreeRegressor( splitter=tree.splitter.EBSTSplitter() ) ), "HTR + TE-BST": ( preprocessing.StandardScaler() | tree.HoeffdingTreeRegressor( splitter=tree.splitter.TEBSTSplitter() ) ), "HTR + QO": ( preprocessing.StandardScaler() | tree.HoeffdingTreeRegressor( splitter=tree.splitter.QOSplitter() ) ), } ) ``` ```python Result: alt.VConcatChart(...) ``` -------------------------------- ### Create GitHub Release Source: https://github.com/online-ml/river/blob/main/CONTRIBUTING.md Create a new release on GitHub using the gh CLI. This command includes release notes with links to the versioned documentation and PyPI. ```sh RELEASE_NOTES=$(cat <<-END - https://riverml.xyz/${RIVER_VERSION}/ - https://pypi.org/project/river/${RIVER_VERSION}/ END ) brew update && brew install gh gh release create $RIVER_VERSION --notes $RELEASE_NOTES ``` -------------------------------- ### Evaluating a Memory-Restricted Hoeffding Tree Regressor Source: https://github.com/online-ml/river/blob/main/docs/examples/on-hoeffding-trees.ipynb This example shows how to configure a Hoeffding Tree Regressor to limit its memory usage to 5 MiB and perform memory checks every 500 instances. It uses the Friedman synthetic dataset and plots the results. ```python plot_performance( synth.Friedman(seed=42).take(10_000), metrics.MAE(), { "Restricted HTR": ( preprocessing.StandardScaler() | tree.HoeffdingTreeRegressor( splitter=tree.splitter.EBSTSplitter(), max_size=5, memory_estimate_period=500 ) ) } ) ``` -------------------------------- ### Visualize Pipeline Source: https://github.com/online-ml/river/blob/main/docs/examples/sentence-classification.ipynb Prints the structure of the machine learning pipeline, including preprocessing and sampling steps. ```python cm ``` ```python model ``` -------------------------------- ### Implement Basic Active Learning Flow Source: https://github.com/online-ml/river/blob/main/docs/recipes/active-learning.ipynb Demonstrates a basic active learning loop using `EntropySampler` with a TFIDF and Logistic Regression model on the SMSSpam dataset. It tracks the number of samples used for training. ```python from river import active from river import datasets from river import feature_extraction from river import linear_model from river import metrics dataset = datasets.SMSSpam() metric = metrics.Accuracy() model = ( feature_extraction.TFIDF(on='body') | linear_model.LogisticRegression() ) model = active.EntropySampler(model, seed=42) n_samples_used = 0 for x, y in dataset: y_pred, ask = model.predict_one(x) metric.update(y, y_pred) if ask: n_samples_used += 1 model.learn_one(x, y) metric ``` -------------------------------- ### Simulate Recommendation Model Performance Source: https://github.com/online-ml/river/blob/main/docs/examples/content-personalization.ipynb Simulates the recommendation process over a specified number of iterations. It samples users and contexts, makes recommendations using a given model, measures user feedback via a reward function, and updates the model. The function returns a plot of the click-through rate over time. ```python import random import altair as alt import pandas as pd def plot_ctr(ctr): # Wrap the data in a Pandas DataFrame df = pd.DataFrame({ "n_iterations": list(range(1, len(ctr) + 1)), "CTR": ctr }) # Create the Altair chart chart = alt.Chart(df).mark_line().encode( x=alt.X("n_iterations", title="n_iterations"), y=alt.Y("CTR", scale=alt.Scale(domain=[0, 1]), title="CTR") ).properties( title=f'final CTR: {ctr[-1]:.2%}', width=600, height=300 ) # Return the chart object so it displays return chart users = ['Tom', 'Anna'] times_of_day = ['morning', 'afternoon'] items = {'politics', 'sports', 'music', 'food', 'finance', 'health', 'camping'} def simulate(n, reward_func, model, seed): rng = random.Random(seed) n_clicks = 0 ctr = [] # click-through rate along time for i in range(n): # Generate a context at random user = rng.choice(users) context = { 'time_of_day': rng.choice(times_of_day) } # Make a single recommendation item = model.rank(user, items=items, x=context)[0] # Measure the reward clicked = reward_func(user, item, context) n_clicks += clicked ctr.append(n_clicks / (i + 1)) # Update the model model.learn_one(user, item, y=clicked, x=context) # Return the output of plot_ctr return plot_ctr(ctr) ``` -------------------------------- ### Load and Inspect MovieLens 100K Dataset Source: https://github.com/online-ml/river/blob/main/docs/examples/matrix-factorization-for-recommender-systems/part-2.ipynb Loads a sample of the MovieLens 100K dataset and prints the features (x) and target (y) for the first entry. This helps in understanding the data structure. ```python import json for x, y in datasets.MovieLens100K(): print(f'x = {json.dumps(x, indent=4)} y = {y}') break ``` -------------------------------- ### Implement Baseline Matrix Factorization Model Source: https://github.com/online-ml/river/blob/main/docs/examples/matrix-factorization-for-recommender-systems/part-1.ipynb Initializes and evaluates the `reco.Baseline` model, which incorporates user and item biases. It uses SGD optimizer and is wrapped with `PredClipper` to constrain predictions between 1 and 5. ```python from river import preprocessing from river import optim from river import reco baseline_params = { 'optimizer': optim.SGD(0.025), 'l2': 0., 'initializer': optim.initializers.Zeros() } model = preprocessing.PredClipper( regressor=reco.Baseline(**baseline_params), y_min=1, y_max=5 ) evaluate(model) ```