### Install umap-learn via Conda or Mamba Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Commands to configure the conda-forge channel and install the umap-learn package. Includes utilities for querying package dependencies and reverse dependencies. ```bash conda config --add channels conda-forge conda config --set channel_priority strict conda install umap-learn mamba install umap-learn conda search umap-learn --channel conda-forge mamba repoquery depends umap-learn --channel conda-forge mamba repoquery whoneeds umap-learn --channel conda-forge ``` -------------------------------- ### Build umap-learn Feedstock Locally (Bash) Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Provides bash commands to clone the umap-learn feedstock repository and build the conda package locally. It includes examples for different platforms (Linux, macOS, Windows), using help, debugging, and filtering build configurations. ```bash # Clone the feedstock git clone https://github.com/conda-forge/umap-learn-feedstock.git cd umap-learn-feedstock # List available build configurations python build-locally.py --help # Build for specific Python version on Linux (uses Docker) python build-locally.py linux_64_python3.11.____cpython # Build for macOS (requires OSX SDK) export OSX_SDK_DIR=$PWD/SDKs python build-locally.py osx_64_python3.11.____cpython # Build for Windows python build-locally.py win_64_python3.11.____cpython # Interactive selection of build config python build-locally.py # Debug mode for troubleshooting python build-locally.py linux_64_python3.11.____cpython --debug # Filter available configurations python build-locally.py --filter "linux_64*" ``` -------------------------------- ### Parametric UMAP with Neural Networks (Python) Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Implements Parametric UMAP using TensorFlow to learn a parametric mapping from high-dimensional to low-dimensional space. This enables fast inference on new data after training. Requires TensorFlow installation. ```python import numpy as np # Note: Requires tensorflow installation # pip install tensorflow try: from umap.parametric_umap import ParametricUMAP # Sample data np.random.seed(42) X_train = np.random.rand(2000, 100).astype(np.float32) X_test = np.random.rand(500, 100).astype(np.float32) # Parametric UMAP with neural network encoder reducer = ParametricUMAP( n_components=2, n_neighbors=15, min_dist=0.1, metric='euclidean', n_epochs=100, verbose=True ) # Fit learns a neural network mapping train_embedding = reducer.fit_transform(X_train) # Fast inference using learned network test_embedding = reducer.transform(X_test) print(f"Train embedding: {train_embedding.shape}") print(f"Test embedding: {test_embedding.shape}") # Access the encoder model encoder = reducer.encoder print(f"Encoder summary: {encoder.summary()}") except ImportError: print("ParametricUMAP requires TensorFlow. Install with: pip install tensorflow") ``` -------------------------------- ### UMAP Hyperparameter Tuning with Scikit-learn Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Shows how to tune UMAP hyperparameters such as n_neighbors, min_dist, and n_components within a scikit-learn pipeline. This example uses cross-validation to evaluate the performance of UMAP combined with a KNeighborsClassifier on the digits dataset. ```python import numpy as np import umap from sklearn.datasets import load_digits from sklearn.model_selection import cross_val_score from sklearn.neighbors import KNeighborsClassifier from sklearn.pipeline import Pipeline digits = load_digits() X, y = digits.data, digits.target results = [] for n_neighbors in [15, 30]: for min_dist in [0.0, 0.1]: for n_components in [5, 10]: pipeline = Pipeline([ ('umap', umap.UMAP( n_neighbors=n_neighbors, min_dist=min_dist, n_components=n_components, random_state=42 )), ('knn', KNeighborsClassifier(n_neighbors=5)) ]) scores = cross_val_score(pipeline, X, y, cv=3, scoring='accuracy') mean_score = scores.mean() results.append({ 'n_neighbors': n_neighbors, 'min_dist': min_dist, 'n_components': n_components, 'accuracy': mean_score }) print(f"n_neighbors={n_neighbors}, min_dist={min_dist}, " f"n_components={n_components}: {mean_score:.3f}") ``` -------------------------------- ### Perform Supervised UMAP Dimension Reduction Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Shows how to incorporate target class labels into the UMAP fitting process to guide the manifold learning toward better class separation. ```python import numpy as np import umap from sklearn.datasets import load_digits import matplotlib.pyplot as plt digits = load_digits() data = digits.data labels = digits.target reducer = umap.UMAP(n_neighbors=15, n_components=2, min_dist=0.1, metric='euclidean', random_state=42) embedding = reducer.fit_transform(data, y=labels) plt.scatter(embedding[:, 0], embedding[:, 1], c=labels, cmap='Spectral', s=5) plt.colorbar() plt.title('Supervised UMAP: Digits Dataset') plt.show() ``` -------------------------------- ### UMAP with Custom and Built-in Distance Metrics (Python) Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Demonstrates using various built-in distance metrics like 'cosine' and 'correlation' with UMAP. It also shows how to define and use a custom distance function, optimized with Numba for performance. This allows for domain-specific data analysis. ```python import numpy as np import umap from numba import njit # Sample data np.random.seed(42) data = np.random.rand(500, 100) # UMAP with built-in metrics # Available: euclidean, manhattan, chebyshev, minkowski, cosine, correlation, etc. reducer_cosine = umap.UMAP(metric='cosine', random_state=42) embedding_cosine = reducer_cosine.fit_transform(data) reducer_correlation = umap.UMAP(metric='correlation', random_state=42) embedding_corr = reducer_reducer_correlation.fit_transform(data) # Custom distance function using Numba for performance @njit def custom_distance(x, y): """Custom weighted Euclidean distance.""" result = 0.0 for i in range(x.shape[0]): weight = 1.0 / (i + 1) # Decreasing weights result += weight * (x[i] - y[i]) ** 2 return np.sqrt(result) reducer_custom = umap.UMAP(metric=custom_distance, random_state=42) embedding_custom = reducer_custom.fit_transform(data) print(f"Cosine metric embedding: {embedding_cosine.shape}") print(f"Correlation metric embedding: {embedding_corr.shape}") print(f"Custom metric embedding: {embedding_custom.shape}") ``` -------------------------------- ### Perform Basic Unsupervised UMAP Dimension Reduction Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Demonstrates how to initialize the UMAP transformer and reduce high-dimensional data to 2D using the scikit-learn compatible fit_transform API. ```python import numpy as np import umap import matplotlib.pyplot as plt np.random.seed(42) data = np.random.rand(1000, 50) reducer = umap.UMAP(n_neighbors=15, n_components=2, min_dist=0.1, metric='euclidean', random_state=42) embedding = reducer.fit_transform(data) plt.scatter(embedding[:, 0], embedding[:, 1], s=5, alpha=0.5) plt.title('UMAP Projection') plt.show() ``` -------------------------------- ### Transform New Data with Fitted UMAP Model Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Illustrates how to fit a UMAP model on training data and subsequently project unseen test data into the same learned embedding space. ```python import numpy as np import umap from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt X = np.random.rand(1000, 50) X_train, X_test = train_test_split(X, test_size=0.2, random_state=42) reducer = umap.UMAP(n_components=2, random_state=42) train_embedding = reducer.fit_transform(X_train) test_embedding = reducer.transform(X_test) plt.scatter(train_embedding[:, 0], train_embedding[:, 1], s=5, label='Train') plt.scatter(test_embedding[:, 0], test_embedding[:, 1], s=5, label='Test') plt.legend() plt.show() ``` -------------------------------- ### Conda Recipe Configuration (meta.yaml) Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt The meta.yaml file defines the conda package metadata, including version, source, build scripts, and runtime dependencies for umap-learn. It specifies requirements like Python, NumPy, Numba, and Scikit-learn. ```yaml {% set name = "umap-learn" %} {% set version = "0.5.11" %} {% set sha256 = "31566ffd495fbf05d7ab3efcba703861c0f5e6fc6998a838d0e2becdd00e54f5" %} package: name: {{ name|lower }} version: {{ version }} source: fn: {{ name }}-{{ version }}.tar.gz url: https://pypi.org/packages/source/{{ name[0] }}/{{ name }}/{{ name | replace('-', '_') }}-{{ version }}.tar.gz sha256: {{ sha256 }} build: number: 0 script: {{ PYTHON }} -m pip install . --no-deps -vv requirements: build: - python # [build_platform != target_platform] - cross-python_{{ target_platform }} # [build_platform != target_platform] host: - python - setuptools - pip run: - python - setuptools - numpy >=1.17 - numba >=0.51.2 - scikit-learn >=0.22 - scipy >=1.3.1 - tbb >=2019.0 - pynndescent >=0.5 - tqdm test: imports: - umap about: home: http://github.com/lmcinnes/umap license: BSD-2-Clause license_family: BSD summary: Uniform Manifold Approximation and Projection ``` -------------------------------- ### UMAP Pipeline with Scikit-learn for Clustering Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Demonstrates integrating UMAP into a scikit-learn pipeline for preprocessing, dimensionality reduction, and clustering. The pipeline first scales the data, then applies UMAP for dimensionality reduction, and finally uses KMeans for clustering. It includes visualization of the UMAP embedding. ```python import numpy as np import umap from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.datasets import make_blobs X, y_true = make_blobs(n_samples=1000, n_features=50, centers=5, random_state=42) pipeline = Pipeline([ ('scaler', StandardScaler()), ('umap', umap.UMAP(n_components=10, random_state=42)), ('kmeans', KMeans(n_clusters=5, random_state=42)) ]) y_pred = pipeline.fit_predict(X) from sklearn.metrics import adjusted_rand_score ari = adjusted_rand_score(y_true, y_pred) print(f"Adjusted Rand Index: {ari:.3f}") viz_pipeline = Pipeline([ ('scaler', StandardScaler()), ('umap', umap.UMAP(n_components=2, random_state=42)) ]) embedding = viz_pipeline.fit_transform(X) import matplotlib.pyplot as plt plt.scatter(embedding[:, 0], embedding[:, 1], c=y_pred, cmap='viridis', s=5) plt.title(f'UMAP + KMeans Clustering (ARI={ari:.3f})') plt.show() ``` -------------------------------- ### Identify Best UMAP Parameters Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt This snippet iterates through a list of UMAP result dictionaries to find the entry with the highest accuracy value. It uses the Python max function with a lambda key to select the dictionary containing the optimal configuration. ```python best = max(results, key=lambda x: x['accuracy']) print(f"\nBest: {best}") ``` -------------------------------- ### Update umap-learn Conda Feedstock Source: https://context7.com/conda-forge/umap-learn-feedstock/llms.txt Steps to update the umap-learn package in a conda feedstock. This involves forking and cloning the repository, creating a new branch, updating the version and checksum in meta.yaml, resetting the build number, re-rendering the feedstock, testing the build locally, and committing the changes. ```bash git clone https://github.com/YOUR_USERNAME/umap-learn-feedstock.git cd umap-learn-feedstock git checkout -b update-to-0.5.12 # Edit recipe/meta.yaml: Update version and sha256 hash curl -sL https://pypi.org/pypi/umap-learn/0.5.12/json | python -c "import sys,json; print(json.load(sys.stdin)['urls'][0]['digests']['sha256'])" # Reset build number to 0 conda smithy rerender python build-locally.py linux_64_python3.11.____cpython git add . git commit -m "Update umap-learn to 0.5.12" git push origin update-to-0.5.12 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.