AGENDA
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.
This. https://www.python.org/
There are a lot of good materials on the net, so please google: smile:
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.
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
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.
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.
This. http://jupyter.org/
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.).
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.
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.
Refer to the Getting Started Jupyter Notebook and execute the following.
print("Hello Jupyter")
Choose Python 3 from New
It will be a screen like this
Put the code to the right of In []: (this square is called a cell) and execute it (execution is Shift + Enter).
Click on the "Untitled" above to give it a name.
Download in Notebook format.
Close & Halt.
If you select "Open" again here, you will return to the original screen.
-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.
・ The screen will look like this, so press "Upload".
・ I was able to upload.
・ Double-click to open
-"Restart & Clear Output" the Kernel.
· Now you can rerun: smile:
・ I uploaded it, but let's delete the previous cell with the "scissors mark" above.
-Set the remaining cells to "Markdown".
・ Enter the following
###The first Jupyter Notebook
-When I executed it with Sift + Enter, I was able to enter a comment.
-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.
-Point to the top cell of the code and press Shfit + Enter to execute the cells one by one.
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)
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
・ 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)
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
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()
-Change the beginning of the above source (% matplotlib inline) to the following and try again.
%matplotlib notebook
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.
If I have time, I will demo it in a Mac environment.
Enjoy :tada:
Recommended Posts