by HuwFulcher · 4y ago · 0 comments
I don’t know whether it’s the Data Science culture or Jupyter but there is a big lack of discipline in writing maintainable code in DS and non-existent git support is part of that.
I always strongly discouraged developing models using notebooks, instead advocating for using .py files and then using notebooks for sanity checking data.
I don’t have any clever ideas for how we can move past Jupyter but the sooner we do the better.
Notebooks can be clean if you follow some rules:
1. Code flow always goes down: holding Option+Enter should execute all fields without any errors. Don't do `x += 1` if `x` is defined underneath.
2. All blocks are idempotent: running any block 5 times should produce the same result as running it 1 time. Don't do `x += 1` unless `x` is defined in that block.
3. Keep block-local variables short and block-global variables long. Don't do `x += 1` unless you are not using `x` anywhere else.
Also, the Table of Contents extension [1] is a life-saver for making long analyses workable.
[1] https://jupyter-contrib-nbextensions.readthedocs.io/en/lates...
It would be nice if there were something that would make out-of-order problems light up, the way that code editors can highlight errors while you're editing. A limitation of "browser as editor" is that it misses out on some of the powerful things that code editors do today.
Another thing is to put things in functions, so temporary variables are disposed of. That's a halfway step to putting things in .py files. A benefit if .py files is not always that jupyter is bad, but that variable scoping is good hygiene.
Personally, I like to label block-global variables in capital case (like PEP8 constants), so as to make them easy to spot. Being formatted like constants also causes me to think twice about altering it after instantiation.
As a table of contents, I usually write some markdown up top with links to markdown HTML anchors elsewhere in the page, which themselves also have a link back to the TOC. Works pretty well. Will have to check out that extension.
4. Use a function in each block, that is defined and the called with appropriate arguments, and return the values of the block. This prevents proliferation of global state - and the functions are really easy to move out to .py modules when things have solidified a bit.
It's not perfect for in-person working because a single person should always keep their work under version control, and they should be able to view meaningful diffs to understand the history.
- I work with several people who are purely data scientists, and I lean on "culture" rather than "Jupyter". In some circles, probably influenced by academia, programming is considered to be low status work. You are not going to solve the problem by switching to .py files, even though for most tasks literally anything is better than Jupyter.
That they don't use git, or that git wasn't originally even a concern, is a consequence of that low-status perception. If you pitched something to the developer community and told them "oh, by the way, you can't use git", they'd synthesize tomatoes out of thin air to throw at you.
- I'd carve an exception for stuff that satisfies ALL of the following: (a) is self-contained in a single notebook, (b) has no dependencies on anything non-standard, (c) is demonstrative in nature, or a personal exercise rather than production software. For example, I wrote my solutions to the Advent of Code problems in a notebook and I liked the experience, especially how you could mix math and code.
I think notebooks are a great way of presenting findings and showing your workings at the same time. If that was their main use then I wouldn’t have any issues
If you want to make the argument about "two kinds of people", I think it's more about A-type/B-type data scientists in the industry. I'm really mostly a developer and not a data scientist, but when I assist in DS tasks I wear a distinct B-type hat, and that informs my perspective. A-type people have different priorities and that's fine; my gripe is when you try to import A-type practices in a B-type scenario.
It was easy to use as a presentation, with figures and plots embedded. With controls enabled, you could demonstrate what varying certain parameters would do and pitch proposed cleaning profiles.
I was rather easily able to send a directory and it's notebooks/data sources to colleagues in the water sciences team so they could validate my results on their own (they were luckily also familiar with Python and Jupyter), and caught some minor bugs in the pipeline.
This was all much more collaborative and concise, and I feel Jupyter played a huge part in it.
Once it was done, it and a "final draft" pdf were added to the Docs in the repo and the pipeline was written out into a full application of it's own.
Add in # %% and it makes the code executable in isolation. Like a cell in jupyter. This means i can write a py file. Execute bits indepentantly and when im ready to check it in just remove the block comments
Once you have a consistent set of questions, and methods to answer them, then yes, copy off the relevant chunks into their own scripts and source these when using similar data to bring you up to speed, and modify them to your tastes.
The issue with starting off with an external script initially is the distracting temptation to refine your code so it can be better used with future data, despite not yet having seen or not knowing what that future data is like. The initial "play and explore" phase of an analysis is very important imo, and notebooks really facilitate that.
one of the key things that a good notebook system must allow you to do is to mix something like markup format + LaTeX + source code. writing math-heavy documentation and explanations is simply impractical and limited (readability suffers) if done in comments. jupyter however is severely limited as it is unreadable in its raw format and therefore does not play well with a version control system such as git
instead there is a solution that allows one to do everything jupyter does good with the additional benefit that it plays with version control really well - ie org-mode [1]. the only difference is that instead of using a browser to interact with it, you use emacs. the added benefit to this is that you can also use full-featured key bindings (emacs / vim) and even integrate a language server for auto-completion [2]
EDIT: moreover the list of supported languages in orgmode far exceeds that of jupyter [3] (or did the last time i made this comparison)
[2] https://emacs-lsp.github.io/lsp-mode/manual-language-docs/ls...
[3] https://orgmode.org/worg/org-contrib/babel/languages/index.h...
If org-mode wasn't backed by Emacs, it would merely be a markdown substitute hence much less useful. There are many org-mode clones for modern editors like neovim or VSCode, except all they offer is front-end features (highlighting, folding, node manipulation etc). There is simply no reason to use those over a decent markdown editor. So I think you have this backwards; Emacs isn't holding back org-mode, rather much of advanced org-mode features are made possible and distinguished by the fact that it builds on Emacs.
Configurability is a strength of a system, but it is no an answer to a difficult learning curve. A user must first understand the system in order to configure it appropriately.
Even at the level of key bindings, the user needs to understand the relative frequency and importance of an operation to choose an appropriate key combination. Universal reconfiguration may even make the system less learnable, if documentation and tutorials can't assume a reasonable default configuration.
In my opinion, configuration is great as one of the final steps of a user's journey, taking the system from something that works to something that sings. It's just the wrong level to sell benefits to beginners.
also the ecosystem is huge and chances are that the configuration you are after is just a package-install away
i'm sorry to burst your strong held convictions but you can choose any of the following
a) use any key-bindings you like including emacs, vim, cua, or combination of
b) use org-mode without any knowledge of more advanced emacs commands (except basic knowledge of using an editor)
c) drink some milk (gotta have strong bones) and learn how to use the emacs system including emacs lisp and have one of the most advanced computing environments in existence at your service
sorry, but that is just the reality
The latter needs to accept that most users, particularly scientists, reject out-of-hand anything requiring configuration or compilation no matter how trivial.
But it's all moot since org-mode is largely promoted by non-scientists (computer science is not a science), and should a wysiwig-inclined scientist ever get past the emacs obstacle, he'll balk at the awkward BEGIN_SRC incantations.
If that were easy, then that other editor would be an emacs. There's a reason emacs gets all these modes, and its because writing extensions is easy. If I want to extend something like VScode or Pycharm, or whatever, it is a massive undertaking.
We get it - what makes you think we don't. We are merely pointing out a superior solution.
Like back in 2004 I would tell people how many of their problems would be resolved if they switched to Linux. Fast forward two decades later, the statement is still true, and most people still don't use Linux. But it wasn't a problematic thing to point it out to them - be it in 2004 or now.
(It's a lot easier to use Emacs than switch to Linux.)
I guess you meant literate programming.
Literate programming is different from interleaving console inputs and outputs and random paragraphs in the same document.
Even if we expand the original idea to comprise that, literate programming is much more than that.
How many python packages are written in literate programming style?
How many programs written as notebooks would be actually better if they were structured differently?
The Jupyter allow you to load big chunk of data or some large model only once, and then use it for experiments in other cells. It is hard to replace this feature with plain `*.py` file. For me, this is the killer feature.
Personally, I start every notebook with
%load_ext autoreload
%autoreload 2
then develop production quality code in .py files.That way, if you put your classifiers in joblib pipelines, once you're done with fitting steps you can just export your trained classifier with:
joblib.dump(pipe, "trained_classifier.dump")
And resume your work with: joblib.load("trained_classifier.dump")
Considering this works for any Python object, a lot of heavy lifting can be exported for later (swift) use this way.One of the main differences for me is that the .py file is run in its entirety (outside of if/else blocks for loading data). That usually corresponds to multiple cells of a Jupyter notebook that one would need to Ctrl+Enter through, where missing one would cause a problem.
The second is just how you can decouple the code and the terminal - it's a personal pet peeve that Jupyter notebooks jump around when running through cells - I don't want to be scrolling all around just to reset some variables to their original values, and it's really nice to run a whole .py script and see an output side by side, where the script is much longer than my screen. I can keep it open at the important part in VSCode, and change some intermediate process, and let all of the ad hoc plotting code remain at the bottom.
Finally, the biggest difference for me is how figures behave - the way I have it set up is that they open in their own window and remain interactive (can zoom/pan). I know you can do it in Jupyter as well, but the workflow really emphasizes inline plotting with non-interactive plots, especially when it comes to sharing them. But with the .py script and IPython command line, I can open up 5 figures, tile them however I'd like, and then refer to them by name/number in my script, so I can clear and overwrite them however I'd like, and they don't close or move around. This makes comparing things very easy, like how changing a parameter changes the rest of my analysis.
Lastly - the way it is set up is more like Matlab... whoops, but I think their workflow is much more ergonomic than a notebook. However, for sharing with other people, I usually just copy and paste the various parts of my scripts into a notebook, as that is the de facto standard.
1. Experiments in notebooks. Notebooks are saved under git but mostly as a backup, I don't care how nicely they play together. I don't get why you would discourage notebooks for running experiments, doing it with .py files sounds kind of miserable.
2. Services and library code in .py files, under version control, just like any other software we write.
Having your services and library code as .py files you can import in is great.
The issue comes with how to move from experimentation to deployment. If you already have services/library code as .py files you make your life a lot easier. The issue comes when everything is spread across multiple, poorly documented notebooks. If you're working with an MLOps team it makes their life a nightmare to take those notebooks and conform them into something usable.
Jupyter is great when it is used in the right way.
People use a great tool in a poor way and then broadly condemn the tool.
And any tool that is sufficiently flexible to be broadly useful can be used in very poor ways.
Jupyter is great, it gets me over the barrier potential for starting a task every time. I build and prove out an algorithm/task piece by piece. Once I'm happy, I move the meat of it to a function in a .py file, and move the code I used to test the algorithm to a unit test function. Delete the duplicated bits and replace with imports, and then what remains is a tutorial/demonstrator notebook using the function I wrote and maybe some nice plots to go along with that, that I wouldn't put in a unit test (nor that show up in docstrings). This can be converted to sphinx docs if the code gets big enough.
What a great tool for incrementally building software! In my world, I build brick by brick, not all at once. Jupyter is a key to that process.
While most programmers have reached this conclusion, they're generally not day-in day-out jupyter users. They need to understand *everything* is transient for scientists who optimize for proof-of-concept and publish-and-forget-it paper writing.
Which itself is a huge problem.
Happily this mindset is changing, at least in some scientific all fields. For example, in particle physics proposals a document ("data management plan") much be written describing how that unconscionable attitude will not be taken with the experiment's data and software. That said, this transient mindset and derision of real software skills is still fairly prevalent in this field.
More "nature of the beast" in my opinion. Science measures itself by how many alluring women it can date; engineering, by how long it can keep the wife happy.
Even for short-lived experiments reproducibility is important. So much of today's experiments ultimately rely on complex stacks of software to get their results and on data which humans can afford to acquire only once. Preserving both is necessary for future re-validation or reuse.
This problem should not be excused.
Partially the lack of discipline comes from the implicit data dependancies between cells. Variables are all globally scoped and unless you ensure the notebook can be ran top to bottom its easy to introduce subtle bugs. I believe Julia's https://github.com/fonsp/Pluto.jl solves this issue quite well.
Another part comes from cells that should really be functions. In my opinion this is because functions are 2nd class citizens compared to cells, and could be improved with UI (function cells? node based programming?).
Programming is more than just manipulating text, so why shouldn't tools move in a direction of just being fancy text editors?
I also use it a lot for experimenting, parameter tuning etc. It's not too bad to have it explicitly distinct from production level code. Run/tune/experiment in notebook, once you're happy with the model -> code it up in .py file(s). Also great for quick presentations :)
However, the fast.ai team is actually doing a pretty solid job running everything off notebooks. So if I wanted to go that direction (and skip the .py files) it's that project I'd look at for how to do it.
Do you mean you _don't_ want to give the students shell access?
By default you can run shell commands from within a Jupyter notebook be prefixing them with `!`.
and if it's just the professor's lab, just a jupyter lab instance with one password works too.
In line with a nephew comment of mine, I feel that bringing the immediate interactivity or iteration cycle of notebooks to the development experience would help a lot, and not be too bad a thing for common development either.
I've heard of the related nbdev project, which seems like an interesting and compelling idea. But it'd be nice to see the reverse: something that makes ordinary python development more immediate than using a debugger/vanilla REPL.
Once this approach is found, a good clean-up/refactor is strongly recommended, to then start a proper software development that will create a live product from the found approach. I call this the switch between research mode and development mode, and it has strong parallels to the way R&D is done in many industries. I believe a lack of understanding of this dual nature of ML is what causes many of the problems in MLOps: plans that don't take into account the research time and risk, mixed teams where engineers don't understand the initial nature of DS work, attempts to put notebooks containing research code in production, etc. Even planning for the refactor doesn't solve it all - what will happen when the next generation of a model has to be created? Will the refactor Ed code be forced on the DS and ruin their research productivity? Will they start from scratch again and not only lose all the refactor/dev cost but also make this a recurring cost? I have been looking for answers for this for years now, and found none so far.
Source: I've been working with data for 27 years, as a data engineer, data architect and data scientist. When I do DE, my code is considered high quality by my peers, but when I'm doing DS research, I know I write bad code - and I won't change that. It's more productive to work this way and do the big refactor (possibly leaving the notebook env behind along the way) than the alternative.
When you get into MLOps as well, having .py templates actually makes the Data Scientist’s job easier as they can plug and play their models into a system that tracks inputs, outputs and changes for them
And then serve the results as a static page under my.logs.intranet/my-job/2022-02-14/my_recurring_task_notebook.ipynb.html
You can get so much more context regarding what went well or wrong compared to browsing through log lines in some more or less user friendly tool.
From the beginning of the article: "With nbdev2, the Jupyter+git problem has been totally solved. It provides a set of hooks which provide clean git diffs, solve most git conflicts automatically, and ensure that any remaining conflicts can be resolved entirely within the standard Jupyter notebook environment."
Notebooks never caught on with me.
It makes notebooks testable, composable, versionable, and more.
"we" have to learn and teach the next sets of people new to computer science