markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
<p style="text-align: right; direction: rtl; float: right; clear: both;"> בדוגמה זו השתמשנו בעובדה שהפרמטר שמוגדר בעזרת שתי כוכביות הוא בהכרח מילון.<br> עברנו על כל המפתחות והערכים שבו בעזרת הפעולה <code>items</code>, והדפסנו את המתכון, רכיב אחר רכיב. </p> <div class="align-center" style="display: flex; text-a...
def calculate_cake_price(apply_discount, *ingredients, discount_rate=10, **prices): if not apply_discount: discount_rate = 0 final_price = 0 for ingredient in ingredients: final_price = final_price + prices.get(ingredient) final_price = final_price - (final_price * discount_rate / ...
week05/2_Functions_Part_2.ipynb
PythonFreeCourse/Notebooks
mit
<div class="align-center" style="display: flex; text-align: right; direction: rtl;"> <div style="display: flex; width: 10%; float: right; "> <img src="images/warning.png" style="height: 50px !important;" alt="אזהרה!"> </div> <div style="width: 90%"> <p style="text-align: right; direction: r...
def append(item, l=[]): l.append(item) return l print(append(4, [1, 2, 3])) print(append('a'))
week05/2_Functions_Part_2.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> עד כאן נראה כאילו הפונקציה פועלת באופן שהיינו מצפים ממנה.<br> ערך ברירת המחדל של הפרמטר <code>l</code> הוא רשימה ריקה, ולכן בקריאה השנייה חוזרת רשימה עם איבר בודד, <samp>['a']</samp>. </p> <p style="text-align: right; direction: rtl; flo...
print(append('b')) print(append('c')) print(append('d')) print(append(4, [1, 2, 3])) print(append('e'))
week05/2_Functions_Part_2.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> משונה ולא הגיוני! ציפינו לקבל את הרשימה <samp>['b']</samp> ואז את הרשימה <samp>['c']</samp> וכן הלאה.<br> במקום זה בכל פעם מצטרף איבר חדש לרשימה. למה? </p> <p style="text-align: right; direction: rtl; float: right; clear: both;"> הסי...
def view_memory_of_l(item, l=[]): l.append(item) print(f"{l} --> {id(l)}") return l same_list1 = view_memory_of_l('a') same_list2 = view_memory_of_l('b') same_list3 = view_memory_of_l('c') new_list1 = view_memory_of_l(4, [1, 2, 3]) new_list2 = view_memory_of_l(5, [1, 2, 3]) new_list3 = view_memory_of_l(6,...
week05/2_Functions_Part_2.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> כיצד נפתור את הבעיה?<br> דבר ראשון – נשתדל שלא להגדיר משתנים מטיפוס שהוא mutable בתוך כותרת הפונקציה.<br> אם נרצה בכל זאת שהפרמטר יקבל רשימה כברירת מחדל, נעשה זאת כך: </p>
def append(item, l=None): if l == None: l = [] l.append(item) return l print(append(4, [1, 2, 3])) print(append('a'))
week05/2_Functions_Part_2.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> שימו לב שהתופעה לא משתחזרת במבנים שהם immutable, כיוון שכשמם כן הם – אי אפשר לשנותם: </p>
def increment(i=0): i = i + 1 return i print(increment(100)) print(increment()) print(increment()) print(increment()) print(increment(100))
week05/2_Functions_Part_2.ipynb
PythonFreeCourse/Notebooks
mit
<span style="text-align: right; direction: rtl; float: right; clear: both;">דוגמאות נוספות<span> <span style="text-align: right; direction: rtl; float: right; clear: both;">חיקוי מדויק של פונקציית get למילונים:<span> <p style="text-align: right; direction: rtl; float: right; clear: both;"> נרענן את זיכרוננו בנוגע ל...
range_arguments = [1, 10, 3] range_result = range(*range_arguments) print(list(range_result))
week05/2_Functions_Part_2.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> או: </p>
preformatted_message = "My name is {me}, and my sister is {sister}" parameters = {'me': 'Mei', 'sister': 'Satsuki'} message = preformatted_message.format(**parameters) print(message)
week05/2_Functions_Part_2.ipynb
PythonFreeCourse/Notebooks
mit
<p style="text-align: right; direction: rtl; float: right; clear: both;"> אם כך, נוכל לכתוב: </p>
def get(dictionary, *args, **kwargs): return dictionary.get(*args, **kwargs)
week05/2_Functions_Part_2.ipynb
PythonFreeCourse/Notebooks
mit
Required Packages If you installed Python through the Anaconda platform, then the packages below should already be installed on your hard drive and Python should be able to find them.
import os import string import numpy import matplotlib import pandas import sklearn import scipy import nltk print("Success!")
00-Introduction/Installation_Check.ipynb
lknelson/text-analysis-2017
bsd-3-clause
Visualization¶ The code in the cell below is not Python but a direct instruction to the Jupyter Notebook. Any visualizations that we produce will appear within the notebook itself (as opposed to an external image processor).
%pylab inline
00-Introduction/Installation_Check.ipynb
lknelson/text-analysis-2017
bsd-3-clause
As a quick, opening toy example to see Python in action, let's find all the present participles used in Jane Austen's Pride and Prejudice. There is a plain text file containing this book in this folder. Part of the reason why people use Python to do work on human-language texts (natural language processing) is because ...
# every line that starts with a hash is a comment # the computer ignores these lines, they are meant to address a human reader # here is some starter code to make sure everything is set up (don't worry about understanding everything here) for line in open('../Data/Austen_PrideAndPrejudice.txt', encoding='utf-8'): f...
00-Introduction/Installation_Check.ipynb
lknelson/text-analysis-2017
bsd-3-clause
Tutorial 4 - Current induced domain wall motion In this tutorial we show how spin transfer torque (STT) can be included in micromagnetic simulations. To illustrate that, we will try to move a domain wall pair using spin-polarised current. Let us simulate a two-dimensional sample with length $L = 500 \,\text{nm}$, width...
# Definition of parameters L = 500e-9 # sample length (m) w = 20e-9 # sample width (m) d = 2.5e-9 # discretisation cell size (m) Ms = 5.8e5 # saturation magnetisation (A/m) A = 15e-12 # exchange energy constant (J/) D = 3e-3 # Dzyaloshinkii-Moriya energy constant (J/m**2) K = 0.5e6 # uniaxial anisotropy constant...
workshops/Durham/tutorial4_current_induced_dw_motion.ipynb
joommf/tutorial
bsd-3-clause
Because we want to move a DW pair, we need to initialise the magnetisation in an appropriate way before we relax the system.
def m_value(pos): x, y, z = pos if 20e-9 < x < 40e-9: return (0, 0, -1) else: return (0, 0, 1) system.m = df.Field(mesh, value=m_value, norm=Ms) fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) system.m.z.plot_plane("z", ax=ax);
workshops/Durham/tutorial4_current_induced_dw_motion.ipynb
joommf/tutorial
bsd-3-clause
Now, we can relax the magnetisation.
md = oc.MinDriver() md.drive(system) fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) system.m.z.plot_plane("z", ax=ax)
workshops/Durham/tutorial4_current_induced_dw_motion.ipynb
joommf/tutorial
bsd-3-clause
And drive the system for half a nano second:
td = oc.TimeDriver() td.drive(system, t=0.5e-9, n=100) fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(111) system.m.z.plot_plane("z", ax=ax);
workshops/Durham/tutorial4_current_induced_dw_motion.ipynb
joommf/tutorial
bsd-3-clause
We see that the DW pair has moved to the positive $x$ direction. Exercise Modify the code below (which is a copy of the example from above) to obtain one domain wall instead of a domain wall pair and move it using the same current.
# Definition of parameters L = 500e-9 # sample length (m) w = 20e-9 # sample width (m) d = 2.5e-9 # discretisation cell size (m) Ms = 5.8e5 # saturation magnetisation (A/m) A = 15e-12 # exchange energy constant (J/) D = 3e-3 # Dzyaloshinkii-Moriya energy constant (J/m**2) K = 0.5e6 # uniaxial anisotropy constant...
workshops/Durham/tutorial4_current_induced_dw_motion.ipynb
joommf/tutorial
bsd-3-clause
For Leoni
fig = plt.figure(figsize=(8, 8)) ax = fig.add_subplot(111) system.m.z.imshow("z", ax=ax, aspect=5) system.m.quiver("z", ax=ax, n=(30, 5), scale=1e7) ax.set_title("Plot slice") ax.set_xlabel("x label") ax.set_ylabel("y label")
workshops/Durham/tutorial4_current_induced_dw_motion.ipynb
joommf/tutorial
bsd-3-clause
The construction if __name__ == '__main__': is a standard way in Python of marking code which should be executed when the file is used as a script. It is a best practice to use the above mentioned template. GRASS GIS parser Every GRASS GIS module must use the GRASS parser mechanism. This very advanced parser helps to ...
%%file r.viewshed.points.py #!/usr/bin/env python #%module #% description: Compute and analyze viewsheds #% keyword: raster #% keyword: viewshed #%end import grass.script as gscript def main(): gscript.parser() if __name__ == '__main__': main()
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Note that the GRASS GIS parser requires a new line character at the end of file. In this case, we use two empty lines because IPython Notebook will remove one. To run the script, we need to set its permissions to 'executable'. We do so using chmod command.
!chmod u+x r.viewshed.points.py
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Now we can execute the script as a GRASS GIS module with --help to get the command line help output.
!./r.viewshed.points.py --help
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Adding parameters as standard options Now we will add parameters to our module. Let's say, we want to pass the name of an elevation raster map and of a vector points map. In the interface definition comment we hence add a section option for each of these maps and define respectively standard (or predefined) options. Fo...
%%file r.viewshed.points.py #!/usr/bin/env python #%module #% description: Compute and analyze viewsheds #% keyword: raster #% keyword: viewshed #%end #%option G_OPT_R_INPUT #% key: elevation #%end #%option G_OPT_V_INPUT #% key: points #%end import grass.script as gscript def main(): options, flags = gscript.par...
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Adding parameters as custom options When using standard options, all items are predefined by the parser but we can modify e.g. key or other items to our needs. However, for other cases, we have to define the options completely from scratch. In our example, we introduce a non-standard key with name max_distance which ha...
%%file r.viewshed.points.py #!/usr/bin/env python #%module #% description: Compute and analyze viewsheds #% keyword: raster #% keyword: viewshed #%end #%option G_OPT_R_INPUT #% key: elevation #%end #%option G_OPT_V_INPUT #% key: points #%end #%option #% key: max_distance #% key_desc: value #% type: double #% descripti...
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Adding parameters as flags
%%file r.viewshed.points.py #!/usr/bin/env python #%module #% description: Compute and analyze viewsheds #% keyword: raster #% keyword: viewshed #%end #%option G_OPT_R_INPUT #% key: elevation #%end #%option G_OPT_V_INPUT #% key: points #%end #%option #% key: max_distance #% key_desc: value #% type: double #% descripti...
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Compilation and formal requirements As mentioned before, a GRASS GIS module must use the GRASS parser to handle its command line parameters. A module reads and/or writes geospatial data as GRASS raster or vector maps. A module should not overwrite existing data unless specified by the user using the --overwrite flag. F...
%%file r.viewshed.points.html <h2>DESCRIPTION</h2> A long description with details about the method, implementation, usage or whatever is appropriate. <h2>EXAMPLES</h2> Examples of how the module can be used alone or in combination with other modules. Possibly using the GRASS North Carolina State Plane Metric sample...
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
All GRASS GIS modules must be distributed under GNU GPL license (version 2 or later). There is a specified way how the first comment in module's main file should look like. Here is how it can look like for our module: """ MODULE: r.viewshed.points AUTHOR(S): John Smith &lt;email at some domain&gt; PURPOSE: Compu...
%%file Makefile MODULE_TOPDIR = ../.. PGM = r.viewshed.points include $(MODULE_TOPDIR)/include/Make/Script.make default: script
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
No we will compile the module which will also add it to our GRASS GIS installation. To do this, we need to have administrator rights (on Linux, use sudo in command line). First we need to create one directory required for the compilation:
!mkdir `grass70 --config path`/scriptstrings !g.gisenv set="MAPSET=PERMANENT" !g.gisenv
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Then we can compile:
!make MODULE_TOPDIR=`grass70 --config path`
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
In these two command, we are using 'backticks' syntax to include output of command into another command. Handling temporary maps and region In scripts we have to often create temporary maps, which needs to be removed after the script is finished, or if there is an error. Similarly, when we need to change computational...
%tb import os import grass.script as gscript def main(): for i in range(5): name = 'tmp_raster_' + str(os.getpid()) + str(i) gscript.mapcalc("{name} = rand(0, 10)".format(name=name), seed=1) if __name__ == '__main__': main()
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
To avoid removing temporary maps manually with g.remove, we write a function which removes those temporary maps after at the end of the script.
%tb import os import grass.script as gscript TMP_MAPS = [] def main(): for i in range(5): name = 'tmp_raster_' + str(os.getpid()) + str(i) TMP_MAPS.append(name) gscript.mapcalc("{name} = rand(0, 10)".format(name=name), seed=1) cleanup() def cleanup(): gscript.run_command('...
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
However in case of error, the cleanup function won't be called:
import os import grass.script as gscript TMP_MAPS = [] def main(): for i in range(5): name = 'tmp_raster_' + str(os.getpid()) + str(i) TMP_MAPS.append(name) gscript.mapcalc("{name} = rand(0, 10)".format(name=name), seed=1) # we raise intentionally error here: raise TypeError cl...
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Therefore we will use Python atexit module to ensure the cleanup functions is called everytime, even when the script ends with error.
import os import atexit import grass.script as gscript TMP_MAPS = [] def main(): for i in range(5): name = 'tmp_raster_' + str(os.getpid()) + str(i) TMP_MAPS.append(name) gscript.mapcalc("{name} = rand(0, 10)".format(name=name), seed=1) # we raise intentionally error here: raise Ty...
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Temporary region Using temporary region is simple - library function use_temp_region is called in the beginning of the script and we can then call g.region anywhere in the script. First, we set the region to match a raster map.
import grass.script as gscript gscript.run_command('g.region', raster='elevation') print gscript.region()
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
As shown in this example, the region set in the script doesn't affect the current region set in the previous step.
import grass.script as gscript def main(): gscript.run_command('g.region', n=100, s=0, w=0, e=100, res=1) print gscript.region() if __name__ == '__main__': gscript.use_temp_region() main() print gscript.region()
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
Complete module example Now we will convert the script from previous section into a fully-fledged module. The input is a vector map with points and elevation map. The output is a new vector map of vector points with viewshed characteristics saved in attribute table and the raster viewsheds (basename specified in G_OPT_...
%%file r.viewshed.points.py #!/usr/bin/env python #%module #% description: Compute and analyze viewsheds #% keyword: raster #% keyword: viewshed #%end #%option G_OPT_R_INPUT #% key: elevation #%end #%option G_OPT_V_INPUT #% key: points #%end #%option G_OPT_V_OUTPUT #% key: output_points #%end #%option G_OPT_R_BASENAME...
GSOC/notebooks/Projects/GRASS/python-grass-addons/04_script_to_grass_module.ipynb
OSGeo-live/CesiumWidget
apache-2.0
We prepare the controlled-Hadamard and controlled-u3 gates that are required in the encoding as below.
def ch(qProg, a, b): """ Controlled-Hadamard gate """ qProg.h(b) qProg.sdg(b) qProg.cx(a, b) qProg.h(b) qProg.t(b) qProg.cx(a, b) qProg.t(b) qProg.h(b) qProg.s(b) qProg.x(b) qProg.s(a) return qProg def cu3(qProg, theta, phi, lambd, c, t): """ Controlled-u3 gate "...
community/terra/qis_adv/two-qubit_state_quantum_random_access_coding.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
Encoding 7 bits into 2 qubits with $(7,2)$-QRAC The sender prepares the state to be sent by working on 3 qubits and uses the first one to control the mixture. She needs controlled unitary gates of $(3,1)$-QRAC encoding for her first 6 bits. When the first qubit is zero, she encodes $x_1x_2x_3$ into the second qubit, an...
#CHANGE THIS 7BIT 0-1 STRING TO PERFORM EXPERIMENT ON ENCODING 0000000, ..., 1111111 x1234567 = "0101010" if len(x1234567) != 7 or not("1" in x1234567 or "0" in x1234567): raise Exception("x1234567 is a 7-bit 0-1 pattern. Please set it to the correct pattern") #compute the value of rotation angle theta of (3,...
community/terra/qis_adv/two-qubit_state_quantum_random_access_coding.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
Below are plots of the experimental results of extracting the first to sixth bit, that results in observing the-$i$th bit with probability at least $0.54$
%%qiskit_job_status # Use the qasm simulator backend = Aer.get_backend("qasm_simulator") # Use the IBM Quantum Experience # backend = least_busy(IBMQ.backends(simulator=False)) shots = 1000 job = execute(circuits, backend=backend, shots=shots) results = job.result() for k in ["DecodeFirst", "DecodeSecond", "DecodeT...
community/terra/qis_adv/two-qubit_state_quantum_random_access_coding.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
The seventh bit is obtained by looking at the content of classical registers. If they are the same, i.e., both are 1 or 0, then we conclude that it is 0, or otherwise 1. For the encoding of 0101010, the seventh bit is 0, so the total probability of observing 00 and 11 must exceed that of observing 01 and 10.
print("Experimental result of ", encodingName+"DecodeSeventh") plot_histogram(results.get_counts(circuits[circuitNames.index(encodingName+"DecodeSeventh")]))
community/terra/qis_adv/two-qubit_state_quantum_random_access_coding.ipynb
antoniomezzacapo/qiskit-tutorial
apache-2.0
Graded = 7/8 1) What books topped the Hardcover Fiction NYT best-sellers list on Mother's Day in 2009 and 2010? How about Father's Day?
#Mother's Day in 2009 was May 10, 2009 response = requests.get("http://api.nytimes.com/svc/books/v2/lists/2009-05-10/hardcover-fiction.json?api-key=2ca9e983dcfd4b1ba330521af1c9c2b2") mom_09_data = response.json() #print(mom_09_data) #mom_09_data.keys() #print(mom_09_data['results']) for item in mom_09_data['results']:...
5/.ipynb_checkpoints/nyt-homework-hon-june6-checkpoint.ipynb
honjy/foundations-homework
mit
2) What are all the different book categories the NYT ranked in June 6, 2009? How about June 6, 2015? Question: To specify a date, include it in the URI path. To specify a response-format, add it as an extension. The other parameters in this table are specified as name-value pairs in a query string. (What is the differ...
response = requests.get("http://api.nytimes.com/svc/books/v2/lists/names.json?date=2009-06-06&api-key=2ca9e983dcfd4b1ba330521af1c9c2b2") june6_09_data = response.json() #print(june6_09_data) #Looks all right? june6_09_data.keys() #print(june6_09_data['results']) #Looks like the categories are under display name and l...
5/.ipynb_checkpoints/nyt-homework-hon-june6-checkpoint.ipynb
honjy/foundations-homework
mit
3) Muammar Gaddafi's name can be transliterated many many ways. His last name is often a source of a million and one versions - Gadafi, Gaddafi, Kadafi, and Qaddafi to name a few. How many times has the New York Times referred to him by each of those names? Tip: Add "Libya" to your search to make sure (-ish) you're tal...
#Gadafi response = requests.get("http://api.nytimes.com/svc/search/v2/articlesearch.json?fq=Gadafi&glocations=Libya&api-key=2ca9e983dcfd4b1ba330521af1c9c2b2") gadafi_data = response.json() #print(gadafi_data) print("The NYT has referred to him by 'Gadafi' a total of", gadafi_data['response']['meta']['hits'], "times") ...
5/.ipynb_checkpoints/nyt-homework-hon-june6-checkpoint.ipynb
honjy/foundations-homework
mit
4) What's the title of the first story to mention the word 'hipster' in 1995? What's the first paragraph? Question: What is the difference between query and filter query?
#hipster response = requests.get("http://api.nytimes.com/svc/search/v2/articlesearch.json?fq=hipster&begin_date=19950101&end_date=19951231&sort=oldest&api-key=2ca9e983dcfd4b1ba330521af1c9c2b2") hipster_data = response.json() #print(hipster_data) hipster_data.keys() #print(hipster_data['response']['docs'][0]) #The firs...
5/.ipynb_checkpoints/nyt-homework-hon-june6-checkpoint.ipynb
honjy/foundations-homework
mit
TA-Stephan: Didn't print out first paragraph. 5) How many times was gay marriage mentioned in the NYT between 1950-1959, 1960-1969, 1970-1978, 1980-1989, 1990-2099, 2000-2009, and 2010-present? Tip: You'll want to put quotes around the search term so it isn't just looking for "gay" and "marriage" in the same article. T...
#gaymarriage response = requests.get("http://api.nytimes.com/svc/search/v2/articlesearch.json?q=%22gay%20marriage%22&begin_date=19500101&end_date=19591231&api-key=2ca9e983dcfd4b1ba330521af1c9c2b2") gay_50_data = response.json() #print(gay_50_data) print("The number of times gay marriage is mentioned between 1950 and 1...
5/.ipynb_checkpoints/nyt-homework-hon-june6-checkpoint.ipynb
honjy/foundations-homework
mit
6) What section talks about motorcycles the most? Tip: You'll be using facets
response = requests.get("http://api.nytimes.com/svc/search/v2/articlesearch.json?q=motorcycle&facet_field=section_name&api-key=2ca9e983dcfd4b1ba330521af1c9c2b2") motor_data = response.json() top_motor = motor_data['response']['facets']['section_name']['terms'] for item in top_motor: print(item['term'], item['count...
5/.ipynb_checkpoints/nyt-homework-hon-june6-checkpoint.ipynb
honjy/foundations-homework
mit
7) How many of the last 20 movies reviewed by the NYT were Critics' Picks? How about the last 40? The last 60? Tip: You really don't want to do this 3 separate times (1-20, 21-40 and 41-60) and add them together. What if, perhaps, you were able to figure out how to combine two lists? Then you could have a 1-20 list, a ...
response = requests.get("http://api.nytimes.com/svc/movies/v2/reviews/search.json?resource-type=all&api-key=2ca9e983dcfd4b1ba330521af1c9c2b2") movie20_data = response.json() #print(movie20_data) #movie20_data.keys() #print(movie20_data['results']) #I am assuming critics_pick = 0 means no and critics_pick = 1 means yes...
5/.ipynb_checkpoints/nyt-homework-hon-june6-checkpoint.ipynb
honjy/foundations-homework
mit
8) Out of the last 40 movie reviews from the NYT, which critic has written the most reviews?
byline_count = [] from collections import Counter #print(movie40_data['results']) for stuff in movie40_data['results']: byline = stuff['byline'] #print(byline) byline_count.append(byline) counts = Counter(byline_count) counts.most_common(1)
5/.ipynb_checkpoints/nyt-homework-hon-june6-checkpoint.ipynb
honjy/foundations-homework
mit
Load up Dependencies
import tensorflow as tf import tensorflow_hub as hub import numpy as np import pandas as pd
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Check if GPU is available for use!
tf.test.is_gpu_available() tf.test.gpu_device_name()
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Load and View Dataset
dataset = pd.read_csv('movie_reviews.csv.bz2', compression='bz2') dataset.info() dataset['sentiment'] = [1 if sentiment == 'positive' else 0 for sentiment in dataset['sentiment'].values] dataset.head()
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Build train, validation and test datasets
reviews = dataset['review'].values sentiments = dataset['sentiment'].values train_reviews = reviews[:30000] train_sentiments = sentiments[:30000] val_reviews = reviews[30000:35000] val_sentiments = sentiments[30000:35000] test_reviews = reviews[35000:] test_sentiments = sentiments[35000:] train_reviews.shape, val_re...
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Basic Text Wrangling
!pip install contractions !pip install beautifulsoup4 import contractions from bs4 import BeautifulSoup import unicodedata import re def strip_html_tags(text): soup = BeautifulSoup(text, "html.parser") [s.extract() for s in soup(['iframe', 'script'])] stripped_text = soup.get_text() stripped_text = r...
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Build Data Ingestion Functions
# Training input on the whole training set with no limit on training epochs. train_input_fn = tf.estimator.inputs.numpy_input_fn( {'sentence': train_reviews}, train_sentiments, batch_size=256, num_epochs=None, shuffle=True) # Prediction on the whole training set. predict_train_input_fn = tf.estimator.inputs.n...
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Build Deep Learning Model with Universal Sentence Encoder
embedding_feature = hub.text_embedding_column( key='sentence', module_spec="https://tfhub.dev/google/universal-sentence-encoder/2", trainable=False) dnn = tf.estimator.DNNClassifier( hidden_units=[512, 128], feature_columns=[embedding_feature], n_classes=2, activati...
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Train for approx 12 epochs
256*1500 / 30000
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Model Training
tf.logging.set_verbosity(tf.logging.ERROR) import time TOTAL_STEPS = 1500 STEP_SIZE = 100 for step in range(0, TOTAL_STEPS+1, STEP_SIZE): print() print('-'*100) print('Training for step =', step) start_time = time.time() dnn.train(input_fn=train_input_fn, steps=STEP_SIZE) elapsed_time = time.ti...
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Model Evaluation
dnn.evaluate(input_fn=predict_train_input_fn) dnn.evaluate(input_fn=predict_test_input_fn)
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Build a Generic Model Trainer on any Input Sentence Encoder
import time TOTAL_STEPS = 1500 STEP_SIZE = 500 my_checkpointing_config = tf.estimator.RunConfig( keep_checkpoint_max = 2, # Retain the 2 most recent checkpoints. ) def train_and_evaluate_with_sentence_encoder(hub_module, train_module=False, path=''): embedding_feature = hub.text_embedding_column( ...
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Train Deep Learning Models on difference Sentence Encoders NNLM - pre-trained and fine-tuning USE - pre-trained and fine-tuning
tf.logging.set_verbosity(tf.logging.ERROR) results = {} results["nnlm-en-dim128"] = train_and_evaluate_with_sentence_encoder( "https://tfhub.dev/google/nnlm-en-dim128/1", path='/storage/models/nnlm-en-dim128_f/') results["nnlm-en-dim128-with-training"] = train_and_evaluate_with_sentence_encoder( "https://tfh...
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
Model Evaluations
results_df = pd.DataFrame.from_dict(results, orient="index") results_df best_model_dir = results_df[results_df['Test Accuracy'] == results_df['Test Accuracy'].max()]['Model Dir'].values[0] best_model_dir embedding_feature = hub.text_embedding_column( key='sentence', module_spec="https://tfhub.dev/google/unive...
New-Second-Edition/Ch10 - The Promise of Deep Learning/Ch10a - Deep Transfer Learning for NLP - Text Classification with Universal Embeddings.ipynb
dipanjanS/text-analytics-with-python
apache-2.0
The Laplacian Matrix is a matrix that is extremely important in graph theory and numerical analysis. It is defined as $L=D-A$. Where $D$ is the degree matrix and $A$ is the adjecency matrix. For the purpose of this problem you don't need to understand the details of these matrices, although their definitions are relati...
def complete_deg(n): """Return the integer valued degree matrix D for the complete graph K_n.""" D=np.zeros((n,n),np.dtype(int)) for i in range(n): D[i::n,i::n]=int(n-1) #makes diagnal = n-1 return D print(complete_deg(10)) raise NotImplementedError() D = complete_deg(5) assert D.shape==(5,5) a...
assignments/assignment03/NumpyEx04.ipynb
rvperry/phys202-2015-work
mit
The adjacency matrix for $K_n$ is an $n \times n$ matrix with zeros along the diagonal and ones everywhere else. Write a function to compute the adjacency matrix for $K_n$ using NumPy.
def complete_adj(n): """Return the integer valued adjacency matrix A for the complete graph K_n.""" A=np.ones((n,n),np.dtype(int)) for i in range(n): A[i::n,i::n]=0 return A raise NotImplementedError() A = complete_adj(5) assert A.shape==(5,5) assert A.dtype==np.dtype(int) assert np.all(A+np.e...
assignments/assignment03/NumpyEx04.ipynb
rvperry/phys202-2015-work
mit
Use NumPy to explore the eigenvalues or spectrum of the Laplacian L of $K_n$. What patterns do you notice as $n$ changes? Create a conjecture about the general Laplace spectrum of $K_n$.
def Laplacian(n): L=complete_deg(n)-complete_adj(n) return L def Eigen(n): E=np.linalg.eigvals(Laplacian(n)) return E print Eigen(24) raise NotImplementedError()
assignments/assignment03/NumpyEx04.ipynb
rvperry/phys202-2015-work
mit
The stress function for a disk of diameter $d$ with center in the origin, and radial inward and opposite forces $P$ placed at $(0, d/2)$ and $(0, -d/2)$ is given by $$\phi = x\arctan\left[\frac{x}{d/2 - y}\right] + x\arctan\left[\frac{x}{d/2 + y}\right] + \frac{P}{\pi d}(x^2 + y^2)$$ We know that the stresses are given...
d, P = symbols("d P", positive=True) phi = x*atan(x/(d/2 - y)) + x*atan(x/(d/2 + y)) + P/(pi*d)*(x**2 + y**2) Sxx = phi.diff(y, 2) Syy = phi.diff(x, 2) Sxy = -phi.diff(x, 1, y, 1) display(Sxx) display(Syy) display(Sxy) Sxx_fun = lambdify((x, y), Sxx.subs({P:1, d:2}), numpy) Syy_fun = lambdify((x, y), Syy.subs({P:1,...
Stresses_disk_point_loads.ipynb
nicoguaro/notebooks_examples
mit
Strains
E, nu = symbols("E nu") G = E/(2*(1 + nu)) Exx = simplify(1/E*(Sxx - nu*Syy)) Eyy = simplify(1/E*(Syy - nu*Sxx)) Exy = simplify(1/G*Sxy) display(Exx) display(Eyy) display(Exy)
Stresses_disk_point_loads.ipynb
nicoguaro/notebooks_examples
mit
Displacements
C1, a, b = symbols("C1 a b") ux, uy = symbols("ux uy", cls=Function) eq1 = diff(ux(x), x) - Exx eq1 from IPython.core.display import HTML def css_styling(): styles = open('./styles/custom_barba.css', 'r').read() return HTML(styles) css_styling()
Stresses_disk_point_loads.ipynb
nicoguaro/notebooks_examples
mit
Parametric Equations Example: Graph the curve $x = \sin{t}$, $y = \cos{t}$, $0 \le t \le \pi$. Read Scipy Lecture Notes (http://www.scipy-lectures.org/) pg. 45 for creating arrays and pg. 83 for plotting.
# define array from 0 to pi with interval size 0.1 t = np.arange(0, np.pi, 0.1) #define x and y x = np.sin(t) y = np.cos(t) # plot the graph plt.plot(x, y) plt.show()
Lab1/MAT491-Lab1.ipynb
rizauddin/Lab-Assignment-MAT491
gpl-3.0
Q1. Graph the curve $x= 26 \sin^3{t}$, $y = 13\cos{t} - 5\cos{2t} - 2\cos{4t}$, $0 \le t \le 2\pi.$ Q2. Graph the curve $x=\mathrm{e}^t \cos{t} - \mathrm{e}^t \sin{t}$, $y = \mathrm{e}^t \sin{t}$, $0 \le t \le \pi.$ Hint: Use np.exp(t) for $\mathrm{e}^t$. Polar Coordinates Example: Sketch the curve $r = 1 + \sin{\theta...
# define array from 0 to pi 100 elements theta = np.linspace(0, 2*np.pi, 100) # define $r = 1 + \sin{\theta}$ r = 1 + np.sin(theta) # add subplot in polar coordinates ax = plt.subplot(111, polar=True) # plot the graph ax.plot(theta, r) plt.show()
Lab1/MAT491-Lab1.ipynb
rizauddin/Lab-Assignment-MAT491
gpl-3.0
Q3. Sketch the curve $r = 1 + \cos{\theta}$. Q4. Sketch the curve $r = 1 - \cos{\theta}$. Quadratic Surfaces Example: Sketch the graph of the surface $z = x^2$.
x = np.arange(-2, 2, 0.25) # points in the x axis y = np.arange(-2, 2, 0.25) # points in the y axis X, Y = np.meshgrid(x, y) # create the "base grid" Z = X**2 # points in the z axis fig = plt.figure() ax = fig.gca(projection='3d') # 3d ax...
Lab1/MAT491-Lab1.ipynb
rizauddin/Lab-Assignment-MAT491
gpl-3.0
How much variance is there? Plot 2 answers this question by adding error bars to the previous plot. Length of the error bar is equal to the standard deviation of actual returns within each respective bucket. Plots such as these would be typically used by a portfolio manager to assess behavior of prospective signals and...
! tar -cvf output3.zip --exclude="2sigma" --exclude="__*" --exclude="*.zip" * !tar -cvf output.zip main.ipynb prepareData.py dnn.jpg data.jpg data_split.jpg rnn.jpg ! ls
ai_newsweek/keras_autoencoder_ai_newsweek_conf.ipynb
GuillaumeDec/machine-learning
gpl-3.0
TensorFlow Let's create a DNNClassifier using TF's built-in classifier, and evaluate its accuracy.
import tensorflow as tf # what should the classifier expect in terms of features feature_columns = [tf.contrib.layers.real_valued_column("", dimension=D)] # defining the actual classifier dnn_spiral_classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns, ...
codelab_3_tensorflow_nn.ipynb
thinkingmachines/deeplearningworkshop
mit
Notice the following: The higher level library vastly simplied the following mechanics: tf.session management training the model running evaluation loops feeding data into the model generating predictions from the model saving the model in a checkpoint file For most use cases, it's likely that the many common models...
%ls '/tmp/spiral_model/'
codelab_3_tensorflow_nn.ipynb
thinkingmachines/deeplearningworkshop
mit
Predicting on a new value Let's classify a new point
def new_points(): return np.array([[1.0, 1.0], [-1.5, -1.0]], dtype = np.int32) predictions = list(dnn_spiral_classifier.predict(input_fn=new_points)) print( "New Samples, Class Predictions: {}\n" .format(predictions))
codelab_3_tensorflow_nn.ipynb
thinkingmachines/deeplearningworkshop
mit
Digging into the DNNClassifier The DNNClassifier is one fo the (Estimators)[https://www.tensorflow.org/api_guides/python/contrib.learn#Estimators] available in the tf.contrib.learn libary. Other estimators include: KMeansClustering DNNRegressor LinearClassifier LinearRegressor LogisticRegressor Each one of these can...
# watch out for this, tf.classifier.evaluate is going to be deprecated, so keep an eye out for a long-term solution to calculating accuracy accuracy_score = dnn_spiral_classifier.evaluate(input_fn=get_inputs, steps=1)["accuracy"]
codelab_3_tensorflow_nn.ipynb
thinkingmachines/deeplearningworkshop
mit
Exercises Get into the (TensorFlow API docs)[https://www.tensorflow.org/api_docs/python/tf]. Try the following and see how it impacts the final scores Change the activation function to a ReLU Change the optimization function to stochastic gradient descent, then change it again to Adagrad Add more steps to training Ad...
# sample code to use for the gold star challenge from https://www.tensorflow.org/get_started/get_started import numpy as np import tensorflow as tf # Model parameters W = tf.Variable([.3], dtype=tf.float32) b = tf.Variable([-.3], dtype=tf.float32) # Model input and output x = tf.placeholder(tf.float32) linear_model ...
codelab_3_tensorflow_nn.ipynb
thinkingmachines/deeplearningworkshop
mit
Joining two tables using edit distance measure typically consists of three steps: 1. Loading the input tables 2. Profiling the tables 3. Performing the join 1. Loading the input tables We begin by loading the two tables. For the purpose of this guide, we use the sample dataset that comes with the package.
# construct the path of the tables to be loaded. Since we are loading a # dataset from the package, we need to access the data from the path # where the package is installed. If you need to load your own data, you can directly # provide your table path to the read_csv command. table_A_path = os.sep.join([ssj.get_ins...
notebooks/Joining two tables using edit distance measure.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
For the purpose of this guide, we will now join tables A and B on 'name' attribute using edit distance measure. Next, we need to decide on what threshold to use for the join. For this guide, we will use a threshold of 5. Specifically, the join will now find tuple pairs from A and B such that the edit distance over ...
# find all pairs from A and B such that the edit distance # on 'name' is at most 5. # l_out_attrs and r_out_attrs denote the attributes from the # left table (A) and right table (B) that need to be included in the output. output_pairs = ssj.edit_distance_join(A, B, 'A.id', 'B.id', 'A.name', 'B.name', 5, ...
notebooks/Joining two tables using edit distance measure.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
Handling missing values By default, pairs with missing values are not included in the output. This is because a string with a missing value can potentially match with all strings in the other table and hence the number of output pairs can become huge. If you want to include pairs with missing value in the output, you...
output_pairs = ssj.edit_distance_join(A, B, 'A.id', 'B.id', 'A.name', 'B.name', 5, allow_missing=True, l_out_attrs=['A.name'], r_out_attrs=['B.name']) output_pairs
notebooks/Joining two tables using edit distance measure.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
Enabling parallel processing If you have multiple cores which you want to exploit for performing the join, you need to use the n_jobs option. If n_jobs is -1, all CPUs are used. If 1 is given, no parallel computing code is used at all, which is useful for debugging and is the default option. For n_jobs below -1, (n...
output_pairs = ssj.edit_distance_join(A, B, 'A.id', 'B.id', 'A.name', 'B.name', 5, l_out_attrs=['A.name'], r_out_attrs=['B.name'], n_jobs=-1) len(output_pairs)
notebooks/Joining two tables using edit distance measure.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
You need to set n_jobs to 1 when you are debugging or you do not want to use any parallel computing code. If you want to execute the join as fast as possible, you need to set n_jobs to -1 which will exploit all the CPUs in your machine. In case there are other concurrent processes running in your machine and you do...
ssj.dataframe_column_to_str(A, 'A.zipcode', inplace=True) ssj.dataframe_column_to_str(B, 'B.zipcode', inplace=True)
notebooks/Joining two tables using edit distance measure.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
Note that the above command preserves the NaN values while converting the numeric column to string type. Next, you can perform the join as shown below:
output_pairs = ssj.edit_distance_join(A, B, 'A.id', 'B.id', 'A.zipcode', 'B.zipcode', 1, l_out_attrs=['A.zipcode'], r_out_attrs=['B.zipcode']) output_pairs
notebooks/Joining two tables using edit distance measure.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
Additional options You can find all the options available for the edit distance join function using the help command as shown below:
help(ssj.edit_distance_join)
notebooks/Joining two tables using edit distance measure.ipynb
anhaidgroup/py_stringsimjoin
bsd-3-clause
Generator network Here we'll build the generator network. To make this network a universal function approximator, we'll need at least one hidden layer. We should use a leaky ReLU to allow gradients to flow backwards through the layer unimpeded. A leaky ReLU is like a normal ReLU, except that there is a small non-zero ...
def generator(z, out_dim, n_units=128, reuse=False, alpha=0.01): ''' Build the generator network. Arguments --------- z : Input tensor for the generator out_dim : Shape of the generator output n_units : Number of units in hidden layer reuse : Reuse the variables...
gan_mnist/Intro_to_GANs_Exercises.ipynb
ianhamilton117/deep-learning
mit
Discriminator The discriminator network is almost exactly the same as the generator network, except that we're using a sigmoid output layer. Exercise: Implement the discriminator network in the function below. Same as above, you'll need to return both the logits and the sigmoid output. Make sure to wrap your code in a...
def discriminator(x, n_units=128, reuse=False, alpha=0.01): ''' Build the discriminator network. Arguments --------- x : Input tensor for the discriminator n_units: Number of units in hidden layer reuse : Reuse the variables with tf.variable_scope alpha : leak pa...
gan_mnist/Intro_to_GANs_Exercises.ipynb
ianhamilton117/deep-learning
mit
Build network Now we're building the network from the functions defined above. First is to get our inputs, input_real, input_z from model_inputs using the sizes of the input and z. Then, we'll create the generator, generator(input_z, input_size). This builds the generator with the appropriate input and output sizes. Th...
tf.reset_default_graph() # Create our input placeholders input_real, input_z = model_inputs(input_size, z_size) # Generator network here g_model = generator(input_z, input_size, g_hidden_size, alpha=alpha) # g_model is the generator output # Disriminator network here d_model_real, d_logits_real = discriminator(input_...
gan_mnist/Intro_to_GANs_Exercises.ipynb
ianhamilton117/deep-learning
mit
Discriminator and Generator Losses Now we need to calculate the losses, which is a little tricky. For the discriminator, the total loss is the sum of the losses for real and fake images, d_loss = d_loss_real + d_loss_fake. The losses will by sigmoid cross-entropies, which we can get with tf.nn.sigmoid_cross_entropy_wit...
# Calculate losses d_labels_real = tf.ones_like(d_logits_real) * (1 - smooth) d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits_real, labels=d_labels_real)) d_labels_fake = tf.zeros_like(d_logits_fake) d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logi...
gan_mnist/Intro_to_GANs_Exercises.ipynb
ianhamilton117/deep-learning
mit
Optimizers We want to update the generator and discriminator variables separately. So we need to get the variables for each part and build optimizers for the two parts. To get all the trainable variables, we use tf.trainable_variables(). This creates a list of all the variables we've defined in our graph. For the gener...
# Optimizers learning_rate = 0.002 # Get the trainable_variables, split into G and D parts t_vars = tf.trainable_variables() g_vars = [var for var in t_vars if var.name.startswith("generator")] d_vars = [var for var in t_vars if var.name.startswith("discriminator")] g_train_opt = tf.train.AdamOptimizer(learning_rate)...
gan_mnist/Intro_to_GANs_Exercises.ipynb
ianhamilton117/deep-learning
mit
Let's see the number of rows in this dataset
df.shape
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
And the number of person,
df.Name.nunique()
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
Okay, so we know that each person represent one observation in this dataset. Let's see the distribution of age in this dataset.
df.Age.describe() df.Age.hist(bins=40) plt.xlabel("Age") plt.ylabel("Number of Person") plt.title("Histogram of Passenger Age");
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
I choose histogram since I only analyze one numerical variable. I choose 40 as nunmber of bins to let the histogram show smooth distribution of the data. And since we see from the statistics that the age is max at 80 years old, every 20 year will have the exact edge of the histogram. I can see from this histogram that ...
p = sns.violinplot(data = df, x = 'Survived', y = 'Age') p.set(title = 'Age Distribution by Survival', xlabel = 'Survival', ylabel = 'Age Distribution', xticklabels = ['Died', 'Survived']);
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
Now this is interesting. We can see that from violin plot, the distribution is a little bit different. I use violin plot because I can see the distribution of Age by Survived side by side. The distribution of the age shows bimodal distribution of people who survived. Many old people died from the tragedy, though we see...
df[(df.Survived == 1) & (df.Age == 80)]
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
To support the plot, I also include relevant statistics between Age and Survived.
df.groupby('Survived').Age.describe().unstack(level=0)
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
If we see from the statistics everything is similar. Children who died minimum is 1 years old, while babies who survive minimum at 5 months old. Again if I observe the plot, many children survived the accident, at least compared to the children who didn't. If you remember from Titanic movies, children and women are pri...
df['WomenChildren'] = np.where((df.Age <= 12) | (df.Sex == 'female'),1,0)
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
I'm using ChiSquare from Scipy library. This function has takes frequency table that I've created earlier, and then output chisquare statistic, p-value, degree of freedom, and the expected frequency table if both variables aren't related. Since for Survived is categorical and some of the variables also categorical, I c...
def compute_freq_chi2(x,y): """This function will compute frequency table of x an y Pandas Series, and use the table to feed for the contigency table Parameters: ------- x,y : Pandas Series, must be same shape for frequency table Return: ------- None. But prints out frequency t...
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
From the frequency table, we can see a magnitude difference of women and children that survived compared to those who didn't. Women and children survived is about 2.5 times higher than women and children whom not survived. On the contrary, adult men is about 5 times higher between not survived and survived. To be fair,...
(df['WomenChildren'] == df.Survived).mean()
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
There you go, I got 79.24% accuracy. Titanic was a massive ship. Again remembering the movie back then, rich and poor people get to the ship. I wonder how Titanic data required social economy status of passenger, which represented by Pclass. We could see if the fare vary across this variable.
df.groupby('Pclass').Fare.mean()
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
From this result, we see that there's huge price jump between upper class and middle/lower class! Although it's no surprise. I recall from the movie, upper class room is family room, and facilitated with a lot of fancy stuff. While in lower class (DiCaprio's room), people have to shared between other passengers. Perhap...
sns.barplot(x="Pclass",y="Fare",hue="Survived",data=df,estimator=np.mean) plt.ylabel("") plt.xlabel("Socio-Econmic Status") plt.title("Average fare for different SES");
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
Looking at this plot, I see something expected and unexpected. First the expected one, I see the average of fare of middle/lower is similar but the difference is huge when compared to the upper class. This is again, expected since earlier we have saw the number. The unexpected one, is whether survive vary in the upper ...
(df[(df.Pclass == 1)] .groupby([df.Cabin.str[:1],'Survived']) .Fare .mean() .unstack())
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit
We see from the table above, Cabin with prefix B is the most expensive one compared to ohers. Cabin C is probably the most expensive on average. But will this guarantee for whether the passengers survive?
(df[(df.Pclass == 1)] .groupby([df.Cabin.str[:1],'Survived']) .PassengerId .count() .unstack())
p2-introds/titanic/titanic.ipynb
napjon/ds-nd
mit