One place for hosting & domains

      Jupyter

      How To Set Up a Jupyter Notebook with Python 3 on Debian 10


      Introduction

      Jupyter Notebook offers a command shell for interactive computing as a web application so that you can share and communicate with code. The tool can be used with several languages, including Python, Julia, R, Haskell, and Ruby. It is often used for working with data, statistical modeling, and machine learning.

      This tutorial will walk you through setting up Jupyter Notebook to run from a Debian 10 server, as well as teach you how to connect to and use the Notebook. Jupyter Notebooks (or just “Notebooks”) are documents produced by the Jupyter Notebook app which contain both computer code and rich text elements (paragraph, equations, figures, links, etc.) which aid in presenting and sharing reproducible research.

      By the end of this guide, you will be able to run Python 3 code using Jupyter Notebook running on a remote Debian 10 server.

      Prerequisites

      In order to complete this guide, you should have a fresh Debian 10 server instance with a basic firewall and a non-root user with sudo privileges configured. You can learn how to set this up by running through our Initial Server Setup with Debian 10 guide.

      Step 1 — Install Pip and Python Headers

      To begin the process, we’ll download and install all of the items we need from the Debian repositories. We will use the Python package manager pip to install additional components a bit later.

      We first need to update the local apt package index and then download and install the packages:

      Next, install pip and the Python header files, which are used by some of Jupyter’s dependencies:

      • sudo apt install python3-pip python3-dev

      Debian 10 (“Buster”) comes preinstalled with Python 3.7.

      We can now move on to setting up a Python virtual environment into which we’ll install Jupyter.

      Step 2 — Create a Python Virtual Environment for Jupyter

      Now that we have Python 3, its header files, and pip ready to go, we can create a Python virtual environment for easier management. We will install Jupyter into this virtual environment.

      To do this, we first need access to the virtualenv command. We can install this with pip.

      Upgrade pip and install the package by typing:

      • sudo -H pip3 install --upgrade pip
      • sudo -H pip3 install virtualenv

      With virtualenv installed, we can start forming our environment. Create and move into a directory where we can keep our project files:

      • mkdir ~/myprojectdir
      • cd ~/myprojectdir

      Within the project directory, create a Python virtual environment by typing:

      This will create a directory called myprojectenv within your myprojectdir directory. Inside, it will install a local version of Python and a local version of pip. We can use this to install and configure an isolated Python environment for Jupyter.

      Before we install Jupyter, we need to activate the virtual environment. You can do that by typing:

      • source myprojectenv/bin/activate

      Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this: (myprojectenv)user@host:~/myprojectdir$.

      You’re now ready to install Jupyter into this virtual environment.

      Step 3 — Install Jupyter

      With your virtual environment active, install Jupyter with the local instance of pip:

      Note: When the virtual environment is activated (when your prompt has (myprojectenv) preceding it), use pip instead of pip3, even if you are using Python 3. The virtual environment’s copy of the tool is always named pip, regardless of the Python version.

      At this point, you’ve successfully installed all the software needed to run Jupyter. We can now start the Notebook server.

      Step 4 — Run Jupyter Notebook

      You now have everything you need to run Jupyter Notebook! To run it, execute the following command:

      A log of the activities of the Jupyter Notebook will be printed to the terminal. When you run Jupyter Notebook, it runs on a specific port number. The first Notebook you run will usually use port 8888. To check the specific port number Jupyter Notebook is running on, refer to the output of the command used to start it:

      Output

      [I 21:23:21.198 NotebookApp] Writing notebook server cookie secret to /run/user/1001/jupyter/notebook_cookie_secret [I 21:23:21.361 NotebookApp] Serving notebooks from local directory: /home/sammy/myprojectdir [I 21:23:21.361 NotebookApp] The Jupyter Notebook is running at: [I 21:23:21.361 NotebookApp] http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72 [I 21:23:21.361 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [W 21:23:21.361 NotebookApp] No web browser found: could not locate runnable browser. [C 21:23:21.361 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72

      If you are running Jupyter Notebook on a local Debian computer (not on a Droplet), you can simply navigate to the displayed URL to connect to Jupyter Notebook. If you are running Jupyter Notebook on a Droplet, you will need to connect to the server using SSH tunneling as outlined in the next section.

      At this point, you can keep the SSH connection open and keep Jupyter Notebook running or can exit the app and re-run it once you set up SSH tunneling. Let’s keep it simple and stop the Jupyter Notebook process. We will run it again once we have SSH tunneling working. To stop the Jupyter Notebook process, press CTRL+C, type Y, and hit ENTER to confirm. The following will be displayed:

      Output

      [C 21:28:28.512 NotebookApp] Shutdown confirmed [I 21:28:28.512 NotebookApp] Shutting down 0 kernels

      We’ll now set up an SSH tunnel so that we can access the Notebook.

      Step 5 — Connect to the Server Using SSH Tunneling

      In this section we will learn how to connect to the Jupyter Notebook web interface using SSH tunneling. Since Jupyter Notebook will run on a specific port on the server (such as :8888, :8889 etc.), SSH tunneling enables you to connect to the server’s port securely.

      The next two subsections describe how to create an SSH tunnel from 1) a Mac or Linux and 2) Windows. Please refer to the subsection for your local computer.

      SSH Tunneling with a Mac or Linux

      If you are using a Mac or Linux, the steps for creating an SSH tunnel are similar to using SSH to log in to your remote server, except that there are additional parameters in the ssh command. This subsection will outline the additional parameters needed in the ssh command to tunnel successfully.

      SSH tunneling can be done by running the following SSH command in a new local terminal window:

      • ssh -L 8888:localhost:8888 your_server_username@your_server_ip

      The ssh command opens an SSH connection, but -L specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side (server). This means that whatever is running on the second port number (e.g. 8888) on the server will appear on the first port number (e.g. 8888) on your local computer.

      Optionally change port 8888 to one of your choosing to avoid using a port already in use by another process.

      server_username is your username (e.g. sammy) on the server which you created and your_server_ip is the IP address of your server.

      For example, for the username sammy and the server address 203.0.113.0, the command would be:

      • ssh -L 8888:localhost:8888 sammy@203.0.113.0

      If no error shows up after running the ssh -L command, you can move into your programming environment and run Jupyter Notebook:

      You’ll receive output with a URL. From a web browser on your local machine, open the Jupyter Notebook web interface with the URL that starts with http://localhost:8888. Ensure that the token number is included, or enter the token number string when prompted at http://localhost:8888.

      SSH Tunneling with Windows and Putty

      If you are using Windows, you can create an SSH tunnel using Putty.

      First, enter the server URL or IP address as the hostname as shown:

      Set Hostname for SSH Tunnel

      Next, click SSH on the bottom of the left pane to expand the menu, and then click Tunnels. Enter the local port number to use to access Jupyter on your local machine. Choose 8000 or greater to avoid ports used by other services, and set the destination as localhost:8888 where :8888 is the number of the port that Jupyter Notebook is running on.

      Now click the Add button, and the ports should appear in the Forwarded ports list:

      Forwarded ports list

      Finally, click the Open button to connect to the server via SSH and tunnel the desired ports. Navigate to http://localhost:8000 (or whatever port you chose) in a web browser to connect to Jupyter Notebook running on the server. Ensure that the token number is included, or enter the token number string when prompted at http://localhost:8000.

      Step 6 — Using Jupyter Notebook

      This section goes over the basics of using Jupyter Notebook. If you don’t currently have Jupyter Notebook running, start it with the jupyter notebook command.

      You should now be connected to it using a web browser. Jupyter Notebook is a very powerful tool with many features. This section will outline a few of the basic features to get you started using the Notebook. Jupyter Notebook will show all of the files and folders in the directory it is run from, so when you’re working on a project make sure to start it from the project directory.

      To create a new Notebook file, select New > Python 3 from the top right pull-down menu:

      Create a new Python 3 notebook

      This will open a Notebook. We can now run Python code in the cell or change the cell to markdown. For example, change the first cell to accept Markdown by clicking Cell > Cell Type > Markdown from the top navigation bar. We can now write notes using Markdown and even include equations written in LaTeX by putting them between the $$ symbols. For example, type the following into the cell after changing it to markdown:

      # First Equation
      
      Let us now implement the following equation:
      $$ y = x^2$$
      
      where $x = 2$
      

      To turn the markdown into rich text, press CTRL+ENTER, and the following should be the results:

      results of markdown

      You can use the markdown cells to make notes and document your code. Let’s implement that equation and print the result. Click on the top cell, then press ALT+ENTER to add a cell below it. Enter the following code in the new cell.

      x = 2
      y = x**2
      print(y)
      

      To run the code, press CTRL+ENTER. You’ll receive the following results:

      first equation results

      You now have the ability to import modules and use the Notebook as you would with any other Python development environment!

      Conclusion

      At this point, you should be able to write reproducible Python code and notes in Markdown using Jupyter Notebook. To get a quick tour of Jupyter Notebook from within the interface, select Help > User Interface Tour from the top navigation menu to learn more.

      From here, you can begin a data analysis and visualization project by reading Data Analysis and Visualization with pandas and Jupyter Notebook in Python 3.



      Source link

      Como Configurar o Jupyter Notebook com Python 3 no Ubuntu 18.04


      Introdução

      O Jupyter Notebook é uma aplicação web open-source que lhe permite criar e compartilhar código interativo, visualizações e muito mais. Esta ferramenta pode ser usada com várias linguagens de programação, incluindo Python, Julia, R, Haskell e Ruby. Ele é frequentemente usado para trabalhar com dados, modelagem estatística e aprendizado de máquina.

      Este tutorial irá orientá-lo na configuração do Jupyter Notebook para ser executado em um servidor Ubuntu 18.04, além de ensinar como se conectar e usar o notebook. Jupyter Notebooks (ou simplesmente Notebooks) são documentos produzidos pelo aplicativo Jupyter Notebook, que contém tanto código de computador quanto elementos de rich text (parágrafos, equações, figuras, links, etc.) que ajudam a apresentar e compartilhar pesquisas reproduzíveis.

      Ao final deste guia, você será capaz de executar código Python 3 usando o Jupyter Notebook em execução em um servidor remoto.

      Pré-requisitos

      Para completar este guia, você deve ter uma nova instância de servidor Ubuntu 18.04, configurado com um firewall básico e um usuário não-root com privilégios sudo. Você pode aprender como configurar isso através de nosso tutorial de configuração inicial de servidor.

      Passo 1 — Configurar o Python

      Para começar o processo, vamos instalar as dependências que precisamos para o nosso ambiente de programação Python a partir dos repositórios do Ubuntu. O Ubuntu 18.04 vem pré-instalado com o Python 3.6. Vamos utilizar o gerenciador de pacotes Python, pip, para instalar componentes adicionais um pouco mais tarde.

      Primeiro precisamos atualizar o índice local de pacotes do apt e depois baixar e instalar os pacotes:

      Em seguida, instale o pip e os arquivos de cabeçalho do Python, que são utilizados por algumas das dependências do Jupyter:

      • sudo apt install python3-pip python3-dev

      Podemos passar agora a configurar um ambiente virtual Python no qual instalaremos o Jupyter.

      Passo 2 — Criar um Ambiente Virtual do Python para o Jupyter

      Agora que temos o Python 3, seus arquivos de cabeçalho e o pip pronto para usar, podemos criar um ambiente virtual Python para gerenciar nossos projetos. Vamos instalar o Jupyter neste ambiente virtual.

      Para fazer isso, primeiro precisamos acessar o comando virtualenv, que podemos instalar com o pip.

      Atualize o pip e instale o pacote digitando:

      • sudo -H pip3 install --upgrade pip
      • sudo -H pip3 install virtualenv

      A flag -H garante que a política de segurança configure a variável de ambiente home para o diretório home do usuário de destino.

      Com o virtualenv instalado, podemos começar a formar nosso ambiente. Crie e mova-se para um diretório onde possamos manter nossos arquivos de projeto. Chamaremos o nosso de meu_projeto, mas você pode usar um nome que seja significativo para você e no qual você esteja trabalhando.

      • mkdir ~/meu_projeto
      • cd ~/meu_projeto

      Dentro do diretório do projeto, criaremos um ambiente virtual do Python. Para o propósito deste tutorial, vamos chamá-lo de meu_projeto_env, mas você pode chamá-lo de algo que seja relevante para o seu projeto.

      • virtualenv meu_projeto_env

      Isso irá criar um diretório chamado meu_projeto_env dentro do diretório meu_projeto. Dentro, ele instalará uma versão local do Python e uma versão local do pip. Podemos usar isso para instalar e configurar um ambiente Python isolado para o Jupyter.

      Antes de instalarmos o Jupyter, precisamos ativar o ambiente virtual. Você pode fazer isso digitando:

      • source meu_projeto_env/bin/activate

      Seu prompt deve mudar para indicar que você agora está operando dentro de um ambiente virtual do Python. Vai parecer algo assim: (meu_projeto_env)usuário@host:~/meu_projeto$.

      Agora você está pronto para instalar o Jupyter nesse ambiente virtual.

      Passo 3 — Instalar o Jupyter

      Com o seu ambiente virtual ativo, instale o Jupyter com a instância local do pip.

      Nota: Quando o ambiente virtual está ativado (quando o seu prompt tem (meu_projeto_env) precedendo-o), usepip em vez de pip3, mesmo se você estiver usando o Python 3. A cópia do ambiente virtual da ferramenta é sempre denominada pip, independentemente da versão do Python.

      Neste ponto, você instalou com sucesso todo o software necessário para executar o Jupyter. Agora podemos iniciar o servidor do Notebook.

      Passo 4 — Executar o Jupyter Notebook

      Agora você tem tudo o que precisa para rodar o Jupyter Notebook! Para executá-lo, execute o seguinte comando:

      Um registro das atividades do Jupyter Notebook será impresso no terminal. Quando você executa o Jupyter Notebook, ele é executado em um número de porta específico. O primeiro Notebook que você executa geralmente usa a porta 8888. Para verificar o número de porta específico em que o Jupyter Notebook está sendo executado, consulte a saída do comando usado para iniciá-lo:

      Output

      [I 21:23:21.198 NotebookApp] Writing notebook server cookie secret to /run/user/1001/jupyter/notebook_cookie_secret [I 21:23:21.361 NotebookApp] Serving notebooks from local directory: /home/sammy/meu_projeto [I 21:23:21.361 NotebookApp] The Jupyter Notebook is running at: [I 21:23:21.361 NotebookApp] http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72 [I 21:23:21.361 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [W 21:23:21.361 NotebookApp] No web browser found: could not locate runnable browser. [C 21:23:21.361 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72

      Se você estiver executando o Jupyter Notebook em um computador local (não em um servidor), poderá navegar até a URL exibida para se conectar ao Jupyter Notebook. Se você estiver executando o Jupyter Notebook em um servidor, será necessário conectar-se ao servidor usando o tunelamento SSH, conforme descrito na próxima seção.

      Neste ponto, você pode manter a conexão SSH aberta e manter o Jupyter Notebook em execução ou sair do aplicativo e executá-lo novamente assim que configurar o tunelamento SSH. Vamos escolher parar o processo do Jupyter Notebook. Vamos executá-lo novamente assim que tivermos o tunelamento SSH configurado. Para parar o processo do Jupyter Notebook, pressione CTRL+C, digite Y e, em seguida, ENTER para confirmar. A seguinte saída será mostrada:

      Output

      [C 21:28:28.512 NotebookApp] Shutdown confirmed [I 21:28:28.512 NotebookApp] Shutting down 0 kernels

      Agora, vamos configurar um túnel SSH para que possamos acessar o Notebook.

      Passo 5 - Conectar ao Servidor Usando o Tunelamento SSH

      Nesta seção, aprenderemos como conectar-se à interface web do Jupyter Notebook usando o tunelamento SSH. Como o Jupyter Notebook será executado em uma porta específica no servidor (tais como :8888, :8889 etc.), o tunelamento SSH permite que você se conecte à porta do servidor com segurança.

      As próximas duas subseções descrevem como criar um túnel SSH a partir de 1) um Mac ou Linux e 2) Windows. Por favor, consulte a subseção para o seu computador local.

      Tunelamento SSH com um Mac ou Linux

      Se você estiver usando um Mac ou Linux, as etapas para criar um túnel SSH são semelhantes ao uso do SSH para efetuar login no seu servidor remoto, exceto que existem parâmetros adicionais no comando ssh. Esta subseção descreverá os parâmetros adicionais necessários no comando ssh para fazer um túnel com sucesso.

      O tunelamento SSH pode ser feito executando o seguinte comando SSH em uma nova janela de terminal local:

      • ssh -L 8888:localhost:8888 usuário_do_servidor@ip_do_seu_servidor

      O comando ssh abre uma conexão SSH, mas -L especifica que a porta no host local (cliente) deve ser encaminhada para o host e porta no lado remoto (servidor). Isso significa que, o que quer que esteja rodando no segundo número de porta (ex: 8888) no servidor aparecerá no primeiro número de porta (ex: 8888) em seu computador local.

      Opcionalmente, altere a porta 8888 para uma de sua escolha, para evitar o uso de uma porta que já esteja em uso por outro processo.

      usuário_do_servidor é o seu usuário (ex: sammy) no servidor que você criou, e ip_do_seu_servidor é o endereço IP do seu servidor.

      Por exemplo, para o usuário sammy e o endereço de servidor 203.0.113.0, o comando seria:

      • ssh -L 8888:localhost:8888 sammy@203.0.113.0

      Se nenhum erro aparecer depois de executar o comando ssh -L, você pode entrar em seu ambiente de programação e executar o Jupyter Notebook:

      Você receberá uma saída com uma URL. Em um navegador web em sua máquina local, abra a interface web do Jupyter Notebook com a URL que começa com http://localhost:8888. Assegure-se de que o número do token esteja incluído ou insira a string do número do token quando solicitado em http://localhost:8888.

      Tunelamento SSH com Windows e Putty

      Se você estiver usando o Windows, poderá criar um túnel SSH usando o Putty.

      Primeiro, insira a URL do servidor ou o endereço IP como o nome do host, como mostrado:

      Em seguida, clique em SSH na parte inferior do painel esquerdo para expandir o menu e, em seguida, clique em Tunnels. Digite o número da porta local que você deseja usar para acessar o Jupyter em sua máquina local. Escolha 8000 ou superior para evitar portas usadas por outros serviços, e defina o destino como localhost:8888 onde :8888 é o número da porta na qual o Jupyter Notebook está sendo executado.

      Agora, clique no botão Add, e as portas deverão aparecer na lista Forwarded ports

      Por fim, clique no botão Open para conectar-se ao servidor via SSH e tunelar as portas desejadas. Navegue até http://localhost:8000 (ou qualquer porta que você escolheu) em um navegador da web para se conectar ao Jupyter Notebook em execução no servidor. Assegure-se de que o número do token esteja incluído ou insira a string do número do token quando solicitado em http://localhost:8000.

      Passo 6 — Usando o Jupyter Notebook

      Esta seção aborda os conceitos básicos do uso do Jupyter Notebook. Se você ainda não tem o Jupyter Notebook em execução, inicie-o com o comando jupyter notebook.

      Agora você deve estar conectado a ele usando um navegador web. O Jupyter Notebook é uma ferramenta muito poderosa com muitos recursos. Esta seção descreverá alguns dos recursos básicos para você começar a usar o Notebook. O Jupyter Notebook mostrará todos os arquivos e pastas no diretório a partir do qual ele é executado. Portanto, quando você estiver trabalhando em um projeto, certifique-se de iniciá-lo no diretório do projeto.

      Para criar um novo arquivo do Notebook, selecione New > Python 3 no menu suspenso superior direito:

      Isso irá abrir um Notebook. Agora podemos executar o código Python na célula ou alterar a célula para markdown. Por exemplo, altere a primeira célula para aceitar Markdown clicando em Cell > Cell Type > Markdown na barra de navegação superior. Agora podemos escrever notas usando Markdown e até incluir equações escritas em LaTeX colocando-as entre os símbolos $$. Por exemplo, digite o seguinte na célula depois de alterá-la para markdown:

      # Primeira Equação
      
      Vamos agora implementar a seguinte equação:
      $$ y = x^2$$
      
      Onde $x = 2$
      

      Para transformar o markdown em rich text, pressione CTRL+ENTER, e o resultado deve ser o seguinte:

      Você pode usar as células markdown para fazer anotações e documentar seu código. Vamos implementar essa equação e imprimir o resultado. Clique na célula superior e pressione ALT+ENTER para adicionar uma célula abaixo dela. Digite o seguinte código na nova célula.

      x = 2
      y = x**2
      print(y)
      

      Para executar o código, pressione CTRL+ENTER. Você receberá os seguintes resultados:

      Agora você tem a capacidade de importar modulos e usar o Notebook como você faria com qualquer outro ambiente de desenvolvimento Python!

      Conclusão

      Parabéns! Agora você deve ser capaz de escrever códigos reproduzíveis em Python e notas no Markdown usando o Jupyter Notebook. Para obter um tour rápido pelo Jupyter Notebook dentro da interface, selecione Help > User Interface Tour no menu de navegação superior para saber mais.

      A partir daqui, você pode iniciar um projeto de análise e visualização de dados lendo Data Analysis and Visualization with pandas and Jupyter Notebook in Python 3.

      Se você tem interesse em pesquisar mais, leia nossa série sobre Visualização e Previsão de Séries Temporais.

      Por Lisa Tagliaferri



      Source link

      How To Set Up Jupyter Notebook with Python 3 on Ubuntu 18.04


      Introduction

      An open-source web application, Jupyter Notebook lets you create and share interactive code, visualizations, and more. This tool can be used with several programming languages, including Python, Julia, R, Haskell, and Ruby. It is often used for working with data, statistical modeling, and machine learning.

      This tutorial will walk you through setting up Jupyter Notebook to run from an Ubuntu 18.04 server, as well as teach you how to connect to and use the notebook. Jupyter Notebooks (or simply Notebooks) are documents produced by the Jupyter Notebook app which contain both computer code and rich text elements (paragraph, equations, figures, links, etc.) which aid in presenting and sharing reproducible research.

      By the end of this guide, you will be able to run Python 3 code using Jupyter Notebook running on a remote server.

      Prerequisites

      In order to complete this guide, you should have a fresh Ubuntu 18.04 server instance with a basic firewall and a non-root user with sudo privileges configured. You can learn how to set this up by running through our initial server setup tutorial.

      Step 1 — Set Up Python

      To begin the process, we’ll install the dependencies we need for our Python programming environment from the Ubuntu repositories. Ubuntu 18.04 comes preinstalled with Python 3.6. We will use the Python package manager pip to install additional components a bit later.

      We first need to update the local apt package index and then download and install the packages:

      Next, install pip and the Python header files, which are used by some of Jupyter’s dependencies:

      • sudo apt install python3-pip python3-dev

      We can now move on to setting up a Python virtual environment into which we’ll install Jupyter.

      Step 2 — Create a Python Virtual Environment for Jupyter

      Now that we have Python 3, its header files, and pip ready to go, we can create a Python virtual environment to manage our projects. We will install Jupyter into this virtual environment.

      To do this, we first need access to the virtualenv command which we can install with pip.

      Upgrade pip and install the package by typing:

      • sudo -H pip3 install --upgrade pip
      • sudo -H pip3 install virtualenv

      The -H flag ensures that the security policy sets the home environment variable to the home directory of the target user.

      With virtualenv installed, we can start forming our environment. Create and move into a directory where we can keep our project files. We’ll call this my_project_dir, but you should use a name that is meaningful for you and what you’re working on.

      • mkdir ~/my_project_dir
      • cd ~/my_project_dir

      Within the project directory, we’ll create a Python virtual environment. For the purpose of this tutorial, we’ll call it my_project_env but you should call it something that is relevant to your project.

      • virtualenv my_project_env

      This will create a directory called my_project_env within your my_project_dir directory. Inside, it will install a local version of Python and a local version of pip. We can use this to install and configure an isolated Python environment for Jupyter.

      Before we install Jupyter, we need to activate the virtual environment. You can do that by typing:

      • source my_project_env/bin/activate

      Your prompt should change to indicate that you are now operating within a Python virtual environment. It will look something like this: (my_project_env)user@host:~/my_project_dir$.

      You’re now ready to install Jupyter into this virtual environment.

      Step 3 — Install Jupyter

      With your virtual environment active, install Jupyter with the local instance of pip.

      Note: When the virtual environment is activated (when your prompt has (my_project_env) preceding it), use pip instead of pip3, even if you are using Python 3. The virtual environment's copy of the tool is always named pip, regardless of the Python version.

      At this point, you’ve successfully installed all the software needed to run Jupyter. We can now start the Notebook server.

      Step 4 — Run Jupyter Notebook

      You now have everything you need to run Jupyter Notebook! To run it, execute the following command:

      A log of the activities of the Jupyter Notebook will be printed to the terminal. When you run Jupyter Notebook, it runs on a specific port number. The first Notebook you run will usually use port 8888. To check the specific port number Jupyter Notebook is running on, refer to the output of the command used to start it:

      Output

      [I 21:23:21.198 NotebookApp] Writing notebook server cookie secret to /run/user/1001/jupyter/notebook_cookie_secret [I 21:23:21.361 NotebookApp] Serving notebooks from local directory: /home/sammy/my_project_dir [I 21:23:21.361 NotebookApp] The Jupyter Notebook is running at: [I 21:23:21.361 NotebookApp] http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72 [I 21:23:21.361 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation). [W 21:23:21.361 NotebookApp] No web browser found: could not locate runnable browser. [C 21:23:21.361 NotebookApp] Copy/paste this URL into your browser when you connect for the first time, to login with a token: http://localhost:8888/?token=1fefa6ab49a498a3f37c959404f7baf16b9a2eda3eaa6d72

      If you are running Jupyter Notebook on a local computer (not on a server), you can navigate to the displayed URL to connect to Jupyter Notebook. If you are running Jupyter Notebook on a server, you will need to connect to the server using SSH tunneling as outlined in the next section.

      At this point, you can keep the SSH connection open and keep Jupyter Notebook running or you can exit the app and re-run it once you set up SSH tunneling. Let's choose to stop the Jupyter Notebook process. We will run it again once we have SSH tunneling set up. To stop the Jupyter Notebook process, press CTRL+C, type Y, and then ENTER to confirm. The following output will be displayed:

      Output

      [C 21:28:28.512 NotebookApp] Shutdown confirmed [I 21:28:28.512 NotebookApp] Shutting down 0 kernels

      We’ll now set up an SSH tunnel so that we can access the Notebook.

      Step 5 — Connect to the Server Using SSH Tunneling

      In this section we will learn how to connect to the Jupyter Notebook web interface using SSH tunneling. Since Jupyter Notebook will run on a specific port on the server (such as :8888, :8889 etc.), SSH tunneling enables you to connect to the server’s port securely.

      The next two subsections describe how to create an SSH tunnel from 1) a Mac or Linux, and 2) Windows. Please refer to the subsection for your local computer.

      SSH Tunneling with a Mac or Linux

      If you are using a Mac or Linux, the steps for creating an SSH tunnel are similar to using SSH to log in to your remote server, except that there are additional parameters in the ssh command. This subsection will outline the additional parameters needed in the ssh command to tunnel successfully.

      SSH tunneling can be done by running the following SSH command in a new local terminal window:

      • ssh -L 8888:localhost:8888 your_server_username@your_server_ip

      The ssh command opens an SSH connection, but -L specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side (server). This means that whatever is running on the second port number (e.g. 8888) on the server will appear on the first port number (e.g. 8888) on your local computer.

      Optionally change port 8888 to one of your choosing to avoid using a port already in use by another process.

      server_username is your username (e.g. sammy) on the server which you created and your_server_ip is the IP address of your server.

      For example, for the username sammy and the server address 203.0.113.0, the command would be:

      • ssh -L 8888:localhost:8888 sammy@203.0.113.0

      If no error shows up after running the ssh -L command, you can move into your programming environment and run Jupyter Notebook:

      You’ll receive output with a URL. From a web browser on your local machine, open the Jupyter Notebook web interface with the URL that starts with http://localhost:8888. Ensure that the token number is included, or enter the token number string when prompted at http://localhost:8888.

      SSH Tunneling with Windows and Putty

      If you are using Windows, you can create an SSH tunnel using Putty.

      First, enter the server URL or IP address as the hostname as shown:

      Set Hostname for SSH Tunnel

      Next, click SSH on the bottom of the left pane to expand the menu, and then click Tunnels. Enter the local port number you want to use to access Jupyter on your local machine. Choose 8000 or greater to avoid ports used by other services, and set the destination as localhost:8888 where :8888 is the number of the port that Jupyter Notebook is running on.

      Now click the Add button, and the ports should appear in the Forwarded ports list:

      Forwarded ports list

      Finally, click the Open button to connect to the server via SSH and tunnel the desired ports. Navigate to http://localhost:8000 (or whatever port you chose) in a web browser to connect to Jupyter Notebook running on the server. Ensure that the token number is included, or enter the token number string when prompted at http://localhost:8000.

      Step 6 — Using Jupyter Notebook

      This section goes over the basics of using Jupyter Notebook. If you don’t currently have Jupyter Notebook running, start it with the jupyter notebook command.

      You should now be connected to it using a web browser. Jupyter Notebook is a very powerful tool with many features. This section will outline a few of the basic features to get you started using the Notebook. Jupyter Notebook will show all of the files and folders in the directory it is run from, so when you’re working on a project make sure to start it from the project directory.

      To create a new Notebook file, select New > Python 3 from the top right pull-down menu:

      Create a new Python 3 notebook

      This will open a Notebook. We can now run Python code in the cell or change the cell to markdown. For example, change the first cell to accept Markdown by clicking Cell > Cell Type > Markdown from the top navigation bar. We can now write notes using Markdown and even include equations written in LaTeX by putting them between the $$ symbols. For example, type the following into the cell after changing it to markdown:

      # First Equation
      
      Let us now implement the following equation:
      $$ y = x^2$$
      
      where $x = 2$
      

      To turn the markdown into rich text, press CTRL+ENTER, and the following should be the results:

      results of markdown

      You can use the markdown cells to make notes and document your code. Let's implement that equation and print the result. Click on the top cell, then press ALT+ENTER to add a cell below it. Enter the following code in the new cell.

      x = 2
      y = x**2
      print(y)
      

      To run the code, press CTRL+ENTER. You’ll receive the following results:

      first equation results

      You now have the ability to import modules and use the Notebook as you would with any other Python development environment!

      Conclusion

      Congratulations! You should now be able to write reproducible Python code and notes in Markdown using Jupyter Notebook. To get a quick tour of Jupyter Notebook from within the interface, select Help > User Interface Tour from the top navigation menu to learn more.

      From here, you can begin a data analysis and visualization project by reading Data Analysis and Visualization with pandas and Jupyter Notebook in Python 3.

      If you’re interested in digging in more, you can read our series on Time Series Visualization and Forecasting.



      Source link