[PYTHON] [Cloud103] # 3 Jupyter Notebook again

AGENDA

  1. Introduction
  2. Python memories
  3. What is Jupyter Notebook?
  4. Try using try.jupyter.org
  5. Convenient usage
  6. I can't do it in the Try environment, but ...

0. Introduction

This in-house study session series covered Python / Jupyter Notebook several times last year.

[Cloud102] # 1 Let's get started with Python (Part 1 Python's first step)

However, although it was easy and free to build an external environment, I used Azure ML Studio and GCP, so I couldn't spend much time explaining the original Python / Jupyter Notebook.

This time, I would like to review how to use Python / Jupyter Notebook using an environment that can be used without any preparation.

1. Python memories

This. https://www.python.org/ 00.JPG

There are a lot of good materials on the net, so please google: smile:

(1) First, sample code

If you have an environment where you can use Python such as Mac, copy and execute the following!

sample.py

import datetime, time

def main():
  for count in range(0, 10):
    print_current_time()
    time.sleep(1)

def print_current_time():
  print (datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))

if __name__ == '__main__':
  main()

The execution result looks like this. 01.JPG

It may be unpleasant for those who have used other languages such as "There is no {}!" Or "There is no; at the end of the sentence!" It is a feature of Python.

(2)The Zen of Python

"The Zen of Python" is an expression of the spirit of Python.

If you have an environment where you can use Python such as Mac, try using REPL (interactive execution environment: start with python without arguments) as follows!

import this

Execution example

02.JPG

Japanese about is here The Zen of Python

Beautiful is better than ugly.
Beautiful is better than ugly.

Explicit is better than implicit.
It is better to clarify than to imply.

Simple is better than complex.
It's better to be plain than complicated.

(3) Comparison with other languages

Language likes and dislikes (as well as editors: sweat :) often make me want to argue about religion, so here's a joke about it. I was pretty happy: smile:

If the programming language is religion

This is easy to understand if it is proper content (although it is strict with Ruby).

Rough explanation of 8 major programming languages

A typical company that actively uses Python is Google.
No matter who writes it, the same processing will be a program with almost the same feeling.
Someone has already written a module when I think "I wonder if I can do this"
It's easy because you don't have to program a lot.

As a non-religious servant, this "easy" is the best. As a matter of fact, frameworks for deep learning are provided almost entirely in Python, such as TensorFlow and Chainer, so I feel like I have no other choice.

2. What is Jupyter Notebook?

This. http://jupyter.org/ 03.JPG

There are also some Japanese reference sites

[Let's use Jupyter Notebook](http://pythondatascience.plavox.info/python%E3%81%AE%E9%96%8B%E7%99%BA%E7%92%B0%E5%A2%83] / jupyter-notebook% E3% 82% 92% E4% BD% BF% E3% 81% A3% E3% 81% A6% E3% 81% BF% E3% 82% 88% E3% 81% 86)

Jupyter Notebook (Read "Jupiter Notebook" or "Jupiter Notebook")Is
While executing a program created in a format called a notebook and recording the execution result,
A tool for advancing data analysis work.

You can easily create and check the program, its execution result, and the memo at that time, so you can check your own.
It is convenient for reviewing past work contents and sharing work results with team members.
It is also suitable for use in school-style classes and training.

... I don't really understand: sweat:

Getting Started Jupyter Notebook

When you save, it will be saved in ipynb format. After that, it will be in the form of creating more and more documents.
You can share the created Book with nbviewer, but in the case of GitHub, it will be displayed as it is.

Now you can share analysis methods etc. with a executable Python code base and with explanations.
I think it will be very useful for sharing know-how.

・ ・ ・ It seems that you can execute the program and record the execution result in notebook format = ipynb format on the browser. Many people are not good at black screen (CLI), so it may be better to be able to do it on the browser.

When using it for personal use, it is very convenient when you save it in the middle and continue later, or when studying (copying) a long source.

By the way, it was originally called iPython, but it is now called jupyter notebook not only for Python but also for other languages (R, Ruby, bash, etc.).

3. Try using try.jupyter.org

Jupyter notebook can be installed relatively easily if you have a Python environment such as Mac, but for Windows it is a little troublesome because you need to start with Python installation. Although there are functional restrictions, there is an official site where you can easily try Jupyter Notebook, so this time I will use that.

https://try.jupyter.org/

When opened in a browser, it looks like this. 04.JPG

As you can see in the upper right, it seems that Rackspace is hosting it. There is a sample, but it's a little difficult, so I'll start from the easy part by creating a new one.

(1) New creation-Save file

Refer to the Getting Started Jupyter Notebook and execute the following.

print("Hello Jupyter")

Choose Python 3 from New 05.JPG

It will be a screen like this 06.JPG

Put the code to the right of In []: (this square is called a cell) and execute it (execution is Shift + Enter).

07.JPG

Click on the "Untitled" above to give it a name. 08.JPG

Download in Notebook format. 09.JPG

Close & Halt. 10.JPG

If you select "Open" again here, you will return to the original screen.

(2) Execute the continuation from the saved file

-Rename the saved file. (Here, 20170904_Sample2.ipynb)

-Click "Upload" to display the local file screen, so specify the file you downloaded and renamed earlier. 11.JPG

・ The screen will look like this, so press "Upload". 12.JPG

・ I was able to upload. 13.JPG

・ Double-click to open 14.JPG

-"Restart & Clear Output" the Kernel. 15-2.JPG

16-2.JPG

· Now you can rerun: smile: 17.JPG

(3) Write Markdown and add a comment

・ I uploaded it, but let's delete the previous cell with the "scissors mark" above. 18.JPG

-Set the remaining cells to "Markdown". 19.JPG

・ Enter the following

###The first Jupyter Notebook
20.JPG

-When I executed it with Sift + Enter, I was able to enter a comment. 21.JPG

-Let's enter the CLI Sample.py that was done first in four parts.

import datetime, time

def main():
  for count in range(0, 10):
    print_current_time()
    time.sleep(1)

def print_current_time():
  print (datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))

if __name__ == '__main__':
  main()

-You can add cells with the "+" button above. 22.JPG

-Point to the top cell of the code and press Shfit + Enter to execute the cells one by one. 23.JPG

(4) Try a Python sample you saw somewhere

Let's copy the following and try it!

・ Introduction to Python

print('Hello World!')

・ Characteristics of Python

total = 0
while total < 10:
    a = input('Please enter a number:')
    if a == '1':
        print('Even one carrot')
        total +=1
    elif a == '2':
        print('Even two pairs of sandals')
        total += 2
    else:
            print('forced termination')
            break
else:
    print('Even 10 strawberries')
    total = 1
print(total)

・ Control syntax (the two are separate)

words = ['cat', 'dog', 'tiger', 'lion']
for s in words:
    print(s)
for n in range(5):
    print(n**2)

・ The introduction is over (a set of 3)

SUFFIXES = { 1000: ['KB','MB','GB','TB','PB','EB','ZB','YB'],
                     1024: ['KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB']}
def approx_size(size, use_1024=True):
    if size < 0:
            raise ValueError('number must not be negative')
            
    base = 1024 if use_1024 else 1000
    for suffix  in SUFFIXES[base]:
        size /= base
        if size < base:
                return '{0: .1f} {1}'.format(size, suffix)
    raise ValueError('number is too large')
print(approx_size(1000000000000), False)
28.JPG

4. Convenient usage

(1) Try to draw a graph 1

Reference article: Basic usage of Jupyter Notebook, a multifunctional web editor useful in the field of machine learning (1/2)

・ Let's copy the following and execute it

import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(20).reshape(5,4), columns=list("abcd"))
df  
24.JPG

・ Let's copy the following and execute it

%matplotlib inline
import matplotlib.pyplot as plt
x = np.linspace(-5,5, 300)
y = np.sin(x)
plt.plot(x,y)
25.JPG

