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
Flow Control Control flow statements help you to structure the code and direct it towards your convenience and introduce loops and so on. If statements
price = -5; if price <0: print("Price is negative!") elif price <1: print("Price is too small!") else: print("Price is suitable.")
Price is negative!
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Especially in text mining, comparing strings is very important:
#Comparing strings name1 = "edinburgh" name2 = "Edinburgh" if name1 == name2: print("Equal") else: print("Not equal") if name1.lower() == name2.lower(): print("Equal") else: print("Not equal")
Not equal Equal
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Using multiple conditions:
number = 9 if number > 1 and not number > 9: print("Number is between 1 and 10") number = 9 name = 'johannes' if number < 5 or 'j' in name: print("Number is lower than 5 or the name contains a 'j'")
Number is between 1 and 10 Number is lower than 5 or the name contains a 'j'
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
While loops
number = 4 while number > 1: print(number) number = number -1
4 3 2
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
For loops For loops allow you to iteratre over elements in a certain collection, for example a list:
# We'll look into lists in a minute number_list = [1, 2, 3, 4] for item in number_list: print(item) list = ['a', 'b', 'c'] for item in list: print(item)
a b c
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Ranges are also useful. Note that the upper element is not included and we can adjust the step size:
for i in range(1,4): print(i) for i in range(30,100, 10): print(i)
30 40 50 60 70 80 90
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Indentation Please be very careful with indentation
number_1 = 3 number_2 = 5 print('No indent (no tabs used)') if number_1 > 1: print('\tNumber 1 higher than 1.') if number_2 > 5: print('\t\tnumber 2 higher than 5') print('\tnumber 2 higher than 5') number_1 = 3 number_2 = 6 print('No indent (no tabs used)') if number_1 > 1: print('\tNumber 1...
No indent (no tabs used) Number 1 higher than 1. number 2 higher than 5 No indent (no tabs used) Number 1 higher than 1. number 2 higher than 5 number 2 higher than 5
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
List & Tuple Lists Lists are great for collecting anything. They can contain objects of different types. For example:
names = [5, "Giovanni", "Rose", "Yongzhe", "Luciana", "Imani"]
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Although that is not best practice. Let's start with a list of names:
names = ["Johannes", "Giovanni", "Rose", "Yongzhe", "Luciana", "Imani"] # Loop names for name in names: print('Name: '+name) # Get 'Giovanni' from list # Lists start counting at 0 giovanni = names[1] print(giovanni.upper()) # Get last item name = names[-1] print(name.upper()) # Get second to last item name = nam...
Name: Johannes Name: Giovanni Name: Rose Name: Yongzhe Name: Luciana Name: Imani GIOVANNI IMANI LUCIANA First three: ['Johannes', 'Giovanni', 'Rose'] First four: ['Johannes', 'Giovanni', 'Rose', 'Yongzhe'] Up until the second to last one: ['Johannes', 'Giovanni', 'Rose', 'Yongzhe'] Last two: ['Luciana', 'Imani']
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Enumeration We can enumerate collections/lists that adds an index to every element:
for index, name in enumerate(names): print(str(index) , " " , name, " is in the list.")
0 Johannes is in the list. 1 Giovanni is in the list. 2 Rose is in the list. 3 Yongzhe is in the list. 4 Luciana is in the list. 5 Imani is in the list.
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Searching and editing
names = ["Johannes", "Giovanni", "Rose", "Yongzhe", "Luciana", "Imani"] # Finding an element print(names.index("Johannes")) # Adding an element names.append("Kumiko") # Adding an element at a specific location names.insert(2, "Roberta") print(names) #Removal fruits = ["apple","orange","pear"] del fruits[0] fruits....
0 ['Johannes', 'Giovanni', 'Roberta', 'Rose', 'Yongzhe', 'Luciana', 'Imani', 'Kumiko'] Fruits: ['orange'] ['Johannes', 'Giovanni', 'Roberta', 'Rose', 'Yongzhe', 'Tom', 'Imani', 'Kumiko'] True Length of the list: 8
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Python starts at 0!!! Sorting and copying
# Temporary sorting: print(sorted(names)) print(names) # Make changes permanent names.sort() print("Sorted names: " + str(names)) names.sort(reverse=True) print("Reverse sorted names: " + str(names)) # Copying list (a shallow copy just duplicates the pointer to the memory address) namez = names namez.remove("Johannes"...
['Yongzhe', 'Tom', 'Rose', 'Roberta', 'Kumiko', 'Imani', 'Giovanni'] ['Yongzhe', 'Tom', 'Rose', 'Roberta', 'Kumiko', 'Imani', 'Giovanni'] After deep copy ['Yongzhe', 'Tom', 'Rose', 'Roberta', 'Kumiko', 'Imani'] ['Yongzhe', 'Tom', 'Rose', 'Roberta', 'Kumiko', 'Imani', 'Giovanni'] ['Yongzhe', 'Tom', 'Rose', 'Roberta', 'K...
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Strings as lists Strings can be manipulated and used just like lists. This is especially handy in text mining:
course = "Predictive analytics" print("Last nine letters: "+course[-9:]) print("Analytics in course title? " + str("analytics" in course)) print("Start location of 'analytics': " + str(course.find("analytics"))) print(course.replace("analytics","analysis")) list_of_words = course.split(" ") for index, word in enumerate...
Last nine letters: analytics Analytics in course title? True Start location of 'analytics': 11 Predictive analysis Word 0 : Predictive Word 1 : analytics
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Sets Sets only contain unique elements. They have to be declared upfront using set() and allow for operations such as intersection():
name_set = set(names) print(name_set) # Add an element name_set.add("Galina") print(name_set) # Discard an element name_set.discard("Johannes") print(name_set) name_set2 = set(["Rose", "Tom"]) # Difference and intersection difference = name_set - name_set2 print(difference) intersection = name_set.intersection(name_...
{'Yongzhe', 'Kumiko', 'Roberta', 'Giovanni', 'Tom', 'Imani', 'Rose'} {'Yongzhe', 'Kumiko', 'Roberta', 'Giovanni', 'Tom', 'Imani', 'Galina', 'Rose'} {'Yongzhe', 'Kumiko', 'Roberta', 'Giovanni', 'Tom', 'Imani', 'Galina', 'Rose'} {'Yongzhe', 'Kumiko', 'Roberta', 'Giovanni', 'Imani', 'Galina'} {'Tom', 'Rose'}
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Dictionary & Function Dictionaries Dictionaries are a great way to store particular data as key-value pairs, which mimics the basic structure of a simple database.
courses = {"Johannes" : "Predictive analytics", "Kumiko" : "Prescriptive analytics", "Luciana" : "Descriptive analytics"} for organizer in courses: print(organizer + " teaches " + courses[organizer])
Johannes teaches Predictive analytics Kumiko teaches Prescriptive analytics Luciana teaches Descriptive analytics
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
We can also write:
for organizer, course in courses.items(): print(organizer + " teaches " + course) # Adding items courses["Imani"] = "Other analytics" print(courses) # Overwrite courses["Johannes"] = "Business analytics" print(courses) # Remove del courses["Johannes"] print(courses) # Looping values for course in courses.values():...
Imani teaches Other analytics Kumiko teaches Prescriptive analytics Luciana teaches Descriptive analytics
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Functions Functions form the backbone of all code. You have already used some, like print(). They can be easily defined by yourself as well.
def my_function(a, b): a = a.title() b = b.upper() print(a+ " "+b) def my_function2(a, b): a = a.title() b = b.upper() return a + " " + b my_function("johannes","de smedt") output = my_function2("johannes","de smedt") print(output)
Johannes DE SMEDT Johannes DE SMEDT
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Notice how the first function already prints, while the second returns a string we have to print ourselves. Python is weakly-typed, so a function can produce different results, like in this example:
# Different output type def calculate_mean(a, b): if (a>0): return (a+b)/2 else: return "a is negative" output = calculate_mean(1,2) print(output) output = calculate_mean(0,1) print(output)
1.5 a is negative
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Comprehensions Comprehensions allow you to quickly/efficiently write lists/dictionaries:
# Finding even numbers evens = [i for i in range(1,11) if i % 2 ==0] print(evens)
[2, 4, 6, 8, 10]
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
In Python, you can easily make tuples such as pairs, like here:
# Double fun pairs = [(x,y) for x in range(1,11) for y in range(5,11) if x>y] print(pairs)
[(6, 5), (7, 5), (7, 6), (8, 5), (8, 6), (8, 7), (9, 5), (9, 6), (9, 7), (9, 8), (10, 5), (10, 6), (10, 7), (10, 8), (10, 9)]
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
They are also useful to perform some pre-processing, e.g., on strings:
# Operations names = ["jamal", "maurizio", "johannes"] titled_names = [name.title() for name in names] print(titled_names) j_s = [name.title() for name in names if name.lower()[0] == 'j'] print(j_s)
['Jamal', 'Maurizio', 'Johannes'] ['Jamal', 'Johannes']
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
IO & Library
# Download some datasets # If you are using git, then you don't need to run the following. !wget -q https://raw.githubusercontent.com/Magica-Chen/WebSNA-notes/main/Week0/data/DM_1.csv !wget -q https://raw.githubusercontent.com/Magica-Chen/WebSNA-notes/main/Week0/data/DM_2.csv !wget -q https://raw.githubusercontent.com/...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Reading files In Python, we can easily open any file type. Naturally, it is most suitable for plainly-structured formats such as .txt., .csv., as so on. You can also open Excel files with appropriate packages, such as pandas (more on this later). Let's read in a .csv file:
# Open a file for reading ('r') file = open('data/DM_1.csv','r') for line in file: print(line)
Name,Email,City,Salary Brent Hopkins,Cum.sociis.natoque@aodiosemper.edu,Mount Pearl,38363 Colt Bender,Vivamus.non.lorem@Proin.org,Castle Douglas,21506 Arthur Hammond,nisl.Maecenas@sed.net,Biloxi,27511 Sean Warner,enim.nisl.elementum@Vivamus.edu,Moere,25201 Tate Greene,velit.justo.nec@aliquetlobortisnisi.edu,Ipswic...
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
We can store this information in objects and start using it:
# File is looped now, hence, reread file file = open('data/DM_1.csv','r') # ignore the header next(file) # Store names with amount (i.e. columns 1 & 2) amount_per_person = {} for line in file: cells = line.split(",") amount_per_person[cells[0]] = int(cells[3]) for person, amount in sorted(amount_per_person.it...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Libraries Libraries are imported by using `import`:
import numpy import pandas import sklearn
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
If you haven't installed sklearn, please install it by:
!pip install sklearn
Collecting sklearn Downloading sklearn-0.0.tar.gz (1.1 kB) Requirement already satisfied: scikit-learn in c:\users\zchen112\anaconda3\lib\site-packages (from sklearn) (0.24.1) Requirement already satisfied: joblib>=0.11 in c:\users\zchen112\anaconda3\lib\site-packages (from scikit-learn->sklearn) (1.0.1) Requirement ...
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
We can import just a few bits using `from`, or create aliases using `as`:
import math as m from math import pi print(numpy.add(1, 2)) print(pi) print(m.sin(1))
3 3.141592653589793 0.8414709848078965
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
In the next part, some basic procedures that exist in NumPy, pandas, and scikit-learn are covered. This only scratches the surface of the possibilities, and many other functions and code will be used later on. Make sure to search around for the possiblities that exist yourself, and get a grasp of how the modules are ca...
import numpy as np import pandas as pd import sklearn
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Numpy
# Create empty arrays/matrices empty_array = np.zeros(5) empty_matrix = np.zeros((5,2)) print('Empty array: \n',empty_array) print('Empty matrix: \n',empty_matrix) # Create matrices mat = np.array([[1,2,3],[4,5,6]]) print('Matrix: \n', mat) print('Transpose: \n', mat.T) print('Item 2,2: ', mat[1,1]) print('Item 2,3: ...
Matrix: [[1 2 3] [4 5 6]] Transpose: [[1 4] [2 5] [3 6]] Item 2,2: 5 Item 2,3: 6 rows and columns: (2, 3) Sum total matrix: 21 Sum row 1: 6 Sum row 2: 15 Sum column 2: 9
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
pandas Creating dataframes pandas is great for reading and creating datasets, as well as performing basic operations on them.
# Creating a matrix with three rows of data data = [['johannes',10], ['giovanni',2], ['john',3]] # Creating and printing a pandas DataFrame object from the matrix df = pd.DataFrame(data) print(df) # Adding columns to the DataFrame object df.columns = ['names', 'years'] print(df) df_2 = pd.DataFrame(data = data, column...
names years 0 johannes 10 1 giovanni 2 2 john 3 3 giovanni 2 4 john 3 names years 5 giovanni 2 6 john 3 7 giovanni 2 8 john 3 9 johannes 10
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Reading files You can read files:
dataset = pd.read_csv('data/DM_1.csv') print(dataset.head())
Name Email City \ 0 Brent Hopkins Cum.sociis.natoque@aodiosemper.edu Mount Pearl 1 Colt Bender Vivamus.non.lorem@Proin.org Castle Douglas 2 Arthur Hammond nisl.Maecenas@sed.net Biloxi 3 Se...
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Using dataframes
# Print all unique values of the column names print(df['names'].unique()) # Print all values and their frequency: print(df['names'].value_counts()) print(df['years'].value_counts()) # Add a column names 'code' with all zeros df['code'] = np.zeros(10) print(df)
names years code 0 johannes 10 0.0 1 giovanni 2 0.0 2 john 3 0.0 3 giovanni 2 0.0 4 john 3 0.0 5 giovanni 2 0.0 6 john 3 0.0 7 giovanni 2 0.0 8 john 3 0.0 9 johannes 10 0.0
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
You can also easily find things in a DataFrame use `.loc`:
# Rows 2 to 5 and all columns: print(df.loc[2:5, :]) # Looping columns for variable in df.columns: print(df[variable]) # Looping columns and obtaining the values (which returns an array) for variable in df.columns: print(df[variable].values)
['johannes' 'giovanni' 'john' 'giovanni' 'john' 'giovanni' 'john' 'giovanni' 'john' 'johannes'] [10 2 3 2 3 2 3 2 3 10] [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
preparing datasets
dataset_1 = pd.read_csv('data/DM_1.csv', encoding='latin1') dataset_2 = pd.read_csv('data/DM_2.csv', encoding='latin1') dataset_1 dataset_2 dataset_2.columns = ['First name', 'Last name', 'Days active'] dataset_2
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
We can convert the second dataset to only have 1 column for names:
# .title() can be used to only make the first letter a capital names = [dataset_2.loc[i,'First name'] + " " + dataset_2.loc[i,'Last name'].title() for i in range(0, len(dataset_2))] # Make a new column for the name dataset_2['Name'] = names # Remove the old columns dataset_2 = dataset_2.drop(['First name', 'Last name...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Bringing together the datasets Now the datasets are made compatible, we can merge them in a few different ways.
# A left join starts from the left dataset, in this case dataset_1, and for every row matches the value in the # column used for joining. As you will see, the result has 22 rows since some names appear multiple times in # the second dataset dataset_2. both = pd.merge(dataset_1, dataset_2, on='Name', how='left') both...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Notice how observation 12 is missing, as there is no corresponding value in `dataset_1`.
both = pd.merge(dataset_1, dataset_2, on='Name', how='outer') both
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
In the last table, we have 23 rows, as both matching and non-matching values are returned.Merging datasets can be really helpful. This code should give you ample ideas on how to do this quickly yourself. As always, there are a number of ways of achieving the same result. Don't hold back to explore other solutions that ...
from sklearn import datasets as ds # Load the Boston Housing dataset dataset = ds.load_boston() # It is a dictionary, see the keys for details: print(dataset.keys()) # The 'DESCR' key holds a description text for the whole dataset print(dataset['DESCR']) # The data (independent variables) are stored under the 'data' k...
0.7406426641094095
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Very often, we need to perform an operation on a single observation. In that case, we have to reshape the data using numpy:
# Consider a single observation so = df.loc[2, :] print(so) # Just the values of the observation without meta data print(so.values) # Reshaping yields a new matrix with one row with as many columns as the original observation (indicated by the -1) print(np.reshape(so.values, (1, -1))) # For two observations: so_2 = ...
[[2.7290e-02 0.0000e+00 7.0700e+00 0.0000e+00 4.6900e-01 7.1850e+00 6.1100e+01 4.9671e+00 2.0000e+00 2.4200e+02 1.7800e+01 3.9283e+02 4.0300e+00] [3.2370e-02 0.0000e+00 2.1800e+00 0.0000e+00 4.5800e-01 6.9980e+00 4.5800e+01 6.0622e+00 3.0000e+00 2.2200e+02 1.8700e+01 3.9463e+02 2.9400e+00]]
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
This concludes our quick run-through of some basic functionality of the modules. Later on, we will use more and more specialized functions and objects, but for now this allows you to play around with data already. Visualisation The visualisations often require a bit of tricks and extra lines of code to make things loo...
# First, we need to import our packages import numpy as np import matplotlib.pyplot as plt import pandas as pd
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Pie and bar chart
# Data to plot labels = 'classification', 'regression', 'time series' sizes = [10, 22, 2] colors = ['lightblue', 'lightgreen', 'pink'] # Allows us to highlight a certain piece of the pie chart explode = (0.1, 0, 0) # Plot a pie chart with the pie() function. Notice how various parameters are given for coloring, l...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Adding a legend:
patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90) plt.legend(patches, labels, loc="best") plt.axis('equal') plt.title("Pie chart of modelling techniques") plt.show() # Bar charts are relatively similar. Here we use the bar() function plt.bar(labels, sizes, align='center') plt.xticks(labels) plt...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Histogram
# This function plots a diagram with the 'data' object providing the data # bins are calculated automatically, as indicated by the 'auto' option, which makes them relatively balanced and # sets appropriate boundaries # color sets the color of the bars # the rwidth sets the bars to somewhat slightly less wide than the b...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
See how we cut the tail off the distribution.
# Now, let's build a histogram with radomly generated data that follows a normal distribution # Mean = 10, stddev = 15, sample size = 1,000 # More on random numbers will follow in module 2 s = np.random.normal(10, 15, 1000) plt.hist(x=s, bins='auto', color='#008000', rwidth=0.85) plt.grid(axis='y') plt.xlabel('Value')...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Boxplot
# Boxplots are even easier. We can just use the boxplot() function without many parameters # We use the implementation of Pandas, which relies on Matplotlib in the background # We now use subplots. data = [3,8,3,4,1,7,5,3,8,2,7,3,1,6,10,10,3,6,5,10] # Subplot with 1 row, 2 columns, here we add figure 1 of 2 (first row,...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Boxplot for multiple variables:
# Generate 4 columns with 10 observations df = pd.DataFrame(data = np.random.random(size=(10,3)), columns = ['class.','reg.','time series']) print(df) boxplot = df.boxplot() plt.title('Triple boxplot') plt.show() df = pd.DataFrame(data = np.random.random(size=(10,3)), columns = ['class.','reg.','time series']) df['nu...
class. reg. time series 0 0.402362 0.348025 0.893360 1 0.496534 0.454527 0.631422 2 0.268591 0.815153 0.371747 3 0.596372 0.121358 0.591864 4 0.575830 0.964928 0.908575 5 0.380839 0.435604 0.488436 6 0.788519 0.562830 0.303210 7 0.424057 0.888664 0.476388 8 0....
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Scatterplot
# We load the data gain x = [3,8,3,4,1,7,5,3,8,2,7,3,1,6,10,10,3,6,5,10] y = [10,7,2,7,5,4,2,3,4,1,5,7,8,4,10,2,3,4,5,6] # Here, we build a simple scatterplot of the two variables plt.scatter(x,y) plt.xlabel('x') plt.ylabel('y') plt.title('Simple scatterplot') plt.show()
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
Hard to tell which variable is what, but it gives an overall impression of the data.
# A simple line plot # We use the plot function for this. 'o-' indicates we want to use circles for markers and connect them with lines plt.plot(x,'o-',color='blue',) # Here we use 'x--' for cross-shaped markers connected with intermittent lines plt.plot(y,'x--',color='red') plt.xlabel('Time') plt.ylabel('Value') plt...
_____no_output_____
MIT
Week0/Week0-notes-python-fundamentals.ipynb
Magica-Chen/WebSNA-notes
---_You are currently looking at **version 1.0** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._--- Assignment 4 - Document Sim...
import numpy as np import nltk nltk.download('punkt') nltk.download('averaged_perceptron_tagger') nltk.download('wordnet') from nltk.corpus import wordnet as wn import pandas as pd def convert_tag(tag): """Convert the tag given by nltk.pos_tag to the tag used by wordnet.synsets""" tag_dict = {'N': 'n',...
[nltk_data] Downloading package punkt to /home/jovyan/nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package averaged_perceptron_tagger to [nltk_data] /home/jovyan/nltk_data... [nltk_data] Package averaged_perceptron_tagger is already up-to- [nltk_data] date! [nltk_d...
MIT
4-5 Applied Text Mining in Python/Assignment 4.ipynb
MLunov/Applied-Data-Science-with-Python-Specialization-Michigan
test_document_path_similarityUse this function to check if doc_to_synsets and similarity_score are correct.*This function should return the similarity score as a float.*
def test_document_path_similarity(): doc1 = 'This is a function to test document_path_similarity.' doc2 = 'Use this function to see if your code in doc_to_synsets \ and similarity_score is correct!' return document_path_similarity(doc1, doc2) test_document_path_similarity()
_____no_output_____
MIT
4-5 Applied Text Mining in Python/Assignment 4.ipynb
MLunov/Applied-Data-Science-with-Python-Specialization-Michigan
___`paraphrases` is a DataFrame which contains the following columns: `Quality`, `D1`, and `D2`.`Quality` is an indicator variable which indicates if the two documents `D1` and `D2` are paraphrases of one another (1 for paraphrase, 0 for not paraphrase).
# Use this dataframe for questions most_similar_docs and label_accuracy paraphrases = pd.read_csv('paraphrases.csv') paraphrases.head()
_____no_output_____
MIT
4-5 Applied Text Mining in Python/Assignment 4.ipynb
MLunov/Applied-Data-Science-with-Python-Specialization-Michigan
___ most_similar_docsUsing `document_path_similarity`, find the pair of documents in paraphrases which has the maximum similarity score.*This function should return a tuple `(D1, D2, similarity_score)`*
def most_similar_docs(): # Your Code Here return max(map(document_path_similarity, paraphrases['D1'], paraphrases['D2'])) # Your Answer Here most_similar_docs()
_____no_output_____
MIT
4-5 Applied Text Mining in Python/Assignment 4.ipynb
MLunov/Applied-Data-Science-with-Python-Specialization-Michigan
label_accuracyProvide labels for the twenty pairs of documents by computing the similarity for each pair using `document_path_similarity`. Let the classifier rule be that if the score is greater than 0.75, label is paraphrase (1), else label is not paraphrase (0). Report accuracy of the classifier using scikit-learn's...
def label_accuracy(): from sklearn.metrics import accuracy_score paraphrases['labels'] = [1 if i > 0.75 else 0 for i in map(document_path_similarity, paraphrases['D1'], paraphrases['D2'])] # Your Code Here return accuracy_score(paraphrases['Quality'], paraphrases['labels']) # Your Answer Here label_ac...
_____no_output_____
MIT
4-5 Applied Text Mining in Python/Assignment 4.ipynb
MLunov/Applied-Data-Science-with-Python-Specialization-Michigan
Part 2 - Topic ModellingFor the second part of this assignment, you will use Gensim's LDA (Latent Dirichlet Allocation) model to model topics in `newsgroup_data`. You will first need to finish the code in the cell below by using gensim.models.ldamodel.LdaModel constructor to estimate LDA model parameters on the corpus...
import pickle import gensim from sklearn.feature_extraction.text import CountVectorizer # Load the list of documents with open('newsgroups', 'rb') as f: newsgroup_data = pickle.load(f) # Use CountVectorizor to find three letter tokens, remove stop_words, # remove tokens that don't appear in at least 20 documents...
_____no_output_____
MIT
4-5 Applied Text Mining in Python/Assignment 4.ipynb
MLunov/Applied-Data-Science-with-Python-Specialization-Michigan
lda_topicsUsing `ldamodel`, find a list of the 10 topics and the most significant 10 words in each topic. This should be structured as a list of 10 tuples where each tuple takes on the form:`(9, '0.068*"space" + 0.036*"nasa" + 0.021*"science" + 0.020*"edu" + 0.019*"data" + 0.017*"shuttle" + 0.015*"launch" + 0.015*"ava...
def lda_topics(): # Your Code Here return ldamodel.print_topics(num_topics=10, num_words=10) # Your Answer Here lda_topics()
_____no_output_____
MIT
4-5 Applied Text Mining in Python/Assignment 4.ipynb
MLunov/Applied-Data-Science-with-Python-Specialization-Michigan
topic_distributionFor the new document `new_doc`, find the topic distribution. Remember to use vect.transform on the the new doc, and Sparse2Corpus to convert the sparse matrix to gensim corpus.*This function should return a list of tuples, where each tuple is `(topic, probability)`*
new_doc = ["\n\nIt's my understanding that the freezing will start to occur because \ of the\ngrowing distance of Pluto and Charon from the Sun, due to it's\nelliptical orbit. \ It is not due to shadowing effects. \n\n\nPluto can shadow Charon, and vice-versa.\n\nGeorge \ Krumins\n-- "] def topic_distribution(): ...
_____no_output_____
MIT
4-5 Applied Text Mining in Python/Assignment 4.ipynb
MLunov/Applied-Data-Science-with-Python-Specialization-Michigan
topic_namesFrom the list of the following given topics, assign topic names to the topics you found. If none of these names best matches the topics you found, create a new 1-3 word "title" for the topic.Topics: Health, Science, Automobiles, Politics, Government, Travel, Computers & IT, Sports, Business, Society & Lifes...
def topic_names(): # Your Code Here return ['Automobiles', 'Health', 'Science', 'Politics', 'Sports', 'Business', 'Society & Lifestyle', 'Religion', 'Education', 'Computers & IT'] # Your Answer Here topic_names()
_____no_output_____
MIT
4-5 Applied Text Mining in Python/Assignment 4.ipynb
MLunov/Applied-Data-Science-with-Python-Specialization-Michigan
NOAA extreme weather eventsThe [National Oceanic and Atmospheric Administration](https://en.wikipedia.org/wiki/National_Oceanic_and_Atmospheric_Administration) has a database of extreme weather events that contains lots of detail for every year ([Link](https://www.climate.gov/maps-data/dataset/severe-storms-and-extrem...
import pandas as pd import numpy as np import random import geopandas import matplotlib.pyplot as plt pd.set_option('display.max_columns', None) # Unlimited columns # Custom function for displaying the shape and head of a dataframe def display(df, n=5): print(df.shape) return df.head(n)
_____no_output_____
MIT
notebooks/DMA8 - NOAA weather events by coords.ipynb
KimDuclos/liveSafe-data
Get map of US counties
# Import a shape file with all the counties in the US. # Note how it doesn't include all the same territories as the # quake contour map. counties = geopandas.read_file('../data_input/1_USCounties/') # Turn state codes from strings to integers for col in ['STATE_FIPS', 'CNTY_FIPS', 'FIPS']: counties[col] = counti...
_____no_output_____
MIT
notebooks/DMA8 - NOAA weather events by coords.ipynb
KimDuclos/liveSafe-data
Process NOAA data for one year onlyAs a starting point that I'll generalize later.
# Get NOAA extreme weather event data for one year df1 = pd.read_csv('../data_local/NOAA/StormEvents_details-ftp_v1.0_d2018_c20190422.csv') print(df1.shape) print(df1.columns) df1.head(2) # Extract only a few useful columns df2 = df1[['TOR_F_SCALE','EVENT_TYPE','BEGIN_LAT','BEGIN_LON']].copy() # Remove any rows with n...
_____no_output_____
MIT
notebooks/DMA8 - NOAA weather events by coords.ipynb
KimDuclos/liveSafe-data
NOAA file processing functionGeneralize the previous operations so they can apply to the data for any year
def process_noaa(filepath): """ Process one year of NOAA Extreme weather events. Requires the list of official counties and the list of official weather event types. Inputs ------ filepath (string) : file path for the list of events from one year. Outputs ------- r...
_____no_output_____
MIT
notebooks/DMA8 - NOAA weather events by coords.ipynb
KimDuclos/liveSafe-data
Process all the available data
import glob import os # Read the CSV files for each year going back to 1996 (the first year # when many of these event types started being recorded) path = '../data_local/NOAA/' filenames = sorted(glob.glob(os.path.join(path, '*.csv'))) layers = [] # Aggregate the dataframes in a list for name in filenames: year...
_____no_output_____
MIT
notebooks/DMA8 - NOAA weather events by coords.ipynb
KimDuclos/liveSafe-data
Process tornado dataIn 2007, the National Weather Service (NWS) switched their scale for measuring tornado intensity, from the Fujita (F) scale to the Enhanced Fujita (EF) scale. I will lump them together here and just make a note for the user that the scale means something slightly different before and after 2007. ...
# Tornadoes by magnitude, using the NWS's original labels. # Notice the two different scales and also a label for 'unknown' tornadoes.TOR_F_SCALE.value_counts() # Function that extracts the scale level and sets unkwnown to zero. def process_fujita(x): if x[-1] == 'U': return 0 else: return int(x...
_____no_output_____
MIT
notebooks/DMA8 - NOAA weather events by coords.ipynb
KimDuclos/liveSafe-data
Visualizing the data
# Sample of 2000 storms in the Lower48 fig, ax = plt.subplots(figsize=(20,20)) counties.plot(ax=ax, color='white', edgecolor='black'); storms.sample(2000).plot(ax=ax, marker='o') ax.set_xlim(-125.0011,-66.9326) ax.set_ylim(24.9493, 49.5904) plt.show()
_____no_output_____
MIT
notebooks/DMA8 - NOAA weather events by coords.ipynb
KimDuclos/liveSafe-data
Floods and tornadoes show basically the same distribution, so I won't plot them separately. For reference, this is what the dataframes that we're about to export look like.
display(storms) display(floods) display(tornadoes)
(30898, 3)
MIT
notebooks/DMA8 - NOAA weather events by coords.ipynb
KimDuclos/liveSafe-data
Export!
storms.to_file("../data_output/5__NOAA/storms.geojson", driver='GeoJSON') floods.to_file("../data_output/5__NOAA/floods.geojson", driver='GeoJSON') tornadoes.to_file("../data_output/5__NOAA/tornadoes.geojson", driver='GeoJSON')
_____no_output_____
MIT
notebooks/DMA8 - NOAA weather events by coords.ipynb
KimDuclos/liveSafe-data
**1D Convolutional Neural Networks**"A Convolutional Neural Network (ConvNet/CNN) is a Deep Learning algorithm which can take in an input image, assign importance (learnable weights and biases) to various aspects/objects in the image and be able to differentiate one from the other. The pre-processing required in a Co...
pip install tensorflow !pip install fsspec # cnn model from numpy import mean from numpy import std from numpy import dstack from pandas import read_csv from matplotlib import pyplot from keras.models import Sequential from keras.layers import Dense from keras.layers import Flatten from keras.layers import Dropout from...
(7352, 128, 9) (7352, 1) (2947, 128, 9) (2947, 1) (7352, 128, 9) (7352, 6) (2947, 128, 9) (2947, 6) >#1: 90.363 >#2: 88.157 >#3: 92.467 >#4: 90.601 >#5: 90.227 >#6: 90.058 >#7: 91.992 >#8: 90.363 >#9: 89.786 >#10: 91.211 [90.3630793094635, 88.15745115280151, 92.46691465377808, 90.60060977935791, 90.22734761238098, 90.0...
MIT
code/clustering_and_classification/1D_CNN.ipynb
iotanalytics/IoTTutorial
Pymaceuticals Inc.--- Analysis* Overall, it is clear that Capomulin is a viable drug regimen to reduce tumor growth.* Capomulin had the most number of mice complete the study, with the exception of Remicane, all other regimens observed a number of mice deaths across the duration of the study. * There is a strong corre...
# Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import scipy.stats as st # Study data files mouse_metadata_path = "data/Mouse_metadata.csv" study_results_path = "data/Study_results.csv" # Read the mouse data and the study results mouse_metadata = pd.read_csv(mouse_metadata_path) study_res...
_____no_output_____
ADSL
pymaceuticals_starter_with_plots.ipynb
vaideheeshah13/MatPlotLib
Summary Statistics
# Generate a summary statistics table of mean, median, variance, standard deviation, and SEM of the tumor volume for each regimen # Use groupby and summary statistical methods to calculate the following properties of each drug regimen: # mean, median, variance, standard deviation, and SEM of the tumor volume. # Asse...
_____no_output_____
ADSL
pymaceuticals_starter_with_plots.ipynb
vaideheeshah13/MatPlotLib
Bar and Pie Charts
# Generate a bar plot showing the total number of measurements taken on each drug regimen using pandas. # Generate a bar plot showing the total number of measurements taken on each drug regimen using using pyplot. # Generate a pie plot showing the distribution of female versus male mice using pandas # Generate a pie...
_____no_output_____
ADSL
pymaceuticals_starter_with_plots.ipynb
vaideheeshah13/MatPlotLib
Quartiles, Outliers and Boxplots
# Calculate the final tumor volume of each mouse across four of the treatment regimens: # Capomulin, Ramicane, Infubinol, and Ceftamin # Start by getting the last (greatest) timepoint for each mouse # Merge this group df with the original dataframe to get the tumor volume at the last timepoint # Put treatments in...
_____no_output_____
ADSL
pymaceuticals_starter_with_plots.ipynb
vaideheeshah13/MatPlotLib
Line and Scatter Plots
# Generate a line plot of tumor volume vs. time point for a mouse treated with Capomulin # Generate a scatter plot of average tumor volume vs. mouse weight for the Capomulin regimen
_____no_output_____
ADSL
pymaceuticals_starter_with_plots.ipynb
vaideheeshah13/MatPlotLib
Correlation and Regression
# Calculate the correlation coefficient and linear regression model # for mouse weight and average tumor volume for the Capomulin regimen
The correlation between mouse weight and the average tumor volume is 0.84
ADSL
pymaceuticals_starter_with_plots.ipynb
vaideheeshah13/MatPlotLib
Microsoft Insights Module Example Notebook
%run /OEA_py %run /NEW_Insights_py # 0) Initialize the OEA framework and Insights module class notebook. oea = OEA() insights = Insights() insights.ingest()
_____no_output_____
CC-BY-4.0
modules/Microsoft_Data/Microsoft_Education_Insights_Premium/notebook/Insights_module_ingestion.ipynb
ahalabi/OpenEduAnalytics
WeatherPy---- Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
w_api = 'f85af5acc7275a9eb032d03a3cca5913' # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time from scipy.stats import linregress # Import API key # from api_keys import weather_api_key # Incorporated citipy to determine city based on latitude a...
_____no_output_____
ADSL
starter_code/old/WeatherPy.ipynb
rbvancleave/python-api-challenge
Generate Cities List
# List for holding lat_lngs and cities lat_lngs = [] cities = [] # Create a set of random lat and lng combinations lats = np.random.uniform(lat_range[0], lat_range[1], size=1500) lngs = np.random.uniform(lng_range[0], lng_range[1], size=1500) lat_lngs = zip(lats, lngs) # Identify nearest city for each lat, lng combin...
_____no_output_____
ADSL
starter_code/old/WeatherPy.ipynb
rbvancleave/python-api-challenge
Perform API Calls* Perform a weather check on each city using a series of successive API calls.* Include a print log of each city as it'sbeing processed (with the city number and city name). Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame Inspect the data and remove the cities...
# Get the indices of cities that have humidity over 100%. # Make a new DataFrame equal to the city data to drop all humidity outliers by index. # Passing "inplace=False" will make a copy of the city_data DataFrame, which we call "clean_city_data".
_____no_output_____
ADSL
starter_code/old/WeatherPy.ipynb
rbvancleave/python-api-challenge
Matplotlib Applied **Aim: SWBAT create a figure with 4 subplots of varying graph types.**
import matplotlib.pyplot as plt import numpy as np from numpy.random import seed, randint seed(100) # Create Figure and Subplots fig, axes = plt.subplots(2,2, figsize=(10,6), sharex=True, sharey=True, dpi=100) # Define the colors and markers to use colors = {0:'g', 1:'b', 2:'r', 3:'y'} markers = {0:'o', 1:'x', 2:'*',...
_____no_output_____
MIT
Phase_1/ds-data_visualization-main/Matplotlib_Applied.ipynb
BenJMcCarty/ds-east-042621-lectures
Go through and play with the code above to try answer the questions below:- What do you think `sharex` and `sharey` do?- What does the `dpi` argument control?- What does `numpy.ravel()` do, and why do they call it here?- What does `yaxis.set_ticks_position()` do?- How do they use the `colors` and `markers` dictionari...
from numpy.random import seed, randint seed(100) x = sorted(randint(0,10,10)) x2 = sorted(randint(0,20,10)) y = sorted(randint(0,10,10)) y2 = sorted(randint(0,20,10))
_____no_output_____
MIT
Phase_1/ds-data_visualization-main/Matplotlib_Applied.ipynb
BenJMcCarty/ds-east-042621-lectures
Great tutorial on matplotlibhttps://www.machinelearningplus.com/plots/matplotlib-tutorial-complete-guide-python-plot-examples/
fig
_____no_output_____
MIT
Phase_1/ds-data_visualization-main/Matplotlib_Applied.ipynb
BenJMcCarty/ds-east-042621-lectures
Now You Code 2: Paint PricingHouse Depot, a big-box hardware retailer, has contracted you to create an app to calculate paint prices. The price of paint is determined by the following factors:- Everyday quality paint is `$19.99` per gallon.- Select quality paint is `$24.99` per gallon.- Premium quality paint is `$32.9...
# Step 2: Write code here choices = ["everyday", "select", "premium"] colorChoices = ["y", "n"] quality = input("which paint quality would you like? ["everyday", "select", "premium"]") if quality in choices if quality == "everyday": quality =19.99 elif quality == "select": quality = 24.99 e...
_____no_output_____
MIT
content/lessons/04/Now-You-Code/NYC2-Paint-Matching.ipynb
MahopacHS/spring2019-rizzenM
Kaggle ML and Data Science Survey Analysis Data 512, Final Project Plan - Zicong Liang Project MotivationThis project an analysis for a survey about Machine Learning and Data Science. Recently, lots of people are talking about machine learning and Data Science. In addition, more and more companies hire data science t...
import pandas as pd my_data = pd.read_csv("multipleChoiceResponses.csv", encoding='ISO-8859-1', delimiter=',', low_memory=False) my_data.head() my_data.shape
_____no_output_____
MIT
Final Project Plan.ipynb
lzctony/data-512-finalproject
Continuous training pipeline with Kubeflow Pipeline and AI Platform **Learning Objectives:**1. Learn how to use Kubeflow Pipeline(KFP) pre-build components (BiqQuery, AI Platform training and predictions)1. Learn how to use KFP lightweight python components1. Learn how to build a KFP with these components1. Learn how ...
#!grep 'BASE_IMAGE =' -A 5 pipeline/covertype_training_pipeline.py !pip list | grep kfp
kfp 1.0.0 kfp-pipeline-spec 0.1.7 kfp-server-api 1.5.0
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
The pipeline uses a mix of custom and pre-build components.- Pre-build components. The pipeline uses the following pre-build components that are included with the KFP distribution: - [BigQuery query component](https://github.com/kubeflow/pipelines/tree/0.2.5/components/gcp/bigquery/query) - [AI Platform Training ...
%%writefile ./pipeline/covertype_training_pipeline.py # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
The custom components execute in a container image defined in `base_image/Dockerfile`.
!cat base_image/Dockerfile
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
The training step in the pipeline employes the AI Platform Training component to schedule a AI Platform Training job in a custom training container. The custom training image is defined in `trainer_image/Dockerfile`.
!cat trainer_image/Dockerfile
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Building and deploying the pipelineBefore deploying to AI Platform Pipelines, the pipeline DSL has to be compiled into a pipeline runtime format, also refered to as a pipeline package. The runtime format is based on [Argo Workflow](https://github.com/argoproj/argo), which is expressed in YAML. Configure environment...
!gsutil ls
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
**HINT:** For **ENDPOINT**, use the value of the `host` variable in the **Connect to this Kubeflow Pipelines instance from a Python client via Kubeflow Pipelines SDK** section of the **SETTINGS** window.For **ARTIFACT_STORE_URI**, copy the bucket name which starts with the qwiklabs-gcp-xx-xxxxxxx-kubeflowpipelines-defa...
REGION = 'us-central1' ENDPOINT = '627be4a1d4049ed3-dot-us-central1.pipelines.googleusercontent.com' # TO DO: REPLACE WITH YOUR ENDPOINT ARTIFACT_STORE_URI = 'gs://dna-gcp-data-kubeflowpipelines-default' # TO DO: REPLACE WITH YOUR ARTIFACT_STORE NAME PROJECT_ID = !(gcloud config get-value core/project) PROJECT_ID = P...
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Build the trainer image
IMAGE_NAME='trainer_image' TAG='test' TRAINER_IMAGE='gcr.io/{}/{}:{}'.format(PROJECT_ID, IMAGE_NAME, TAG)
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
**Note**: Please ignore any **incompatibility ERROR** that may appear for the packages visions as it will not affect the lab's functionality.
!gcloud builds submit --timeout 15m --tag $TRAINER_IMAGE trainer_image
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Build the base image for custom components
IMAGE_NAME='base_image' TAG='test2' BASE_IMAGE='gcr.io/{}/{}:{}'.format(PROJECT_ID, IMAGE_NAME, TAG) !pwd !gcloud builds submit --timeout 15m --tag $BASE_IMAGE base_image
Creating temporary tarball archive of 2 file(s) totalling 290 bytes before compression. Uploading tarball of [base_image] to [gs://dna-gcp-data_cloudbuild/source/1621581960.433286-cef9441cb3234402ad8faeccf31ce5fe.tgz] Created [https://cloudbuild.googleapis.com/v1/projects/dna-gcp-data/locations/global/builds/d2e1016b-5...
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Compile the pipelineYou can compile the DSL using an API from the **KFP SDK** or using the **KFP** compiler.To compile the pipeline DSL using the **KFP** compiler. Set the pipeline's compile time settingsThe pipeline can run using a security context of the GKE default node pool's service account or the service accoun...
USE_KFP_SA = False COMPONENT_URL_SEARCH_PREFIX = 'https://raw.githubusercontent.com/kubeflow/pipelines/0.2.5/components/gcp/' RUNTIME_VERSION = '1.15' PYTHON_VERSION = '3.7' ENDPOINT='https://627be4a1d4049ed3-dot-us-central1.pipelines.googleusercontent.com' %env USE_KFP_SA={USE_KFP_SA} %env BASE_IMAGE={BASE_IMAGE} %e...
env: USE_KFP_SA=False env: BASE_IMAGE=gcr.io/dna-gcp-data/base_image:test2 env: TRAINER_IMAGE=gcr.io/dna-gcp-data/trainer_image:test env: COMPONENT_URL_SEARCH_PREFIX=https://raw.githubusercontent.com/kubeflow/pipelines/0.2.5/components/gcp/ env: RUNTIME_VERSION=1.15 env: PYTHON_VERSION=3.7 env: ENDPOINT=https://627be4a...
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Use the CLI compiler to compile the pipeline
!dsl-compile --py pipeline/covertype_training_pipeline.py --output covertype_training_pipeline.yaml
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
The result is the `covertype_training_pipeline.yaml` file.
!head covertype_training_pipeline.yaml
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Deploy the pipeline package
PIPELINE_NAME='covertype_continuous_training' !kfp --endpoint $ENDPOINT pipeline upload \ -p $PIPELINE_NAME \ covertype_training_pipeline.yaml
Pipeline 7eda6268-681e-41eb-8f65-a9c853030888 has been submitted Pipeline Details ------------------ ID 7eda6268-681e-41eb-8f65-a9c853030888 Name covertype_continuous_training Description Uploaded at 2021-05-21T08:50:00+00:00 +--------------------------+----------------------------------------------...
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Submitting pipeline runsYou can trigger pipeline runs using an API from the KFP SDK or using KFP CLI. To submit the run using KFP CLI, execute the following commands. Notice how the pipeline's parameters are passed to the pipeline run. List the pipelines in AI Platform Pipelines
!kfp --endpoint $ENDPOINT experiment list
+--------------------------------------+-------------------------------+---------------------------+ | Experiment ID | Name | Created at | +======================================+===============================+===========================+ | 889c1532-fee9-4...
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Submit a runFind the ID of the `covertype_continuous_training` pipeline you uploaded in the previous step and update the value of `PIPELINE_ID` .
PIPELINE_ID='7eda6268-681e-41eb-8f65-a9c853030888' # TO DO: REPLACE WITH YOUR PIPELINE ID EXPERIMENT_NAME = 'Covertype_Classifier_Training' RUN_ID = 'Run_001' SOURCE_TABLE = 'covertype_dataset.covertype' DATASET_ID = 'covertype_dataset' EVALUATION_METRIC = 'accuracy' MODEL_ID = 'covertype_classifier' VERSION_ID = 'v01...
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Run the pipeline using the `kfp` command line by retrieving the variables from the environment to pass to the pipeline where:- EXPERIMENT_NAME is set to the experiment used to run the pipeline. You can choose any name you want. If the experiment does not exist it will be created by the command- RUN_ID is the name of th...
!kfp --endpoint $ENDPOINT run submit \ -e $EXPERIMENT_NAME \ -r $RUN_ID \ -p $PIPELINE_ID \ project_id=$PROJECT_ID \ gcs_root=$GCS_STAGING_PATH \ region=$REGION \ source_table_name=$SOURCE_TABLE \ dataset_id=$DATASET_ID \ evaluation_metric_name=$EVALUATION_METRIC \ model_id=$MODEL_ID \ version_id=$VERSION_ID \ replace_...
_____no_output_____
Apache-2.0
on_demand/kfp-caip-sklearn/lab-02-kfp-pipeline/lab-02.ipynb
bharathraja23/mlops-on-gcp
Feature: TF-IDF Distances Create TF-IDF vectors from question texts and compute vector distances between them. Imports This utility package imports `numpy`, `pandas`, `matplotlib` and a helper `kg` module into the root namespace.
from pygoose import * from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_distances, euclidean_distances
_____no_output_____
MIT
notebooks/feature-tfidf.ipynb
MinuteswithMetrics/kaggle-quora-question-pairs
Config Automatically discover the paths to various data folders and compose the project structure.
project = kg.Project.discover()
_____no_output_____
MIT
notebooks/feature-tfidf.ipynb
MinuteswithMetrics/kaggle-quora-question-pairs