scientific-computing-system 1.0.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +284 -0
- package/LICENSE +0 -0
- package/README.md +89 -218
- package/SECURITY.md +0 -0
- package/bin/scs.js +12 -2
- package/index.js +115 -1
- package/package.json +45 -1
- package/.binder/postBuild +0 -9
- package/.binder/requirements.txt +0 -10
- package/.gitattributes +0 -35
- package/.github/CODEOWNERS +0 -4
- package/.github/FUNDING.yml +0 -3
- package/.github/ISSUE_TEMPLATE/bug_report.md +0 -50
- package/.github/ISSUE_TEMPLATE/config.yml +0 -8
- package/.github/ISSUE_TEMPLATE/feature_request.md +0 -28
- package/.github/PULL_REQUEST_TEMPLATE.md +0 -29
- package/.github/dependabot.yml +0 -32
- package/.github/labeler.yml +0 -50
- package/.github/workflows/benchmarks.yml +0 -97
- package/.github/workflows/bot-reviewer.yml +0 -58
- package/.github/workflows/changelog.yml +0 -130
- package/.github/workflows/cli-package-smoke.yml +0 -45
- package/.github/workflows/codeql.yml +0 -55
- package/.github/workflows/npm-publish.yml +0 -33
- package/.github/workflows/p08-cancel-noncanonical-runs.yml +0 -41
- package/.github/workflows/pr-automation.yml +0 -78
- package/.github/workflows/public-external-validation-p08-v2-glm.yml +0 -161
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge-gate.yml +0 -72
- package/.github/workflows/public-external-validation-p08-v2-recovery-merge.yml +0 -113
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-anatomy-gate.yml +0 -57
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge-gate.yml +0 -63
- package/.github/workflows/public-external-validation-p08-v2-run-recovery-merge.yml +0 -89
- package/.github/workflows/public-external-validation-p08-v2-run-recovery.yml +0 -182
- package/.github/workflows/public-external-validation-p08-v3-glm-gate.yml +0 -67
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm-gate.yml +0 -78
- package/.github/workflows/public-external-validation-p08-v4-recovery-glm.yml +0 -248
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm-gate.yml +0 -66
- package/.github/workflows/public-external-validation-p08-v5-run-recovery-glm.yml +0 -218
- package/.github/workflows/pypi-registry-smoke.yml +0 -116
- package/.github/workflows/release.yml +0 -359
- package/.github/workflows/tests.yml +0 -250
- package/.github/workflows/tmp-compassion-raw-acquire.yml +0 -63
- package/.github/workflows/wsl-science-runner-smoke.yml +0 -45
- package/.pre-commit-config.yaml +0 -48
- package/CITATION.cff +0 -29
- package/CODE_OF_CONDUCT.md +0 -25
- package/CONTRIBUTING.md +0 -275
- package/ROADMAP.md +0 -155
- package/assets/logo.svg +0 -38
- package/assets/social_preview.png +0 -0
- package/benchmarks/results.json +0 -43
- package/benchmarks/robust_runner.py +0 -118
- package/benchmarks/run_benchmarks.py +0 -394
- package/cliff.toml +0 -100
- package/dashboard/app.py +0 -224
- package/docs/ARCHITECTURE.md +0 -252
- package/docs/CASE_STUDY_HUBBLE.md +0 -78
- package/docs/CASE_STUDY_QUANTUM_ML.md +0 -79
- package/docs/api.md +0 -133
- package/docs/assets/icon.svg +0 -17
- package/docs/assets/logo.svg +0 -38
- package/docs/benchmarks.md +0 -62
- package/docs/cookbook.md +0 -930
- package/docs/getting-started.md +0 -185
- package/docs/index.md +0 -111
- package/docs/maintenance.md +0 -61
- package/docs/ml_reference.md +0 -92
- package/docs/research-workflows.md +0 -82
- package/docs/stylesheets/extra.css +0 -122
- package/docs/tour_of_numerical_methods.md +0 -330
- package/docs/tutorials/core_demo.md +0 -35
- package/docs/tutorials/data_analysis_demo.md +0 -43
- package/docs/tutorials/diffeq_demo.md +0 -48
- package/docs/tutorials/fft2_demo.md +0 -67
- package/docs/tutorials/graph_demo.md +0 -45
- package/docs/tutorials/hypothesis_demo.md +0 -44
- package/docs/tutorials/hypothesis_tests_demo.md +0 -170
- package/docs/tutorials/hypothesis_with_stats_demo.md +0 -80
- package/docs/tutorials/knowledge_demo.md +0 -114
- package/docs/tutorials/linalg_demo.md +0 -103
- package/docs/tutorials/math_utils_demo.md +0 -46
- package/docs/tutorials/ml_advanced_demo.md +0 -96
- package/docs/tutorials/ml_and_viz_demo.md +0 -93
- package/docs/tutorials/ml_demo.md +0 -70
- package/docs/tutorials/modeling_demo.md +0 -82
- package/docs/tutorials/montecarlo_demo.md +0 -42
- package/docs/tutorials/nlp_attention_demo.md +0 -107
- package/docs/tutorials/nlp_bpe_demo.md +0 -103
- package/docs/tutorials/nlp_mini_gpt_demo.md +0 -110
- package/docs/tutorials/nlp_viz.md +0 -76
- package/docs/tutorials/numerical_integration_demo.md +0 -65
- package/docs/tutorials/optimization_demo.md +0 -106
- package/docs/tutorials/pandas_io_demo.md +0 -160
- package/docs/tutorials/pca_demo.md +0 -87
- package/docs/tutorials/probability_demo.md +0 -48
- package/docs/tutorials/quantum_demo.md +0 -31
- package/docs/tutorials/quick_start.md +0 -44
- package/docs/tutorials/scientific_demo.md +0 -46
- package/docs/tutorials/signals_demo.md +0 -167
- package/docs/tutorials/stats_demo.md +0 -94
- package/docs/tutorials/stiff_ode_demo.md +0 -84
- package/docs/tutorials/time_series_demo.md +0 -145
- package/examples/core_demo.py +0 -40
- package/examples/data_analysis_demo.py +0 -60
- package/examples/diffeq_demo.py +0 -34
- package/examples/discovery_pipeline_demo.py +0 -57
- package/examples/ensemble_showcase.py +0 -81
- package/examples/fft2_demo.py +0 -32
- package/examples/graph_demo.py +0 -49
- package/examples/hypothesis_custom_generator.py +0 -121
- package/examples/hypothesis_demo.py +0 -48
- package/examples/hypothesis_tests_demo.py +0 -52
- package/examples/hypothesis_with_stats_demo.py +0 -43
- package/examples/interpolate_demo.py +0 -57
- package/examples/knowledge_demo.py +0 -100
- package/examples/linalg_demo.py +0 -61
- package/examples/math_utils_demo.py +0 -53
- package/examples/ml_and_viz_demo.py +0 -47
- package/examples/modeling_demo.py +0 -110
- package/examples/montecarlo_demo.py +0 -41
- package/examples/nlp_attention_demo.py +0 -168
- package/examples/nlp_bpe_demo.py +0 -79
- package/examples/nlp_mini_gpt_demo.py +0 -76
- package/examples/nlp_viz_demo.py +0 -98
- package/examples/numerical_integration_demo.py +0 -60
- package/examples/optimization_demo.py +0 -34
- package/examples/pca_demo.py +0 -124
- package/examples/pde_demo.py +0 -65
- package/examples/plot_demo.py +0 -84
- package/examples/plotting_notebook.ipynb +0 -87
- package/examples/probability_demo.py +0 -39
- package/examples/quantum_demo.py +0 -42
- package/examples/scientific_demo.py +0 -49
- package/examples/signals_demo.py +0 -86
- package/examples/stats_demo.py +0 -40
- package/examples/tour_of_numerical_methods.ipynb +0 -497
- package/mkdocs.yml +0 -159
- package/pyproject.toml +0 -288
- package/requirements-dev.lock +0 -427
- package/requirements-dev.txt +0 -39
- package/requirements.lock +0 -6
- package/requirements.txt +0 -13
- package/scripts/build_gif.py +0 -111
- package/scripts/build_video.py +0 -214
- package/scripts/cleanup_deployments.py +0 -173
- package/scripts/crop_readme_png.py +0 -40
- package/scripts/make_pi_dashboard.py +0 -316
- package/scripts/make_pi_gif.py +0 -138
- package/scripts/publish.py +0 -203
- package/scripts/render_promo.mjs +0 -93
- package/scripts/render_readme.py +0 -211
- package/scripts/render_readme_sections.py +0 -168
- package/scripts/verify_cli_install.py +0 -99
- package/scripts/verify_cookbook.py +0 -601
- package/scripts/verify_d1_numerics.py +0 -504
- package/scripts/verify_d2_edge_cases.py +0 -442
- package/scripts/verify_d4_hypothesis.py +0 -337
- package/scripts/verify_ml_reference.py +0 -160
- package/scripts/verify_pypi_release.py +0 -97
- package/scripts/verify_release_integrity.py +0 -194
- package/src/cds/__init__.py +0 -132
- package/src/cds/__main__.py +0 -8
- package/src/cds/_version.py +0 -11
- package/src/cds/bayes/__init__.py +0 -25
- package/src/cds/bayes/conjugate.py +0 -560
- package/src/cds/cli/__init__.py +0 -104
- package/src/cds/cli/__main__.py +0 -8
- package/src/cds/cli/_handlers.py +0 -323
- package/src/cds/cli/_parser.py +0 -155
- package/src/cds/cli/_style.py +0 -208
- package/src/cds/cli/_system_info.py +0 -71
- package/src/cds/core/__init__.py +0 -5
- package/src/cds/core/_numeric.py +0 -92
- package/src/cds/core/models.py +0 -166
- package/src/cds/data_analysis/__init__.py +0 -30
- package/src/cds/data_analysis/dataset.py +0 -122
- package/src/cds/data_analysis/loader.py +0 -75
- package/src/cds/data_analysis/pandas_io.py +0 -108
- package/src/cds/data_analysis/transform.py +0 -36
- package/src/cds/data_analysis/viz.py +0 -88
- package/src/cds/data_io/__init__.py +0 -27
- package/src/cds/data_io/streaming.py +0 -314
- package/src/cds/diffeq/__init__.py +0 -37
- package/src/cds/diffeq/_implicit.py +0 -349
- package/src/cds/diffeq/solvers.py +0 -312
- package/src/cds/diffeq/symplectic.py +0 -225
- package/src/cds/fractals/__init__.py +0 -34
- package/src/cds/fractals/sets.py +0 -356
- package/src/cds/genetics/__init__.py +0 -22
- package/src/cds/genetics/sequence.py +0 -199
- package/src/cds/graph/__init__.py +0 -31
- package/src/cds/graph/algorithms.py +0 -399
- package/src/cds/hypothesis/__init__.py +0 -51
- package/src/cds/hypothesis/evaluator.py +0 -311
- package/src/cds/hypothesis/generator.py +0 -275
- package/src/cds/hypothesis/mining.py +0 -314
- package/src/cds/infotheory/__init__.py +0 -25
- package/src/cds/infotheory/measures.py +0 -276
- package/src/cds/interpolate/__init__.py +0 -156
- package/src/cds/knowledge/__init__.py +0 -45
- package/src/cds/knowledge/graph.py +0 -489
- package/src/cds/knowledge/notes.py +0 -231
- package/src/cds/knowledge/retrieval.py +0 -339
- package/src/cds/math_utils/__init__.py +0 -46
- package/src/cds/math_utils/calculus.py +0 -40
- package/src/cds/math_utils/linalg.py +0 -496
- package/src/cds/math_utils/special.py +0 -167
- package/src/cds/math_utils/svd.py +0 -261
- package/src/cds/ml/__init__.py +0 -60
- package/src/cds/ml/boosting.py +0 -304
- package/src/cds/ml/clustering.py +0 -190
- package/src/cds/ml/decomposition.py +0 -172
- package/src/cds/ml/ensemble.py +0 -152
- package/src/cds/ml/linear_models.py +0 -225
- package/src/cds/ml/metrics.py +0 -227
- package/src/cds/ml/model_selection.py +0 -150
- package/src/cds/ml/naive_bayes.py +0 -179
- package/src/cds/ml/neighbors.py +0 -162
- package/src/cds/ml/neural.py +0 -204
- package/src/cds/ml/preprocessing.py +0 -131
- package/src/cds/ml/tree.py +0 -228
- package/src/cds/ml/voting.py +0 -175
- package/src/cds/modeling/__init__.py +0 -44
- package/src/cds/modeling/_base.py +0 -210
- package/src/cds/modeling/_nodes.py +0 -526
- package/src/cds/modeling/expression.py +0 -81
- package/src/cds/modeling/fitting.py +0 -477
- package/src/cds/modeling/model.py +0 -134
- package/src/cds/modeling/solver.py +0 -187
- package/src/cds/montecarlo/__init__.py +0 -24
- package/src/cds/montecarlo/markov.py +0 -112
- package/src/cds/montecarlo/methods.py +0 -294
- package/src/cds/nlp/__init__.py +0 -170
- package/src/cds/nlp/attention.py +0 -285
- package/src/cds/nlp/autograd/__init__.py +0 -70
- package/src/cds/nlp/autograd/_grad.py +0 -120
- package/src/cds/nlp/autograd/ops.py +0 -133
- package/src/cds/nlp/autograd/tensor.py +0 -298
- package/src/cds/nlp/bpe.py +0 -449
- package/src/cds/nlp/data.py +0 -70
- package/src/cds/nlp/embed.py +0 -190
- package/src/cds/nlp/layers.py +0 -259
- package/src/cds/nlp/model.py +0 -456
- package/src/cds/nlp/optim.py +0 -163
- package/src/cds/nlp/training.py +0 -167
- package/src/cds/nlp/viz.py +0 -254
- package/src/cds/numerical_integration/__init__.py +0 -31
- package/src/cds/numerical_integration/quadrature.py +0 -480
- package/src/cds/optimization/__init__.py +0 -26
- package/src/cds/optimization/_metaheuristics.py +0 -287
- package/src/cds/optimization/constrained.py +0 -212
- package/src/cds/optimization/minimize.py +0 -425
- package/src/cds/pde/__init__.py +0 -266
- package/src/cds/plot/__init__.py +0 -49
- package/src/cds/plot/_backend.py +0 -32
- package/src/cds/plot/charts.py +0 -462
- package/src/cds/probability/__init__.py +0 -65
- package/src/cds/probability/_advanced.py +0 -283
- package/src/cds/probability/distributions.py +0 -236
- package/src/cds/probability/extra_distributions.py +0 -199
- package/src/cds/provenance/__init__.py +0 -25
- package/src/cds/provenance/manifest.py +0 -355
- package/src/cds/py.typed +0 -0
- package/src/cds/quantum/__init__.py +0 -51
- package/src/cds/quantum/circuit.py +0 -122
- package/src/cds/quantum/multi_qubit.py +0 -310
- package/src/cds/quantum/simulator.py +0 -53
- package/src/cds/scientific/__init__.py +0 -34
- package/src/cds/scientific/constants.py +0 -35
- package/src/cds/scientific/formulas.py +0 -116
- package/src/cds/sensitivity.py +0 -204
- package/src/cds/signals/__init__.py +0 -59
- package/src/cds/signals/filters.py +0 -449
- package/src/cds/signals/processing.py +0 -224
- package/src/cds/signals/stft.py +0 -177
- package/src/cds/signals/wavelet.py +0 -146
- package/src/cds/stats/__init__.py +0 -99
- package/src/cds/stats/_distributions.py +0 -102
- package/src/cds/stats/bootstrap.py +0 -188
- package/src/cds/stats/descriptive.py +0 -172
- package/src/cds/stats/hypothesis_tests.py +0 -294
- package/src/cds/stats/nonparametric.py +0 -141
- package/src/cds/stats/power.py +0 -290
- package/src/cds/stats/regression.py +0 -51
- package/src/cds/stats/time_series.py +0 -420
- package/src/cds/tools/__init__.py +0 -29
- package/src/cds/tools/adapters.py +0 -218
- package/src/cds/tools/registry.py +0 -181
- package/src/cds/uncertainty/__init__.py +0 -17
- package/src/cds/uncertainty/propagation.py +0 -233
- package/src/cds/units/__init__.py +0 -45
- package/src/cds/units/core.py +0 -199
- package/src/cds/validation/__init__.py +0 -41
- package/src/cds/validation/adequacy.py +0 -157
- package/src/cds/validation/checks.py +0 -485
- package/src/cds/validation/report.py +0 -50
- package/src/cds/wavelets/__init__.py +0 -5
- package/src/cds/wavelets/haar.py +0 -219
- package/src/cds/workflow/__init__.py +0 -77
- package/src/cds/workflow/engine.py +0 -116
- package/src/cds/workflow/gates.py +0 -120
- package/src/cds/workflow/orchestrator.py +0 -431
- package/src/cds/workflow/selection.py +0 -454
- package/src/cds/workflow/tooling.py +0 -155
- package/src/cds/workflow/types.py +0 -107
- package/tests/__init__.py +0 -0
- package/tests/conftest.py +0 -109
- package/tests/test_advanced_fitting.py +0 -247
- package/tests/test_audit_completion_coverage.py +0 -183
- package/tests/test_audit_guard_coverage.py +0 -115
- package/tests/test_audit_hardening.py +0 -138
- package/tests/test_audit_hardening_coverage.py +0 -111
- package/tests/test_bayes_v2.py +0 -208
- package/tests/test_benchmarks.py +0 -111
- package/tests/test_bootstrap.py +0 -135
- package/tests/test_cli.py +0 -51
- package/tests/test_cli_color.py +0 -114
- package/tests/test_cli_extended.py +0 -239
- package/tests/test_cli_system_info.py +0 -36
- package/tests/test_constrained_opt.py +0 -174
- package/tests/test_core.py +0 -273
- package/tests/test_data_analysis.py +0 -146
- package/tests/test_data_analysis_lazy_bridge.py +0 -68
- package/tests/test_data_analysis_pandas_io.py +0 -119
- package/tests/test_data_io.py +0 -149
- package/tests/test_dataset.py +0 -91
- package/tests/test_diffeq.py +0 -186
- package/tests/test_diffeq_implicit.py +0 -173
- package/tests/test_domain_validation.py +0 -66
- package/tests/test_edge_misc_numerical.py +0 -666
- package/tests/test_edge_ml_quantum_linalg.py +0 -191
- package/tests/test_edge_nlp.py +0 -229
- package/tests/test_edge_quantum_evaluator_cli.py +0 -601
- package/tests/test_edge_stats_optimization_signals.py +0 -406
- package/tests/test_extra_distributions.py +0 -206
- package/tests/test_fft2.py +0 -67
- package/tests/test_fitting_bootstrap.py +0 -202
- package/tests/test_fractals.py +0 -387
- package/tests/test_genetics.py +0 -159
- package/tests/test_graph.py +0 -380
- package/tests/test_hardening_privacy_provenance.py +0 -306
- package/tests/test_hypothesis.py +0 -216
- package/tests/test_hypothesis_engine.py +0 -59
- package/tests/test_hypothesis_mining.py +0 -247
- package/tests/test_hypothesis_tests.py +0 -277
- package/tests/test_infotheory.py +0 -302
- package/tests/test_interpolate.py +0 -189
- package/tests/test_knowledge.py +0 -1149
- package/tests/test_layering.py +0 -112
- package/tests/test_linalg_extended.py +0 -179
- package/tests/test_linalg_qr_cholesky.py +0 -68
- package/tests/test_markov.py +0 -155
- package/tests/test_math_utils.py +0 -157
- package/tests/test_ml_boosting.py +0 -148
- package/tests/test_ml_clustering.py +0 -92
- package/tests/test_ml_ensemble.py +0 -103
- package/tests/test_ml_knn.py +0 -95
- package/tests/test_ml_linreg.py +0 -70
- package/tests/test_ml_logreg.py +0 -84
- package/tests/test_ml_metrics.py +0 -125
- package/tests/test_ml_model_selection.py +0 -108
- package/tests/test_ml_naive_bayes.py +0 -183
- package/tests/test_ml_pca.py +0 -98
- package/tests/test_ml_preprocessing.py +0 -104
- package/tests/test_ml_tree.py +0 -89
- package/tests/test_ml_viz.py +0 -58
- package/tests/test_ml_voting.py +0 -219
- package/tests/test_modeling.py +0 -726
- package/tests/test_modeling_fit_validation.py +0 -46
- package/tests/test_montecarlo.py +0 -245
- package/tests/test_multi_qubit.py +0 -466
- package/tests/test_nlp_attention.py +0 -335
- package/tests/test_nlp_autograd.py +0 -435
- package/tests/test_nlp_bpe.py +0 -463
- package/tests/test_nlp_embed.py +0 -240
- package/tests/test_nlp_layers.py +0 -276
- package/tests/test_nlp_model.py +0 -172
- package/tests/test_nlp_training.py +0 -262
- package/tests/test_nlp_viz.py +0 -188
- package/tests/test_numerical_integration.py +0 -374
- package/tests/test_numerical_invariants.py +0 -768
- package/tests/test_numerical_oracles.py +0 -241
- package/tests/test_optimization.py +0 -139
- package/tests/test_optimization_metaheuristics.py +0 -221
- package/tests/test_pde.py +0 -294
- package/tests/test_plot_charts.py +0 -247
- package/tests/test_plot_lazy.py +0 -48
- package/tests/test_power.py +0 -226
- package/tests/test_probability.py +0 -274
- package/tests/test_probability_advanced.py +0 -226
- package/tests/test_property_invariants.py +0 -277
- package/tests/test_provenance.py +0 -215
- package/tests/test_provenance_audit_hardening.py +0 -45
- package/tests/test_public_api.py +0 -75
- package/tests/test_quantum.py +0 -195
- package/tests/test_release_contract.py +0 -105
- package/tests/test_retrieval.py +0 -255
- package/tests/test_scientific.py +0 -185
- package/tests/test_selection_audit_hardening.py +0 -55
- package/tests/test_sensitivity.py +0 -59
- package/tests/test_sensitivity_global.py +0 -73
- package/tests/test_signals.py +0 -146
- package/tests/test_signals_filters.py +0 -460
- package/tests/test_special_invariants.py +0 -222
- package/tests/test_special_numerics.py +0 -44
- package/tests/test_statistical_audit.py +0 -75
- package/tests/test_stats.py +0 -206
- package/tests/test_stats_audit_coverage.py +0 -17
- package/tests/test_stats_nonparametric.py +0 -87
- package/tests/test_stats_time_series.py +0 -352
- package/tests/test_stft.py +0 -208
- package/tests/test_streaming_analytics.py +0 -128
- package/tests/test_svd.py +0 -170
- package/tests/test_symplectic.py +0 -200
- package/tests/test_tool_adapters.py +0 -197
- package/tests/test_tools_registry.py +0 -132
- package/tests/test_uncertainty.py +0 -171
- package/tests/test_units.py +0 -139
- package/tests/test_validation.py +0 -100
- package/tests/test_validation_adequacy.py +0 -129
- package/tests/test_validation_advanced.py +0 -110
- package/tests/test_wavelet.py +0 -170
- package/tests/test_wavelets_v2.py +0 -119
- package/tests/test_workflow.py +0 -173
- package/tests/test_workflow_gates.py +0 -144
- package/tests/test_workflow_orchestrator.py +0 -516
- package/tests/test_workflow_orchestrator_blocked_review.py +0 -95
- package/tests/test_workflow_selection.py +0 -312
- package/tests/test_workflow_selection_coverage.py +0 -114
- package/tests/test_workflow_tooling.py +0 -190
package/tests/test_ml_metrics.py
DELETED
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
"""Tests for cds.ml.metrics — classification and regression metrics."""
|
|
2
|
-
|
|
3
|
-
import pytest
|
|
4
|
-
|
|
5
|
-
from cds.ml.metrics import (
|
|
6
|
-
accuracy,
|
|
7
|
-
confusion_matrix,
|
|
8
|
-
macro_prf,
|
|
9
|
-
mean_absolute_error,
|
|
10
|
-
mean_squared_error,
|
|
11
|
-
precision_recall_f1,
|
|
12
|
-
r2_score,
|
|
13
|
-
roc_auc,
|
|
14
|
-
)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class TestValidation:
|
|
18
|
-
def test_empty_raises(self) -> None:
|
|
19
|
-
with pytest.raises(ValueError, match="non-empty"):
|
|
20
|
-
accuracy([], [])
|
|
21
|
-
|
|
22
|
-
def test_length_mismatch_raises(self) -> None:
|
|
23
|
-
with pytest.raises(ValueError, match="same length"):
|
|
24
|
-
precision_recall_f1(["a", "b"], ["a"])
|
|
25
|
-
|
|
26
|
-
def test_regression_mismatch_raises(self) -> None:
|
|
27
|
-
with pytest.raises(ValueError, match="same length"):
|
|
28
|
-
mean_squared_error([1.0], [1.0, 2.0])
|
|
29
|
-
|
|
30
|
-
def test_r2_mismatch_raises(self) -> None:
|
|
31
|
-
with pytest.raises(ValueError, match="same length"):
|
|
32
|
-
r2_score([1.0], [1.0, 2.0])
|
|
33
|
-
|
|
34
|
-
def test_roc_auc_single_class_raises(self) -> None:
|
|
35
|
-
with pytest.raises(ValueError, match="two distinct"):
|
|
36
|
-
roc_auc(["a", "a", "a"], [0.9, 0.8, 0.7])
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
class TestAccuracy:
|
|
40
|
-
def test_perfect_and_zero(self) -> None:
|
|
41
|
-
y = ["a", "b", "a"]
|
|
42
|
-
assert accuracy(y, y) == 1.0
|
|
43
|
-
assert accuracy(y, ["b", "a", "b"]) == 0.0
|
|
44
|
-
|
|
45
|
-
def test_partial(self) -> None:
|
|
46
|
-
assert accuracy([1, 2, 3, 4], [1, 2, 0, 0]) == 0.5
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
class TestConfusionMatrix:
|
|
50
|
-
def test_first_appearance_label_order(self) -> None:
|
|
51
|
-
result = confusion_matrix(["b", "a", "b"], ["b", "a", "a"])
|
|
52
|
-
assert result.labels == ["b", "a"]
|
|
53
|
-
# rows = true (b, a), cols = predicted (b, a)
|
|
54
|
-
assert result.matrix == [[1, 1], [0, 1]]
|
|
55
|
-
|
|
56
|
-
def test_prediction_only_label_appended(self) -> None:
|
|
57
|
-
result = confusion_matrix(["a"], ["z"])
|
|
58
|
-
assert result.labels == ["a", "z"]
|
|
59
|
-
assert result.matrix == [[0, 1], [0, 0]]
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
class TestPrf:
|
|
63
|
-
def test_perfect_predictions(self) -> None:
|
|
64
|
-
prf = precision_recall_f1(["x", "y"], ["x", "y"])
|
|
65
|
-
assert prf["x"].precision == prf["x"].recall == prf["x"].f1 == 1.0
|
|
66
|
-
|
|
67
|
-
def test_zero_denominators_score_zero(self) -> None:
|
|
68
|
-
# label "never" is never predicted and never true
|
|
69
|
-
prf = precision_recall_f1(["a", "b"], ["a", "b"])
|
|
70
|
-
assert prf["a"] is not None
|
|
71
|
-
# label never predicted: precision denominator zero
|
|
72
|
-
mixed = precision_recall_f1(["a", "a", "b"], ["a", "a", "a"])
|
|
73
|
-
assert mixed["b"].precision == 0.0
|
|
74
|
-
assert mixed["b"].recall == 0.0
|
|
75
|
-
assert mixed["b"].f1 == 0.0
|
|
76
|
-
|
|
77
|
-
def test_partial_scores(self) -> None:
|
|
78
|
-
prf = precision_recall_f1(["a", "a", "b", "b"], ["a", "b", "b", "b"])
|
|
79
|
-
a = prf["a"]
|
|
80
|
-
assert a.precision == pytest.approx(1.0)
|
|
81
|
-
assert a.recall == pytest.approx(0.5)
|
|
82
|
-
assert a.f1 == pytest.approx(2 * 1.0 * 0.5 / 1.5)
|
|
83
|
-
|
|
84
|
-
def test_macro_averages(self) -> None:
|
|
85
|
-
m = macro_prf(["a", "a", "b", "b"], ["a", "b", "b", "b"])
|
|
86
|
-
assert m.precision == pytest.approx((1.0 + 2 / 3) / 2)
|
|
87
|
-
assert m.recall == pytest.approx((0.5 + 1.0) / 2)
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
class TestRegressionMetrics:
|
|
91
|
-
def test_mse_mae(self) -> None:
|
|
92
|
-
assert mean_squared_error([0.0, 0.0], [1.0, -1.0]) == 1.0
|
|
93
|
-
assert mean_absolute_error([0.0, 0.0], [1.0, -3.0]) == 2.0
|
|
94
|
-
|
|
95
|
-
def test_r2_perfect_and_mean_predictor(self) -> None:
|
|
96
|
-
assert r2_score([1.0, 2.0, 3.0], [1.0, 2.0, 3.0]) == pytest.approx(1.0)
|
|
97
|
-
mean_fit = [2.0, 2.0, 2.0]
|
|
98
|
-
assert r2_score([1.0, 2.0, 3.0], mean_fit) == pytest.approx(0.0)
|
|
99
|
-
|
|
100
|
-
def test_r2_constant_targets(self) -> None:
|
|
101
|
-
assert r2_score([5.0, 5.0], [5.0, 5.0]) == 1.0
|
|
102
|
-
assert r2_score([5.0, 5.0], [4.0, 4.0]) == 0.0
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
class TestRocAuc:
|
|
106
|
-
"""Semantics: the *second* distinct label seen is the positive class."""
|
|
107
|
-
|
|
108
|
-
def test_perfect_separation(self) -> None:
|
|
109
|
-
assert roc_auc(["neg", "neg", "pos", "pos"], [0.1, 0.2, 0.8, 0.9]) == 1.0
|
|
110
|
-
|
|
111
|
-
def test_reversed_separation(self) -> None:
|
|
112
|
-
# positive class ("neg", seen second) gets the LOW scores
|
|
113
|
-
assert roc_auc(["pos", "pos", "neg", "neg"], [0.8, 0.9, 0.1, 0.2]) == 0.0
|
|
114
|
-
|
|
115
|
-
def test_cross_class_tie_counts_half(self) -> None:
|
|
116
|
-
# pos {0.5, 0.9} vs neg {0.1, 0.5}: one tie pair → AUC = 3.5/4
|
|
117
|
-
auc = roc_auc(["neg", "pos", "neg", "pos"], [0.1, 0.5, 0.5, 0.9])
|
|
118
|
-
assert auc == pytest.approx(0.875)
|
|
119
|
-
|
|
120
|
-
def test_all_tied_scores(self) -> None:
|
|
121
|
-
assert roc_auc(["pos", "neg", "pos", "neg"], [1.0, 1.0, 1.0, 1.0]) == 0.5
|
|
122
|
-
|
|
123
|
-
def test_label_order_independence(self) -> None:
|
|
124
|
-
# first-seen label being negative still works via complement logic
|
|
125
|
-
assert roc_auc(["neg", "pos"], [0.3, 0.7]) == 1.0
|
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
"""Tests for cds.ml.model_selection — k-fold cross-validation."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
from collections.abc import Sequence
|
|
6
|
-
|
|
7
|
-
import pytest
|
|
8
|
-
|
|
9
|
-
from cds.ml.metrics import Label, accuracy
|
|
10
|
-
from cds.ml.model_selection import CVResult, SupervisedModel, cross_val_score, k_fold_indices
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
class _ConstantModel:
|
|
14
|
-
"""Predicts the majority label of training data."""
|
|
15
|
-
|
|
16
|
-
def fit(self, X: list[list[float]], y: Sequence[Label]) -> _ConstantModel:
|
|
17
|
-
self._label: Label = max(set(y), key=list(y).count)
|
|
18
|
-
return self
|
|
19
|
-
|
|
20
|
-
def predict(self, x: list[float]) -> Label:
|
|
21
|
-
return self._label
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
def _factory() -> SupervisedModel:
|
|
25
|
-
return _ConstantModel()
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
class TestKFoldIndices:
|
|
29
|
-
def test_contiguous_deterministic(self) -> None:
|
|
30
|
-
folds = k_fold_indices(6, 3)
|
|
31
|
-
assert len(folds) == 3
|
|
32
|
-
for train, test in folds:
|
|
33
|
-
assert sorted(train + test) == list(range(6))
|
|
34
|
-
assert folds[0][1] == [0, 1]
|
|
35
|
-
assert folds[2][1] == [4, 5]
|
|
36
|
-
|
|
37
|
-
def test_uneven_sizes_early_folds_larger(self) -> None:
|
|
38
|
-
folds = k_fold_indices(5, 2)
|
|
39
|
-
sizes = [len(test) for _, test in folds]
|
|
40
|
-
assert sizes == [3, 2]
|
|
41
|
-
|
|
42
|
-
def test_shuffle_changes_folds_but_preserves_partition(self) -> None:
|
|
43
|
-
plain = k_fold_indices(7, 7, shuffle=False)
|
|
44
|
-
shuffled = k_fold_indices(7, 7, shuffle=True, seed=42)
|
|
45
|
-
again = k_fold_indices(7, 7, shuffle=True, seed=42)
|
|
46
|
-
assert all(sorted(t + v) == list(range(7)) for t, v in shuffled)
|
|
47
|
-
assert shuffled != plain
|
|
48
|
-
# same seed reproduces the exact partition
|
|
49
|
-
assert shuffled == again
|
|
50
|
-
|
|
51
|
-
def test_invalid_k_raises(self) -> None:
|
|
52
|
-
with pytest.raises(ValueError, match="k must be >= 2"):
|
|
53
|
-
k_fold_indices(5, 1)
|
|
54
|
-
|
|
55
|
-
def test_n_smaller_than_k_raises(self) -> None:
|
|
56
|
-
with pytest.raises(ValueError, match="n must be >= k"):
|
|
57
|
-
k_fold_indices(2, 5)
|
|
58
|
-
|
|
59
|
-
def test_invalid_n_raises(self) -> None:
|
|
60
|
-
with pytest.raises(ValueError, match="n must be >= 1"):
|
|
61
|
-
k_fold_indices(0, 2)
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
class TestCrossValScore:
|
|
65
|
-
X = [[float(i)] for i in range(6)]
|
|
66
|
-
y = ["a", "a", "a", "b", "b", "b"]
|
|
67
|
-
|
|
68
|
-
def test_scores_and_mean(self) -> None:
|
|
69
|
-
result = cross_val_score(_factory, self.X, self.y, k=3)
|
|
70
|
-
assert isinstance(result, CVResult)
|
|
71
|
-
assert len(result.scores) == 3
|
|
72
|
-
assert result.mean_score == pytest.approx(sum(result.scores) / 3)
|
|
73
|
-
|
|
74
|
-
def test_shuffled_seeded_is_reproducible(self) -> None:
|
|
75
|
-
a = cross_val_score(_factory, self.X, self.y, k=2, shuffle=True, seed=7)
|
|
76
|
-
b = cross_val_score(_factory, self.X, self.y, k=2, shuffle=True, seed=7)
|
|
77
|
-
assert a == b
|
|
78
|
-
|
|
79
|
-
def test_custom_scorer(self) -> None:
|
|
80
|
-
result = cross_val_score(
|
|
81
|
-
_factory,
|
|
82
|
-
self.X,
|
|
83
|
-
self.y,
|
|
84
|
-
k=3,
|
|
85
|
-
scorer=lambda yt, yp: 1.0 if list(yt) == list(yp) else 0.0,
|
|
86
|
-
)
|
|
87
|
-
assert all(s in (0.0, 1.0) for s in result.scores)
|
|
88
|
-
|
|
89
|
-
def test_empty_X_raises(self) -> None:
|
|
90
|
-
with pytest.raises(ValueError, match="non-empty"):
|
|
91
|
-
cross_val_score(_factory, [], [], k=2)
|
|
92
|
-
|
|
93
|
-
def test_length_mismatch_raises(self) -> None:
|
|
94
|
-
with pytest.raises(ValueError, match="same length"):
|
|
95
|
-
cross_val_score(_factory, self.X, self.y[:-1], k=2)
|
|
96
|
-
|
|
97
|
-
def test_ragged_rows_raise(self) -> None:
|
|
98
|
-
with pytest.raises(ValueError, match="same length"):
|
|
99
|
-
cross_val_score(_factory, [[1.0], [1.0, 2.0]], ["a", "b"], k=2)
|
|
100
|
-
|
|
101
|
-
def test_k_exceeding_n_raises_via_fold_check(self) -> None:
|
|
102
|
-
with pytest.raises(ValueError, match="n must be >= k"):
|
|
103
|
-
cross_val_score(_factory, self.X, self.y, k=10)
|
|
104
|
-
|
|
105
|
-
def test_accuracy_default_matches_explicit(self) -> None:
|
|
106
|
-
explicit = cross_val_score(_factory, self.X, self.y, k=3, scorer=accuracy)
|
|
107
|
-
default = cross_val_score(_factory, self.X, self.y, k=3)
|
|
108
|
-
assert explicit == default
|
|
@@ -1,183 +0,0 @@
|
|
|
1
|
-
"""Tests for :mod:`cds.ml.naive_bayes` (Gaussian Naive Bayes)."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import math
|
|
6
|
-
|
|
7
|
-
import pytest
|
|
8
|
-
|
|
9
|
-
from cds.ml.metrics import Label
|
|
10
|
-
from cds.ml.naive_bayes import GaussianNaiveBayes
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def _separable() -> tuple[list[list[float]], list[str]]:
|
|
14
|
-
X = [
|
|
15
|
-
[0.0, 0.0],
|
|
16
|
-
[0.5, 0.2],
|
|
17
|
-
[-0.2, 0.4],
|
|
18
|
-
[10.0, 10.0],
|
|
19
|
-
[10.5, 9.8],
|
|
20
|
-
[9.8, 10.4],
|
|
21
|
-
]
|
|
22
|
-
y = ["a", "a", "a", "b", "b", "b"]
|
|
23
|
-
return X, y
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
def test_separate_gaussians_classified_perfectly() -> None:
|
|
27
|
-
X, y = _separable()
|
|
28
|
-
clf = GaussianNaiveBayes().fit(X, y)
|
|
29
|
-
assert clf.predict([0.1, -0.1]) == "a"
|
|
30
|
-
assert clf.predict([10.2, 10.1]) == "b"
|
|
31
|
-
for row, label in zip(X, y):
|
|
32
|
-
assert clf.predict(row) == label
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
def test_predict_matches_argmax_of_proba() -> None:
|
|
36
|
-
X, y = _separable()
|
|
37
|
-
clf = GaussianNaiveBayes().fit(X, y)
|
|
38
|
-
probs = clf.predict_proba([4.0, 4.5])
|
|
39
|
-
argmax = max(probs, key=lambda label: probs[label])
|
|
40
|
-
assert clf.predict([4.0, 4.5]) == argmax
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
def test_probas_sum_to_one_everywhere() -> None:
|
|
44
|
-
X, y = _separable()
|
|
45
|
-
clf = GaussianNaiveBayes().fit(X, y)
|
|
46
|
-
for query in ([0.0, 0.0], [5.0, 5.0], [100.0, -100.0], [-50.0, 50.0]):
|
|
47
|
-
assert sum(clf.predict_proba(query).values()) == pytest.approx(1.0)
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
def test_single_feature_closed_form_with_unequal_priors() -> None:
|
|
51
|
-
# Class "a" (prior 3/5): {0, 2, 4} -> N(2, 8/3).
|
|
52
|
-
# Class "b" (prior 2/5): {10, 12} -> N(11, 1).
|
|
53
|
-
X = [[0.0], [2.0], [4.0], [10.0], [12.0]]
|
|
54
|
-
y = ["a", "a", "a", "b", "b"]
|
|
55
|
-
clf = GaussianNaiveBayes().fit(X, y)
|
|
56
|
-
query = 4.0
|
|
57
|
-
log_joint_a = (
|
|
58
|
-
math.log(3 / 5)
|
|
59
|
-
- 0.5 * math.log(2 * math.pi * (8.0 / 3.0))
|
|
60
|
-
- (query - 2.0) ** 2 / (2 * 8.0 / 3.0)
|
|
61
|
-
)
|
|
62
|
-
log_joint_b = (
|
|
63
|
-
math.log(2 / 5) - 0.5 * math.log(2 * math.pi * 1.0) - (query - 11.0) ** 2 / (2 * 1.0)
|
|
64
|
-
)
|
|
65
|
-
expected_a = math.exp(log_joint_a) / (math.exp(log_joint_a) + math.exp(log_joint_b))
|
|
66
|
-
expected_b = math.exp(log_joint_b) / (math.exp(log_joint_a) + math.exp(log_joint_b))
|
|
67
|
-
probs = clf.predict_proba([query])
|
|
68
|
-
assert probs["a"] == pytest.approx(expected_a)
|
|
69
|
-
assert probs["b"] == pytest.approx(expected_b)
|
|
70
|
-
assert sum(probs.values()) == pytest.approx(1.0)
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
def test_population_variance_used_in_closed_form() -> None:
|
|
74
|
-
# Single class pair where ddof choice matters: class "a" on {0, 2} has
|
|
75
|
-
# population variance 1 (sample variance would be 2).
|
|
76
|
-
X = [[0.0], [2.0], [10.0], [12.0]]
|
|
77
|
-
y = ["a", "a", "b", "b"]
|
|
78
|
-
clf = GaussianNaiveBayes().fit(X, y)
|
|
79
|
-
# Query x=11 sits exactly on b's mean (sigma^2 = 1); a's mean is 1,
|
|
80
|
-
# giving a squared distance of 100 over 2 * sigma^2.
|
|
81
|
-
log_joint_b = math.log(0.5) - 0.5 * math.log(2 * math.pi)
|
|
82
|
-
log_joint_a = math.log(0.5) - 0.5 * math.log(2 * math.pi) - 50.0
|
|
83
|
-
expected_b = math.exp(log_joint_b) / (math.exp(log_joint_a) + math.exp(log_joint_b))
|
|
84
|
-
assert clf.predict_proba([11.0])["b"] == pytest.approx(expected_b)
|
|
85
|
-
assert clf.predict([11.0]) == "b"
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def test_zero_variance_feature_smoothed_and_harmless() -> None:
|
|
89
|
-
# Feature 1 separates the classes; feature 2 is constant inside each
|
|
90
|
-
# class (zero per-class variance) but varies globally.
|
|
91
|
-
X = [[0.0, 1.0], [2.0, 1.0], [10.0, 5.0], [12.0, 5.0]]
|
|
92
|
-
y = ["a", "a", "b", "b"]
|
|
93
|
-
clf = GaussianNaiveBayes().fit(X, y)
|
|
94
|
-
assert clf.epsilon_ == pytest.approx(26e-9) # max global feature variance
|
|
95
|
-
assert clf.predict([1.0, 1.0]) == "a"
|
|
96
|
-
assert clf.predict([11.0, 5.0]) == "b"
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
def test_constant_matrix_falls_back_to_absolute_floor() -> None:
|
|
100
|
-
X = [[7.0, 7.0], [7.0, 7.0]]
|
|
101
|
-
clf = GaussianNaiveBayes().fit(X, ["a", "b"])
|
|
102
|
-
assert clf.epsilon_ == pytest.approx(1e-12)
|
|
103
|
-
# Identical likelihoods: posteriors collapse to the priors.
|
|
104
|
-
assert clf.predict_proba([7.0, 7.0]) == {"a": 0.5, "b": 0.5}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
def test_epsilon_matches_documented_rule() -> None:
|
|
108
|
-
X = [[0.0, 0.0], [2.0, 1.0], [4.0, 2.0]]
|
|
109
|
-
y = ["a", "b", "b"]
|
|
110
|
-
clf = GaussianNaiveBayes().fit(X, y)
|
|
111
|
-
# Global variances: feature 0 -> 8/3, feature 1 -> 2/3; max is 8/3.
|
|
112
|
-
assert clf.epsilon_ == pytest.approx((8.0 / 3.0) * 1e-9)
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
def test_repeated_fits_are_deterministic() -> None:
|
|
116
|
-
X, y = _separable()
|
|
117
|
-
first = GaussianNaiveBayes().fit(X, y)
|
|
118
|
-
second = GaussianNaiveBayes().fit(X, y)
|
|
119
|
-
queries = ([0.0, 0.0], [5.0, 5.0], [10.0, 10.0])
|
|
120
|
-
for query in queries:
|
|
121
|
-
assert first.predict_proba(query) == second.predict_proba(query)
|
|
122
|
-
assert first.predict(query) == second.predict(query)
|
|
123
|
-
assert first.epsilon_ == second.epsilon_
|
|
124
|
-
assert first._classes == second._classes
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
def test_tie_resolves_to_earliest_seen_label() -> None:
|
|
128
|
-
clf = GaussianNaiveBayes().fit([[0.0], [2.0]], ["first", "second"])
|
|
129
|
-
assert clf.predict_proba([1.0]) == {"first": 0.5, "second": 0.5}
|
|
130
|
-
assert clf.predict([1.0]) == "first"
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
def test_int_labels_supported() -> None:
|
|
134
|
-
clf = GaussianNaiveBayes().fit([[0.0], [10.0]], [0, 1])
|
|
135
|
-
probs: dict[Label, float] = clf.predict_proba([9.9])
|
|
136
|
-
assert probs[1] > probs[0]
|
|
137
|
-
assert clf.predict([0.1]) == 0
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
def test_empty_width_rows_yield_prior_only_posteriors() -> None:
|
|
141
|
-
clf = GaussianNaiveBayes().fit([[], [], []], ["a", "a", "b"])
|
|
142
|
-
assert clf.predict_proba([]) == {"a": pytest.approx(2 / 3), "b": pytest.approx(1 / 3)}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
def test_init_rejects_nonpositive_var_smoothing() -> None:
|
|
146
|
-
with pytest.raises(ValueError, match="var_smoothing must be > 0"):
|
|
147
|
-
GaussianNaiveBayes(var_smoothing=0.0)
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
def test_fit_rejects_empty_x() -> None:
|
|
151
|
-
with pytest.raises(ValueError, match="non-empty"):
|
|
152
|
-
GaussianNaiveBayes().fit([], [])
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
def test_fit_rejects_length_mismatch() -> None:
|
|
156
|
-
with pytest.raises(ValueError, match="same length"):
|
|
157
|
-
GaussianNaiveBayes().fit([[1.0]], ["a", "b"])
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
def test_fit_rejects_ragged_rows() -> None:
|
|
161
|
-
with pytest.raises(ValueError, match="same length"):
|
|
162
|
-
GaussianNaiveBayes().fit([[1.0, 2.0], [1.0]], ["a", "b"])
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
def test_predict_before_fit_raises() -> None:
|
|
166
|
-
clf = GaussianNaiveBayes()
|
|
167
|
-
with pytest.raises(ValueError, match="not fitted"):
|
|
168
|
-
clf.predict_proba([1.0])
|
|
169
|
-
with pytest.raises(ValueError, match="not fitted"):
|
|
170
|
-
clf.predict_proba_one([1.0])
|
|
171
|
-
with pytest.raises(ValueError, match="not fitted"):
|
|
172
|
-
clf.predict([1.0])
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
def test_predict_rejects_wrong_query_width() -> None:
|
|
176
|
-
X, y = _separable()
|
|
177
|
-
clf = GaussianNaiveBayes().fit(X, y)
|
|
178
|
-
with pytest.raises(ValueError, match="features"):
|
|
179
|
-
clf.predict_proba([1.0])
|
|
180
|
-
with pytest.raises(ValueError, match="features"):
|
|
181
|
-
clf.predict_proba_one([1.0, 2.0, 3.0])
|
|
182
|
-
with pytest.raises(ValueError, match="features"):
|
|
183
|
-
clf.predict([1.0])
|
package/tests/test_ml_pca.py
DELETED
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
"""Tests for :mod:`cds.ml.decomposition` (PCA via Jacobi eigen-solver)."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import pytest
|
|
6
|
-
|
|
7
|
-
from cds.ml import PCA
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
def test_pca_finds_dominant_direction() -> None:
|
|
11
|
-
# Data stretched along the (1,1) diagonal: PC1 must capture ~all variance.
|
|
12
|
-
X = [[1.0, 1.0], [2.0, 2.0], [3.0, 3.0], [4.0, 4.0]]
|
|
13
|
-
model = PCA(n_components=1).fit(X)
|
|
14
|
-
assert model.explained_variance_ratio_[0] == pytest.approx(1.0, abs=1e-9)
|
|
15
|
-
axis = model.components_[0]
|
|
16
|
-
# Sign is arbitrary; the line spanned must be the diagonal.
|
|
17
|
-
assert abs(axis[0]) == pytest.approx(abs(axis[1]), abs=1e-8)
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
def test_pca_projection_preserves_pairwise_distances() -> None:
|
|
21
|
-
X = [[0.0, 0.0], [2.0, 0.5], [4.0, 1.0], [6.0, 1.5]]
|
|
22
|
-
model, Z = PCA(n_components=1).fit_transform(X)
|
|
23
|
-
assert len(Z) == 4
|
|
24
|
-
assert all(len(z) == 1 for z in Z)
|
|
25
|
-
# 2-D points are collinear → 1-D projection reconstructs them exactly.
|
|
26
|
-
rebuilt = model.inverse_transform(Z)
|
|
27
|
-
for original, row in zip(X, rebuilt):
|
|
28
|
-
for a, b in zip(original, row):
|
|
29
|
-
assert a == pytest.approx(b, abs=1e-8)
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
def test_pca_two_components_recover_full_space() -> None:
|
|
33
|
-
X = [[1.0, 2.0], [3.0, 4.0], [5.0, 7.0], [7.0, 1.0]]
|
|
34
|
-
model = PCA(n_components=2).fit(X)
|
|
35
|
-
Z = model.transform(X)
|
|
36
|
-
rebuilt = model.inverse_transform(Z)
|
|
37
|
-
for original, row in zip(X, rebuilt):
|
|
38
|
-
for a, b in zip(original, row):
|
|
39
|
-
assert a == pytest.approx(b, abs=1e-8)
|
|
40
|
-
assert sum(model.explained_variance_ratio_) == pytest.approx(1.0, abs=1e-9)
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
def test_pca_diagonal_covariance_hits_annihilation_skip() -> None:
|
|
44
|
-
# Centered orthogonal columns give an already-diagonal covariance, so
|
|
45
|
-
# Jacobi's inner loop skips every pair without rotating.
|
|
46
|
-
# Var([-1, 1]) with ddof=1 is 2.0.
|
|
47
|
-
X = [[-1.0, 0.0], [1.0, 0.0]]
|
|
48
|
-
model = PCA(n_components=2).fit(X)
|
|
49
|
-
assert model.explained_variance_[0] == pytest.approx(2.0)
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def test_pca_partial_zero_pairs_skip_rotation() -> None:
|
|
53
|
-
# Columns 0 and 1 are identical (correlated), column 2 is exactly
|
|
54
|
-
# orthogonal to both: the sweep must rotate pair (0,1) while skipping
|
|
55
|
-
# pairs (0,2) and (1,2) as already annihilated.
|
|
56
|
-
c0 = [1.0, 1.0, -1.0, -1.0]
|
|
57
|
-
c2 = [1.0, -1.0, 1.0, -1.0]
|
|
58
|
-
X = [[c0[i], c0[i], c2[i]] for i in range(4)]
|
|
59
|
-
model = PCA(n_components=3).fit(X)
|
|
60
|
-
# Spectrum of [[4/3, 4/3, 0], [4/3, 4/3, 0], [0, 0, 4/3]]:
|
|
61
|
-
# diagonalized to 8/3 (duplicated axis), 4/3 (orthogonal column), ~0.
|
|
62
|
-
assert model.explained_variance_[0] == pytest.approx(8.0 / 3.0)
|
|
63
|
-
assert model.explained_variance_[1] == pytest.approx(4.0 / 3.0)
|
|
64
|
-
assert model.explained_variance_[2] == pytest.approx(0.0, abs=1e-9)
|
|
65
|
-
assert sum(model.explained_variance_ratio_) == pytest.approx(1.0, abs=1e-9)
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
def test_pca_constant_data_zero_variance_guard() -> None:
|
|
69
|
-
X = [[5.0, 5.0], [5.0, 5.0], [5.0, 5.0]]
|
|
70
|
-
model = PCA(n_components=1).fit(X)
|
|
71
|
-
assert model.explained_variance_ == [pytest.approx(0.0)]
|
|
72
|
-
assert model.explained_variance_ratio_ == [0.0]
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
def test_pca_init_validation() -> None:
|
|
76
|
-
with pytest.raises(ValueError, match="n_components must be >= 1"):
|
|
77
|
-
PCA(0)
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
def test_pca_fit_validations() -> None:
|
|
81
|
-
with pytest.raises(ValueError, match="at least 2 samples"):
|
|
82
|
-
PCA(1).fit([[1.0, 2.0]])
|
|
83
|
-
with pytest.raises(ValueError, match="same length"):
|
|
84
|
-
PCA(1).fit([[1.0, 2.0], [3.0]])
|
|
85
|
-
with pytest.raises(ValueError, match="must not exceed"):
|
|
86
|
-
PCA(3).fit([[1.0, 2.0], [3.0, 4.0]])
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
def test_pcar_result_transform_width_mismatch() -> None:
|
|
90
|
-
model = PCA(1).fit([[1.0, 2.0], [3.0, 4.0]])
|
|
91
|
-
with pytest.raises(ValueError, match="features"):
|
|
92
|
-
model.transform([[1.0]])
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
def test_pca_inverse_width_mismatch() -> None:
|
|
96
|
-
model = PCA(1).fit([[1.0, 2.0], [3.0, 4.0]])
|
|
97
|
-
with pytest.raises(ValueError, match="components to invert"):
|
|
98
|
-
model.inverse_transform([[1.0, 2.0]])
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
"""Tests for :mod:`cds.ml.preprocessing` (StandardScaler + split)."""
|
|
2
|
-
|
|
3
|
-
from __future__ import annotations
|
|
4
|
-
|
|
5
|
-
import pytest
|
|
6
|
-
|
|
7
|
-
from cds.ml import StandardScaler, train_test_split
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
def test_scaler_centers_and_scales() -> None:
|
|
11
|
-
X = [[1.0, 10.0], [3.0, 30.0], [5.0, 50.0]]
|
|
12
|
-
scaled = StandardScaler().fit_transform(X)
|
|
13
|
-
cols = list(zip(*scaled))
|
|
14
|
-
assert sum(cols[0]) == pytest.approx(0.0, abs=1e-12)
|
|
15
|
-
assert sum(cols[1]) == pytest.approx(0.0, abs=1e-12)
|
|
16
|
-
variances = [sum(v * v for v in col) / len(col) for col in cols]
|
|
17
|
-
assert variances[0] == pytest.approx(1.0)
|
|
18
|
-
assert variances[1] == pytest.approx(1.0)
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
def test_scaler_zero_variance_column_maps_to_zero() -> None:
|
|
22
|
-
scaler = StandardScaler().fit([[2.0, 7.0], [2.0, 9.0]])
|
|
23
|
-
scaled = scaler.transform([[2.0, 100.0], [2.0, -100.0]])
|
|
24
|
-
assert [row[0] for row in scaled] == [0.0, 0.0]
|
|
25
|
-
# Inverse restores the constant column to its fitted mean.
|
|
26
|
-
restored = scaler.inverse_transform(scaled)
|
|
27
|
-
assert restored[0][0] == 2.0
|
|
28
|
-
assert restored[1][0] == 2.0
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
def test_scaler_round_trip() -> None:
|
|
32
|
-
X = [[-4.0, 2.5], [0.0, 1.0], [4.0, 6.5]]
|
|
33
|
-
scaler = StandardScaler()
|
|
34
|
-
scaled = scaler.fit_transform(X)
|
|
35
|
-
restored = scaler.inverse_transform(scaled)
|
|
36
|
-
for row_orig, row_rest in zip(X, restored):
|
|
37
|
-
for a, b in zip(row_orig, row_rest):
|
|
38
|
-
assert a == pytest.approx(b, abs=1e-12)
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def test_scaler_fit_validations() -> None:
|
|
42
|
-
with pytest.raises(ValueError, match="non-empty"):
|
|
43
|
-
StandardScaler().fit([])
|
|
44
|
-
with pytest.raises(ValueError, match="same length"):
|
|
45
|
-
StandardScaler().fit([[1.0, 2.0], [3.0]])
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
def test_scaler_transform_validations() -> None:
|
|
49
|
-
scaler = StandardScaler()
|
|
50
|
-
with pytest.raises(ValueError, match="not fitted"):
|
|
51
|
-
scaler.transform([[1.0]])
|
|
52
|
-
scaler.fit([[1.0, 2.0]])
|
|
53
|
-
with pytest.raises(ValueError, match="non-empty"):
|
|
54
|
-
scaler.transform([])
|
|
55
|
-
with pytest.raises(ValueError, match="features"):
|
|
56
|
-
scaler.transform([[1.0, 2.0, 3.0]])
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
def test_scaler_inverse_before_fit_raises() -> None:
|
|
60
|
-
with pytest.raises(ValueError, match="not fitted"):
|
|
61
|
-
StandardScaler().inverse_transform([[1.0]])
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
def test_split_partitions_and_sizes() -> None:
|
|
65
|
-
X = [[float(i)] for i in range(20)]
|
|
66
|
-
y = [i * 2.0 for i in range(20)]
|
|
67
|
-
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, seed=42)
|
|
68
|
-
assert len(X_te) == len(y_te) == 5
|
|
69
|
-
assert len(X_tr) == len(y_tr) == 15
|
|
70
|
-
# Alignment preserved within each partition.
|
|
71
|
-
for xr, yr in zip(X_tr, y_tr):
|
|
72
|
-
assert yr == xr[0] * 2.0
|
|
73
|
-
# Disjoint partitions covering the original set.
|
|
74
|
-
seen = sorted([row[0] for row in X_tr] + [row[0] for row in X_te])
|
|
75
|
-
assert seen == [float(i) for i in range(20)]
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
def test_split_deterministic_given_seed() -> None:
|
|
79
|
-
X = [[float(i)] for i in range(10)]
|
|
80
|
-
y = [float(i) for i in range(10)]
|
|
81
|
-
a = train_test_split(X, y, seed=7)
|
|
82
|
-
b = train_test_split(X, y, seed=7)
|
|
83
|
-
assert a == b
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
def test_split_shuffles_with_seed() -> None:
|
|
87
|
-
X = [[float(i)] for i in range(10)]
|
|
88
|
-
y = [float(i) for i in range(10)]
|
|
89
|
-
X_tr, _, _, _ = train_test_split(X, y, seed=0)
|
|
90
|
-
# The training rows must NOT be the identity prefix when shuffled.
|
|
91
|
-
assert any(row[0] != i for i, row in zip(range(len(X_tr)), X_tr))
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
def test_split_validations() -> None:
|
|
95
|
-
with pytest.raises(ValueError, match="non-empty"):
|
|
96
|
-
train_test_split([], [])
|
|
97
|
-
with pytest.raises(ValueError, match="same length"):
|
|
98
|
-
train_test_split([[1.0]], [1.0, 2.0])
|
|
99
|
-
with pytest.raises(ValueError, match="same length"):
|
|
100
|
-
train_test_split([[1.0, 2.0], [3.0]], [1.0, 2.0])
|
|
101
|
-
with pytest.raises(ValueError, match=r"test_size must be in \(0, 1\)"):
|
|
102
|
-
train_test_split([[1.0]], [1.0], test_size=0.0)
|
|
103
|
-
with pytest.raises(ValueError, match=r"test_size must be in \(0, 1\)"):
|
|
104
|
-
train_test_split([[1.0]], [1.0], test_size=1.0)
|