Как выложить jupiter notebook на github
Перейти к содержимому

Как выложить jupiter notebook на github

  • автор:

Как запустить Jupyter Notebook с GitHub

Jupyter Notebooks становятся стандартом де факто для программирования в области ИИ, машинного обучения и Data Science. Они также очень эффективны в обучении, используя принцип литературного программирования для сочетания в одном документе программного кода и его описания. В этой статье я опишу несколько способов запуска Jupyter Notebooks, как локально на вашем компьютере, так и в облаке.

Ранее, в статье про Azure Notebooks, я описывал как можно удобно запускать код онлайн и делиться кодом с помощью этого инструмента. К сожалению, этот сервис превратился в более профессиональное решение, но необходимость запускать Jupyter Notebooks осталась. Рассмотрим, как же можно запустить Jupyter Notebook.

Просто посмотреть

Если вы просто хотите посмотреть на код в ноутбуке, не запуская его — это очень просто! Если код расположен в репозитории GitHub — просто откройте файл .ipynb , и его содержимое будет показано прямо в браузере.

Можно также использовать nbviewer для просмотра ноутбуков. Для этого нужно будет ввести онлайн имя/репозиторий на GitHub, либо любую URL, доступную через интернет. Вот пример того, как выглядит репозиторий GitHub при открытии в nbviewer.

Ещё одной хорошей опцией будет использовать Visual Studio Code, в которой возможность просмотра ноутбуков встроена “из коробки”. Если Visual Studio Code не установлена — можно использовать онлайн-версию vscode.dev, или github.dev.

GitHub.dev — это отличный способ открыть любой репозиторий в режиме Visual Studio Code для простого редактирования файлов. Для этого достаточно в адресе репозитория заменить github.com на github.dev . Заодно становится доступным просмотр ноутбуков.

Запуск локально или в облаке

В большинстве случае вам захочется не только посмотреть, но и запустить Jupyter notebooks, изменить код и посмотреть, как он работает. В этом случае — читайте дальше!

  • Установить всё необходимое окружение у себя на компьютере
  • Использовать облачные сервисы

В первом случае у вас есть полный контроль над окружением, файлами и вычислительными ресурсами, но придётся потратить некоторое время на установку. Во втором случае, вы будете использовать чьи-то вычислительные ресурсы, и скорее всего количество бесплатных ресурсов, доступных вам, будет ограничено. Зато не потребуется установка ПО, и вы сможете начать работать за считанные минуты.

Локальная установка

Если вы работаете в области ИИ, машинного обучения или Data Science, у вас уже скорее всего установлена среда Python. Иметь Python на своём компьютере — это в любом случае хорошая идея, поскольку велика вероятность, что она вам рано или поздно понадобится.

Проще всего установить Python с помощью дистрибутива Miniconda. Хотя большинство обычно рекомендует ставить Anaconda, которая включает в себя большое количество библиотек, я всегда рекомендую начинать с “голой” установки Python, а все библиотеки устанавливать по мере необходимости. У Miniconda размер первоначального установщика всего 50 Mb, в противовес почти 500 Mb у Anaconda.

Установив Miniconda, будет необходимо установить Jupyter:

conda install -c conda-forge notebook 
pip install notebook 

После установки, перейдите в папку с вашими ноутбуками, и запустите Jupyter:

jupyter notebook 

Откроется окно браузера, и можно начинать работать!

Classical Jupyter Notebook

В некоторых репозиториях GitHub есть файл requirements.txt , содержащий сведения о необходимых для работы проекта библиотеках. В этом случае рекомендуется перед запуском ноутбука установить эти библиотеки командой

pip install -r requirements.txt 

Возможно, вместо классического Jupyter, вы захотите установить JupyterLab, его более продвинутую версию.

pip install juputerlab jupyter-lab 

Jupyter Lab

JupyterLab больше напоминает полноценную среду разработки, позволяя вам, помимо ноутбуков, редактировать скрипты Python, текстовые файлы и многое другое.

Поддержка языков .NET

Jupyter поддерживает много различных языков программирования в дополнение к Python. Если вы хотите использовать C# или F#, вы можете установить .NET Interactive. Установка поддержки .NET для Jupyter описана здесь

Используем Visual Studio Code