(2) Confirmation of such precautions

As with any programming language, you need to be careful about the accuracy because the content is binary. Let's try the example we did in the previous study session again.

[Cloud102] # 3-1 AML Studio NOTEBOOK Bonus

(3) Try to draw a graph 2

Then try the "Rotable 3D Plot Display" in the same document.

%matplotlib inline
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-3, 3, 0.25)
y = np.arange(-3, 3, 0.25)
X, Y = np.meshgrid(x, y)
Z = np.sin(X)+ np.cos(Y)

fig = plt.figure()
ax = Axes3D(fig)
ax.plot_wireframe(X,Y,Z)

plt.show()
26.JPG

-Change the beginning of the above source (% matplotlib inline) to the following and try again.

%matplotlib notebook

5. I can't do it in the Try environment, but ...

I tried a sample that calls an external API etc. in the Try environment, but it seems that there are restrictions and I could not execute it. 27.JPG

If I have time, I will demo it in a Mac environment.

Enjoy :tada:

Recommended Posts

[Cloud103] # 3 Jupyter Notebook again
Jupyter Notebook memo
Introducing Jupyter Notebook
Powerful Jupyter Notebook
Jupyter notebook password
Get started Jupyter Notebook
3 Jupyter notebook (Python) tricks
Jupyter in Cloud9 IDE
Shortcut key for Jupyter notebook
Introduced Jupyter Notebook to CentOS 7
Using Graphviz with Jupyter Notebook
Display HTML in Jupyter notebook
Use pip with Jupyter Notebook
Multiprocessing error in Jupyter Notebook
Try using Jupyter Notebook dynamically
[Super Basics] About jupyter Notebook
High charts on Jupyter notebook
View PDF on Jupyter Notebook
Use Cython with Jupyter Notebook
Play with Jupyter Notebook (IPython Notebook)
[Complete version] Jupyter Notebook shortcut
Run Jupyter Notebook on windows
How to use Jupyter Notebook
python3.8 venv environment jupyter notebook
Snippet settings for python jupyter notebook
Jupyter Notebook essential for software development
Python memo Anaconda x Jupyter Notebook
Post a Jupyter Notebook as a blog post
Visualize decision trees with jupyter notebook
Make a sound with Jupyter notebook
Jupyter Notebook Magic Command Personal Summary
Paste Jupyter Notebook document into Wordpress
Easy Jupyter environment construction with Cloud9
Generate Jupyter notebook ".ipynb" in Python
Simply view the Jupyter notebook file
[Cloud102] # 3-1 Bonus for AML Studio NOTEBOOK
Run azure ML on jupyter notebook
Jupyter Notebook: 4 banal tips and tricks
[MEMO] [Development environment construction] Jupyter Notebook
Use markdown with jupyter notebook (with shortcut)
Add more kernels with Jupyter Notebook
View graphs inline in Jupyter Notebook
Convenient analysis with Pandas + Jupyter notebook
Install Anaconda on Mac and upload Jupyter (IPython) notebook to Anaconda Cloud
Launch jupyter notebook (+ take security measures)
Easy to use Jupyter notebook (Python3.5)
Try running Jupyter Notebook on Mac
Somehow I tried using jupyter notebook
Try starting Jupyter Notebook ~ Esper training
I tried VS Code's Jupyter notebook
[Cloud102] # 1 Let's get started with Python (Part 2 Jupyter Notebook Construction AWS Edition)
Use nb extensions with Anaconda's Jupyter notebook
Memory leak in Python Jupyter Lab (Notebook)?
Markdown to get Jupyter notebook results to Qiita
Jupyter Notebook extension, nbextensions settings for myself
Use apache Spark with jupyter notebook (IPython notebook)
Jupyter Notebook does not show matplotlib graphs
I want to blog with Jupyter Notebook
Use Jupyter Lab and Jupyter Notebook with EC2
Make Jupyter Notebook a service on CentOS
Try SVM with scikit-learn on Jupyter Notebook