markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Create the labels vertices and link them to the segmentsWe're now going to create vertices to represent the labels in our graph and connect them to the 1min segments
def create_label_vertices(LabelDetectionOutput, video_name, g, confidence_threshold=80): labels = LabelDetectionOutput['Labels'] for instance in labels: #keeping only the labels with high confidence label_details_obj = instance['Label'] confidence = label_details_obj['Confidence'] ...
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] Let's list the labels vertices to see what was created above.Explanation: g.V() returns all vertices, .hasLabel(V_LABEL) returns only the vertices of label/type V_LABEL, .valueMap().limit(20).toList() gives us the list with properties for the first 20 items.
#retrieving a list of the first 20 labels label_list = g.V().hasLabel(V_LABEL).valueMap().limit(20).toList() label_list
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Let's display a graph with our video's labels and the child labels relationships in between labels.
print_graph(V_VIDEO, video_name, [E_HAS_LABEL, E_HAS_CHILD_LABEL], node_limit=15)
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] A typical query would be to search for videos who have a specific label.Explanation: g.V().has(V_LABEL, 'name', ..) returns the first label vertex from the previous computed list, .in_(E_HAS_LABEL) returns all vertices who have an incoming edge (inE) pointing to this label vertex, .valueMap().toList() returns t...
g.V().has(V_LABEL, 'name', label_list[0]['name'][0]).in_(E_HAS_LABEL).valueMap().toList()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Create the topics and associated topic terms verticesWe are going to re-arrange a bit the raw results from the topic modeling job to make it more readable
comprehend_topics_df.head()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
We extract the segment id/number from the docname column in a separate column, cast it to numeric values, drop the docname column and sort by segment_id
comprehend_topics_df['segment_id'] = comprehend_topics_df['docname'].apply(lambda x: x.split(':')[-1]) comprehend_topics_df['segment_id'] = pd.to_numeric(comprehend_topics_df['segment_id'], errors='coerce') comprehend_topics_df = comprehend_topics_df.drop('docname', axis=1) comprehend_topics_df = comprehend_topics_df.s...
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Looks better!Note that:- a segment_id can belong to several topics- proportion = the proportion of the document that is concerned with the topic Let's now create our topic vertices
def create_topic_vertices(topics_df, terms_df, video_name, g): #retrieve all segments for the video segments_vertex_list = g.V().has(V_VIDEO, 'name', video_name).out(E_HAS_SEGMENT).order().by('StartTimestampMillis', Order.asc).valueMap().toList() for index, row in topics_df.iterrows(): ...
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Let's display our video, few segments and their associated topics
#please note that we limit the number of nodes being displayed print_graph(V_VIDEO, video_name, [E_HAS_SEGMENT, E_HAS_TOPIC], node_limit=10)
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Let's display a partial graph showing relationships between the video -> segment -> topic -> term
print_graph(V_VIDEO, video_name, [E_HAS_SEGMENT, E_HAS_TOPIC, E_HAS_TERM], node_limit=20)
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] We're now listing all the segments that are in topic 2 (try different topic numbers if you want)Explanation: g.V().has(V_TOPIC, 'name', '2') returns the topic vertex with name=2, .in_(E_HAS_TOPIC) returns all vertices that have a edge pointing into that topic vertex, .valueMap().toList() returns the list of ite...
g.V().has(V_TOPIC, 'name', '2').in_(E_HAS_TOPIC).valueMap().toList()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Create the NER vertices and link them to the segments
#create the entity and entity_type vertices including the related edges def create_ner_vertices(ner_job_data, video_name, g, score_threshold=0.8): #retrieve all segments for the video segments_vertex_list = g.V().has(V_VIDEO, 'name', video_name).out(E_HAS_SEGMENT).order().by('StartTimestampMillis', Order.a...
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] Let's get a list of the first 20 entitiesExplanation: g.V().hasLabel(V_ENTITY) returns all vertices of label/type V_ENTITY, .valueMap().limit(20).toList() returns the list of the first 20 items with their properties (just name in that case).
entities_list = g.V().hasLabel(V_ENTITY).valueMap().limit(20).toList() entities_list
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] Let's now look up the first entity of the previous entities_list and check its typeExplanation: g.V().has(V_ENTITY, 'name', ...) return the first V_ENTITY vertex of the entities_list list, .out(E_IS_OF_ENTITY_TYPE) returns vertices connected to this V_ENTITY vertex by a E_IS_OF_ENTITY_TYPE edge.
g.V().has(V_ENTITY, 'name', entities_list[0]['name'][0]).out(E_IS_OF_ENTITY_TYPE).valueMap().toList()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] Let's see now which video segments contains that entityExplanation: g.V().has(V_ENTITY, 'name', ...) return the first V_ENTITY vertex of the entities_list list, .in_(E_HAS_ENTITY) returns all vertices that have an incoming edge into that V_ENTITY vertex and .valueMap().toList() returns the list with properties.
g.V().has(V_ENTITY, 'name', entities_list[0]['name'][0]).in_(E_HAS_ENTITY).valueMap().toList()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
[QUERY] Similar query but this time we traverse further the graph and only return the list of videos which have this specific entity.Explanation: g.V().has(V_ENTITY, 'name', ...) return the first V_ENTITY vertex of the entities_list list, .in_(E_HAS_ENTITY) returns the V_VIDEO_SEGMENT vertices that have an incoming edg...
g.V().has(V_ENTITY, 'name', entities_list[0]['name'][0]).in_(E_HAS_ENTITY).in_(E_HAS_SEGMENT).dedup().valueMap().toList()
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
Let's now display a graph showing the relationship between Video -> Segment -> Entity
print_graph(V_VIDEO, video_name, [E_HAS_SEGMENT, E_HAS_ENTITY], node_size=800, node_limit=30)
_____no_output_____
MIT-0
notebooks/part3-neptune-graph.ipynb
aws-samples/aws-video-metadata-knowledge-graph-workshop
**SQL DATA CLEANING, OUTLIERS AND ANALYTICS** **1. Connecting to our Database**
#loading the sql extension into our environment %load_ext sql # Then connect to our in memory sqlite database %sql sqlite://
_____no_output_____
MIT
SQL_WORLD_SUICIDE_ANALYTICS.ipynb
allanstar-byte/ESTRELLA
**2. Importing Data from CSV files** The dataset we will use contains suicide cases from different countries in the world with different generations, age groups and other factors as outlined below.
# Importing the pandas library # We will use a function read_csv from pandas to read our datasets as shown # import pandas as pd # Loading our table from the respective CSV files with open('/content/Suicide.csv','r') as f: Suicide = pd.read_csv(f, index_col=0, encoding='utf-8') %sql DROP TABLE if EXISTS Suicide %...
* sqlite:// Done. * sqlite:// * sqlite:// Done.
MIT
SQL_WORLD_SUICIDE_ANALYTICS.ipynb
allanstar-byte/ESTRELLA
**3. Analytics**
#1. identifying top 5 countries with the highest suicide cases in the world %%sql SELECT Country, SUM (Suicides_no) FROM Suicide GROUP BY Country ORDER BY SUM (Suicides_no) DESC limit 5; #2. identifying top 5 countries with the lowest suicide cases in the world %%sql SELECT Country, SUM (Suicides_no) FROM Suicide ...
* sqlite:// Done.
MIT
SQL_WORLD_SUICIDE_ANALYTICS.ipynb
allanstar-byte/ESTRELLA
Introduction to Python***Welcome to your first iPython Notebook.***![python](https://cognitiveclass.ai/wp-content/uploads/2016/10/Machine-Learning-with-Python.png) **About iPython Notebooks**iPython Notebooks are interactive coding environments embedded in a webpage. You will be using iPython notebooks in this class....
print("Hello Friend") print(30)
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Exercise 1.1:** Display "Batman is the best superhero" using print function.
### START CODE HERE ### (1 line of code) print("Batman is the best superhero") ### END CODE HERE ###
Batman is the best superhero
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Expected Output: **"Batman is the best superhero" Python Variables **Creating Variables :**Unlike other programming languages, Python has no command for declaring a variable.A variable is created the moment you first assign a value to it.**Example:**
x = 5 y = "Python" print(x) print(y)
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
Variables do not need to be declared with any particular type and can even change type after they have been set.
x = 4 # x is of type int y = "python" # x is now of type str print(x) print(y)
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Variable Names :**A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:* A variable name must start with a letter or the underscore character.* A variable name cannot start with a number.* A variable name can only contain alpha-numer...
### START CODE HERE ### (4 line of code) x = 10 y = "Hello there" print(x) print(y) ### END CODE HERE ###
10 Hello there
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Expected Output:**10Hello there **Exercise 1.3:**Create a variable called **z**, assign** x + y** to it, and display the result.
### START CODE HERE ### x = 5 y = 15 z = x + y print(z) ### END CODE HERE ###
20
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Expected output: ** 20 Python Numbers**There are three numeric types in Python:*** ** int*** ** float*** **complex** **Int **:Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
x = 1 y = 35656222554887711 z = -3255522 print(type(x)) # To verify the type of any object in Python, use the type() function print(type(y)) print(type(z))
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Float :**Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z))
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Complex :**Complex numbers are written with a "j" as the imaginary part.
x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z))
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Exercise 1.4:**Find whether E=3.4j is integer, float or complex.
### START CODE HERE ### (1 line of code) E=3.4j print(type(E)) ### END CODE HERE ###
<class 'complex'>
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Expected output:** class 'complex' Python Casting **Specify a Variable Type :**There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.Casting in pyt...
x = int(1) # x will be 1 y = int(2.8) # y will be 2 z = int("3") # z will be 3
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Floats:**
x = float(1) # x will be 1.0 y = float(2.8) # y will be 2.8 z = float("3") # z will be 3.0 w = float("4.2") # w will be 4.2
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Strings:**
x = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0'
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
Main advantage of type casting is you can print and integer and a string in the same line.**Example: **
a = " kingdoms in Westeros" b = str(7) print (b + a)
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Excercise 1.5:**Create a variable **x** and assign the integer 3 to it. Create another variable **y** and assign string '4' to it. Add both variables using **int** function.
### START CODE HERE ### (≈ 4 lines of code) x = 3 y = "4" z = x + int(y) print(z) ### END CODE HERE ###
7
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Expected Output:**7 Python Strings**String literals**:String literals in python are surrounded by either single quotation marks, or double quotation marks.'hello' is the same as "hello".Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. Square bracket...
a = "Hello, World!" print(a[1]) # Gets the character at position 1 (remember that the first character has the position 0) b = "Hello, World!" print(b[2:5]) #Gets the characters from position 2 to position 5 (not included)
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**The strip() method:**The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! " print(a.strip()) # returns "Hello, World!"
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**The len() method:**The len() method returns the length of a string
a = "Hello, World!" print(len(a))
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**The lower() method:**The lower() method returns the string in lower case
a = "Hello, World!" print(a.lower()) print(a) #Orignal value of a is not changed a=a.lower() #Orignal value of a is changed print(a)
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**The upper() method:**The upper() method returns the string in upper case
a = "Hello, World!" print(a.upper())
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**The replace() method :**The replace() method replaces a string with another string.
a = "Hello, World!" print(a.replace("H", "J"))
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**The split() method :**The split() method splits the string into substrings if it finds instances of the separator
a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!']
_____no_output_____
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Exercise 1.6:**Get the first character of the string **str** and print it.
### START CODE HERE ### (≈ 3 lines of code) str="Learning python" x = str[0] print(x) ### END CODE HERE ###
L
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Expected Output:**L **Exercise 1.7:**Get the characters from position 3 to position 8 (not included) using strinf slicing method and print it.
### START CODE HERE ### (≈ 3 lines of code) str="Learning python" x = str[3:8] print(x) ### END CODE HERE ###
rning
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
**Expected Output:**rning **Exercise 1.8:** For E="HELLO FRIENS" make the string lowercase, print, replace **s** by **d** and return the length of the string.
### START CODE HERE ### (≈ 4-5 lines of code) E = "HELLO FRIENS" E = E.lower() print(E) E = E.replace("s","d") print(E) print(len(E)) ### END CODE HERE ###
hello friens hello friend 12
MIT
Copy of 01-Python Intro(1).ipynb
manjeetchavhan15/python
Compute a sparse inverse solution using the Gamma-Map empirical Bayesian methodSee Wipf et al. "A unified Bayesian framework for MEG/EEG source imaging."NeuroImage, vol. 44, no. 3, pp. 947?66, Mar. 2009.
# Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu> # # License: BSD (3-clause) import numpy as np import mne from mne.datasets import sample from mne.inverse_sparse import gamma_map from mne.viz import plot_sparse_source_estimates print(__doc__) data_path = sample.data_path() subjects_dir = data_path + '/subject...
_____no_output_____
BSD-3-Clause
0.14/_downloads/plot_gamma_map_inverse.ipynb
drammock/mne-tools.github.io
Introducción **Contexto comercial.** Usted es un analista en una entidad bancaria, y se le proporciona un conjunto de datos de los clientes. Su jefe le pide que analice la información para determinar si existen similaridades entre grupos de clientes para lanzar una campaña de mercadeo.**Problema comercial.** Su tarea...
import matplotlib.pyplot as plt import numpy as np import pandas as pd import scipy import seaborn as sns import sklearn # Paquete base de ML from scipy.stats import norm from sklearn.cluster import KMeans from sklearn.preprocessing import MinMaxScaler, MaxAbsScaler, RobustScaler, StandardScaler %matplotlib inline ur...
_____no_output_____
MIT
Taller_semana_7.ipynb
AngieCat26/MujeresDigitales
Ejercicio 1:Realice una normalización de los datos numéricos es decir que los valores oscilen entre 0 y 1 en las columnas annual_inc y loan_amnt.Consejo: antes de realizar la normalización asegúrese de que el tipo de dichas columnas si sea numérico.
# Escriba aquí su codigo def normalize(df): resultado = df.copy() for normalizado in df.columns: max = df[normalizado].max() min = df[normalizado].min() resultado[normalizado] = (df[normalizado] - min) / (max - min) return resultado df_normalizado = normalize(df[['annual_inc', 'loan_amnt']]) df_norm...
_____no_output_____
MIT
Taller_semana_7.ipynb
AngieCat26/MujeresDigitales
Ejercicio 2:Emplee el algoritmo de k-means para agrupar a los clientes usando un número de clusters de 4.
# Escriba aquí su codigo k = 4 kmeans = KMeans(n_clusters = k, init='k-means++') kmeans.fit(df_normalizado) labels = kmeans.predict(df_normalizado) centroids = kmeans.cluster_centers_ centroids
_____no_output_____
MIT
Taller_semana_7.ipynb
AngieCat26/MujeresDigitales
Ejercicio 3 (Opcional):Realice un gráfico de dispersión (scatter) para vizualizar los cluster que descubrió en el punto anterior (ejercicio 2). Usando colores diferentes para identificar los 4 cluster.
# Escriba aquí su codigo plt.figure(figsize=(6, 6)) color_map = {1:'r', 2:'g', 3:'b' , 4:'c'} colors = [color_map[x+1] for x in labels] plt.scatter(df_normalizado['annual_inc'], df_normalizado['loan_amnt'], color=colors, alpha=0.4, edgecolor='k') for idx, centroid in enumerate(centroids): plt.scatter(*centroid, ma...
_____no_output_____
MIT
Taller_semana_7.ipynb
AngieCat26/MujeresDigitales
Ejercicio 4 (Opcional):Use el método del codo para verificar cual es el número de clusters óptimo. Revise desde 1 clúster hasta 11 para realizar esta validación.
# Escriba aquí su codigo sum_sq_d = [] K = range(1, 11) for k in K: km = KMeans(n_clusters = k) km = km.fit(df_normalizado[['annual_inc', 'loan_amnt']]) sum_sq_d.append(km.inertia_) plt.figure(figsize=(8,6)) plt.plot(K, sum_sq_d, 'rx-.') plt.xlabel('Numero de Clusters, k', fontsize=12) plt.xticks(range(1,11), fon...
_____no_output_____
MIT
Taller_semana_7.ipynb
AngieCat26/MujeresDigitales
Hands On: Seleksi Fitur Seleksi fitur (feature selection) adalah proses memilih feature yang tepat untuk melatih model ML. Untuk melakukan feature selection, kita perlu memahami hubungan antara variables.Hubungan antar dua random variables disebut correlation dan dapat dihitung dengan menggunakan correlation coefficie...
import pandas as pd import numpy as np from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 data = pd.read_csv("train.csv") X = data.iloc[:,0:20] #independent colums y = data.iloc[:,-1] # target colum i.e price range # apply SelectKBest class to extract bestfeatures = Sel...
Specs Score 13 ram 931267.519053 11 px_height 17363.569536 0 battery_power 14129.866576 12 px_width 9810.586750 8 mobile_wt 95.972863 6 int_memory 89.839124 15 sc_w 16.480319 16 talk_time 13.236400 4 fc ...
MIT
Pertemuan 7/Seleksi_Fitur.ipynb
DiendaRHR/Metodologi-Data-Science
2. Feature Importance---*Feature importance* mengacu pada kelas teknik untuk menetapkan skor ke fitur input ke model prediktif yang menunjukkan *importance* relatif dari setiap fitur saat membuat prediksi.Skor *Feature importance* dapat dihitung untuk masalah yang melibatkan prediksi nilai numerik, yang disebut regres...
import pandas as pd import numpy as np data = pd.read_csv("train.csv") X = data.iloc[:,0:20] #independent columns y = data.iloc[:,-1] #target column i.e price range from sklearn.ensemble import ExtraTreesClassifier import matplotlib.pyplot as plt model = ExtraTreesClassifier() model.fit(X,y) print(model.feature_...
[0.06211811 0.01976522 0.03262347 0.01943255 0.0312432 0.01696415 0.03540888 0.0328172 0.03525155 0.03272211 0.03170136 0.04648436 0.04934521 0.40406817 0.03209748 0.03192379 0.03393193 0.01437244 0.01841761 0.0193112 ]
MIT
Pertemuan 7/Seleksi_Fitur.ipynb
DiendaRHR/Metodologi-Data-Science
3. Matriks Korelasi dengan Heatmap---* Korelasi menyatakan bagaimana fitur terkait satu sama lain atau variabel target.* Korelasi bisa positif (kenaikan satu nilai fitur meningkatkan nilai variabel target) atau negatif (kenaikan satu nilai fitur menurunkan nilai variabel target)* Heatmap memudahkan untuk mengidentifik...
import pandas as pd import numpy as np import seaborn as sns data = pd.read_csv("train.csv") X = data.iloc[:,0:20] #independent columns y = data.iloc[:,-1] #target column i.e price range #get correlations of each features in dataset corrmat = data.corr() top_corr_features = corrmat.index plt.figure(figsize=(20,2...
_____no_output_____
MIT
Pertemuan 7/Seleksi_Fitur.ipynb
DiendaRHR/Metodologi-Data-Science
Your first neural networkIn this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and th...
%matplotlib inline %load_ext autoreload %autoreload 2 %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt
The autoreload extension is already loaded. To reload it, use: %reload_ext autoreload
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Load and prepare the dataA critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon!
data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head()
_____no_output_____
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Checking out the dataThis dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the `cnt` column. You can see the first few rows of the data above.Below is a plot showing the number of bike riders ov...
rides[:24*10].plot(x='dteday', y='cnt')
_____no_output_____
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Dummy variablesHere we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to `get_dummies()`.
dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday'] for each in dummy_fields: dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False) rides = pd.concat([rides, dummies], axis=1) fields_to_drop = ['instant', 'dteday', 'season', 'weathersit', 'weekday', 'atemp', 'mnth...
_____no_output_____
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Scaling target variablesTo make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.The scaling factors are saved so we can go backwards when we use the network for predictions.
quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed'] # Store scalings in a dictionary so we can convert back later scaled_features = {} for each in quant_features: mean, std = data[each].mean(), data[each].std() scaled_features[each] = [mean, std] data.loc[:, each] = (data[each] - me...
_____no_output_____
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Splitting the data into training, testing, and validation setsWe'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders.
# Save data for approximately the last 21 days test_data = data[-21*24:] # Now remove the test data from the data set data = data[:-21*24] # Separate the data into features and targets target_fields = ['cnt', 'casual', 'registered'] features, targets = data.drop(target_fields, axis=1), data[target_fields] test_feat...
_____no_output_____
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set).
# Hold out the last 60 days or so of the remaining data as a validation set train_features, train_targets = features[:-60*24], targets[:-60*24] val_features, val_targets = features[-60*24:], targets[-60*24:]
_____no_output_____
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Time to build the networkBelow you'll build your network. We've built out the structure. You'll implement both the forward pass and backwards pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.The network has two layers, a hid...
############# # In the my_answers.py file, fill out the TODO sections as specified ############# def MSE(y, Y): return np.mean((y-Y)**2)
_____no_output_____
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Unit testsRun these unit tests to check the correctness of your network implementation. This will help you be sure your network was implemented correctly befor you starting trying to train it. These tests must all be successful to pass the project.
from my_answers import NeuralNetwork import unittest inputs = np.array([[0.5, -0.2, 0.1]]) targets = np.array([[0.4]]) test_w_i_h = np.array([[0.1, -0.2], [0.4, 0.5], [-0.3, 0.2]]) test_w_h_o = np.array([[0.3], [-0.1]]) class TestMethods(unittest.T...
..... ---------------------------------------------------------------------- Ran 5 tests in 0.004s OK
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Training the networkHere you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se...
import sys #################### ### Set the hyperparameters in you myanswers.py file ### #################### from my_answers import iterations, learning_rate, hidden_nodes, output_nodes N_i = train_features.shape[1] network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate) losses = {'train':[], 'val...
_____no_output_____
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Check out your predictionsHere, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly.
fig, ax = plt.subplots(figsize=(8,4)) mean, std = scaled_features['cnt'] predictions = network.run(test_features).T*std + mean ax.plot(predictions[0], label='Prediction') ax.plot((test_targets['cnt']*std + mean).values, label='Data') ax.set_xlim(right=len(predictions)) ax.legend() dates = pd.to_datetime(rides.loc[tes...
_____no_output_____
MIT
Predicting_bike_sharing_data.ipynb
gwillig/bikesharing
Lab 2 - Plotting Vector using NumPy and MatPlotLib In this laboratory we will be disucssin the basics of numerical and scientific programming by working with Vectors using NumPy and MatPlotLib. ObjectivesAt the end of this activity you will be able to:1. Be familiar with the libraries in Python for numerical and sci...
import numpy as np x = np.array(-0.5) x
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
*Vectors* Vectors are array of numerical values or scalars that would represent any feature space. Feature spaces or simply dimensions or the parameters of an equation or a function. *Representing Vectors* Now that you know how to represent vectors using their component and matrix form we can now hard-code them in Py...
A = np.array([4,3]) B = np.array([2, -5]) print('Vector A is ', A) print('Vector B is ', B)
Vector A is [4 3] Vector B is [ 2 -5]
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
Describing vectors in NumPy Describing vectors is very important if we want to perform basic to advanced operations with them. The fundamental ways in describing vectors are knowing their shape, size and dimensions.
### Checking shapes ### Shapes tells us how many rows and columns are there ball1 = np.array([1,2,3]) ball2 = np.array([0,1,-1]) pool = np.array([J,K]) ## Matrix pool.shape U = np.array([ [1, 2], [2, 3] ]) U.shape ### Checking size ### Array/Vector sizes tells us many total number of elements are there in the v...
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
Great! Now let's try to explore in performing operations with these vectors. Addition The addition rule is simple, the we just need to add the elements of the matrices according to their index. So in this case if we add vector $A$ and vector $B$ we will have a resulting vector: $$R = 6\hat{x}-2\hat{y} \\ \\or \\ \\ R ...
position1 = np.array([0, 0, 0]) position2 = np.array([1, 1, 0]) position3 = np.array([-1, 2, 0]) position4 = np.array([2, 5, 3]) R = position1 + position2 + position3 + position4 #Eager execution R R1 = np.add(position1,position2) #functional method R2 = np.add(R1,position3) R3 = np.add(R2,position4) R3 Rm = np.mul...
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
Try for yourself! Try to implement subtraction and division with vectors $A$ and $B$!
### Try out you code here! Don't forget to take a screenshot or a selfie!
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
$$W = \hat{x} + \hat{y}\\T = -2\hat{x} -3\hat{y}\\R3 = W + (T*-W)$$
W = np.array([1, 1]) T = np.array([-2, -3]) # R3 = np.add(W,np.multiply(T,np.multiply(-1,W))) R3 = W + (T*(-1*W)) R3
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
Scaling Scaling or scalar multiplication takes a scalar value and performs multiplication with a vector. Let's take the example below: $$S = 5 \cdot A$$ We can do this in numpy through:
A = np.array([1,5,8,9]) S = 5*A S S = np.multiply(5,A) S
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
$$R = 3X - Y\\X = \hat{x} + \hat{y} , Y = 2\hat{x} - 3\hat{y}$$
X = np.array([1, 1]) Y = np.array([2, -3]) R = np.subtract(np.multiply(3,X),Y) ## functional method # R = 3*X - Y R
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
MatPlotLib MatPlotLib or MATLab Plotting library is Python's take on MATLabs plotting feature. MatPlotLib can be used vastly from graping values to visualizing several dimensions of data. Visualizing Data It's not enough just sloving these vectors so might need to visualize them. So we'll use MatPlotLib for that. We'...
import matplotlib.pyplot as plt ## use this one if not in jupyterlab/notebook # from matplotlib import pyplot as plt import matplotlib
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
![image](https://matplotlib.org/3.1.0/_images/sphx_glr_named_colors_003.png)
A = [2,-1] B = [5,2] plt.scatter(A[0],A[1], label='A', c='magenta') plt.scatter(B[0],B[1], label='B', c='mediumspringgreen') plt.grid() plt.legend() plt.show() A = np.array([-5,0]) B = np.array([0,5]) plt.title("Resultant Vector\nMagnitude:{:.2f}".format(R_mag)) plt.xlim(-15, 15) plt.ylim(-15, 15) # print(B) ...
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
$\sqrt{A^2+B^2+C^2}$
R R_mag = np.sqrt(np.sum(A**2+B**2)) ##Euclidean Distance / Euclidean Norm rise = R[1] run = R[0] slope = rise/run slope ## angle of the vector? arctan(rise/run)
_____no_output_____
Apache-2.0
Week 2 - Intro to Vectors and Numpy/LinAlg_Lab_2.ipynb
bryanpioloEspanol/linearAlgebra2021
Now let's find the best threshold for our requirements.Precision needs to be at least 0.5, and recall has to be as max as possible.It's usually true that the bigger is precision, the lower is the recall. So we need to find the threshold that coresponds to precision = 0.5
proba = pipeline.predict_proba(X_test) precision, recall, thresholds = precision_recall_curve(y_test, proba[:, 1]) print(len(precision), len(recall), len(thresholds)) # according to documentation, precision and recall # have 1 and 0 at the end, so we should remove them before plotting. precision = precision[:-1] recall...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/original_model.ipynb
LDSSA/batch4-students
Red line shows the point where precision is equal 0.5. It looks like the biggest recall for precision >= 0.5 is around 0.2Let's find the exact value.
min_index = [i for i, prec in enumerate(precision) if prec >= 0.5][0] print(min_index) precision[min_index] recall[min_index] thresholds[min_index] best_preds = [1 if pred > thresholds[min_index] else 0 for pred in proba[:, 1]] verify_success_rate_above(y_test, best_preds) verify_amount_found(y_test, best_preds) with o...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/original_model.ipynb
LDSSA/batch4-students
Parsing InputsIn the chapter on [Grammars](Grammars.ipynb), we discussed how grammars can beused to represent various languages. We also saw how grammars can be used togenerate strings of the corresponding language. Grammars can also perform thereverse. That is, given a string, one can decompose the string into itscon...
from bookutils import YouTubeVideo YouTubeVideo('2yS9EfBEirE')
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
**Prerequisites*** You should have read the [chapter on grammars](Grammars.ipynb).* An understanding of derivation trees from the [chapter on grammar fuzzer](GrammarFuzzer.ipynb) is also required. SynopsisTo [use the code provided in this chapter](Importing.ipynb), write```python>>> from fuzzingbook.Parser import ```...
import bookutils from typing import Dict, List, Tuple, Collection, Set, Iterable, Generator, cast from Fuzzer import Fuzzer # minor dependendcy from Grammars import EXPR_GRAMMAR, START_SYMBOL, RE_NONTERMINAL from Grammars import is_valid_grammar, syntax_diagram, Grammar from GrammarFuzzer import GrammarFuzzer, display...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Why Parsing for Fuzzing? Why would one want to parse existing inputs in order to fuzz? Let us illustrate the problem with an example. Here is a simple program that accepts a CSV file of vehicle details and processes this information.
def process_inventory(inventory): res = [] for vehicle in inventory.split('\n'): ret = process_vehicle(vehicle) res.extend(ret) return '\n'.join(res)
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
The CSV file contains details of one vehicle per line. Each row is processed in `process_vehicle()`.
def process_vehicle(vehicle): year, kind, company, model, *_ = vehicle.split(',') if kind == 'van': return process_van(year, company, model) elif kind == 'car': return process_car(year, company, model) else: raise Exception('Invalid entry')
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Depending on the kind of vehicle, the processing changes.
def process_van(year, company, model): res = ["We have a %s %s van from %s vintage." % (company, model, year)] iyear = int(year) if iyear > 2010: res.append("It is a recent model!") else: res.append("It is an old but reliable model!") return res def process_car(year, company, model):...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Here is a sample of inputs that the `process_inventory()` accepts.
mystring = """\ 1997,van,Ford,E350 2000,car,Mercury,Cougar\ """ print(process_inventory(mystring))
We have a Ford E350 van from 1997 vintage. It is an old but reliable model! We have a Mercury Cougar car from 2000 vintage. It is an old but reliable model!
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Let us try to fuzz this program. Given that the `process_inventory()` takes a CSV file, we can write a simple grammar for generating comma separated values, and generate the required CSV rows. For convenience, we fuzz `process_vehicle()` directly.
import string CSV_GRAMMAR: Grammar = { '<start>': ['<csvline>'], '<csvline>': ['<items>'], '<items>': ['<item>,<items>', '<item>'], '<item>': ['<letters>'], '<letters>': ['<letter><letters>', '<letter>'], '<letter>': list(string.ascii_letters + string.digits + string.punctuation + ' \t\n') }
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
We need some infrastructure first for viewing the grammar.
syntax_diagram(CSV_GRAMMAR)
start
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
We generate `1000` values, and evaluate the `process_vehicle()` with each.
gf = GrammarFuzzer(CSV_GRAMMAR, min_nonterminals=4) trials = 1000 valid: List[str] = [] time = 0 for i in range(trials): with Timer() as t: vehicle_info = gf.fuzz() try: process_vehicle(vehicle_info) valid.append(vehicle_info) except: pass time += ...
0 valid strings, that is GrammarFuzzer generated 0.000000% valid entries from 1000 inputs Total time of 5.692460 seconds
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
This is obviously not working. But why?
gf = GrammarFuzzer(CSV_GRAMMAR, min_nonterminals=4) trials = 10 time = 0 for i in range(trials): vehicle_info = gf.fuzz() try: print(repr(vehicle_info), end="") process_vehicle(vehicle_info) except Exception as e: print("\t", e) else: print()
'9w9J\'/,LU<"l,|,Y,Zv)Amvx,c\n' Invalid entry '(n8].H7,qolS' not enough values to unpack (expected at least 4, got 2) '\nQoLWQ,jSa' not enough values to unpack (expected at least 4, got 2) 'K1,\n,RE,fq,%,,sT+aAb' Invalid entry "m,d,,8j4'),-yQ,B7" Invalid entry 'g4,s1\t[}{.,M,<,\nzd,.am' Invalid entry ',Z[,z,c,#x1...
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
None of the entries will get through unless the fuzzer can produce either `van` or `car`.Indeed, the reason is that the grammar itself does not capture the complete information about the format. So here is another idea. We modify the `GrammarFuzzer` to know a bit about our format.
import copy import random class PooledGrammarFuzzer(GrammarFuzzer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._node_cache = {} def update_cache(self, key, values): self._node_cache[key] = values def expand_node_randomly(self, node): (symbol...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Let us try again!
gf = PooledGrammarFuzzer(CSV_GRAMMAR, min_nonterminals=4) gf.update_cache('<item>', [ ('<item>', [('car', [])]), ('<item>', [('van', [])]), ]) trials = 10 time = 0 for i in range(trials): vehicle_info = gf.fuzz() try: print(repr(vehicle_info), end="") process_vehicle(vehicle_info) ex...
',h,van,|' Invalid entry 'M,w:K,car,car,van' Invalid entry 'J,?Y,van,van,car,J,~D+' Invalid entry 'S4,car,car,o' invalid literal for int() with base 10: 'S4' '2*-,van' not enough values to unpack (expected at least 4, got 2) 'van,%,5,]' Invalid entry 'van,G3{y,j,h:' Invalid entry '$0;o,M,car,car' Invalid entry ...
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
At least we are getting somewhere! It would be really nice if _we could incorporate what we know about the sample data in our fuzzer._ In fact, it would be nice if we could _extract_ the template and valid values from samples, and use them in our fuzzing. How do we do that? The quick answer to this question is: Use a ...
def simple_parse_csv(mystring: str) -> DerivationTree: children: List[DerivationTree] = [] tree = (START_SYMBOL, children) for i, line in enumerate(mystring.split('\n')): children.append(("record %d" % i, [(cell, []) for cell in line.split(',')])) retur...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
We also change the default orientation of the graph to *left to right* rather than *top to bottom* for easier viewing using `lr_graph()`.
def lr_graph(dot): dot.attr('node', shape='plain') dot.graph_attr['rankdir'] = 'LR'
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
The `display_tree()` shows the structure of our CSV file after parsing.
tree = simple_parse_csv(mystring) display_tree(tree, graph_attr=lr_graph)
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
This is of course simple. What if we encounter slightly more complexity? Again, another example from the Wikipedia.
mystring = '''\ 1997,Ford,E350,"ac, abs, moon",3000.00\ ''' print(mystring)
1997,Ford,E350,"ac, abs, moon",3000.00
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
We define a new annotation method `highlight_node()` to mark the nodes that are interesting.
def highlight_node(predicate): def hl_node(dot, nid, symbol, ann): if predicate(dot, nid, symbol, ann): dot.node(repr(nid), dot_escape(symbol), fontcolor='red') else: dot.node(repr(nid), dot_escape(symbol)) return hl_node
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Using `highlight_node()` we can highlight particular nodes that we were wrongly parsed.
tree = simple_parse_csv(mystring) bad_nodes = {5, 6, 7, 12, 13, 20, 22, 23, 24, 25} def hl_predicate(_d, nid, _s, _a): return nid in bad_nodes highlight_err_node = highlight_node(hl_predicate) display_tree(tree, log=False, node_attr=highlight_err_node, graph_attr=lr_graph)
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
The marked nodes indicate where our parsing went wrong. We can of course extend our parser to understand quotes. First we define some of the helper functions `parse_quote()`, `find_comma()` and `comma_split()`
def parse_quote(string, i): v = string[i + 1:].find('"') return v + i + 1 if v >= 0 else -1 def find_comma(string, i): slen = len(string) while i < slen: if string[i] == '"': i = parse_quote(string, i) if i == -1: return -1 if string[i] == ',': ...
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
We can update our `parse_csv()` procedure to use our advanced quote parser.
def parse_csv(mystring): children = [] tree = (START_SYMBOL, children) for i, line in enumerate(mystring.split('\n')): children.append(("record %d" % i, [(cell, []) for cell in comma_split(line)])) return tree
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
Our new `parse_csv()` can now handle quotes correctly.
tree = parse_csv(mystring) display_tree(tree, graph_attr=lr_graph)
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
That of course does not survive long:
mystring = '''\ 1999,Chevy,"Venture \\"Extended Edition, Very Large\\"",,5000.00\ ''' print(mystring)
1999,Chevy,"Venture \"Extended Edition, Very Large\"",,5000.00
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook
A few embedded quotes are sufficient to confuse our parser again.
tree = parse_csv(mystring) bad_nodes = {4, 5} display_tree(tree, node_attr=highlight_err_node, graph_attr=lr_graph)
_____no_output_____
MIT
docs/notebooks/Parser.ipynb
cn-fairy/fuzzingbook