{"data":{"slug":"github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-lightgbm-analysis-0f90d6f86cad","title":"LightGBM Feature Importance Analysis","summary":"Train a LightGBM model on tabular data and export feature importance rankings as a table and figure. Requires Rscript and specific R packages.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-lightgbm-analysis-0f90d6f86cad","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-lightgbm-analysis-0f90d6f86cad","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-lightgbm-analysis-0f90d6f86cad.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-awesome-med-research-skills-data-analysis-lightgbm-analysis-0f90d6f86cad\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Ensure `Rscript` is available and install required R packages: `optparse`, `data.table`, and `lightgbm`. The input file must include a target column and have at least 20 rows after removing missing target values. Character features are label-encoded internally.","instructions":"---\nname: lightgbm-analysis\ndescription: Use when training a LightGBM model on tabular data in R and returning model metrics, feature importance ranking tables, and feature importance plots.\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n# LightGBM Analysis\n\nUse this skill to build a LightGBM model on tabular data and export feature importance ranking results as both a table and a figure.\n\n## Use This Skill When\n\n- You need a command-line LightGBM workflow written in R.\n- You need classification or regression on structured tabular data.\n- You need ranked feature importance outputs for reporting or interpretation.\n- You need standardized outputs under `table\/`, `figure\/`, and `data\/`.\n\n## Primary Command\n\n```bash\nRscript scripts\/main.R \\\n  --data_file <input_file> \\\n  --target_var <target_column> \\\n  --output_dir <output_dir>\n```\n\n## Prerequisites\n\n- `Rscript` is available in the shell.\n- Required R packages: `optparse`, `data.table`, `lightgbm`.\n- Install basic dependencies with `Rscript -e 'install.packages(c(\"optparse\", \"data.table\"), repos=\"https:\/\/cloud.r-project.org\")'`.\n- Install the R `lightgbm` package from the LightGBM project because it is usually not available from CRAN.\n\n## Core Arguments\n\n| Argument | Required | Description |\n|----------|----------|-------------|\n| `--data_file` | Yes | Input data file in CSV format or tab-delimited TXT\/TSV format |\n| `--target_var` | Yes | Target column used for modeling |\n| `--output_dir` | No | Output directory, default `.\/LightGBM_Results` |\n| `--fail_if_output_exists` | No | Stop instead of overwriting when `output_dir` already contains files |\n| `--task_type` | No | `auto`, `regression`, `binary`, or `multiclass`. Default `auto` |\n| `--feature_cols` | No | Comma-separated feature columns. Default uses all columns except target and dropped columns |\n| `--drop_cols` | No | Comma-separated columns to exclude before modeling |\n| `--importance_type` | No | `gain` or `split`. Default `gain` |\n| `--top_n` | No | Number of features to show in the importance plot. Default `20` |\n| `--output_format` | No | `csv` or `txt` table export. Default `csv` |\n\n## Modeling Arguments\n\n| Argument | Default | Description |\n|----------|---------|-------------|\n| `--metric` | `auto` | Evaluation metric matched to task type |\n| `--test_size` | `0.2` | Test-set proportion |\n| `--valid_size` | `0.2` | Validation proportion taken from the training partition |\n| `--nrounds` | `500` | Maximum boosting rounds |\n| `--learning_rate` | `0.05` | Shrinkage rate |\n| `--num_leaves` | `31` | Maximum leaf count per tree |\n| `--max_depth` | `-1` | Maximum tree depth, `-1` means no explicit limit |\n| `--min_data_in_leaf` | `5` | Minimum samples per leaf |\n| `--feature_fraction` | `0.8` | Column sampling ratio |\n| `--bagging_fraction` | `0.8` | Row sampling ratio |\n| `--bagging_freq` | `1` | Bagging frequency |\n| `--lambda_l1` | `0` | L1 regularization |\n| `--lambda_l2` | `0` | L2 regularization |\n| `--early_stopping_rounds` | `50` | Early stopping patience |\n| `--seed` | `42` | Random seed |\n\n## Input Requirements\n\n- The input file must include the target column.\n- Prefer `.csv` or `.tsv` inputs. `.txt` files must be tab-delimited.\n- The skill expects at least 20 rows after removing missing target values.\n- Features may be numeric, integer, logical, character, or factor-like text.\n- Character features are label-encoded internally for LightGBM.\n- Missing target values are removed before modeling.\n- Missing feature values are left for LightGBM to handle.\n- If `task_type=auto`, the script infers regression or classification from the target values.\n\nBundled test data examples:\n\n```csv\nV1,fustat,CAMK2N2,GGT6,GPR161,RAB26,RIBC2\nTCGA-C5-A1M5,1,2.248291938,5.274690305,2.825215762,3.121114894,5.35318565\nTCGA-EA-A5O9,0,3.346176843,5.404368414,2.604616977,0.629473197,4.429314674\nTCGA-C5-A3HL,0,3.363100974,5.363314779,4.124799581,4.127228806,4.916596068\n```\n\n## Minimal Workflow\n\n1. Confirm the input file exists and the target column name is correct.\n2. Remove identifier or sensitive columns such as `id`, `sample_id`, `patient_id`, accession numbers, or the bundled sample identifier column `V1` before training.\n3. Set `--drop_cols` and optionally `--feature_cols` so the model only sees intended predictors.\n4. If you need overwrite protection, add `--fail_if_output_exists` or choose a fresh `--output_dir`.\n5. Run `scripts\/main.R`.\n6. Check `table\/` for the importance table, model metrics, and remediation guidance.\n7. Check `figure\/` for the feature importance ranking plot and `data\/` for the run summary.\n\nAvoid ambiguous text exports. If a `.txt` file is parsed as one column, re-export it as tab-delimited text or CSV before rerunning.\n\nFor quick validation in small audit environments, prefer the bundled `dt_sample3.txt` smoke test shown below with reduced `--nrounds` and `--early_stopping_rounds`. The full binary example on `dt_sample1.csv` is still useful as a complete workflow example, but it can exceed short runtime budgets.\n\nIf you omit `--data_file` or `--target_var`, the script exits with `SKILL_MISSING_INPUT`.\n\n## Outputs\n\nExpected output structure:\n\n```text\n<output_dir>\/\n\u251c\u2500\u2500 table\/\n\u251c\u2500\u2500 figure\/\n\u2514\u2500\u2500 data\/\n```\n\nPrimary result files:\n\n- `table\/lightgbm_feature_importance.<output_format>`\n- `table\/lightgbm_model_metrics.<output_format>`\n- `table\/lightgbm_remediation.<output_format>`\n- `figure\/lightgbm_feature_importance_<importance_type>.pdf`\n- `data\/lightgbm_run_summary.txt`\n- `data\/lightgbm_categorical_levels.txt` when categorical or character predictors were encoded\n\nFeature importance table fields include:\n\n- `feature`\n- `gain`\n- `split`\n- `cover`\n- `importance_type`\n- `importance_value`\n- `rank`\n- `gain_share`\n- `split_share`\n\nModel metrics include:\n\n- `task_type`\n- `metric_primary`\n- `best_iteration`\n- `train_rows`\n- `valid_rows`\n- `test_rows`\n- `prediction_collapse_flag`\n- `model_quality_flag`\n- `interpretation_status`\n- `primary_issue`\n- `model_quality_issues`\n- `rerun_hint`\n- `model_quality_note`\n- task-specific evaluation metrics such as `rmse`, `mae`, `accuracy`, `auc`, or `logloss`\n\nRemediation table fields include:\n\n- `task_type`\n- `model_quality_flag`\n- `interpretation_status`\n- `issue_code`\n- `issue_detail`\n- `recommended_action`\n- `suggested_rerun_change`\n\nRun summary file includes the task type, best iteration, primary quality fields, top features, and artifact paths for the completed run.\n\n## Overwrite Behavior\n\n- Rerunning into an existing `output_dir` replaces prior result files with the new metrics, importance table, remediation table, figure, and session metadata.\n- Set `--fail_if_output_exists` when you want the run to stop instead of replacing prior artifacts.\n- If you need an audit trail, prefer a timestamped or per-run `output_dir`.\n- The script now warns when `output_dir` already contains files.\n\n## Success And Failure Contract\n\nSuccess:\n\n- Console output should end with `LightGBM analysis completed successfully`.\n- `table\/lightgbm_model_metrics.<output_format>` and `table\/lightgbm_feature_importance.<output_format>` should exist.\n- `table\/lightgbm_remediation.<output_format>` and `data\/lightgbm_run_summary.txt` should exist.\n- `figure\/lightgbm_feature_importance_<importance_type>.pdf` should exist.\n- The importance table should contain at least one non-zero `gain` or `split` value.\n\nFailure or caution:\n\n- If parsing fails, expect a `SKILL_*` message instead of a raw stack trace.\n- If `best_iteration <= 1`, predictions collapse to one class, `recall` is `0`, `f1` is `NA`, or the selected importance values are mostly zero, do not treat the ranking as reliable.\n- Review `model_quality_flag` and `model_quality_note` in `table\/lightgbm_model_metrics.csv` before interpreting the exported ranking.\n- Use `interpretation_status` to decide whether the run is report-ready: `eligible` means interpretation-ready, `eligible_with_caveats` means the ranking may still be usable with caveats, and `caution_only` means diagnostic-only.\n- Review `table\/lightgbm_remediation.csv` and `rerun_hint` for the exact failure mode and recommended rerun changes.\n- Recheck delimiter choice, identifier leakage, and `--min_data_in_leaf` before trusting the outputs.\n\n## Caution Remediation\n\n- `best_iteration<=1`: lower `--min_data_in_leaf` and verify that the selected predictors have usable signal.\n- `single_predicted_class`: review class balance and feature selection before using the ranking downstream.\n- `recall=0` or `no_positive_predictions`: revisit `--feature_cols` and the target balance before treating the run as report-ready.\n- `<importance_type>_importance_sparse`: compare against the alternate importance type and review whether the retained predictors have enough signal.\n\n## Agent Response Contract\n\nWhen this skill completes, the agent should report:\n\n- resolved `task_type`\n- `best_iteration`\n- primary evaluation metrics from `table\/lightgbm_model_metrics.<output_format>`\n- top ranked features from `table\/lightgbm_feature_importance.<output_format>`\n- `model_quality_flag` and `interpretation_status`\n- artifact paths for the metrics table, importance table, remediation table, figure, and run summary file\n\nIf `model_quality_flag` is not `ok`, the agent must explicitly say the run is diagnostic-only or caveat-limited and include the recommended rerun changes from `rerun_hint` or `table\/lightgbm_remediation.<output_format>`.\n\n## Feature Importance Guidance\n\n- Use `gain` when you care about overall contribution to loss reduction.\n- Use `split` when you care about how often a feature is used in tree splits.\n- Prefer `gain` for most ranking summaries and reports.\n- Low importance does not imply no business value, especially under correlated features.\n\n## Read These Files When Needed\n\n| Need | File |\n|------|------|\n| LightGBM method details and importance interpretation | `references\/algorithm.md` |\n| CLI examples | `references\/cli-guide.md` |\n| Error diagnosis | `references\/troubleshooting.md` |\n| Main entry point | `scripts\/main.R` |\n| Sample test data | `tests\/data\/` |\n\n## Quick Examples\n\nFast smoke test with `dt_sample3.txt`:\n\n```bash\nRscript scripts\/main.R \\\n  --data_file tests\/data\/dt_sample3.txt \\\n  --target_var Group \\\n  --drop_cols V1 \\\n  --task_type binary \\\n  --nrounds 80 \\\n  --early_stopping_rounds 20 \\\n  --top_n 15 \\\n  --output_dir tests\/output_smoke_txt\n```\n\nAudit-friendly binary preset for short runtime budgets:\n\n```bash\nRscript scripts\/main.R \\\n  --data_file tests\/data\/dt_sample1.csv \\\n  --target_var fustat \\\n  --drop_cols V1 \\\n  --task_type binary \\\n  --nrounds 120 \\\n  --early_stopping_rounds 20 \\\n  --output_dir tests\/output_binary_fast\n```\n\nFull binary workflow example with `dt_sample1.csv`:\n\n```bash\nRscript scripts\/main.R \\\n  --data_file tests\/data\/dt_sample1.csv \\\n  --target_var fustat \\\n  --drop_cols V1 \\\n  --task_type binary \\\n  --output_dir tests\/output_binary\n```\n\nSplit-based importance export example with `dt_sample2.csv`:\n\nUse this to verify split-based ranking output. Review `model_quality_flag` and `interpretation_status` before treating the bundled example as report-ready because this path can remain diagnostic-only on small test splits.\n\n```bash\nRscript scripts\/main.R \\\n  --data_file tests\/data\/dt_sample2.csv \\\n  --target_var fustat \\\n  --feature_cols CAMK2N2,GGT6,GPR161,RAB26,RIBC2 \\\n  --drop_cols V1 \\\n  --task_type binary \\\n  --importance_type split \\\n  --output_dir tests\/output_binary_split\n```\n\nAudit-friendly regression preset with `dt_sample1.csv` and `RIBC2` as the target:\n\n```bash\nRscript scripts\/main.R \\\n  --data_file tests\/data\/dt_sample1.csv \\\n  --target_var RIBC2 \\\n  --drop_cols V1 \\\n  --task_type regression \\\n  --nrounds 120 \\\n  --early_stopping_rounds 20 \\\n  --output_dir tests\/output_regression_fast\n```\n\nFull regression workflow with `dt_sample1.csv` and `RIBC2` as the target:\n\n```bash\nRscript scripts\/main.R \\\n  --data_file tests\/data\/dt_sample1.csv \\\n  --target_var RIBC2 \\\n  --drop_cols V1 \\\n  --task_type regression \\\n  --output_dir tests\/output_regression\n```\n\nTab-delimited TXT input with automatic binary target encoding from `Group`:\n\n```bash\nRscript scripts\/main.R \\\n  --data_file tests\/data\/dt_sample3.txt \\\n  --target_var Group \\\n  --drop_cols V1 \\\n  --task_type binary \\\n  --top_n 15 \\\n  --output_dir tests\/output_group_txt\n```\n\n## Validation\n\n```bash\nRscript scripts\/main.R --help\n```\n\nUse the smoke test under `## Quick Examples` for a fast validation pass. After a successful run, verify that these files exist under the selected `output_dir`:\n\n- `table\/lightgbm_feature_importance.csv`\n- `table\/lightgbm_model_metrics.csv`\n- `table\/lightgbm_remediation.csv`\n- `figure\/lightgbm_feature_importance_<importance_type>.pdf`\n- `data\/lightgbm_run_summary.txt`\n- `data\/lightgbm_categorical_levels.txt` if categorical or character predictors were encoded\n\n## When Not To Use\n\n- The input file is an unstructured note, JSON blob, or free-text report.\n- The text file delimiter is unknown and you cannot inspect or re-export it.\n- The table still contains sample IDs, patient IDs, accession numbers, or similar identifiers that should not be model features.\n- The input still contains direct identifiers or sensitive fields that you have not reviewed and removed from modeling.\n\n## Common Errors\n\n- `SKILL_FILE_NOT_FOUND`: Input file path is wrong or inaccessible.\n- `SKILL_MISSING_COLUMNS`: The target or requested feature columns are missing.\n- `SKILL_INVALID_DATA`: Data types, target encoding, or row count are unsuitable for LightGBM.\n- `SKILL_DEGENERATE_MODEL`: Training finished but the exported importance table is all zero and should not be interpreted.\n- `SKILL_INVALID_PARAMETER`: An argument value is invalid.\n- `SKILL_DEPENDENCY_MISSING`: Required package such as `lightgbm` is unavailable.\n- `SKILL_TRAINING_FAILED`: LightGBM training failed.\n\nBefore sharing exported artifacts, verify that identifier-like columns such as `V1`, sample IDs, or patient IDs were excluded from modeling and from any published tables. If `model_quality_flag` is not `ok`, treat the run as a diagnostic result rather than an interpretable ranking.\n\nIf the issue is not obvious, read `references\/troubleshooting.md`.\n","use_cases":["Train a LightGBM model on medical research data to identify the most important features.","Generate feature importance rankings for reporting or interpretation in a medical research context."],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/awesome-med-research-skills\/Data%20Analysis\/LightGBM-analysis\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T06:50:56.000000Z","updated_at":"2026-11-24T07:13:04.000000Z","seo_title":"LightGBM Feature Importance Analysis","seo_description":"Train a LightGBM model on tabular data and export feature importance ranking results as both a table and a figure.","seo_keywords":["LightGBM feature importance","tabular data analysis","medical research feature ranking","LightGBM model training","feature importance plot"]}}