Редактировать и исполнять ноутбуки в браузере — не лучшая идея. Намного больше возможностей доступно при использовании Visual Studio Code, в которой есть отличная поддержка Jupyter Notebooks, с возможностью просмотра значений переменных, отладки и т.д. Для выполнения ноутбуков, вам нужно будет установить расширение Python (или расширение .NET, для C#/F#). Вам также понадобится установленное на вашем компьютере Python-окружение, описанное в предыдущем разделе.

Jupyter Notebook in VS Code

Вот ещё немного документации по использованию Jupyter в VS Code.

Установка Python на ваш компьютер — хорошее решение в долгосрочной перспективе, но если вы хотите запустить ноутбук по-быстрому — имеет смысл использовать облачное окружение. Вам не придётся ничего устанавливать на свой компьютер, и вы сможете наслаждаться работой уже через несколько минут. Иногда имеет смысл использовать облачные окружения даже тогда, когда у вас есть Python — например, чтобы избежать конфликта библиотек и запустить ноутбук в “чистом” окружении.

MyBinder

MyBinder.org позволяет вам создать виртуализированное (точнее, контейнеризованное) окружение Jupyter из любого GitHub-репозитория. Вы просто вводите GitHub URL, а Binder создаст контейнер и запустит среду Jupyter. Многие репозитории с ноутбуками даже содержат кнопку Launch Binder, позволяющую вам открыть проект в Binder автоматически.

Binder Welcome Screen

Binder попытается создать окружение, наилучшим образом подходящее для вашего проекта. Например, если в репозитории есть файл requirements.txt с описанием необходимых библиотек, они будут автоматически установлены. Более тонко можно настраивать конфигурацию с помощью файлов в директории binder — вплоть до описания Docker-контейнера, который необходимо собрать для запуска.

GitHub Codespaces

GitHub Codespaces — это новая встроенная в GitHub возможность открывать любой репозиторий в виртуализированном облачном окружении, доступном через среду VS Code в браузере или настольной версии. В настоящий момент Codespaces функционируют в режиме бета-тестирования, предоставляя индивидуальным пользователям некоторый объем бесплатных вычислительных ресурсов.

Codespaces Open Dialog

Datalore, CoCalc и др.

  • JetBrains Datalore предоставляет некоторый объем бесплатных вычислительных ресурсов (в настоящий момент — 120 часов в месяц), а также некоторое количество GPU. Вам придётся предварительно загрузить ваши ноутбуки в рабочую область Datalore.
  • CoCalc — это полноценное окружение для специалистов по Data Science, поддерживающее несколько популярных языков, таких как R, Julia и Sage, систему символьной компьютерной алгебры. Вы также можете запускать ограниченный набор GUI-приложений Linux и редактировать тексты в LaTeX. Я ранее писал про CoCalc в моей заметке про использование систем символьной алгебры для школьников.
  • Про Google Colab вы скорее всего и так уже знаете, поэтому я не буду здесь его подробно описывать.

Заключение

  • Установить Python-окружение на ваш компьютер, и использоват интерфейс Jupyter/JupyterLab в браузере, или Visual Studio Code
  • Запустить в облачной среде онлайн, используя Binder, или одну из описанных выше опций.

У обоих подходов есть свои позитивные и негативные стороны, и я надеюсь, что после прочтения этой заметки вы сможете легко выбрать для себя оптимальный способ запуска Jupyter Notebooks.

Dmitri Soshnikov 2021-09-08 EDUCATION
jupyter notebooks

Sharing using GitHub

GitHub is a development platform where we “can host and review code, manage projects, and build software.” GitHub hosts source code for 75+ million projects including the pandas package we have been using among many others.

1. Go to the GitHub Homepage

To use GitHub one needs to register for a (free) account. To register for a GitHub account we need to:

  1. Open a web browser
  2. Navigate to github.com

We should see the the web page below.

Note: If you already have a GitHub account you do NOT need to create a new one. Please skip down to step 3.

github-homepage-new-user.png

2. To create a GitHub account

  • On the GitHub homepage enter:
    • a username
    • an email address
    • a password

    An example is shown in the screenshot below.

    github-new-user-sign-up.png

    We are asked to confirm the email address that we used to sign. Please confirm the email address.

    Select a plan

    We have to choose a plan that we would like to use. We will use the personal (default) plan.

    Click on Continue.

    github-welcome-step-2.png

    Completing our signup

    We can select any options we would like (on none).

    Click Submit to complete our Github account setup.

    github-welcome-step-3.png

    3. Create a new reprository

    • Click on Start a project as shown below.

    github-dashboard.png

    Create a new repository:

    • Add a repository name. We choose to name our repository sharing-github .
    • Personal GitHub accounts require that projects be public.
    • Check the Initialize this repository with a README option.
    • Click the green Create repository button.

    github-new-repository-sharing-github.png

    After creating the new repository, we will be taken to the project homepage (shown below).

    github-new-repository-homepage.png

    If we click on the GitHub icon at the top of the page, we will go to our GitHub homepage.

    Our GitHub homepage will now show the new repository under Your repositories (as shown below).

    github-new-user-with-repository.png

    Congratulations!! We now have a GitHub account and we have created our first repository.

    4. Uploading an example file (notebook) to the repository

    We will use GitHub’s web interface to upload our files to our new repository.

    Before we upload one of our existing files, we will first create a new notebook with a “print(‘hello world’)” Python statement in a single cell.

    4.1 Create a new sample notebook

    • At the Jupyter dashboard, click on New button and select a Python 3 notebook.
    • In the first cell of the notebok, enter the following Python statement:
     print('hello world') 

    To add our new sample notebook to our GitHub repository, we will return to our repository’s homepage at https://github.com.

    4.2 Upload the new sample notebook to our GitHub repository

    • Go to GitHub in our browser. We can click the link to the left.
    • Click on the sharing-github repository
    • Click on the Upload file button
    • Drag and drop the sample notebook or click the choose your files link to select the sample notebook.
      • We will see any files that we have uploaded at the bottom of the drag and drop area.
      • Type “Adds sample notebook” in the subject field.
      • We can either add the same message below in the extended description or leave it blank.

      After commiting the change we should see that there are now two files in the repository: 1) the README and 2) the new sample notebook (as seen in the screenshot below).

      github-new-file-added.png

      We can actually preview the notebook by clicking on it (shown below). Note that GitHub will automatically render your notebook so that it’s displayed in the browser. This can be a great way to quickly show other people what you’ve been up to!

      github-sharing-notebook-preview.png

      5. Upload our previous working notebook to the repository

      In anticipation of our next lesson on sharing notebooks in a dynamic rather than static way, let’s upload the notebook that we have bene working on. To do this we will repeat many of the steps above.

      Upload our file:

      • Return to sharing-github repository on GitHub
      • Click on the Upload file button
      • Drag and drop the data analysis notebook completed in the previous lesson or click the choose your files link to select the notebook.
        • We will see any files that we have uploaded at the bottom of the drag and drop area.
        • Typing “Added data analysis notebook” in the subject field.
        • We can either add the same message below in the extended description or leave it blank.

        After commiting the change we should see that there are now three files in the repository: 1) the README and 2) the sample notebook and 3) our new data analysis notebook.

        Where to find more about GitHub

        • GitHub Guide — Hello World
        • All the GitHub guides
        • Hubspot git and GitHub tutorial
        • Plurlsight’s GitHub beginner’s guide
        • Code School’s GitHub tutorial

        More about Git version control

        • Try this 15 minute interactive git tutorial
        • Try some additioanl git exercises here

        Key Points

        • GitHub is a development platform where we “can host and review code, manage projects, and build software.
        • A GitHub repository can be created, populated, and shared without command line or other special-purpose version control tools.
        • Jupyter Notebooks shared through GitHub are rendered, but are static. GitHub does not run the notebook(s) in a repository.

        Как залить проект jupiter lab на git hub?

        Я использую Binder с помощью которого открываю Jupyter NoteBook. Все как в мануале сделал — создал репо на гитхабе, сделал публичным, ввел линку на репо в Binder нажал launch и все запустилось. Но беда в том, что даже сохраняя Notebook (arrrow 1) я теряю данные, так как файл .ipynb (файл ноутбука в котором пишу код питона) не уходит в репо гитхаба.
        Кнопки гитхаба и binder (arrow2) не заливают проект на гит хаб, это ссылки на мою репо и на доки Binder.
        Доки я изучал и не нашел решения проблемы своей — правильное использование Юпитера с сохранением текущего прогресса.

        61f550ed0ebc3745804642.jpeg

        • Вопрос задан более года назад
        • 1018 просмотров

        3 комментария

        Простой 3 комментария

        GitHub Version Control for Jupyter Notebooks¶

        To use the version control for Jupyter Notebooks using GitHub, you must perform the following tasks:

        1. Configure Version Control Settings
        2. Configure a GitHub Token
        3. Link Jupyter Notebooks to GitHub

        After configuring the GitHub repository, you can perform the following tasks to manage the notebook versions:

        • Pushing Commits to GitHub
        • Viewing and Comparing the Jupyter Notebook Versions
        • Restoring a Commit from GitHub
        • Creating a Pull Request from Jupyter Notebooks
        • Resolving Conflicts While Using GitHub

        Configuring a GitHub Token¶

        You can configure a GitHub Token for Jupyter notebooks at per user and per account setting level from the My Accounts or JupyterLab interface.

        ../../../../../_images/ConfigGitHubinNote-jupy.png

        • To configure the GitHub token for Jupyter notebooks for your account, see Configuring a GitHub Token .
        • To configure the GitHub token from the Jupyter notebooks, perform the following steps:
          1. Navigate to Notebooks >> Jupyter and open a Jupyter notebook.
          2. From the left sidebar, click on the Github Versions icon as shown in the following figure.
          3. Click Configure now.
          4. In the dialog box add the generated GitHub token and click Save. The GitHub token is now configured for your account.

        Linking Jupyter Notebooks to GitHub¶

        After configuring the GitHub token, you can link the Jupyter notebooks to GitHub.

        1. Obtain the GitHub repository URL.
          1. Navigate to the GitHub profile and click Repositories.
          2. From the list of repositories, click the repository that you want to link.
          3. Copy the URL that is displayed within that repository. Alternatively, you can navigate to the GitHub profile and copy the URL from the browser’s address-bar.

          Note If you want to add HTTPS *.git link as the GitHub repository URL, click Clone or Download. A drop-down text box is displayed. Copy the HTTPS URL or click Use HTTP (if it exists) to copy the HTTP URL.

      • Navigate to Notebooks >> Jupyter and open a Jupyter notebook.
      • From the left sidebar, click on the GitHub Versions icon as shown in the following figure. ../../../../../_images/link-github-jp.png
      • Click the Link Now option.
      • In the Link Notebook to GitHub dialog box, perform the following actions:
        1. Add the GitHub repository URL in the Repository Web URL text field. Ensure that the GitHub profile token has read permissions for the repository to checkout a commit and write permissions for the repository to push a commit.
        2. Select a branch from the Branch drop-down list.
        3. Add an object path file in the Object Path text field.
        4. If you want to strip the outputs from the notebooks before committing to GitHub, select the Strip Output checkbox. A sample is as shown in the following figure. ../../../../../_images/link-github-config-jp.png
        5. Click Save.
      • Pushing Commits to GitHub¶

        After you link notebooks with a GitHub profile, you can start using the notebook to push commits to the GitHub directly from a notebook.

        Steps¶

        1. Open the required Jupyter notebook and save the changes.
        2. From the left sidebar, click on the GitHub Versions icon.
        3. Click the Push icon to commit. A dialog opens to push commits.
        4. Add a commit message and click Save to push the commit to the GitHub repository. You can use the option force commit to force push over the old commit (irrespective of any conflict).

        Qubole does not store commits or revisions of notebooks. However, commits or revisions of notebooks can be fetched from users’ GitHub account whenever required.

        Viewing and Comparing the Jupyter Notebook Versions¶

        You can view a particular version of the Jupyter notebook by using the View option in the GITHUB VERSIONS sidebar as shown below.

        ../../../../../_images/view-in-github.png

        You can compare a version of the Jupyter notebook with the previous version or version with current changes by using the Compare option in the GITHUB VERSIONS sidebar as shown below.

        The Compare icon on top of the left sidebar compares the current notebook with the head of the branch. The Compare hyperlink in the left sidebar compares the given version with the previous version.

        The following image shows a sample comparison of Jupyter notebook versions.

        ../../../../../_images/compare-in-github.png

        Restoring a Commit from GitHub¶

        1. Open the required Jupyter notebook.
        2. From the left sidebar, click on the GitHub Versions icon.
        3. Select a version from the list and click Restore to checkout that version.
        4. Click OK to checkout that version in the confirmation dialog box.

        Qubole does not store commits or revisions of notebooks. However, commits or revisions of notebooks can be fetched from users’ GitHub account whenever required.

        Creating a Pull Request from Jupyter Notebooks¶

        1. Open the required Jupyter notebook.
        2. From the left side bar, click on the GitHub Versions icon.
        3. Click on the Gear icon in the GITHUB VERSIONS pane. The Link Notebook to GitHub dialog is displayed.
        4. Click on the Create PR hyperlink.
        5. Proceed with the steps in GitHub to create the PR. For more information, see GitHub Documentation.

        Resolving Conflicts While Using GitHub¶

        There may be conflicts while pushing/checking out commits in the GitHub versions.

        You can use the option force commit to force push over the old commit (irrespective of any conflict).

        Perform the following steps to resolve conflicts in commits:

        1. Clone the notebook.
        2. Link the cloned notebook to the same GitHub repo branch and path as the original notebook.
        3. Checkout the latest version of the cloned notebook.
        4. Manually port changes from the original notebook to the cloned notebook.
        5. You can commit the cloned notebook after porting changes.

        © Copyright 2021, Qubole.

        Read the Docs v: latest

        Versions latest Downloads html epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *