### Install Development Tools using Conda and Pip Source: https://github.com/gaa-uam/scikit-fda/wiki/IDE-configuration Installs essential Python development tools including isort, mypy, and wemake-python-styleguide within a specified conda environment. These tools are crucial for code formatting, type checking, and style enforcement. ```bash conda activate pip install isort mypy wemake-python-styleguide ``` -------------------------------- ### Functional Linear Regression Setup in Python Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Sets up functional linear regression models using scikit-fda. This example focuses on scalar-on-function regression using the Tecator dataset to predict fat content from NIR spectra. It includes data loading, splitting, and preparation for regression. ```python import numpy as np import pandas as pd from skfda.datasets import fetch_tecator, fetch_weather from skfda.ml.regression import ( LinearRegression, KNeighborsRegressor, FPCARegression, ) from skfda.representation.basis import BSplineBasis from sklearn.model_selection import train_test_split # Example 1: Scalar-on-function regression (Tecator dataset) # Predict fat content from NIR spectra tecator = fetch_tecator() X = tecator["data"] y = tecator["target"] # Fat content (scalar) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, random_state=42 ) ``` -------------------------------- ### Install Scikit-FDA using Pip and Conda Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Instructions for installing the scikit-fda library using either pip or conda package managers. No specific dependencies are mentioned for installation itself. ```bash # Install via pip pip install scikit-fda # Install via conda conda install -c conda-forge scikit-fda ``` -------------------------------- ### Install scikit-fda from source using pip Source: https://github.com/gaa-uam/scikit-fda/blob/develop/README.rst Installs the latest version of scikit-fda directly from its GitHub repository. This involves cloning the repository and then performing a manual installation using pip. Ensure your Python version is supported (3.8+). ```bash git clone https://github.com/GAA-UAM/scikit-fda.git pip install ./scikit-fda ``` -------------------------------- ### Start Gitflow Release Branch Source: https://github.com/gaa-uam/scikit-fda/wiki/How-to-make-a-release Initiates a new release branch using the Gitflow branching model. This command prepares the repository for a new release by creating a dedicated branch for it. ```bash git flow release start X.Y.Z ``` -------------------------------- ### Install scikit-fda from source with specific Python version Source: https://github.com/gaa-uam/scikit-fda/blob/develop/README.rst Installs the latest version of scikit-fda from source using a specific Python version (e.g., python3.8). This is useful if you have multiple Python versions installed and need to ensure compatibility. ```bash git clone https://github.com/GAA-UAM/scikit-fda.git python3.8 -m pip install ./scikit-fda ``` -------------------------------- ### Install scikit-fda using pip Source: https://github.com/gaa-uam/scikit-fda/blob/develop/README.rst Installs the stable version of the scikit-fda package using pip. This is the recommended method for most users and requires a Python version above 3.8. ```bash pip install scikit-fda ``` -------------------------------- ### Install scikit-fda using conda Source: https://github.com/gaa-uam/scikit-fda/blob/develop/README.rst Installs the stable version of the scikit-fda package from the conda-forge channel. This method is suitable for users who manage their environments with Conda. ```bash conda install -c conda-forge scikit-fda ``` -------------------------------- ### Configure VSCode for Python Linting Source: https://github.com/gaa-uam/scikit-fda/wiki/IDE-configuration Configures VSCode settings to enable and utilize Python linting tools such as MyPy and Flake8. This ensures code quality by enforcing style guides and detecting potential errors during development. The `python.pythonPath` setting specifies the interpreter to use. ```json { "python.linting.enabled": true, "python.linting.mypyEnabled": true, "python.linting.flake8Enabled": true, "python.pythonPath": "~/anaconda3/bin/python" } ``` -------------------------------- ### Compute Functional Metrics and Distances (Python) Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Demonstrates the computation of various distances and metrics between functional observations using scikit-fda. It covers L2, Lp (including L1 and L-infinity), and Fisher-Rao distances, as well as pairwise distance matrix calculation. The example also shows how to integrate these metrics into machine learning models like KNeighborsClassifier and defines a custom weighted L2 distance. ```python from skfda.datasets import fetch_growth from skfda.misc.metrics import ( l2_distance, lp_distance, LpDistance, fisher_rao_distance, PairwiseMetric, ) import numpy as np import matplotlib.pyplot as plt from skfda.ml.classification import KNeighborsClassifier # Load data growth = fetch_growth() fd = growth["data"][:10] # Use subset for demonstration # L2 distance between first two curves dist_l2 = l2_distance(fd[0], fd[1]) print(f"L2 distance between curve 0 and 1: {dist_l2:.4f}") # Lp distance with different p values dist_l1 = lp_distance(fd[0], fd[1], p=1) dist_linf = lp_distance(fd[0], fd[1], p=np.inf) print(f"L1 distance: {dist_l1:.4f}") print(f"L∞ distance: {dist_linf:.4f}") # Fisher-Rao distance (elastic metric) dist_fr = fisher_rao_distance(fd[0], fd[1]) print(f"Fisher-Rao distance: {dist_fr:.4f}") # Pairwise distance matrix pairwise_l2 = PairwiseMetric(l2_distance) distance_matrix = pairwise_l2(fd, fd) print(f"Distance matrix shape: {distance_matrix.shape}") # Using metric in classifiers knn_custom = KNeighborsClassifier( n_neighbors=3, metric=LpDistance(p=1), # Use L1 metric ) # Custom distance function def weighted_l2(fd1, fd2): """Weighted L2 distance giving more importance to early time points.""" t = fd1.grid_points[0] weights = np.exp(-t) # Exponential decay weights diff = fd1.data_matrix - fd2.data_matrix return np.sqrt(np.trapz(weights * diff[0, :, 0]**2, t)) # Visualize distance matrix fig, ax = plt.subplots(figsize=(8, 6)) im = ax.imshow(distance_matrix, cmap='viridis') ax.set_xlabel("Sample Index") ax.set_ylabel("Sample Index") ax.set_title("Pairwise L2 Distance Matrix") plt.colorbar(im, ax=ax) plt.show() ``` -------------------------------- ### Scikit-learn Pipelines for Functional Data Analysis Source: https://context7.com/gaa-uam/scikit-fda/llms.txt This Python code demonstrates building scikit-learn pipelines that incorporate scikit-fda components for functional data analysis. It includes examples of smoothing, functional principal component analysis (FPCA), and applying classifiers like SVM and KNN. The code performs cross-validation and hyperparameter tuning using GridSearchCV. ```python from sklearn.pipeline import Pipeline from sklearn.model_selection import cross_val_score, GridSearchCV from sklearn.preprocessing import StandardScaler from skfda.datasets import fetch_growth from skfda.preprocessing.dim_reduction import FPCA from skfda.preprocessing.smoothing import KernelSmoother from skfda.misc.hat_matrix import NadarayaWatsonHatMatrix from skfda.ml.classification import KNeighborsClassifier from sklearn.svm import SVC import numpy as np # Load data X, y = fetch_growth(return_X_y=True) # Pipeline 1: Smoothing -> FPCA -> SVM # Note: This extracts FPCA scores then uses standard SVM fpca = FPCA(n_components=5) fpca.fit(X) X_scores = fpca.transform(X) pipeline_svm = Pipeline([ ('scaler', StandardScaler()), ('svm', SVC(kernel='rbf')), ]) scores_svm = cross_val_score(pipeline_svm, X_scores, y, cv=5) print(f"FPCA + SVM CV accuracy: {scores_svm.mean():.3f} ± {scores_svm.std():.3f}") # Pipeline 2: Smoothing -> Functional KNN (end-to-end functional) smoother = KernelSmoother( kernel_estimator=NadarayaWatsonHatMatrix(bandwidth=0.5) ) X_smooth = smoother.fit_transform(X) knn = KNeighborsClassifier(n_neighbors=5) scores_knn = cross_val_score(knn, X_smooth, y, cv=5) print(f"Smoothed KNN CV accuracy: {scores_knn.mean():.3f} ± {scores_knn.std():.3f}") # Grid search over functional classifier parameters param_grid = { 'n_neighbors': [3, 5, 7, 9, 11], } grid_search = GridSearchCV( KNeighborsClassifier(), param_grid, cv=5, scoring='accuracy', ) grid_search.fit(X, y) print(f"Best params: {grid_search.best_params_}") print(f"Best score: {grid_search.best_score_:.3f}") # Compare multiple preprocessing approaches from skfda.preprocessing.smoothing import BasisSmoother from skfda.representation.basis import BSplineBasis results = {} # Raw data scores = cross_val_score(KNeighborsClassifier(n_neighbors=5), X, y, cv=5) results['Raw'] = scores.mean() # Kernel smoothed X_kernel = KernelSmoother( kernel_estimator=NadarayaWatsonHatMatrix(bandwidth=0.3) ).fit_transform(X) scores = cross_val_score(KNeighborsClassifier(n_neighbors=5), X_kernel, y, cv=5) results['Kernel Smoothed'] = scores.mean() # Basis smoothed X_basis = X.to_basis(BSplineBasis(n_basis=10)) scores = cross_val_score(KNeighborsClassifier(n_neighbors=5), X_basis, y, cv=5) results['Basis Smoothed'] = scores.mean() print("\nPreprocessing comparison:") for method, score in results.items(): print(f" {method}: {score:.3f}") ``` -------------------------------- ### Load Built-in Functional Datasets in Python Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Shows how to load various real-world functional datasets provided by scikit-fda, such as growth, weather, phoneme, tecator, and gait data. It demonstrates accessing the data and targets, and handling different data formats. ```python from skfda.datasets import ( fetch_growth, fetch_weather, fetch_phoneme, fetch_tecator, fetch_gait, make_gaussian_process, make_multimodal_samples, ) # Berkeley Growth Study - height measurements of children growth = fetch_growth() fd_growth = growth["data"] # FDataGrid with growth curves y_growth = growth["target"] # 0=male, 1=female print(f"Growth curves: {fd_growth.n_samples} samples") # Canadian Weather - daily temperature and precipitation X, y = fetch_weather(return_X_y=True, as_frame=True) fd_weather = X.iloc[:, 0].array fd_temperatures = fd_weather.coordinates[0] # Extract temperature coordinate print(f"Weather stations: {fd_temperatures.n_samples}") ``` -------------------------------- ### Create and Manipulate FDataGrid Objects in Python Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Demonstrates how to create and use FDataGrid objects for representing discretized functional data. It covers creating data from a matrix, evaluating functions at specific points, computing derivatives and integrals, concatenating data, and plotting. ```python import numpy as np from skfda import FDataGrid import matplotlib.pyplot as plt # Create functional data from a matrix of observations # Each row is a sample, columns are values at grid points data_matrix = [ [1, 2, 4, 5, 8], [2, 3, 5, 7, 9], [0, 1, 3, 4, 6] ] grid_points = [0, 0.25, 0.5, 0.75, 1.0] fd = FDataGrid(data_matrix, grid_points) print(f"Number of samples: {fd.n_samples}") # 3 print(f"Domain dimension: {fd.dim_domain}") # 1 print(f"Codomain dimension: {fd.dim_codomain}") # 1 print(f"Domain range: {fd.domain_range}") # ((0.0, 1.0),) # Evaluate functions at specific points eval_points = np.array([0.3, 0.6]) values = fd(eval_points) print(f"Values at {eval_points}: shape {values.shape}") # (3, 2, 1) # Compute derivative fd_derivative = fd.derivative(order=1) # Compute integral integrals = fd.integrate() print(f"Integrals: {integrals}") # Concatenate functional data objects fd_combined = fd.concatenate(fd) print(f"Combined samples: {fd_combined.n_samples}") # 6 # Plot the functional data fd.plot() plt.title("Discretized Functional Data") plt.show() ``` -------------------------------- ### Recursive Maxima Hunting - Redundancy Source: https://github.com/gaa-uam/scikit-fda/blob/develop/docs/modules/preprocessing/dim_reduction/recursive_maxima_hunting.rst Configure the redundancy detection method for Recursive Maxima Hunting. This parameter masks redundant points to exclude them from future considerations, addressing potential issues from numerical errors or inappropriate corrections. ```APIDOC ## Recursive Maxima Hunting - Redundancy ### Description This section details the redundancy detection mechanism for the Recursive Maxima Hunting method. It aims to explicitly mask redundant points to prevent them from being incorrectly identified as maxima due to numerical errors or suboptimal corrections. ### Method Not applicable (Configuration Parameter) ### Endpoint Not applicable (Configuration Parameter) ### Parameters #### Query Parameters - **redundancy** (object) - Required - An object implementing the following interface: - `skfda.preprocessing.dim_reduction.variable_selection.recursive_maxima_hunting.DependenceThresholdRedundancy` ### Request Example ```json { "redundancy": "DependenceThresholdRedundancy(threshold=0.95)" } ``` ### Response #### Success Response (200) This section describes the expected output or behavior after configuring the redundancy detection parameter. Specific response details depend on the overall algorithm execution. #### Response Example ```json { "message": "Redundancy detection configured successfully." } ``` ``` -------------------------------- ### Perform One-Way Functional ANOVA (Python) Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Conducts a one-way functional ANOVA test to determine if there are significant differences between the means of multiple groups of functional data. The example demonstrates loading data, partitioning it into groups, performing the ANOVA test, and interpreting the p-value. It also shows how to use additional options like bootstrap replications and returning the sampling distribution. ```python from skfda.datasets import fetch_gait from skfda.inference.anova import oneway_anova from skfda.representation.basis import FourierBasis import skfda import matplotlib.pyplot as plt # Load gait data gait = fetch_gait() fd_hip = gait["data"].coordinates[0] # Divide into groups (simulating different conditions) n = len(fd_hip) partition_size = n // 3 fd_group1 = fd_hip[:partition_size] fd_group2 = fd_hip[partition_size:2*partition_size] fd_group3 = fd_hip[2*partition_size:3*partition_size] # Perform one-way ANOVA statistic, p_value = oneway_anova(fd_group1, fd_group2, fd_group3) print(f"V_n statistic: {statistic:.4f}") print(f"p-value: {p_value:.4f}") if p_value < 0.05: print("Reject H0: Group means are significantly different") else: print("Fail to reject H0: No significant difference between group means") # With additional options statistic, p_value, distribution = oneway_anova( fd_group1, fd_group2, fd_group3, n_reps=2000, # Number of bootstrap replications return_dist=True, # Return sampling distribution ) # Visualize group means means = [fd_group1.mean(), fd_group2.mean(), fd_group3.mean()] fd_means = skfda.concatenate(means) fig, ax = plt.subplots(figsize=(10, 6)) fd_means.plot(ax=ax) ax.legend(["Group 1", "Group 2", "Group 3"]) ax.set_title(f"Group Means (p-value: {p_value:.4f})") plt.show() ``` -------------------------------- ### Extrapolation Methods Source: https://github.com/gaa-uam/scikit-fda/blob/develop/docs/modules/representation/extrapolation.rst This section details the common extrapolation methods available for functional data objects. ```APIDOC ## Extrapolation Methods This section details the common extrapolation methods available for functional data objects. ### Classes - **skfda.representation.extrapolation.BoundaryExtrapolation**: Extrapolation that uses the boundary values. - **skfda.representation.extrapolation.ExceptionExtrapolation**: Extrapolation that raises an exception when evaluating outside the domain. - **skfda.representation.extrapolation.FillExtrapolation**: Extrapolation that fills outside values with a specified constant. - **skfda.representation.extrapolation.PeriodicExtrapolation**: Extrapolation that assumes periodicity of the data. ``` -------------------------------- ### K-Nearest Neighbors Classification in Python Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Demonstrates k-nearest neighbors classification for functional data using scikit-fda. It includes loading data, splitting into train/test sets, basic KNN with L2 distance, prediction, evaluation, and hyperparameter tuning with grid search. It also shows how to use a custom L1 metric. ```python from sklearn.model_selection import train_test_split, GridSearchCV from skfda.datasets import fetch_growth from skfda.ml.classification import KNeighborsClassifier from skfda.misc.metrics import l2_distance, LpDistance # Load data X, y = fetch_growth(return_X_y=True) # Split into train and test sets X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.25, stratify=y, random_state=42 ) # Basic KNN classifier with L2 distance knn = KNeighborsClassifier(n_neighbors=5) knn.fit(X_train, y_train) # Predict and evaluate predictions = knn.predict(X_test) accuracy = knn.score(X_test, y_test) print(f"Test accuracy: {accuracy:.3f}") # Predict probabilities probabilities = knn.predict_proba(X_test[:5]) print(f"Class probabilities:\n{probabilities}") # Grid search for optimal hyperparameters param_grid = { "n_neighbors": [3, 5, 7, 9, 11, 13], } grid_search = GridSearchCV( KNeighborsClassifier(), param_grid, cv=5, scoring="accuracy", ) grid_search.fit(X_train, y_train) print(f"Best parameters: {grid_search.best_params_}") print(f"Best CV score: {grid_search.best_score_:.3f}") print(f"Test score: {grid_search.score(X_test, y_test):.3f}") # Use custom metric (Lp distance with p=1) knn_l1 = KNeighborsClassifier(n_neighbors=5, metric=LpDistance(p=1)) knn_l1.fit(X_train, y_train) print(f"L1 metric accuracy: {knn_l1.score(X_test, y_test):.3f}") ``` -------------------------------- ### Custom Extrapolation Source: https://github.com/gaa-uam/scikit-fda/blob/develop/docs/modules/representation/extrapolation.rst Information on how to create custom extrapolation methods by subclassing the Evaluator class. ```APIDOC ## Custom Extrapolation Custom extrapolators can be created by subclassing the :class:`Evaluator ` class. ### Class - **skfda.representation.evaluator.Evaluator**: Base class for evaluators, including custom extrapolation. ``` -------------------------------- ### Apply Kernel Smoothing to Functional Data Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Demonstrates applying kernel smoothing to functional data using `KernelSmoother` with different kernel estimators (Nadaraya-Watson, Local Linear Regression, K-Neighbors). It also shows how to perform automatic bandwidth selection using cross-validation. ```python from skfda.datasets import fetch_phoneme from skfda.preprocessing.smoothing import KernelSmoother from skfda.misc.hat_matrix import ( NadarayaWatsonHatMatrix, LocalLinearRegressionHatMatrix, KNeighborsHatMatrix, ) from skfda.preprocessing.smoothing.validation import SmoothingParameterSearch import matplotlib.pyplot as plt import numpy as np # Load noisy phoneme data phoneme = fetch_phoneme() fd = phoneme["data"][:100] # Nadaraya-Watson kernel smoothing smoother_nw = KernelSmoother( kernel_estimator=NadarayaWatsonHatMatrix(bandwidth=0.1) ) fd_smooth_nw = smoother_nw.fit_transform(fd) # Local Linear Regression smoothing smoother_llr = KernelSmoother( kernel_estimator=LocalLinearRegressionHatMatrix(bandwidth=0.1) ) fd_smooth_llr = smoother_llr.fit_transform(fd) # K-Neighbors smoothing smoother_knn = KernelSmoother( kernel_estimator=KNeighborsHatMatrix(n_neighbors=5) ) fd_smooth_knn = smoother_knn.fit_transform(fd) # Automatic bandwidth selection using cross-validation bandwidth_range = np.linspace(0.01, 0.5, 20) param_search = SmoothingParameterSearch( KernelSmoother(kernel_estimator=NadarayaWatsonHatMatrix()), bandwidth_range, param_name="kernel_estimator__bandwidth", ) param_search.fit(fd) print(f"Best bandwidth: {param_search.best_params_}") fd_optimal = param_search.transform(fd) # Plot comparison fig, axes = plt.subplots(2, 2, figsize=(12, 10)) fd[0].plot(axes[0, 0]) axes[0, 0].set_title("Original") fd_smooth_nw[0].plot(axes[0, 1]) axes[0, 1].set_title("Nadaraya-Watson") fd_smooth_llr[0].plot(axes[1, 0]) axes[1, 0].set_title("Local Linear Regression") fd_optimal[0].plot(axes[1, 1]) axes[1, 1].set_title("Optimal Bandwidth (CV)") plt.tight_layout() plt.show() ``` -------------------------------- ### Represent Functional Data using FDataBasis in Python Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Illustrates how to convert discretized functional data (FDataGrid) into a basis representation (FDataBasis) using different basis types like B-Spline and Fourier. It also shows how to create FDataBasis directly and perform operations like differentiation. ```python import numpy as np from skfda import FDataGrid from skfda.representation.basis import ( BSplineBasis, FourierBasis, MonomialBasis, FDataBasis, ) import matplotlib.pyplot as plt # Create discretized data first t = np.linspace(0, 1, 100) data_matrix = [np.sin(2 * np.pi * t) + 0.1 * np.random.randn(100) for _ in range(5)] fd_grid = FDataGrid(data_matrix, t) # Convert to B-spline basis representation bspline_basis = BSplineBasis(n_basis=10, domain_range=(0, 1)) fd_bspline = fd_grid.to_basis(bspline_basis) print(f"Coefficients shape: {fd_bspline.coefficients.shape}") # (5, 10) # Convert to Fourier basis (good for periodic data) fourier_basis = FourierBasis(n_basis=7, domain_range=(0, 1)) fd_fourier = fd_grid.to_basis(fourier_basis) # Create FDataBasis directly from coefficients coefficients = np.array([[1, 0.5, 0.3, 0.1]]) monomial_basis = MonomialBasis(n_basis=4, domain_range=(0, 1)) fd_mono = FDataBasis(monomial_basis, coefficients) # Evaluate at specific points values = fd_mono(np.array([0.0, 0.5, 1.0])) # Compute derivative in basis representation fd_derivative = fd_bspline.derivative() # Plot comparison of representations fig, axes = plt.subplots(1, 2, figsize=(12, 4)) fd_grid[0].plot(axes[0]) axes[0].set_title("Original (Grid)") fd_bspline[0].plot(axes[1]) axes[1].set_title("B-Spline Representation") plt.show() ``` -------------------------------- ### Recursive Maxima Hunting - Stopping Criterion Source: https://github.com/gaa-uam/scikit-fda/blob/develop/docs/modules/preprocessing/dim_reduction/recursive_maxima_hunting.rst Configure the stopping criterion for the Recursive Maxima Hunting algorithm. This determines when the iterative selection process should terminate based on the relevance of the remaining points. ```APIDOC ## Recursive Maxima Hunting - Stopping Criterion ### Description This section details the stopping criteria for the Recursive Maxima Hunting algorithm. It defines the conditions under which the algorithm terminates, typically when the remaining points are no longer considered sufficiently relevant. ### Method Not applicable (Configuration Parameter) ### Endpoint Not applicable (Configuration Parameter) ### Parameters #### Query Parameters - **stopping_criterion** (object) - Required - An object implementing one of the following interfaces: - `skfda.preprocessing.dim_reduction.variable_selection.recursive_maxima_hunting.ScoreThresholdStop` - `skfda.preprocessing.dim_reduction.variable_selection.recursive_maxima_hunting.AsymptoticIndependenceTestStop` ### Request Example ```json { "stopping_criterion": "ScoreThresholdStop(threshold=0.01)" } ``` ### Response #### Success Response (200) This section describes the expected output or behavior after configuring the stopping criterion. Specific response details depend on the overall algorithm execution. #### Response Example ```json { "message": "Stopping criterion configured successfully." } ``` ``` -------------------------------- ### Functional Regression: FPCA and K-Neighbors Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Demonstrates functional regression using FPCA and K-Neighbors. It fits models to training data and predicts on test data, then scores the performance using R-squared. ```python from skfda.regression import FPCARegression from sklearn.neighbors import KNeighborsRegressor # FPCA-based regression fpca_reg = FPCARegression(n_components=5) fpca_reg.fit(X_train, y_train) y_pred = fpca_reg.predict(X_test) r2_fpca = fpca_reg.score(X_test, y_test) print(f"FPCA Regression R²: {r2_fpca:.3f}") # K-Neighbors functional regression knn_reg = KNeighborsRegressor(n_neighbors=5) knn_reg.fit(X_train, y_train) r2_knn = knn_reg.score(X_test, y_test) print(f"KNN Regression R²: {r2_knn:.3f}") ``` -------------------------------- ### Load and Generate Functional Data Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Loads pre-defined datasets (phoneme, tecator) and generates synthetic functional data (Gaussian process, multimodal samples). These datasets are foundational for demonstrating various functional data analysis techniques. ```python from skfda.datasets import fetch_phoneme, fetch_tecator, make_gaussian_process, make_multimodal_samples import matplotlib.pyplot as plt # Phoneme data - speech recognition log-periodograms phoneme = fetch_phoneme() fd_phoneme = phoneme["data"] y_phoneme = phoneme["target"] # Tecator dataset - NIR spectra for meat analysis tecator = fetch_tecator() fd_spectra = tecator["data"] y_fat = tecator["target"] # Fat content # Generate synthetic Gaussian process data fd_gaussian = make_gaussian_process( n_samples=50, n_features=100, random_state=42, ) # Generate multimodal synthetic samples fd_multimodal = make_multimodal_samples( n_samples=30, n_modes=2, random_state=42, ) # Plot examples fig, axes = plt.subplots(2, 2, figsize=(12, 10)) # Assuming fd_growth is defined elsewhere for plotting # fd_growth.plot(axes[0, 0], group=y_growth) # axes[0, 0].set_title("Berkeley Growth Study") # Assuming fd_temperatures is defined elsewhere for plotting # fd_temperatures[:10].plot(axes[0, 1]) # axes[0, 1].set_title("Canadian Weather (Temperature)") fd_phoneme[:20].plot(axes[1, 0]) axes[1, 0].set_title("Phoneme Data") fd_multimodal.plot(axes[1, 1]) axes[1, 1].set_title("Synthetic Multimodal") plt.tight_layout() plt.show() ``` -------------------------------- ### Conversion Between Depth and Outlyingness Source: https://github.com/gaa-uam/scikit-fda/blob/develop/docs/modules/exploratory/depth.rst Explains the relationship between depth and outlyingness measures and provides information on how to convert one into the other, specifically defining a depth based on an outlyingness measure. ```APIDOC ## Conversion Between Depth and Outlyingness ### Description Depth and outlyingness are closely related concepts. This section describes how to convert between them, providing a mechanism to define a depth measure that is based on an existing outlyingness measure. ### Depth Based on Outlyingness - `skfda.exploratory.depth.OutlyingnessBasedDepth`: A class that defines a depth measure derived from an outlyingness measure. ``` -------------------------------- ### Nearest Neighbors Regression Source: https://github.com/gaa-uam/scikit-fda/blob/develop/docs/modules/ml/regression.rst Implements nearest neighbors algorithms for regression tasks. It utilizes k-nearest neighbors and radius neighbors approaches. ```APIDOC ## Nearest Neighbors Regression ### Description This module contains nearest neighbors estimators to perform regression. It includes implementations for k-nearest neighbors and radius neighbors algorithms. ### Available Classes - `skfda.ml.regression.KNeighborsRegressor` - `skfda.ml.regression.RadiusNeighborsRegressor` ### Usage Examples - Scalar Regression: `sphx_glr_auto_examples_ml_plot_neighbors_scalar_regression.py` - Functional Regression: `sphx_glr_auto_examples_ml_plot_neighbors_functional_regression.py` ``` -------------------------------- ### FPLS Regression Source: https://github.com/gaa-uam/scikit-fda/blob/develop/docs/modules/ml/regression.rst Offers an implementation of Functional Partial Least Squares (FPLS) regression. This method accepts functional or multivariate data for both regressor and response, using a regression deflation strategy. ```APIDOC ## FPLS Regression ### Description This module includes the implementation of FPLS (Functional Partial Least Squares) regression. This implementation accepts either functional or multivariate data as the regressor and the response. FPLS regression consists on performing the FPLS dimensionality reduction algorithm but using a regression deflation strategy. ### Available Classes - `skfda.ml.regression.FPLSRegression` ``` -------------------------------- ### Cite scikit-fda repository Source: https://github.com/gaa-uam/scikit-fda/blob/develop/README.rst BibTeX entry for citing the scikit-fda software repository. This citation is useful for acknowledging the software itself, including its developers and the repository URL. ```bibtex @misc{ramos-carreno++_2024_scikit-fda-repo, author = {The scikit-fda developers}, doi = {10.5281/zenodo.3468127}, month = feb, title = {scikit-fda: Functional Data Analysis in Python}, url = {https://github.com/GAA-UAM/scikit-fda}, year = {2024} } ``` -------------------------------- ### Perform Curve Registration (Alignment) Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Demonstrates curve alignment techniques to remove phase variation and focus on amplitude differences. Includes Fisher-Rao Elastic Registration and Shift Registration. ```python from skfda.datasets import fetch_growth, make_multimodal_samples from skfda.preprocessing.registration import ( FisherRaoElasticRegistration, ShiftRegistration, landmark_shift_registration, ) from skfda.exploratory.stats import fisher_rao_karcher_mean from skfda.representation.interpolation import SplineInterpolation import numpy as np # Placeholder for actual registration code # Example: # growth = fetch_growth() # fd = growth["data"] # elastic_registration = FisherRaoElasticRegistration() # fd_registered = elastic_registration.fit_transform(fd) # shift_registration = ShiftRegistration() # fd_shifted = shift_registration.fit_transform(fd) # landmark_registration = landmark_shift_registration(fd, landmarks=[0.2, 0.8]) print("Registration code examples would go here.") ``` -------------------------------- ### Clustering Functional Data: K-Means and Fuzzy C-Means Source: https://context7.com/gaa-uam/scikit-fda/llms.txt Groups functional data into clusters using K-Means and Fuzzy C-Means algorithms. It loads weather data, performs clustering, predicts cluster assignments and membership degrees, and visualizes the results. ```python from skfda.datasets import fetch_weather from skfda.ml.clustering import KMeans, FuzzyCMeans from skfda.exploratory.visualization.clustering import ( ClusterPlot, ClusterMembershipPlot, ) import matplotlib.pyplot as plt # Load Canadian Weather temperature data X, y = fetch_weather(return_X_y=True, as_frame=True) fd = X.iloc[:, 0].array.coordinates[0] # K-Means clustering n_clusters = 4 kmeans = KMeans(n_clusters=n_clusters, random_state=42) kmeans.fit(fd) # Get cluster assignments labels = kmeans.predict(fd) print(f"Cluster assignments: {labels}") # Get cluster centroids centroids = kmeans.cluster_centers_ print(f"Number of centroids: {centroids.n_samples}") # Fuzzy C-Means clustering fuzzy_cmeans = FuzzyCMeans(n_clusters=n_clusters, random_state=42) fuzzy_cmeans.fit(fd) # Get membership degrees (soft clustering) membership = fuzzy_cmeans.predict_proba(fd) print(f"Membership shape: {membership.shape}") # (n_samples, n_clusters) # Visualize clusters fig, axes = plt.subplots(1, 2, figsize=(14, 5)) # K-Means cluster plot ClusterPlot(kmeans, fd).plot(axes=axes[0]) axes[0].set_title("K-Means Clustering") # Fuzzy C-Means membership plot ClusterMembershipPlot(fuzzy_cmeans, fd).plot(axes=axes[1]) axes[1].set_title("Fuzzy C-Means Membership") plt.tight_layout() plt.show() # Plot centroids fig, ax = plt.subplots(figsize=(10, 6)) centroids.plot(ax=ax) ax.legend([f"Cluster {i}" for i in range(n_clusters)]) ax.set_title("K-Means Cluster Centroids") plt.show() ``` -------------------------------- ### Finish Gitflow Release Branch Source: https://github.com/gaa-uam/scikit-fda/wiki/How-to-make-a-release Completes the release branch workflow in Gitflow. This action merges the release branch into the master and develop branches and cleans up the release branch. ```bash git flow release finish X.Y.Z ``` -------------------------------- ### Kernel Regression Source: https://github.com/gaa-uam/scikit-fda/blob/develop/docs/modules/ml/regression.rst Provides an implementation of Kernel Regression for functional data with a scalar response variable. This is a non-parametric technique. ```APIDOC ## Kernel Regression ### Description This module includes the implementation of Kernel Regression for FData with a scalar as a response variable. It is a non-parametric technique that uses a `HatMatrix` object. ### Available Classes - `skfda.ml.regression.KernelRegression` ```