<jupyter_start><jupyter_text><jupyter_code>!pip install river<jupyter_output><empty_output><jupyter_text>Regression<jupyter_code>from river import stream
from river.datasets import base


class SolarFlare(base.FileDataset):
    def __init__(self):
        super().__init__(
            n_samples=1066,
            n_features=10,
            n_outputs=1,
            task=base.MO_REG,
            filename="solar-flare.csv.zip",
        )

    def __iter__(self):
        return stream.iter_csv(
            self.path,
            target="m-class-flares",
            converters={
                "zurich-class": str,
                "largest-spot-size": str,
                "spot-distribution": str,
                "activity": int,
                "evolution": int,
                "previous-24h-flare-activity": int,
                "hist-complex": int,
                "hist-complex-this-pass": int,
                "area": int,
                "largest-spot-area": int,
                "c-class-flares": int,
                "m-class-flares": int,
                "x-class-flares": int,
            },
        )
    
from pprint import pprint
from river import datasets

for x, y in SolarFlare():
    pprint(x)
    pprint(y)
    break
import numbers
from river import compose
from river import datasets
from river import evaluate
from river import linear_model
from river import metrics
from river import preprocessing
from river import tree

dataset = SolarFlare()
num = compose.SelectType(numbers.Number) | preprocessing.MinMaxScaler()
cat = compose.SelectType(str) | preprocessing.OneHotEncoder(sparse=False)
model = tree.HoeffdingTreeRegressor()
pipeline = (num + cat) | model
metric = metrics.MAE()
#evaluate.progressive_val_score(dataset, pipeline, metric)
import matplotlib.pyplot as plt

errors = []
for x, y in SolarFlare():
    y_pred = pipeline.predict_one(x)
    metric = metric.update(y, y_pred)
    errors.append(metric.get())
    pipeline = pipeline.learn_one(x, y)

fig, ax = plt.subplots(figsize=(16, 6))
ax.plot(
    errors,
    "ro",
    alpha=0.6,
    markersize=2,
    linewidth=4
)
fig, ax = plt.subplots(figsize=(16, 6))
ax.plot(
    errors,
    "ro",
    alpha=0.6,
    markersize=2,
    linewidth=4
)
ax.set_xlabel("number of points")
ax.set_ylabel("MAE");<jupyter_output><empty_output><jupyter_text>Adaptive Models on a Concept Drift Data Stream<jupyter_code>from river import (
    synth, ensemble, tree,
    evaluate, metrics
)

models = [
    tree.HoeffdingTreeRegressor(),
    tree.HoeffdingAdaptiveTreeRegressor(),
    ensemble.AdaptiveRandomForestRegressor(seed=42),
]

results = {}
for model in models:
    metric = metrics.MSE()
    errors = []
    dataset = synth.ConceptDriftStream(
        seed=42, position=500, width=40
    ).take(1000)    
    for i, (x, y) in enumerate(dataset):
        y_pred = model.predict_one(x)
        metric = metric.update(y, y_pred)
        model = model.learn_one(x, y)
        if (i % 100) == 0:
            errors.append(dict(step=i, error=metric.get()))
    results[str(model.__class__).split(".")[-1][:-2]] = errors
results
import pandas as pd
import seaborn as sns

plt.figure(figsize=(16, 6))
styles = ["-","--","-.",":"]
markers = [
    '.', ',', 'o', 'v', '^', '<', '>',
    '1', '2', '3', '4', '8', 's', 'p',
    '*', 'h', 'H', '+', 'x', 'D', 'd',
    '|', '_', 'P', 'X', 0, 1, 2, 3, 4,
    5, 6, 7, 8, 9, 10, 11
]

for i, (model, errors) in enumerate(results.items()):
    df = pd.DataFrame(errors)
    sns.lineplot(
        data=df,
        x="step",
        y="error",
        linestyle=styles[i%len(styles)],
        alpha=0.5,
        markersize=22,
        markers=markers[i%len(markers)],        
        label=model,
        linewidth=4
    )
    
plt.ylabel("MSE")
plt.xlabel("Step")
sns.set_style("ticks")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14785788923719959, 'fraction_numerical': 0.018025078369905956, 'mean_word_length': 2.5751633986928106, 'pattern_counts': {'":': 14, '<': 14, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '568896', 'license': 'MIT', 'n_tokens_mistral': 1383, 'n_tokens_neox': 1307, 'n_words': 277, 'path': 'chapter8/Online_Learning.ipynb', 'repo_name': 'JGualOb/Machine-Learning-for-Time-Series-with-Python', 'size': '3828'}