# Molfeat > Featurización molecular para ML con más de 100 featurizers: ECFP, MACCS, descriptores, modelos preentrenados como ChemBERTa. Convierte SMILES en features para QSAR y ML molecular. Fuente: https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/molfeat Markdown: https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/molfeat.md Repositorio: https://github.com/K-Dense-AI/scientific-agent-skills Autor: K-Dense-AI Licencia: Apache-2.0 license Actualizado: el mes pasado Coste de contexto: 41 tok instalada, 3.1k tok al activarse, 14.5k tok con todos los archivos del bundle Bundle: 5 archivos, 56 KB Permisos que pide: read write edit bash ## Instalación Un skill son archivos markdown: los mismos archivos valen para cualquier agente y lo único que cambia es el directorio de destino, es decir la bandera `--agent`. Añade `-g` para instalarlo en todos los proyectos de la máquina. ```bash # Claude Code npx -y skills add K-Dense-AI/scientific-agent-skills --skill molfeat --agent claude-code # Cursor npx -y skills add K-Dense-AI/scientific-agent-skills --skill molfeat --agent cursor # Codex npx -y skills add K-Dense-AI/scientific-agent-skills --skill molfeat --agent codex # Gemini CLI npx -y skills add K-Dense-AI/scientific-agent-skills --skill molfeat --agent gemini # Windsurf npx -y skills add K-Dense-AI/scientific-agent-skills --skill molfeat --agent windsurf # Cline npx -y skills add K-Dense-AI/scientific-agent-skills --skill molfeat --agent cline ``` ## Qué hace - Convierte SMILES o moléculas RDKit en representaciones numéricas con más de 100 featurizers preentrenados y manuales - Ofrece Calculators, Transformers y Pretrained Transformers compatibles con scikit-learn para featurización en lote - Permite descubrir featurizers disponibles mediante ModelStore, incluyendo modelos como ChemBERTa - Guarda y recarga configuraciones de featurización para reproducibilidad con to_state_yaml_file - Maneja SMILES inválidos y datasets grandes con procesamiento paralelo y por bloques ## Cuándo usarla - Construir modelos QSAR/QSPR o de predicción de propiedades moleculares - Hacer cribado virtual o búsqueda de similitud estructural - Analizar espacio químico con clustering, visualización o reducción de dimensionalidad - Entrenar redes neuronales sobre datos moleculares o construir pipelines de featurización ## Qué la activa - "Convierte esta lista de SMILES en fingerprints ECFP con molfeat" - "Genera embeddings de ChemBERTa para estos compuestos" - "Construye un pipeline de featurización molecular para un modelo QSAR" ## Antes de instalar - Necesita Python 3.9-3.10 (molfeat 0.11.0 no soporta 3.11+), además de datamol y PyTorch, con extras opcionales para modelos GNN o transformer. ## Archivos - SKILL.md — 12 KB - references/api_reference.md — 11 KB - references/available_featurizers.md — 11 KB - references/choosing_a_featurizer.md — 5 KB - references/examples.md — 17 KB ## SKILL.md Reproducido tal cual desde K-Dense-AI/scientific-agent-skills bajo Apache-2.0 license. Esta sección es el documento original y está en inglés. # Molfeat - Molecular Featurization Hub ## Overview Molfeat is a comprehensive Python library for molecular featurization that unifies 100+ pre-trained embeddings and hand-crafted featurizers. Convert chemical structures (SMILES strings or RDKit molecules) into numerical representations for machine learning tasks including QSAR modeling, virtual screening, similarity searching, and deep learning applications. Features fast parallel processing, scikit-learn compatible transformers, and built-in caching. **Version note:** Examples target **molfeat 0.11.0** (PyPI stable, May 2025). Requires **Python 3.9–3.10** (`requires-python` caps below 3.11). Depends on **datamol ≥0.8.0** and **PyTorch ≥1.13**. Since 0.8.7, prefer datamol `Mol` objects over raw `rdkit.Chem.Mol`. Since 0.10.1, fingerprint calculators use RDKit's `rdFingerprintGenerator` API internally. Since 0.11.0, pretrained models load in memory and base models are set to PyTorch evaluation mode automatically. ## When to Use This Skill This skill should be used when working with: - **Molecular machine learning**: Building QSAR/QSPR models, property prediction - **Virtual screening**: Ranking compound libraries for biological activity - **Similarity searching**: Finding structurally similar molecules - **Chemical space analysis**: Clustering, visualization, dimensionality reduction - **Deep learning**: Training neural networks on molecular data - **Featurization pipelines**: Converting SMILES to ML-ready representations - **Cheminformatics**: Any task requiring molecular feature extraction ## Installation Use a Python 3.9 or 3.10 environment (molfeat does not install on 3.11+ as of 0.11.0): ```bash uv pip install "molfeat==0.11.0" # With all pip-installable optional dependencies uv pip install "molfeat[all]==0.11.0" ``` **Optional dependency extras (PyPI):** - `molfeat[dgl]` — GNN models (GIN variants); upstream recommends `dgl<=2.0` (graphbolt issues in newer DGL) - `molfeat[graphormer]` — Graphormer models - `molfeat[transformer]` — ChemBERTa, ChemGPT, MolT5 - `molfeat[fcd]` — FCD descriptors - `molfeat[pyg]` — PyTorch Geometric featurizers - `molfeat[viz]` — NGLView visualization widgets **External featurizers:** MAP4 is not bundled in molfeat extras — install from [reymond-group/map4](https://github.com/reymond-group/map4) separately. Some heavy deps (DGL, dgllife, graphormer-pretrained) are easier via conda-forge; see [optional dependencies](https://molfeat-docs.datamol.io/stable/). ## Core Concepts Molfeat organizes featurization into three hierarchical classes: ### 1. Calculators (`molfeat.calc`) Callable objects that convert individual molecules into feature vectors. Accept RDKit `Chem.Mol` objects or SMILES strings. **Use calculators for:** - Single molecule featurization - Custom processing loops - Direct feature computation **Example:** ```python from molfeat.calc import FPCalculator calc = FPCalculator("ecfp", radius=3, fpSize=2048) features = calc("CCO") # Returns numpy array (2048,) ``` ### 2. Transformers (`molfeat.trans`) Scikit-learn compatible transformers that wrap calculators for batch processing with parallelization. **Use transformers for:** - Batch featurization of molecular datasets - Integration with scikit-learn pipelines - Parallel processing (automatic CPU utilization) **Example:** ```python from molfeat.trans import MoleculeTransformer from molfeat.calc import FPCalculator transformer = MoleculeTransformer(FPCalculator("ecfp"), n_jobs=-1) features = transformer(smiles_list) # Parallel processing ``` ### 3. Pretrained Transformers (`molfeat.trans.pretrained`) Specialized transformers for deep learning models with batched inference and caching. **Use pretrained transformers for:** - State-of-the-art molecular embeddings - Transfer learning from large chemical datasets - Deep learning feature extraction **Example:** ```python from molfeat.trans.pretrained import PretrainedMolTransformer transformer = PretrainedMolTransformer("ChemBERTa-77M-MLM", n_jobs=-1) embeddings = transformer(smiles_list) # Deep learning embeddings ``` ## Quick Start Workflow ### Basic Featurization ```python import datamol as dm from molfeat.calc import FPCalculator from molfeat.trans import MoleculeTransformer # Load molecular data smiles = ["CCO", "CC(=O)O", "c1ccccc1", "CC(C)O"] # Create calculator and transformer calc = FPCalculator("ecfp", radius=3) transformer = MoleculeTransformer(calc, n_jobs=-1) # Featurize molecules features = transformer(smiles) print(f"Shape: {features.shape}") # (4, 2048) ``` ### Save and Load Configuration ```python # Save featurizer configuration for reproducibility transformer.to_state_yaml_file("featurizer_config.yml") # Reload exact configuration loaded = MoleculeTransformer.from_state_yaml_file("featurizer_config.yml") ``` ### Handle Errors Gracefully ```python # Process dataset with potentially invalid SMILES transformer = MoleculeTransformer( calc, n_jobs=-1, ignore_errors=True, # Continue on failures verbose=True # Log error details ) features = transformer(smiles_with_errors) # Returns None for failed molecules ``` ## Choosing a Featurizer and Common Workflows Featurizer choice by task — traditional ML (RF, SVM, XGBoost), deep learning, similarity searching, and pharmacophore-based approaches — plus worked workflows for QSAR model building, virtual screening, similarity search, scikit-learn pipeline integration, and comparing multiple featurizers, are in [references/choosing_a_featurizer.md](references/choosing_a_featurizer.md). The full featurizer list is in [references/available_featurizers.md](references/available_featurizers.md); more examples are in [references/examples.md](references/examples.md). ## Discovering Available Featurizers Use the ModelStore to explore all available featurizers: ```python from molfeat.store.modelstore import ModelStore store = ModelStore() # List all available models all_models = store.available_models print(f"Total featurizers: {len(all_models)}") # Search for specific models chemberta_models = store.search(name="ChemBERTa") for model in chemberta_models: print(f"- {model.name}: {model.description}") # Get usage information model_card = store.search(name="ChemBERTa-77M-MLM")[0] model_card.usage() # Display usage examples # Load model transformer = store.load("ChemBERTa-77M-MLM") ``` ## Advanced Features ### Custom Preprocessing ```python class CustomTransformer(MoleculeTransformer): def preprocess(self, mol): """Custom preprocessing pipeline""" if isinstance(mol, str): mol = dm.to_mol(mol) mol = dm.standardize_mol(mol) mol = dm.remove_salts(mol) return mol transformer = CustomTransformer(FPCalculator("ecfp"), n_jobs=-1) ``` ### Batch Processing Large Datasets ```python import numpy as np def featurize_in_chunks(smiles_list, transformer, chunk_size=10000): """Process large datasets in chunks to manage memory""" all_features = [] for i in range(0, len(smiles_list), chunk_size): chunk = smiles_list[i:i+chunk_size] features = transformer(chunk) all_features.append(features) return np.vstack(all_features) ``` ### Caching Expensive Embeddings Prefer molfeat's built-in pretrained-model cache when possible. For custom embedding caches, use NumPy arrays instead of pickle (pickle can execute arbitrary code when loading untrusted files): ```python import numpy as np from pathlib import Path cache_file = Path("embeddings_cache.npz") # fixed path under your project transformer = PretrainedMolTransformer("ChemBERTa-77M-MLM", n_jobs=-1) if cache_file.exists(): embeddings = np.load(cache_file)["embeddings"] else: embeddings = transformer(smiles_list) np.savez(cache_file, embeddings=embeddings) ``` ## Performance Tips 1. **Use parallelization**: Set `n_jobs=-1` to utilize all CPU cores 2. **Batch processing**: Process multiple molecules at once instead of loops 3. **Choose appropriate featurizers**: Fingerprints are faster than deep learning models 4. **Cache pretrained models**: Leverage built-in caching for repeated use 5. **Use float32**: Set `dtype=np.float32` when precision allows 6. **Handle errors efficiently**: Use `ignore_errors=True` for large datasets ## Common Featurizers Reference **Quick reference for frequently used featurizers:** | Featurizer | Type | Dimensions | Speed | Use Case | |------------|------|------------|-------|----------| | `ecfp` | Fingerprint | 2048 | Fast | General purpose | | `maccs` | Fingerprint | 167 | Very fast | Scaffold similarity | | `desc2D` | Descriptors | 200+ | Fast | Interpretable models | | `mordred` | Descriptors | 1800+ | Medium | Comprehensive features | | `map4` | Fingerprint | 1024 | Fast | Large-scale screening | | `ChemBERTa-77M-MLM` | Deep learning | 768 | Slow* | Transfer learning | | `gin-supervised-masking` | GNN | Variable | Slow* | Graph-based models | *First run is slow; subsequent runs benefit from caching ## Resources This skill includes comprehensive reference documentation: ### references/api_reference.md Complete API documentation covering: - `molfeat.calc` - All calculator classes and parameters - `molfeat.trans` - Transformer classes and methods - `molfeat.store` - ModelStore usage - Common patterns and integration examples - Performance optimization tips **When to load:** Reference when implementing specific calculators, understanding transformer parameters, or integrating with scikit-learn/PyTorch. ### references/available_featurizers.md Comprehensive catalog of all 100+ featurizers organized by category: - Transformer-based language models (ChemBERTa, ChemGPT) - Graph neural networks (GIN, Graphormer) - Molecular descriptors (RDKit, Mordred) - Fingerprints (ECFP, MACCS, MAP4, and 15+ others) - Pharmacophore descriptors (CATS, Gobbi) - Shape descriptors (USR, ElectroShape) - Scaffold-based descriptors **When to load:** Reference when selecting the optimal featurizer for a specific task, exploring available options, or understanding featurizer characteristics. **Search tip:** Use grep to find specific featurizer types: ```bash grep -i "chembert" references/available_featurizers.md grep -i "pharmacophore" references/available_featurizers.md ``` ### references/examples.md Practical code examples for common scenarios: - Installation and quick start - Calculator and transformer examples - Pretrained model usage - Scikit-learn and PyTorch integration - Virtual screening workflows - QSAR model building - Similarity searching - Troubleshooting and best practices **When to load:** Reference when implementing specific workflows, troubleshooting issues, or learning molfeat patterns. ## Troubleshooting ### Invalid Molecules Enable error handling to skip invalid SMILES: ```python transformer = MoleculeTransformer( calc, ignore_errors=True, verbose=True ) ``` ### Memory Issues with Large Datasets Process in chunks or use streaming approaches for datasets > 100K molecules. ### Pretrained Model Dependencies Some models require additional packages. Install specific extras (pin version for reproducibility): ```bash uv pip install "molfeat[transformer]==0.11.0" # For ChemBERTa/ChemGPT uv pip install "molfeat[dgl]==0.11.0" # For GIN models uv pip install "molfeat[graphormer]==0.11.0" # For Graphormer ``` ### Reproducibility Save exact configurations and document versions: ```python transformer.to_state_yaml_file("config.yml") import molfeat print(f"molfeat version: {molfeat.__version__}") ``` ## Additional Resources - **Official Documentation**: https://molfeat-docs.datamol.io/ - **GitHub Repository**: https://github.com/datamol-io/molfeat - **PyPI Package**: https://pypi.org/project/molfeat/ - **Tutorial**: https://portal.valencelabs.com/datamol/post/types-of-featurizers-b1e8HHrbFMkbun6 ## Dónde encaja - Categoría: [Datos y analítica](https://skillsagentes.com/categorias/datos-analitica.md) — Consulta, limpia y visualiza datos sin salir del agente. - Creador: [K-Dense-AI](https://skillsagentes.com/creators/k-dense-ai.md) — 163 skills en el directorio - [Todas las skills](https://skillsagentes.com/skills.md) - [Ranking de instalaciones](https://skillsagentes.com/ranking.md) ## Otras skills del mismo repositorio - [Citation Management](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/citation-management.md): Gestión integral de citas académicas: busca en OpenAlex, PubMed y Google Scholar, extrae metadatos precisos, valida citas y genera entradas BibTeX correctamente formateadas. - [Scientific Slides](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/scientific-slides.md): Crea decks de diapositivas y presentaciones para charlas de investigación: PowerPoint, presentaciones de conferencia, seminarios, defensas de tesis. Da estructura, plantillas, guía de tiempos y validación visual. - [Literature Review](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/literature-review.md): Realiza revisiones bibliográficas sistemáticas y completas usando varias bases académicas (PubMed, arXiv, bioRxiv, Semantic Scholar). Genera markdown y PDF con citas verificadas en varios estilos (APA, Nature, Vancouver). - [Infographics](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/infographics.md): Crea infografías profesionales con Nano Banana Pro AI y refinamiento iterativo inteligente. Usa Gemini 3.6 Flash para revisar la calidad e integra investigación con Perplexity Sonar. Soporta 10 tipos, 8 estilos y paletas para daltonismo. - [Latex Posters](https://skillsagentes.com/skills/k-dense-ai/scientific-agent-skills/latex-posters.md): Crea pósteres de investigación profesionales en LaTeX con beamerposter, tikzposter o baposter, para conferencias y comunicación científica: layout, colores, columnas múltiples e integración de figuras. --- Skills Agentes · [Índice de páginas en markdown](https://skillsagentes.com/sitemap.md) · [Inicio](https://skillsagentes.com/index.md)