Contributing#
This project is a community effort, and everyone is welcome tocontribute. It is hosted onscikit-learn/scikit-learn.The decision making process and governance structure of scikit-learn is laidout inScikit-learn governance and decision-making.
Scikit-learn is somewhatselective when it comes toadding new algorithms, and the best way to contribute and to help the projectis to start working on known issues.SeeIssues for New Contributors to get started.
Our community, our values
We are a community based on openness and friendly, didactic,discussions.
We aspire to treat everybody equally, and value their contributions. Weare particularly seeking people from underrepresented backgrounds in OpenSource Software and scikit-learn in particular to participate andcontribute their expertise and experience.
Decisions are made based on technical merit and consensus.
Code is not the only way to help the project. Reviewing pullrequests, answering questions to help others on mailing lists orissues, organizing and teaching tutorials, working on the website,improving the documentation, are all priceless contributions.
We abide by the principles of openness, respect, and consideration ofothers of the Python Software Foundation:https://www.python.org/psf/codeofconduct/
In case you experience issues using this package, do not hesitate to submit aticket to theGitHub issue tracker. You are alsowelcome to post feature requests or pull requests.
Ways to contribute#
There are many ways to contribute to scikit-learn, with the most common onesbeing contribution of code or documentation to the project. Improving thedocumentation is no less important than improving the library itself. If youfind a typo in the documentation, or have made improvements, do not hesitate tocreate a GitHub issue or preferably submit a GitHub pull request.Full documentation can be found under the doc/ directory.
But there are many other ways to help. In particular helping toimprove, triage, and investigate issues andreviewing other developers’ pull requests are veryvaluable contributions that decrease the burden on the projectmaintainers.
Another way to contribute is to report issues you’re facing, and give a “thumbsup” on issues that others reported and that are relevant to you. It also helpsus if you spread the word: reference the project from your blog and articles,link to it from your website, or simply star to say “I use it”:
In case a contribution/issue involves changes to the API principlesor changes to dependencies or supported versions, it must be backed by aEnhancement proposals (SLEPs), where a SLEP must be submitted as a pull-request toenhancement proposalsusing theSLEP templateand follows the decision-making process outlined inScikit-learn governance and decision-making.
Contributing to related projects#
Scikit-learn thrives in an ecosystem of several related projects, which alsomay have relevant issues to work on, including smaller projects such as:
and larger projects:
and so on.
Look for issues marked “help wanted” or similar. Helping these projects may helpscikit-learn too. See alsoRelated Projects.
Automated Contributions Policy#
Please refrain from submitting issues or pull requests generated byfully-automated tools. Maintainers reserve the right, at their sole discretion,to close such submissions and to block any account responsible for them.
Ideally, contributions should follow from a human-to-human discussion in theform of an issue.
Submitting a bug report or a feature request#
We use GitHub issues to track all bugs and feature requests; feel free to openan issue if you have found a bug or wish to see a feature implemented.
In case you experience issues using this package, do not hesitate to submit aticket to theBug Tracker. You arealso welcome to post feature requests or pull requests.
It is recommended to check that your issue complies with thefollowing rules before submitting:
Verify that your issue is not being currently addressed by otherissuesorpull requests.
If you are submitting an algorithm or feature request, please verify thatthe algorithm fulfills ournew algorithm requirements.
If you are submitting a bug report, we strongly encourage you to follow the guidelines inHow to make a good bug report.
How to make a good bug report#
When you submit an issue toGitHub, please do your best tofollow these guidelines! This will make it a lot easier to provide you with goodfeedback:
The ideal bug report contains ashort reproducible code snippet, this way anyone can try to reproduce the bug easily. If yoursnippet is longer than around 50 lines, please link to aGist or a GitHub repo.
If not feasible to include a reproducible snippet, please be specific aboutwhatestimators and/or functions are involved and the shape of the data.
If an exception is raised, pleaseprovide the full traceback.
Please include youroperating system type and version number, as well asyourPython, scikit-learn, numpy, and scipy versions. This informationcan be found by running:
python-c"import sklearn; sklearn.show_versions()"
Please ensure allcode snippets and error messages are formatted inappropriate code blocks. SeeCreating and highlighting code blocksfor more details.
If you want to help curate issues, read aboutBug triaging and issue curation.
Contributing code#
Note
To avoid duplicating work, it is highly advised that you search through theissue tracker andthePR list.If in doubt about duplicated work, or if you want to work on a non-trivialfeature, it’s recommended to first open an issue intheissue trackerto get some feedback from core developers.
One easy way to find an issue to work on is by applying the “help wanted”label in your search. This lists all the issues that have been unclaimedso far. If you’d like to work on such issue, leave a comment with your idea ofhow you plan to approach it, and start working on it. If somebody else hasalready said they’d be working on the issue in the past 2-3 weeks, please letthem finish their work, otherwise consider it stalled and take it over.
To maintain the quality of the codebase and ease the review process, anycontribution must conform to the project’scoding guidelines, in particular:
Don’t modify unrelated lines to keep the PR focused on the scope stated in itsdescription or issue.
Only write inline comments that add value and avoid stating the obvious: explainthe “why” rather than the “what”.
Most importantly: Do not contribute code that you don’t understand.
Video resources#
These videos are step-by-step introductions on how to contribute toscikit-learn, and are a great companion to the following text guidelines.Please make sure to still check our guidelines below, since they describe ourlatest up-to-date workflow.
Crash Course in Contributing to Scikit-Learn & Open Source Projects:Video,Transcript
Example of Submitting a Pull Request to scikit-learn:Video,Transcript
Sprint-specific instructions and practical tips:Video,Transcript
3 Components of Reviewing a Pull Request:Video,Transcript
Note
In January 2021, the default branch name changed frommaster
tomain
for the scikit-learn GitHub repository to use more inclusive terms.These videos were created prior to the renaming of the branch.For contributors who are viewing these videos to set up theirworking environment and submitting a PR,master
should be replaced tomain
.
How to contribute#
The preferred way to contribute to scikit-learn is to fork themainrepository on GitHub,then submit a “pull request” (PR).
In the first few steps, we explain how to locally install scikit-learn, andhow to set up your git repository:
Create an account onGitHub if you do not already have one.
Fork theproject repository: click on the ‘Fork’button near the top of the page. This creates a copy of the code under youraccount on the GitHub user account. For more details on how to fork arepository seethis guide.
Clone your fork of the scikit-learn repo from your GitHub account to yourlocal disk:
gitclonegit@github.com:YourLogin/scikit-learn.git# add --depth 1 if your connection is slowcdscikit-learn
Follow steps 2-6 inBuilding from source to build scikit-learn indevelopment mode and return to this document.
Install the development dependencies:
pipinstallpytestpytest-covruff==0.11.2mypynumpydoc
Add the
upstream
remote. This saves a reference to the mainscikit-learn repository, which you can use to keep your repositorysynchronized with the latest changes:gitremoteaddupstreamgit@github.com:scikit-learn/scikit-learn.git
Check that the
upstream
andorigin
remote aliases are configured correctlyby running:gitremote-v
This should display:
origin git@github.com:YourLogin/scikit-learn.git (fetch)origin git@github.com:YourLogin/scikit-learn.git (push)upstream git@github.com:scikit-learn/scikit-learn.git (fetch)upstream git@github.com:scikit-learn/scikit-learn.git (push)
You should now have a working installation of scikit-learn, and your git repositoryproperly configured. It could be useful to run some test to verify your installation.Please refer toUseful pytest aliases and flags for examples.
The next steps now describe the process of modifying code and submitting a PR:
Synchronize your
main
branch with theupstream/main
branch,more details onGitHub Docs:gitcheckoutmaingitfetchupstreamgitmergeupstream/main
Create a feature branch to hold your development changes:
gitcheckout-bmy_feature
and start making changes. Always use a feature branch. It’s goodpractice to never work on the
main
branch!(Optional) Installpre-commit torun code style checks before each commit:
pipinstallpre-commitpre-commitinstall
pre-commit checks can be disabled for a particular commit with
gitcommit-n
.Develop the feature on your feature branch on your computer, using Git todo the version control. When you’re done editing, add changed files using
gitadd
and thengitcommit
:gitaddmodified_filesgitcommit
to record your changes in Git, then push the changes to your GitHubaccount with:
gitpush-uoriginmy_feature
Followtheseinstructions to create a pull request from your fork. This will send anotification to potential reviewers. You may want to consider sending a message tothediscord in the developmentchannel for more visibility if your pull request does not receive attention aftera couple of days (instant replies are not guaranteed though).
It is often helpful to keep your local feature branch synchronized with thelatest changes of the main scikit-learn repository:
gitfetchupstreamgitmergeupstream/main
Subsequently, you might need to solve the conflicts. You can refer to theGit documentation related to resolving merge conflict using the commandline.
Learning Git
TheGit documentation andhttp://try.github.io are excellent resources to get started with git,and understanding all of the commands shown here.
Pull request checklist#
Before a PR can be merged, it needs to be approved by two core developers.An incomplete contribution – where you expect to do more work before receivinga full review – should be marked as adraft pull requestand changed to “ready for review” when it matures. Draft PRs may be useful to:indicate you are working on something to avoid duplicated work, requestbroad review of functionality or API, or seek collaborators. Draft PRs oftenbenefit from the inclusion of atask list inthe PR description.
In order to ease the reviewing process, we recommend that your contributioncomplies with the following rules before marking a PR as “ready for review”. Thebolded ones are especially important:
Give your pull request a helpful title that summarizes what yourcontribution does. This title will often become the commit message oncemerged so it should summarize your contribution for posterity. In somecases “Fix <ISSUE TITLE>” is enough. “Fix #<ISSUE NUMBER>” is never agood title.
Make sure your code passes the tests. The whole test suite can be runwith
pytest
, but it is usually not recommended since it takes a longtime. It is often enough to only run the test related to your changes:for example, if you changed something insklearn/linear_model/_logistic.py
, running the following commands willusually be enough:pytestsklearn/linear_model/_logistic.py
to make sure the doctestexamples are correctpytestsklearn/linear_model/tests/test_logistic.py
to run the testsspecific to the filepytestsklearn/linear_model
to test the wholelinear_model
modulepytestdoc/modules/linear_model.rst
to make sure the user guideexamples are correct.pytestsklearn/tests/test_common.py-kLogisticRegression
to run all ourestimator checks (specifically forLogisticRegression
, if that’s theestimator you changed).
There may be other failing tests, but they will be caught by the CI soyou don’t need to run the whole test suite locally. For guidelines on howto use
pytest
efficiently, see theUseful pytest aliases and flags.Make sure your code is properly commented and documented, andmakesure the documentation renders properly. To build the documentation, pleaserefer to ourDocumentation guidelines. The CI will alsobuild the docs: please refer toGenerated documentation on GitHub Actions.
Tests are necessary for enhancements to beaccepted. Bug-fixes or new features should be provided withnon-regression tests. These testsverify the correct behavior of the fix or feature. In this manner, furthermodifications on the code base are granted to be consistent with thedesired behavior. In the case of bug fixes, at the time of the PR, thenon-regression tests should fail for the code base in the
main
branchand pass for the PR code.If your PR is likely to affect users, you need to add a changelog entry describingyour PR changes. See theREADMEfor more details.
Follow theCoding guidelines.
When applicable, use the validation tools and scripts in the
sklearn.utils
module. A list of utility routines available for developers can be found in theUtilities for Developers page.Often pull requests resolve one or more other issues (or pull requests).If merging your pull request means that some other issues/PRs shouldbe closed, you shoulduse keywords to create link to them(e.g.,
Fixes#1234
; multiple issues/PRs are allowed as long as eachone is preceded by a keyword). Upon merging, those issues/PRs willautomatically be closed by GitHub. If your pull request is simplyrelated to some other issues/PRs, or it only partially resolves the targetissue, create a link to them without using the keywords (e.g.,Towards#1234
).PRs should often substantiate the change, through benchmarks ofperformance and efficiency (seeMonitoring performance) or throughexamples of usage. Examples also illustrate the features and intricacies ofthe library to users. Have a look at other examples in theexamples/directory for reference. Examples should demonstrate why the newfunctionality is useful in practice and, if possible, compare it to othermethods available in scikit-learn.
New features have some maintenance overhead. We expect PR authorsto take part in the maintenance for the code they submit, at leastinitially. New features need to be illustrated with narrativedocumentation in the user guide, with small code snippets.If relevant, please also add references in the literature, with PDF linkswhen possible.
The user guide should also include expected time and space complexityof the algorithm and scalability, e.g. “this algorithm can scale to alarge number of samples > 100000, but does not scale in dimensionality:
n_features
is expected to be lower than 100”.
You can also check ourCode Review Guidelines to get an idea of what reviewerswill expect.
You can check for common programming errors with the following tools:
Code with a good unit test coverage (at least 80%, better 100%), check with:
pipinstallpytestpytest-covpytest--covsklearnpath/to/tests
See alsoTesting and improving test coverage.
Run static analysis with
mypy
:mypysklearn
This must not produce new errors in your pull request. Using
#type:ignore
annotation can be a workaround for a few cases that are not supported bymypy, in particular,when importing C or Cython modules,
on properties with decorators.
Bonus points for contributions that include a performance analysis witha benchmark script and profiling output (seeMonitoring performance).Also check out theHow to optimize for speed guide for more details onprofiling and Cython optimizations.
Note
The current state of the scikit-learn code base is not compliant withall of those guidelines, but we expect that enforcing those constraintson all new contributions will get the overall code base quality in theright direction.
See also
For two very well documented and more detailed guides on developmentworkflow, please pay a visit to theScipy Development Workflow -and theAstropy Workflow for Developerssections.
Continuous Integration (CI)#
Azure pipelines are used for testing scikit-learn on Linux, Mac and Windows,with different dependencies and settings.
CircleCI is used to build the docs for viewing.
Github Actions are used for various tasks, including building wheels andsource distributions.
Commit message markers#
Please note that if one of the following markers appears in the latest commitmessage, the following actions are taken.
Commit Message Marker | Action Taken by CI |
---|---|
[ci skip] | CI is skipped completely |
[cd build] | CD is run (wheels and source distribution are built) |
[lint skip] | Azure pipeline skips linting |
[scipy-dev] | Build & test with our dependencies (numpy, scipy, etc.) development builds |
[free-threaded] | Build & test with CPython 3.13 free-threaded |
[pyodide] | Build & test with Pyodide |
[azure parallel] | Run Azure CI jobs in parallel |
[float32] | Run float32 tests by setting |
[doc skip] | Docs are not built |
[doc quick] | Docs built, but excludes example gallery plots |
[doc build] | Docs built including example gallery plots (very long) |
Note that, by default, the documentation is built but only the examplesthat are directly modified by the pull request are executed.
Resolve conflicts in lock files#
Here is a bash snippet that helps resolving conflicts in environment and lock files:
# pull latest upstream/maingitpullupstreammain--no-rebase# resolve conflicts - keeping the upstream/main version for specific filesgitcheckout--theirsbuild_tools/*/*.lockbuild_tools/*/*environment.yml\build_tools/*/*lock.txtbuild_tools/*/*requirements.txtgitaddbuild_tools/*/*.lockbuild_tools/*/*environment.yml\build_tools/*/*lock.txtbuild_tools/*/*requirements.txtgitmerge--continue
This will mergeupstream/main
into our branch, automatically prioritising theupstream/main
for conflicting environment and lock files (this is good enough, becausewe will re-generate the lock files afterwards).
Note that this only fixes conflicts in environment and lock files and you might haveother conflicts to resolve.
Finally, we have to re-generate the environment and lock files for the CIs by running:
pythonbuild_tools/update_environments_and_lock_files.py
Stalled pull requests#
As contributing a feature can be a lengthy process, somepull requests appear inactive but unfinished. In such a case, takingthem over is a great service for the project. A good etiquette to take over is:
Determine if a PR is stalled
A pull request may have the label “stalled” or “help wanted” if wehave already identified it as a candidate for other contributors.
To decide whether an inactive PR is stalled, ask the contributor ifshe/he plans to continue working on the PR in the near future.Failure to respond within 2 weeks with an activity that moves the PRforward suggests that the PR is stalled and will result in taggingthat PR with “help wanted”.
Note that if a PR has received earlier comments on the contributionthat have had no reply in a month, it is safe to assume that the PRis stalled and to shorten the wait time to one day.
After a sprint, follow-up for un-merged PRs opened during sprint willbe communicated to participants at the sprint, and those PRs will betagged “sprint”. PRs tagged with “sprint” can be reassigned ordeclared stalled by sprint leaders.
Taking over a stalled PR: To take over a PR, it is important tocomment on the stalled PR that you are taking over and to link from thenew PR to the old one. The new PR should be created by pulling from theold one.
Stalled and Unclaimed Issues#
Generally speaking, issues which are up for grabs will have a“help wanted”.tag. However, not all issues which need contributors will have this tag,as the “help wanted” tag is not always up-to-date with the stateof the issue. Contributors can find issues which are still up for grabsusing the following guidelines:
First, todetermine if an issue is claimed:
Check for linked pull requests
Check the conversation to see if anyone has said that they’re working oncreating a pull request
If a contributor comments on an issue to say they are working on it,a pull request is expected within 2 weeks (new contributor) or 4 weeks(contributor or core dev), unless a larger time frame is explicitly given.Beyond that time, another contributor can take the issue and make apull request for it. We encourage contributors to comment directly on thestalled or unclaimed issue to let community members know that they will beworking on it.
If the issue is linked to astalled pull request,we recommend that contributors follow the proceduredescribed in theStalled pull requestssection rather than working directly on the issue.
Issues for New Contributors#
New contributors should look for the following tags when looking for issues. Westrongly recommend that new contributors tackle “easy” issues first: this helpsthe contributor become familiar with the contribution workflow, and for the coredevs to become acquainted with the contributor; besides which, we frequentlyunderestimate how easy an issue is to solve!
Good first issue tag
A great way to start contributing to scikit-learn is to pick an item fromthe list ofgood first issuesin the issue tracker. Resolving these issues allows you to start contributingto the project without much prior knowledge. If you have already contributedto scikit-learn, you should look at Easy issues instead.
Easy tag
If you have already contributed to scikit-learn, another great way to contributeto scikit-learn is to pick an item from the list ofEasy issues in the issuetracker. Your assistance in this area will be greatly appreciated by themore experienced developers as it helps free up their time to concentrate onother issues.
Help wanted tag
We often use the help wanted tag to mark issues regardless of difficulty.Additionally, we use the help wanted tag to mark Pull Requests which have beenabandoned by their original contributor and are available for someone to pick up wherethe original contributor left off. The list of issues with the help wanted tag can befoundhere.Note that not all issues which need contributors will have this tag.
Documentation#
We are glad to accept any sort of documentation:
Function/method/class docstrings: Also known as “API documentation”, thesedescribe what the object does and detail any parameters, attributes andmethods. Docstrings live alongside the code insklearn/, and aregenerated according todoc/api_reference.py. Toadd, update, remove, or deprecate a public API that is listed inAPI Reference, thisis the place to look at.
User guide: These provide more detailed information about the algorithmsimplemented in scikit-learn and generally live in the rootdoc/ directoryanddoc/modules/.
Examples: These provide full code examples that may demonstrate the useof scikit-learn modules, compare different algorithms or discuss theirinterpretation, etc. Examples live inexamples/.
Other reStructuredText documents: These provide various other useful information(e.g., theContributing guide) and live indoc/.
Guidelines for writing docstrings#
You can use
pytest
to test docstrings, e.g. assuming theRandomForestClassifier
docstring has been modified, the following commandwould test its docstring compliance:pytest--doctest-modulessklearn/ensemble/_forest.py-kRandomForestClassifier
The correct order of sections is: Parameters, Returns, See Also, Notes, Examples.See thenumpydoc documentation forinformation on other possible sections.
When documenting the parameters and attributes, here is a list of somewell-formatted examples
n_clusters : int, default=3 The number of clusters detected by the algorithm.some_param : {"hello", "goodbye"}, bool or int, default=True The parameter description goes here, which can be either a string literal (either `hello` or `goodbye`), a bool, or an int. The default value is True.array_parameter : {array-like, sparse matrix} of shape (n_samples, n_features) \ or (n_samples,) This parameter accepts data in either of the mentioned forms, with one of the mentioned shapes. The default value is `np.ones(shape=(n_samples,))`.list_param : list of inttyped_ndarray : ndarray of shape (n_samples,), dtype=np.int32sample_weight : array-like of shape (n_samples,), default=Nonemultioutput_array : ndarray of shape (n_samples, n_classes) or list of such arrays
In general have the following in mind:
Use Python basic types. (
bool
instead ofboolean
)Use parenthesis for defining shapes:
array-likeofshape(n_samples,)
orarray-likeofshape(n_samples,n_features)
For strings with multiple options, use brackets:
input:{'log','squared','multinomial'}
1D or 2D data can be a subset of
{array-like,ndarray,sparsematrix,dataframe}
. Note thatarray-like
can also be alist
, whilendarray
is explicitly only anumpy.ndarray
.Specify
dataframe
when “frame-like” features are being used, such asthe column names.When specifying the data type of a list, use
of
as a delimiter:listofint
. When the parameter supports arrays giving details about theshape and/or data type and a list of such arrays, you can use one ofarray-likeofshape(n_samples,)orlistofsucharrays
.When specifying the dtype of an ndarray, use e.g.
dtype=np.int32
afterdefining the shape:ndarrayofshape(n_samples,),dtype=np.int32
. Youcan specify multiple dtype as a set:array-likeofshape(n_samples,),dtype={np.float64,np.float32}
. If one wants to mention arbitraryprecision, useintegral
andfloating
rather than the Python dtypeint
andfloat
. When bothint
andfloating
are supported, there isno need to specify the dtype.When the default is
None
,None
only needs to be specified at theend withdefault=None
. Be sure to include in the docstring, what itmeans for the parameter or attribute to beNone
.
Add “See Also” in docstrings for related classes/functions.
“See Also” in docstrings should be one line per reference, with a colon and anexplanation, for example:
See Also--------SelectKBest : Select features based on the k highest scores.SelectFpr : Select features based on a false positive rate test.
The “Notes” section is optional. It is meant to provide information onspecific behavior of a function/class/classmethod/method.
A
Note
can also be added to an attribute, but in that case it requiresusing the..rubric::Note
directive.Add one or twosnippets of code in “Example” section to show how it canbe used. The code should be runable as is, i.e. it should include allrequired imports. Keep this section as brief as possible.
Guidelines for writing the user guide and other reStructuredText documents#
It is important to keep a good compromise between mathematical and algorithmicdetails, and give intuition to the reader on what the algorithm does.
Begin with a concise, hand-waving explanation of what the algorithm/code does onthe data.
Highlight the usefulness of the feature and its recommended application.Consider including the algorithm’s complexity(\(O\left(g\left(n\right)\right)\)) if available, as “rules of thumb” canbe very machine-dependent. Only if those complexities are not available, thenrules of thumb may be provided instead.
Incorporate a relevant figure (generated from an example) to provide intuitions.
Include one or two short code examples to demonstrate the feature’s usage.
Introduce any necessary mathematical equations, followed by references. Bydeferring the mathematical aspects, the documentation becomes more accessibleto users primarily interested in understanding the feature’s practicalimplications rather than its underlying mechanics.
When editing reStructuredText (
.rst
) files, try to keep line length under88 characters when possible (exceptions include links and tables).In scikit-learn reStructuredText files both single and double backtickssurrounding text will render as inline literal (often used for code, e.g.,
list
). This is due to specific configurations we have set. Singlebackticks should be used nowadays.Too much information makes it difficult for users to access the content theyare interested in. Use dropdowns to factorize it by using the following syntax
..dropdown:: Dropdown title Dropdown content.
The snippet above will result in the following dropdown:
Dropdown title#
Dropdown content.
Information that can be hidden by default using dropdowns is:
low hierarchy sections such as
References
,Properties
, etc. (see forinstance the subsections inDetection error tradeoff (DET));in-depth mathematical details;
narrative that is use-case specific;
in general, narrative that may only interest users that want to go beyondthe pragmatics of a given tool.
Do not use dropdowns for the low level section
Examples
, as it should stayvisible to all users. Make sure that theExamples
section comes right afterthe main discussion with the least possible folded section in-between.Be aware that dropdowns break cross-references. If that makes sense, hide thereference along with the text mentioning it. Else, do not use dropdown.
Guidelines for writing references#
When bibliographic references are available witharxivorDigital Object Identifier identification numbers,use the sphinx directives
:arxiv:
or:doi:
. For example, see references inSpectral Clustering Graphs.For the “References” section in docstrings, see
sklearn.metrics.silhouette_score
as an example.To cross-reference to other pages in the scikit-learn documentation use thereStructuredText cross-referencing syntax:
Section: to link to an arbitrary section in the documentation, usereference labels (seeSphinx docs).For example:
.._my-section:My section----------This is the text of the section.To refer to itself use:ref:`my-section`.
You should not modify existing sphinx reference labels as this would breakexisting cross references and external links pointing to specific sectionsin the scikit-learn documentation.
Glossary: linking to a term in theGlossary of Common Terms and API Elements:
:term:`cross_validation`
Function: to link to the documentation of a function, use the full importpath to the function:
:func:`~sklearn.model_selection.cross_val_score`
However, if there is a
..currentmodule::
directive above you in the document,you will only need to use the path to the function succeeding the currentmodule specified. For example:..currentmodule:: sklearn.model_selection:func:`cross_val_score`
Class: to link to documentation of a class, use the full import path to theclass, unless there is a
..currentmodule::
directive in the document above(see above)::class:`~sklearn.preprocessing.StandardScaler`
You can edit the documentation using any text editor, and then generate theHTML output by followingBuilding the documentation. The resulting HTML fileswill be placed in_build/html/
and are viewable in a web browser, for instance byopening the local_build/html/index.html
file or by running a local server
python-mhttp.server-d_build/html
Building the documentation#
Before submitting a pull request check if your modifications have introducednew sphinx warnings by building the documentation locally and try to fix them.
First, make sure you haveproperly installed thedevelopment version. On top of that, building the documentation requires installing someadditional packages:
pipinstallsphinxsphinx-gallerynumpydocmatplotlibPillowpandas\polarsscikit-imagepackagingseabornsphinx-prompt\sphinxext-opengraphsphinx-copybuttonplotlypooch\pydata-sphinx-themesphinxcontrib-sasssphinx-design\sphinx-remove-toctrees
To build the documentation, you need to be in thedoc
folder:
cddoc
In the vast majority of cases, you only need to generate the web site withoutthe example gallery:
make
The documentation will be generated in the_build/html/stable
directoryand are viewable in a web browser, for instance by opening the local_build/html/stable/index.html
file.To also generate the example gallery you can use:
makehtml
This will run all the examples, which takes a while. You can also run only a few examples based on their file names.Here is a way to run all examples with filenames containingplot_calibration
:
EXAMPLES_PATTERN="plot_calibration"makehtml
You can use regular expressions for more advanced use cases.
Set the environment variableNO_MATHJAX=1
if you intend to view the documentation inan offline setting. To build the PDF manual, run:
makelatexpdf
Sphinx version
While we do our best to have the documentation build under as manyversions of Sphinx as possible, the different versions tend tobehave slightly differently. To get the best results, you shoulduse the same version as the one we used on CircleCI. Look at thisGitHub searchto know the exact version.
Generated documentation on GitHub Actions#
When you change the documentation in a pull request, GitHub Actions automaticallybuilds it. To view the documentation generated by GitHub Actions, simply go to thebottom of your PR page, look for the item “Check the rendered docs here!” andclick on ‘details’ next to it:

