Accessing Jupyter notebooks programatically
In a previous post we created a simple classifier using Scikit-Learn's LogisticRegression
.
As we pieced together our model, we structured the code into a class called CustomModel
, with two functions: fit
and predict
.
To start working programatically with the notebook created in that post, you will first need to install the ipynb
package:
pip install git+https://github.com/blairhudson/ipynb
(Note: This is actually a fork of an IPython repo. Unfortunately the master has a bug with parsing tuple-based assignments (e.g. X, y = ...
). A pull request has been submitted.)
Now you're ready to go!
Using the ipynb package¶
To simplify things considerably, make sure that you have a copy of the source in the current working directory, and rename it to model.ipynb
.
Now, thanks to the ipynb
package you can access the CustomModel
class like this:
from ipynb.fs.defs.model import CustomModel
To prove it, let's generate predictions on the same sample data:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y,
train_size=0.75,
test_size=0.25,
random_state=1234) # more reproducibility
# load our model
model = CustomModel()
# fit our model
model.fit(X_train, y_train)
# generate some predictions
model.predict(X_test)
Magic ✨