Testing and improving test coverage#
High-qualityunit testingis a corner-stone of the scikit-learn development process. For thispurpose, we use thepytestpackage. The tests are functions appropriately named, located intests
subdirectories, that check the validity of the algorithms and thedifferent options of the code.
Runningpytest
in a folder will run all the tests of the correspondingsubpackages. For a more detailedpytest
workflow, please refer to thePull request checklist.
We expect code coverage of new features to be at least around 90%.
Writing matplotlib-related tests#
Test fixtures ensure that a set of tests will be executing with the appropriateinitialization and cleanup. The scikit-learn test suite implements apyplot
fixture which can be used withmatplotlib
.
Thepyplot
fixture should be used when a test function is dealing withmatplotlib
.matplotlib
is a soft dependency and is not required.This fixture is in charge of skipping the tests ifmatplotlib
is notinstalled. In addition, figures created during the tests will beautomatically closed once the test function has been executed.
To use this fixture in a test function, one needs to pass it as anargument:
deftest_requiring_mpl_fixture(pyplot):# you can now safely use matplotlib
Workflow to improve test coverage#
To test code coverage, you need to install thecoverage package in addition topytest
.
Run
pytest--covsklearn/path/to/tests
. The output lists for each file the linenumbers that are not tested.Find a low hanging fruit, looking at which lines are not tested,write or adapt a test specifically for these lines.
Loop.
Monitoring performance#
This section is heavily inspired from thepandas documentation.
When proposing changes to the existing code base, it’s important to make surethat they don’t introduce performance regressions. Scikit-learn usesasv benchmarks to monitor theperformance of a selection of common estimators and functions. You can viewthese benchmarks on thescikit-learn benchmark page.The corresponding benchmark suite can be found in theasv_benchmarks/
directory.
To use all features of asv, you will need eitherconda
orvirtualenv
. Formore details please check theasv installation webpage.
First of all you need to install the development version of asv:
pipinstallgit+https://github.com/airspeed-velocity/asv
and change your directory toasv_benchmarks/
:
cdasv_benchmarks
The benchmark suite is configured to run against your local clone ofscikit-learn. Make sure it is up to date:
gitfetchupstream
In the benchmark suite, the benchmarks are organized following the samestructure as scikit-learn. For example, you can compare the performance of aspecific estimator betweenupstream/main
and the branch you are working on:
asvcontinuous-bLogisticRegressionupstream/mainHEAD
The command uses conda by default for creating the benchmark environments. Ifyou want to use virtualenv instead, use the-E
flag:
asvcontinuous-Evirtualenv-bLogisticRegressionupstream/mainHEAD
You can also specify a whole module to benchmark:
asvcontinuous-blinear_modelupstream/mainHEAD
You can replaceHEAD
by any local branch. By default it will only report thebenchmarks that have changed by at least 10%. You can control this ratio withthe-f
flag.
To run the full benchmark suite, simply remove the-b
flag :
asvcontinuousupstream/mainHEAD
However this can take up to two hours. The-b
flag also accepts a regularexpression for a more complex subset of benchmarks to run.
To run the benchmarks without comparing to another branch, use therun
command:
asvrun-blinear_modelHEAD^!
You can also run the benchmark suite using the version of scikit-learn alreadyinstalled in your current Python environment:
asvrun--python=same
It’s particularly useful when you installed scikit-learn in editable mode toavoid creating a new environment each time you run the benchmarks. By defaultthe results are not saved when using an existing installation. To save theresults you must specify a commit hash:
asvrun--python=same--set-commit-hash=<commithash>
Benchmarks are saved and organized by machine, environment and commit. To seethe list of all saved benchmarks:
asvshow
and to see the report of a specific run:
asvshow<commithash>
When running benchmarks for a pull request you’re working on please report theresults on github.
The benchmark suite supports additional configurable options which can be setin thebenchmarks/config.json
configuration file. For example, the benchmarkscan run for a provided list of values for then_jobs
parameter.
More information on how to write a benchmark and how to use asv can be found intheasv documentation.
Issue Tracker Tags#
All issues and pull requests on theGitHub issue trackershould have (at least) one of the following tags:
- Bug:
Something is happening that clearly shouldn’t happen.Wrong results as well as unexpected errors from estimators go here.
- Enhancement:
Improving performance, usability, consistency.
- Documentation:
Missing, incorrect or sub-standard documentations and examples.
- New Feature:
Feature requests and pull requests implementing a new feature.
There are four other tags to help new contributors:
- Good first issue:
This issue is ideal for a first contribution to scikit-learn. Ask for helpif the formulation is unclear. If you have already contributed toscikit-learn, look at Easy issues instead.
- Easy:
This issue can be tackled without much prior experience.
- Moderate:
Might need some knowledge of machine learning or the package,but is still approachable for someone new to the project.
- Help wanted:
This tag marks an issue which currently lacks a contributor or aPR that needs another contributor to take over the work. Theseissues can range in difficulty, and may not be approachablefor new contributors. Note that not all issues which needcontributors will have this tag.
Maintaining backwards compatibility#
Deprecation#
If any publicly accessible class, function, method, attribute or parameter is renamed,we still support the old one for two releases and issue a deprecation warning when it iscalled, passed, or accessed.
Deprecating a class or a function
Suppose the functionzero_one
is renamed tozero_one_loss
, we add the decoratorutils.deprecated
tozero_one
and callzero_one_loss
from thatfunction:
from..utilsimportdeprecateddefzero_one_loss(y_true,y_pred,normalize=True):# actual implementationpass@deprecated("Function `zero_one` was renamed to `zero_one_loss` in 0.13 and will be ""removed in 0.15. Default behavior is changed from `normalize=False` to ""`normalize=True`")defzero_one(y_true,y_pred,normalize=False):returnzero_one_loss(y_true,y_pred,normalize)
One also needs to movezero_one
fromAPI_REFERENCE
toDEPRECATED_API_REFERENCE
and addzero_one_loss
toAPI_REFERENCE
in thedoc/api_reference.py
file to reflect the changes inAPI Reference.
Deprecating an attribute or a method
If an attribute or a method is to be deprecated, use the decoratordeprecated
on the property. Please note that thedeprecated
decorator should be placed before theproperty
decoratorif there is one, so that the docstrings can be rendered properly. For instance, renamingan attributelabels_
toclasses_
can be done as:
@deprecated("Attribute `labels_` was deprecated in 0.13 and will be removed in 0.15. Use ""`classes_` instead")@propertydeflabels_(self):returnself.classes_
Deprecating a parameter
If a parameter has to be deprecated, aFutureWarning
warning must be raisedmanually. In the following example,k
is deprecated and renamed to n_clusters:
importwarningsdefexample_function(n_clusters=8,k="deprecated"):ifk!="deprecated":warnings.warn("`k` was renamed to `n_clusters` in 0.13 and will be removed in 0.15",FutureWarning,)n_clusters=k
When the change is in a class, we validate and raise warning infit
:
importwarningsclassExampleEstimator(BaseEstimator):def__init__(self,n_clusters=8,k='deprecated'):self.n_clusters=n_clustersself.k=kdeffit(self,X,y):ifself.k!="deprecated":warnings.warn("`k` was renamed to `n_clusters` in 0.13 and will be removed in 0.15.",FutureWarning,)self._n_clusters=self.kelse:self._n_clusters=self.n_clusters
As in these examples, the warning message should always give both theversion in which the deprecation happened and the version in which theold behavior will be removed. If the deprecation happened in version0.x-dev, the message should say deprecation occurred in version 0.x andthe removal will be in 0.(x+2), so that users will have enough time toadapt their code to the new behaviour. For example, if the deprecation happenedin version 0.18-dev, the message should say it happened in version 0.18and the old behavior will be removed in version 0.20.
The warning message should also include a brief explanation of the change and pointusers to an alternative.
In addition, a deprecation note should be added in the docstring, recalling thesame information as the deprecation warning as explained above. Use the..deprecated::
directive:
..deprecated:: 0.13``k`` was renamed to``n_clusters`` in version 0.13 and will be removed in 0.15.
What’s more, a deprecation requires a test which ensures that the warning israised in relevant cases but not in other cases. The warning should be caughtin all other tests (using e.g.,@pytest.mark.filterwarnings
),and there should be no warning in the examples.
Change the default value of a parameter#
If the default value of a parameter needs to be changed, please replace thedefault value with a specific value (e.g.,"warn"
) and raiseFutureWarning
when users are using the default value. The followingexample assumes that the current version is 0.20 and that we change thedefault value ofn_clusters
from 5 (old default for 0.20) to 10(new default for 0.22):
importwarningsdefexample_function(n_clusters="warn"):ifn_clusters=="warn":warnings.warn("The default value of `n_clusters` will change from 5 to 10 in 0.22.",FutureWarning,)n_clusters=5
When the change is in a class, we validate and raise warning infit
:
importwarningsclassExampleEstimator:def__init__(self,n_clusters="warn"):self.n_clusters=n_clustersdeffit(self,X,y):ifself.n_clusters=="warn":warnings.warn("The default value of `n_clusters` will change from 5 to 10 in 0.22.",FutureWarning,)self._n_clusters=5
Similar to deprecations, the warning message should always give both theversion in which the change happened and the version in which the old behaviorwill be removed.
The parameter description in the docstring needs to be updated accordingly by addingaversionchanged
directive with the old and new default value, pointing to theversion when the change will be effective:
..versionchanged:: 0.22 The default value for`n_clusters` will change from 5 to 10 in version 0.22.
Finally, we need a test which ensures that the warning is raised in relevant cases butnot in other cases. The warning should be caught in all other tests(using e.g.,@pytest.mark.filterwarnings
), and there should be no warningin the examples.
Code Review Guidelines#
Reviewing code contributed to the project as PRs is a crucial component ofscikit-learn development. We encourage anyone to start reviewing code of otherdevelopers. The code review process is often highly educational for everybodyinvolved. This is particularly appropriate if it is a feature you would like touse, and so can respond critically about whether the PR meets your needs. Whileeach pull request needs to be signed off by two core developers, you can speedup this process by providing your feedback.
Note
The difference between an objective improvement and a subjective nit isn’talways clear. Reviewers should recall that code review is primarily aboutreducing risk in the project. When reviewing code, one should aim atpreventing situations which may require a bug fix, a deprecation, or aretraction. Regarding docs: typos, grammar issues and disambiguations arebetter addressed immediately.
Important aspects to be covered in any code review#
Here are a few important aspects that need to be covered in any code review,from high-level questions to a more detailed check-list.
Do we want this in the library? Is it likely to be used? Do you, asa scikit-learn user, like the change and intend to use it? Is it inthe scope of scikit-learn? Will the cost of maintaining a newfeature be worth its benefits?
Is the code consistent with the API of scikit-learn? Are publicfunctions/classes/parameters well named and intuitively designed?
Are all public functions/classes and their parameters, return types, andstored attributes named according to scikit-learn conventions and documented clearly?
Is any new functionality described in the user-guide and illustrated with examples?
Is every public function/class tested? Are a reasonable set ofparameters, their values, value types, and combinations tested? Dothe tests validate that the code is correct, i.e. doing what thedocumentation says it does? If the change is a bug-fix, is anon-regression test included? Look atthisto get started with testing in Python.
Do the tests pass in the continuous integration build? Ifappropriate, help the contributor understand why tests failed.
Do the tests cover every line of code (see the coverage report in the buildlog)? If not, are the lines missing coverage good exceptions?
Is the code easy to read and low on redundancy? Should variable names beimproved for clarity or consistency? Should comments be added? Should commentsbe removed as unhelpful or extraneous?
Could the code easily be rewritten to run much more efficiently forrelevant settings?
Is the code backwards compatible with previous versions? (or is adeprecation cycle necessary?)
Will the new code add any dependencies on other libraries? (this isunlikely to be accepted)
Does the documentation render properly (see theDocumentation section for more details), and are the plotsinstructive?
Standard replies for reviewing includes some frequent comments that reviewers may make.
Communication Guidelines#
Reviewing open pull requests (PRs) helps move the project forward. It is agreat way to get familiar with the codebase and should motivate thecontributor to keep involved in the project.[1]
Every PR, good or bad, is an act of generosity. Opening with a positivecomment will help the author feel rewarded, and your subsequent remarks maybe heard more clearly. You may feel good also.
Begin if possible with the large issues, so the author knows they’ve beenunderstood. Resist the temptation to immediately go line by line, or to openwith small pervasive issues.
Do not let perfect be the enemy of the good. If you find yourself makingmany small suggestions that don’t fall into theCode Review Guidelines, considerthe following approaches:
refrain from submitting these;
prefix them as “Nit” so that the contributor knows it’s OK not to address;
follow up in a subsequent PR, out of courtesy, you may want to let theoriginal contributor know.
Do not rush, take the time to make your comments clear and justify yoursuggestions.
You are the face of the project. Bad days occur to everyone, in thatoccasion you deserve a break: try to take your time and stay offline.
Adapted from the numpycommunication guidelines.
Reading the existing code base#
Reading and digesting an existing code base is always a difficult exercisethat takes time and experience to master. Even though we try to write simplecode in general, understanding the code can seem overwhelming at first,given the sheer size of the project. Here is a list of tips that may helpmake this task easier and faster (in no particular order).
Get acquainted with theAPIs of scikit-learn objects: understand whatfit,predict,transform, etc. are used for.
Before diving into reading the code of a function / class, go through thedocstrings first and try to get an idea of what each parameter / attributeis doing. It may also help to stop a minute and thinkhow would I do thismyself if I had to?
The trickiest thing is often to identify which portions of the code arerelevant, and which are not. In scikit-learna lot of input checkingis performed, especially at the beginning of thefit methods.Sometimes, only a very small portion of the code is doing the actual job.For example looking at the
fit
method ofLinearRegression
, what you’re looking formight just be the call thescipy.linalg.lstsq
, but it is buried intomultiple lines of input checking and the handling of different kinds ofparameters.Due to the use ofInheritance,some methods may be implemented in parent classes. All estimators inheritat least from
BaseEstimator
, andfrom aMixin
class (e.g.ClassifierMixin
) that enables defaultbehaviour depending on the nature of the estimator (classifier, regressor,transformer, etc.).Sometimes, reading the tests for a given function will give you an idea ofwhat its intended purpose is. You can use
gitgrep
(see below) to findall the tests written for a function. Most tests for a specificfunction/class are placed under thetests/
folder of the moduleYou’ll often see code looking like this:
out=Parallel(...)(delayed(some_function)(param)forparaminsome_iterable)
. This runssome_function
in parallel usingJoblib.out
is then an iterable containingthe values returned bysome_function
for each call.We useCython to write fast code. Cython code islocated in
.pyx
and.pxd
files. Cython code has a more C-like flavor:we use pointers, perform manual memory allocation, etc. Having some minimalexperience in C / C++ is pretty much mandatory here. For more information seeCython Best Practices, Conventions and Knowledge.Master your tools.
With such a big project, being efficient with your favorite editor orIDE goes a long way towards digesting the code base. Being able to quicklyjump (orpeek) to a function/class/attribute definition helps a lot.So does being able to quickly see where a given name is used in a file.
Git also has some built-in killerfeatures. It is often useful to understand how a file changed over time,using e.g.
gitblame
(manual). This can also be done directlyon GitHub.gitgrep
(examples) is also extremelyuseful to see every occurrence of a pattern (e.g. a function call or avariable) in the code base.
Configure
gitblame
to ignore the commit that migrated the code style toblack
and thenruff
.gitconfigblame.ignoreRevsFile.git-blame-ignore-revs
Find out more information in black’sdocumentation for avoiding ruining git blame.