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 |
|---|---|---|---|---|---|
1. Who Scored More Goals Per Year? | plt.suptitle('Goals Per Year For Fvery Player', fontsize = 15 )
ronaldo_df.groupby(['year'])['player'].count().plot(kind='bar',color='brown',label='Ronaldo',figsize=(15,5),width = 0.4)
messi_df.groupby(['year'])['player'].count().plot(kind='bar',color='#14D622',label='Messi',figsize=(15,5),width = 0.2)
plt.legend()
plt... | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
From this comparison we can understand: 1. 2012 was a dramatic year in Messi and Ronaldo's career, it was the best year for Messi career's and the worst year for Ronaldo career's. 2. Until 2012 Messi scored more goals than Ronaldo, and from 2013 Ronaldo scores more goals. 3. Ronaldo is more stable than Messi across... | messi_type = df[df['player'] == 'Messi'].type.value_counts()
ronaldo_type = df[df['player'] == 'Ronaldo'].type.value_counts()
df_types = pd.DataFrame({ 'Messi' : messi_type ,
'Ronaldo' : ronaldo_type})
df_types.T
print("This graph show the number of goals in percent of the total goals for each ... | This graph show the number of goals in percent of the total goals for each player
| CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
From this comparison we can understand: 1. Messi scored 60% of his goals in his dominant foot, compared to Ronaldo who scored a little less than 40% in his dominant foot. 2. Ronaldo scored more goals on penalties and header. 3. Messi and Ronaldo scored the same percents with free kicks. 3. Who Scored More Solo Goa... | df['Solo_messi'] = ((df['assisted'] == 'Solo') & (df['player'] == 'Messi'))
df['Solo_ronaldo']= ((df['assisted'] == 'Solo') & (df['player'] == 'Ronaldo'))
Solo_ronaldo = (df['Solo_ronaldo'] == True).sum()
Solo_messi = (df['Solo_messi'] == True).sum()
nonSolo_messi = (len(df['Solo_messi']) - Solo_messi)
nonSolo_ronaldo... | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
From this comparison we can understand: Ronaldo scored a few more solo goals than Messi. 4. Who Scored More Goals Per Possition? | df['pos']=df.pos.str.strip()
messi_pos = df[df['player'] == 'Messi'].pos.value_counts()
ronaldo_pos = df[df['player'] == 'Ronaldo'].pos.value_counts()
df_pos = pd.DataFrame({ 'Messi' : messi_pos ,
'Ronaldo' : ronaldo_pos})
df_pos = df_pos/df_pos.sum()
df_pos.plot.bar(title = 'player favorite position', col... | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
From this comparison we can understand: 1. The best position for Ronaldo is LW and for Messi is RW.2. Messi better than Ronaldo in CF possition.3. Ronaldo better than Messi on the "weak side".4. Messi scored from more possionss than Ronaldo, but in low percents. 5. Who Was The Best Scorer In "LaLiga" (the spanish l... | plt.plot()
ronaldo_df.loc[ronaldo_df.comp=='LaLiga'].groupby(['year'])['player'].count().plot(kind='line',color = 'brown',label='Ronaldo',figsize=(20,8))
messi_df.loc[(messi_df.comp=='LaLiga')].groupby(['year'])['player'].count().plot(kind='line',color = '#14D622',label='Messi',figsize=(20,6))
plt.title('Goals Scored I... | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
Average goals per player per season: | df.loc[df.comp=='LaLiga'].groupby(['player','year'])[['year']].count().groupby(["player"]).mean().style.set_caption("Average goals per player per season") | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
From this comparison we can understand: 1. Ronaldo is more stable than Messi across the years.2. In the period from 2009 to 2018, Messi was the best scorer for 6 seasons (2009, 2010, 2012, 2016, 2017, 2018) compared to only 4 seasons for Ronaldo (2011, 2013, 2014, 2015).3. Ronaldo scores an average of 2 goals more t... | plt.subplot(1,2,1)
df.loc[(df['comp']=='Champions League') & (df['round'] == 'Group Stage')].groupby(['player'])['date'].count().plot(kind='bar',width = 0.2, color = ( "#14D622","brown"))
plt.title('Goals Scored in "UEFA Champions League" Group stages',fontsize = 20)
plt.xlabel('Players',fontsize = 14)
plt.ylabel('Numb... | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
Goals Scored in UEFA Champions League Knockout stages: | df.loc[(df['comp']=='Champions League') & (df['round'] == 'Group Stage')].groupby(['player','comp'])[['date']].count() | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
Goals Scored in "UEFA Champions League" Group stages: | df.loc[(df['comp']=='Champions League') & (df['round'] != 'Group Stage')].groupby(['player','comp'])[['date']].count() | _____no_output_____ | CC0-1.0 | projects/projects_summer_2021/15_football.ipynb | nlihin/my-binder |
Introduction to Python 3 in jupyternotebookThis is an introduction to the Python programming language for participants on the Programming with openBIM course as arranged by [BIMFag](https://bimfag.no/). It is based on [learnpythons basic course](https://www.learnpython.org/). It is not a complete Python course, so for... | ### Change this cell from a Code cell to a Markdown cell, by using the roll down menu above. | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Let the program tell something to a userThe print statement is a powerfull directive in python and it enables a program to print out a result, eg. "Hello, world". Which prints a data type called a string to the screen. | # Here we print the string "Hello, world!" to the screen.
print("Hello, world!") | Hello, world!
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
We will use the print statement several times in this course together with "string formatting". A typpical way of formatting a string is by appending another string to it, like "Hello, "+"world". | # Here we append the two strings "Hello, " and "world!" to the screen.
print("Hello,"+"world!") | Hello,world!
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
As seen above now we didn't get a space between the two strings. A space could either be part of e.g. the first string, or be a separate string in itself like " ". Lets append that too. | # Here we append the three strings "Hello,", " " and "world!"
print("Hello,"+" "+"world!") | Hello, world!
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Let the program ask a user for input and show the resultSince we want to say hello to you too, you could use the "input()" function to get user intput and store that in a variable, and print to screen. | # Here we get the name from the user and store it in a variable called name, append that to another vairable as we print.
x = input("Write your name here: ")
y = "Hello, "
print(y+x+"!") | Write your name here: Ingvild
Hello, Ingvild!
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Variables and types Python is completely object oriented, and not "statically typed". In other programming languages, that is statically typed, you need to declare the variable and what type of data it holds, before using it. In Python you do not need to declare variables before using them, or declare their type. This... | # This is how you define an integer
myInt = 9
print(myInt)
# To define a floating point number you could use one of the following approaches
myFloat1 = 9.0
print(myFloat1)
myFloat2 = float(9)
print(myFloat2)
myFloat3 = 9.
print(myFloat3) | 9.0
9.0
9.0
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
One could aslo "cast" an integer into a float, like we do in the myFloat2=float(9). * An integer x can be cast into float by using float(x)* A float y can be cast into an integer by using int(y)* An integer x and a float y can both be cast into a string by respectively str(x) and str(y). | # Here we first define an integer, and cast it into a float
myInt = 9
myFloat = float(myInt)
print("My Integer: %s, and my Float: %s" % (myInt,myFloat))
# Here we cast myInt and myFloat (from above) into strings
myIntegerString = str(myInt)
print(myIntegerString)
myFloatString= str(myFloat)
print(myFloatString) | 9
9.0
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Strings Strings can be define by using single (') or double quoates("). The difference between the two is that using double quotes makes it easy to include apostrophes (whereas these would terminate the string if using single quotes) | myString = "Don't worry about apostrophes"
print(myString)
escapedString = 'Don\'t worry about apostrophes'
print(escapedString)
#Strings are just an array of characters
myString = "abcdefgh"
print(myString)
third = myString[2]
print(third)
last = myString[-1]
print(last) | abcdefgh
c
h
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
MiniExcercise:Fetch the character "d" from myString and print it to screen | # Write your code here
| _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Exercise 1 The target of this exercise is to create a string, an integer, and a floating point number. The string should be named mystring and should contain the word "hello". The floating point number should be named myfloat and should contain the number 10.0, and the integer should be named myint and should contain ... | # change this code
mystring = "change this"
myfloat = "change this"
myint = "change this"
# testing code
if mystring == "hello":
print("String: %s" % mystring)
if isinstance(myfloat, float) and myfloat == 10.0:
print("Float: %f" % myfloat)
if isinstance(myint, int) and myint == 20:
print("Integer: %d" % my... | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Exercise 2Run the code below first without changing anything, supplying a number to it. Then, use a cast to correct it so that it outputs correct math on numbers. | # Here we take and input of a number, and then multiply it 5 times and then prints the result.
inputVariable = input("Provide a number: ")
x = inputVariable * 5
print(x) | Provide a number: 6
66666
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Naming conventions:Different programming languages have different "best practice" naming for their naming of variables, funtions and classes. In python, the naming conventions are described at: [PEP8](https://www.python.org/dev/peps/pep-0008/naming-conventions) | # Examples of naming conventions
CONSTANTS_ARE_ALL_UPPERCASE = "my constant string"
variables_should_be_all_lowercase_separated_with_underscores = 1
def functions_should_do_the_same():
var1 = 4
retrun var1 | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Basic String formattingAs seen in the testing code: ```Python testing codeif mystring == "hello": print("String: %s" % mystring)if isinstance(myfloat, float) and myfloat == 10.0: print("Float: %f" % myfloat)if isinstance(myint, int) and myint == 20: print("Integer: %d" % myint)```We use some string formatting... | # Execute this to check multiple variables inserted into a string
print("string %s, number %d and floatingpoint %f without formatting, or formatted %0.5f" % ("hello",10,10.0, 10.0)) | string hello, number 10 and floatingpoint 10.000000 without formatting, or formatted 10.00000
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
MiniExercise 2B:Try doing float printing with only two decimals | # Execute this to check multiple variables inserted into a string
print("Print the float %f" % (10.0)) | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
String functionsIn addition to this there are several other string formatting options that you could do. Strings are objects that have several predefined functions. Feel free to add some code cells below here with some of the example code snippets from [w3schools on strings](https://www.w3schools.com/python/python_str... | # Example 1 -- eg. convert a string to lower letters
a = "HElLo!"
print(a.lower())
# covert to captial letters
print(a.upper())
# Example 2 -- eg. split a string into two.
a = "Hello, world!"
#split at a specific character
var = a.split(",")
print(var)
#split whitespace at beginning or end
print(var[1].split()) | ['Hello', ' world!']
['world!']
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Exercise 3Build a script in the cell below that: 1) Takes in a string that you input2) Make sure it is a string3) Store it in a variable 4) Print out the variable5) Then grab only the first and last characters in the name6) Store it in a new variable7) Print out the new variablesee [w3schools on strings](https://www.w... | ### Exercise 3 answer here:
| _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Collection types (Arrays)There are four collection data types in the Python programming language:* List is a collection which is ordered and changeable. Allows duplicate members.* Tuple is a collection which is ordered and unchangeable. Allows duplicate members.* Set is a collection which is unordered and unindexed. N... | myList = ["apple", 1, "cherry", 10]
print(myList) | ['apple', 1, 'cherry', 10]
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
You access the list items by referring to the index number. Remember that the index starts at 0. | myList = [1,2,3,4,5]
print(myList[1]) | 2
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Lists are changableLists are changable, so you could eg. add or remove from it. | # Adding to a list my append()
myList = [1,2,3]
myList.append(3) # adds the value 3 to the list
print(myList)
# Removing from a list by remove()
myList.remove(2) # removes the value 2 from the list
print(myList)
# Removing from a list by pop()
myList.pop() # removes the last item in the list
print(myList)
myList.pop(... | [1, 2, 3, 3]
[1, 3, 3]
[1, 3]
[3]
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
TupleA tuple is a collection which is ordered and **unchangeable**. In Python tuples are written with parenthesis. When working with IFC and the ifcopenshell, we often work with tuples. | myTuple = ("apple", 1, "cherry", 10)
print(myTuple) | ('apple', 1, 'cherry', 10)
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
You access the tuple items, similar as for lists, by referring to the index number. Remember that the index starts at 0. | myTuple = (1,2,3,4,5)
print(myTuple[1]) | 2
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Tuples are unchangableTuples are unchangable, but you could cast it into a list and work with it as a list. | myTuple = (1,2,3,4,5)
myList = list(myTuple) # Cast tuple into a list
myList.pop(2)
myTuple = tuple(myList) # Cast list into a tuple
print(myTuple) | (1, 2, 4, 5)
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Check the number of elements in list or tupleIt is often needed to check how many elements that are in a list or a tuple. | # Check how many elements there are in myList (defined above)
print(len(myList))
# Check how many elements there are in myTuple (defined above)
print(len(myTuple)) | 3
3
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Exercise 4 - how many IfcWall elements are in Grethes Hus model? In the excercise below we want you to use what you have learned above to find how many elements of type IfcWall are in the Grethes Hus Modell. We have provided some code to get the file and to query out all elements of type IfcWall and stored it in a var... | # We import ifcopenshell and open the Grethes Hus Model and store it in a variable called file.
import ifcopenshell
file = ifcopenshell.open("models/Grethes-hus-bok-2.ifc")
#We query the file for its number of IfcWall type elements
walls = file.by_type("IfcWall")
"""ToDo: Change the zero below to list out the numbe... | 0
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Conditions and If statements > Python supports the usual logical conditions from mathematics:> * Equals: a == b> * Not Equals: a != b> * Less than: a < b> * Less than or equal to: a <= b> * Greater than: a > b> * Greater than or equal to: a >= b>> These conditions can be used in several ways, most commonly in "if stat... | ## Here we refer back to the variable "numberOfWalls" as defined above, and check if its greated than 0.
if numberOfWalls > 0:
print("You probably did something right above.") | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
elif and elseWe could also add to the If statement, by using an **Elif** statement. This will allow you to add another condition to check. At the end, we could also do an **Else** statement. This will be executed if no of the previous conditions where met. The syntax for this is: ```Python if : do something... | if numberOfWalls > 0:
print("You probably did something right above.")
elif numberOfWalls == 0:
print("You did probably do something wrong above")
else:
print("How could this happen...?") | You did probably do something wrong above
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Check if an element exist in a list or tupleOften times one would like to check if a particular value is in a list or a tuple. This is easy with python. | # Check if a value is in a list
myList = ["BIMFag", "banana", "BIM"]
if "BIMFag" in myList:
print("I found BIMFag in myList!")
myTuple = ["BIMFag", "banana", "BIM"]
if "BIMFag" in myTuple:
print("I found BIMFag in myTuple!") | I found BIMFag in myList!
I found BIMFag in myTuple!
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
While LoopsConditions and if statements are usefull also in while loops. While loops are executing as long as a condition is met. The syntax for while loops are: ```Python x = 1 while x<10: Checks if x is less than 10 do something eg. print(x) since x is bigger than zero this will print for as long ... | # Lets see it in action. Print out x as long as its less than the number of walls
x = 1
while x < numberOfWalls:
print(x)
x = x +1
else:
print("x is: %s and numberOfWalls is: %s"%(x,numberOfWalls)) | x is: 1 and numberOfWalls is: 0
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Loops, break and elseNotice that the loop exits when the condition is no longer met. Notice also that loops could also have an else statement, similar to if statements. If the loop condition are no longer met, then the else part is executed. If we want to exit the while loop early one could use the special **break** s... | x = 1
## Loop while True --> True is always True...
while True:
print(x)
# check if x is bigger or eaqual to 10
if x >= 10:
break # if condition met, break out of the while loop.
x = x+1 # if the condition of the if statement was false, this get executed in the while loop.
| 1
2
3
4
5
6
7
8
9
10
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
For LoopsA *for* loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).The syntax for for loops in python is: ```Pythonfor element in listOfElements: Do something with each element eg. print it out. print(element)```Notice the **indentation** here as well.... | myTuple = (1,2,3,4,5,6)
for element in myTuple:
print(element)
for i in range(6):
print(myTuple[i]) | 1
2
3
4
5
6
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Iterating over a number of IfcWindow objects and access attributesBelow we'll use a for loop to loop through all IfcWindow elements and print out some of it's direct attributes. See the IFC data dictinary for IFC 2.3 [here](https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/FINAL/HTML/). The main access page for t... | # We import ifcopenshell and open the Grethes Hus Model and store it in a variable called file.
import ifcopenshell
file = ifcopenshell.open("models/Grethes-hus-bok-2.ifc")
#We query the file for its number of IfcWindow type elements
windows = file.by_type("IfcWindow")
"""By uncommenting (removing the '#') the line... | The window elements name is: M_Fixed:_1400x2200mm:348960
The window elements name is: M_Fixed:_1400x2200mm:350239
The window elements name is: M_Fixed:_1400x2200mm:350479
The window elements name is: M_Fixed:_1400x2200mm:350484
The window elements name is: M_Fixed:_1400x2200mm:350489
The window elements name is: M_Fixe... | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Functions Functions are a useful way to divide your code into blocks of code, that only runs when they are called. It is also a good way to share a small snippet of code with others. A function is defined by the special ```def```statement. Like the example below. Defining a function | def myDefinedFunction():
print("This is a print statement within my function") | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Notice that the function uses the same indendation style as for If statements and loops as walked through above. A function could contain all the concepts we have walked through above as well. Notice however that noting happended above. That is why we havent called the function. It is however stored, so that we can cal... | myDefinedFunction() | This is a print statement within my function
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Input variables to functionsWe could also build functions that takes in input variables that could be used in the function. Lets define a function that takes in a string variable and prints it out. | # A function definition that takes in a parameter called "string"
def myDefinedFunction2(string):
print("My variable is %s"%string)
# A call to myDefinedFunction2 with the string variable "Hello again!"
myDefinedFunction2("Hello again!")
# A new call to myDefinedFunction2 with the string "and again and again"
myDe... | My variable is and again and again
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Input variables and assumed typeWhat would happen if we call myDefinedFunction2 with a number, instead of a string? Try it below. | string = 10
"""Try calling myDefinedFunction2 with the variable define above"""
| _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Exercise 5 - ensure that a function works as intendedYou can pass as many variables to a function as you'd like, just separate them with a comma like we do with var1 and var 2 below. They could be whatever object you'd like. Below we want to create a function that takes in two variables, var1 and var2. If they are bot... | def myFunc3(var1,var2):
"""Fill in code to comlete the challenge"""
"""Don't change the code below"""
myFunc3("Hello, ","World!")
myFunc3("hello",4) | Hello, World!
['hello', 4]
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Lists and tuples as input variablesWe could also add lists and tuples as input variables to functions. | def myFunc4(myList):
for elem in myList:
print(elem)
# Define a list
aList = [1,2,3]
# Send it as input variable to myFunc4
myFunc4(aList)
# Define a tuple
aTuple = (4,5,6)
# Send it as input variable to myFunc4
myFunc4(aTuple) | 1
2
3
4
5
6
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
What will happend if you pass a string instead of a list?Try below to call the function above passing in a string value like eg. ```myFunc4("your name")```What do you think will happen? | ### Do the test here ###
| _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Have functions return valuesA good way to use functions is to have them perform som logic on input variables and have them return the result. For this you use the ```return``` statement. | # defines a function that takes in a list of items as parameter,
# loops through it and adds all integers together, and then returns the resulting value
def myFunc5(myList):
tmp = 0 # Defined outside the for loop to be able to return it outside the scope of the loop
for elem in myList:
if isinstance(el... | 54
| MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Exercise 6 - Names and Descriptions of Window objects. Many times one would get an ifc model where one want to change or restructure information in the file. That is tediouse work on big models, so one may want to script it. In addition it would be a good code block to have, regardless of object type. In IFC the name ... | ### Add your code here ###
| _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Classes and ObjectsWe have already worked alot with objects, some window objects, some string objects, and even some list objects. So, what is objects and where do they come from? Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes. Class... | ## Defines a Window Class
class MyWindowClass:
nameVariable = "Window"
def namePrint(self):
print("My Name is "+self.nameVariable) | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Creating objects from class definitionsWhen you have defined a class, you could create several objects based on it. | ## Defines two different objects based on the MyWindowClass
window1 = MyWindowClass()
window2 = MyWindowClass() | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Accessing Object variables and functionsNow the window1 and window2 objects have both a nameVariable and namePrint function each. As we have seen above, we access its variables (attributes) by the "." operator. | # Get the nameVariable of window1
window1.nameVariable | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
MiniExercise: Do the same for window2 below | ### Get the the name variable of window2
| _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Exercise 7 - Setting object variablesBoth windows have the same name. Use what you know from above to set the name of window1 and window2 to something proper. | ### Solve Exercise 7 here:
| _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Exercise 8 - Accessing object functionsIn the MyWindowClass definition we have a function to print out the name. Show below how this function can be accessed on both window1 and window2. | ### Solve Exercise 8 here:
| _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Modules and PackagesIn programming, a module is a piece of software that has a specific functionality. For example, when building a ping pong game, one module could be responsible for the game logic, and another module could be responsible for drawing the game on the screen. Each module is a different file, which can ... | # Import the ifc_viewer class of ifc_viewer module
| _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
Using Packages and Modules in another programAnother package we already have used is the **ifcopenshell**. Packages are namespaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.Each package in Python is a directory which MUST contain a special file called __init_... | import ifcopenshell
import ifcopenshell.geom
from ifc_viewer import ifc_viewer
# Storing the model in a file variable, and giving the path to the file as input.
file = ifcopenshell.open("../models/Grethes_hus_bok_2.ifc")
# Storing all windows of the file by ising the by_type function of the file class
windows = fil... | _____no_output_____ | MIT | Course 1/Notebooks/01_Basic_Introduction_to_Python_for_use_with_BIM.ipynb | nasirkuvvetli/intro-python-bim |
04_2 Model_Stacking This notebook includes the data preparation and the developement of a Stacking model.Due to NDA agreements no data can be displayed. Data Preparation, Data Cleaning, and Preparation for Modelling is the same for all algorithms. To directly go to modelling click [here](modelling) --- Data preparati... | import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
import seaborn as sns
import matplotlib.pyplot as plt
import sys
sys.path.append("..")
... | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
Create data frame with important features So that everyone is on track with the feature selection, we created another csv file to rate the importance and only use important features for training our models and further analysis. Only important features are used to train the model. In this case we use 17 features beside... | # read list with feature importance
data_log = pd.read_csv('../data/Capstone_features_Features.csv')
data_log.head()
# create list of important features (feature importance < 3)
list_imp_feat = list(data_log[data_log['ModelImportance'] < 3]['VarName'])
len(list_imp_feat)
df_model = df[list_imp_feat].copy()
df_model.inf... | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
Fill and drop NaN Values for V.SLPOG.act.PRC and ME.SFCI.act.gPkWh contain missing values. The EDA showed that these are mainly caused during harbour times when the main engine was not running. Therefore it makes sense to fill the missing values with 0. | df_model['V.SLPOG.act.PRC'].fillna(0,inplace=True)
df_model['ME.SFCI.act.gPkWh'].fillna(0,inplace=True)
df_model['A.SOG.next.kn'] = (df_model['V.SOG.act.kn'].shift(-1) - df_model['V.SOG.act.kn'])
df_model['A.SOG.next.kn'].fillna(df_model['V.SOG.act.kn'], inplace=True)
df_model['A.SOG.next.kn'].describe() | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
The remaining rows with missing values are dropped. | df_model.dropna(inplace=True)
df_model.info()
plt.figure(figsize = (30,28))
sns.heatmap(df_model.corr(), annot = True, cmap = 'RdYlGn') | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
Define target | X = df_model.drop(['ME.FMS.act.tPh'], axis = 1)
y = df_model['ME.FMS.act.tPh']
X.rename(columns={'passage_type_Europe<13.5kn': 'passage_type_Europe_smaller_13.5kn', 'passage_type_Europe>13.5kn': 'passage_type_Europe_greater_13.5kn',\
'passage_type_SouthAmerica<13.5kn': 'passage_type_SouthAmerica_smaller_13.5kn', 'p... | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
Train Test Split Due to the high amount of data, a split into 10% test data and 90% train data is chosen. The random state is set to 42 to have comparable results for diffent models. To account for the imbalance in the distribution of passage types the stratify parameter is used for this feature. This results in appro... | X_train, X_test, y_train, y_test = train_test_split(X, y, stratify = X['passage_type'], test_size = 0.1, random_state = 42) | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
Create dummy values for passage type As passage_type is the only object type, get_dummies will only create dummies for passage_type. | X_train = pd.get_dummies(X_train, drop_first=True)
X_test = pd.get_dummies(X_test, drop_first=True) | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
Set MLFlow connection MLFlow is used to track and compare different models and model settings. | runmlflow = False
# setting the MLFlow connection and experiment
if runmlflow == True:
mlflow.set_tracking_uri(TRACKING_URI)
mlflow.set_experiment(EXPERIMENT_NAME)
mlflow.start_run(run_name='Stacking (Poly, RF_Hyper)') # CHANGE!
run = mlflow.active_run() | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
--- Modelling | RSEED = 42 | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
For all models in this project a MinMaxScaler is applied. For this model a random forrest is used. The hyperparameter are selected based on grid search and offer a reasonable balance between optimal results and overfitting. These settings are used in a pipeline. Pipeline | estimators = [
('rfh', make_pipeline(MinMaxScaler(), RandomForestRegressor(criterion= 'squared_error',
max_depth= 40,
max_features= 'auto',
max_leaf_nodes= 7000,
... | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
Fit and predict | reg.fit(X_train, y_train)
y_pred = reg.predict(X_test)
y_pred_train = reg.predict(X_train) | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
--- Analysis Errors and residuals The root mean squared error (RMSE) is used to evaluate the model. | y_pred2 = y_pred.copy()
y_pred2_train = y_pred_train.copy()
y_pred2[y_pred2 < 0.013509] = 0
y_pred2_train[y_pred2_train < 0.013509] = 0 #0.013509
print('RMSE train: ', mean_squared_error(y_train, y_pred2_train, squared= False))
rmse_train = mean_squared_error(y_train, y_pred2_train, squared= False)
print('RMSE test: ... | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
Plotting actual values against predicted shows that the points are close to the optimal diagonale. However, this plot and the yellowbrick residual plot show some dificulties the model has when predicting low target values. | fig=plt.figure(figsize=(6, 6))
plt.axline([1, 1], [2, 2],color='lightgrey')
plt.scatter(y_train, y_pred2_train, color ='#33424F')
plt.scatter(y_test, y_pred2, color = '#FF6600')
#plt.xticks(np.arange(0,501,100));
#plt.yticks(np.arange(0,501,100));
plt.xlabel("ME.FMS.act.tPh actual");
plt.ylabel("ME.FMS.act.tPh predicte... | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
--- Write to MLFlow | #seting parameters that should be logged on MLFlow
#these parameters were used in feature engineering (inputing missing values)
#or parameters of the model (fit_intercept for Linear Regression model)
params = {
"features drop": 'EntryDate,Date_daily, Type_daily, TI.LOC.act.ts, WEA.WDR.act.deg, WEA.WSR.act.mPs, WE... | _____no_output_____ | MIT | notebooks/04_2_Model_Stacking.ipynb | SuRreal1000/capstone_know_your_ship |
Theta Sketch Examples Basic Sketch Usage | from datasketches import theta_sketch, update_theta_sketch, compact_theta_sketch
from datasketches import theta_union, theta_intersection, theta_a_not_b | _____no_output_____ | BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
To start, we'll create a sketch with 1 million points in order to demonstrate basic sketch operations. | n = 1000000
k = 12
sk1 = update_theta_sketch(k)
for i in range(0, n):
sk1.update(i)
print(sk1) | ### Update Theta sketch summary:
lg nominal size : 12
lg current size : 13
num retained keys : 6560
resize factor : 8
sampling probability : 1
seed hash : 37836
ordered? : false
theta (fraction) : 0.00654224
theta (raw 64-bit) : 603415087386602... | BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
The summary contains most data fo interest, but we can also query for specific information. And in this case, since we know the exact number of distinct items presented ot the sketch, we can look at the estimate, upper, and lower bounds as a percentage of the exact value. | print("Upper bound (1 std. dev) as % of true value:\t", round(100*sk1.get_upper_bound(1) / n, 4))
print("Sketch estimate as % of true value:\t\t", round(100*sk1.get_estimate() / n, 4))
print("Lower bound (1 std. dev) as % of true value:\t", round(100*sk1.get_lower_bound(1) / n, 4)) | Upper bound (1 std. dev) as % of true value: 101.5208
Sketch estimate as % of true value: 100.2715
Lower bound (1 std. dev) as % of true value: 99.0374
| BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
We can serialize and reconstruct the sketch. If we compact the sketch prior to serialization, we can still query the rebuilt sketch but cannot update it further. | sk1_bytes = sk1.compact().serialize()
len(sk1_bytes)
new_sk1 = theta_sketch.deserialize(sk1_bytes)
print("Estimate: \t\t", new_sk1.get_estimate())
print("Estimation mode: \t", new_sk1.is_estimation_mode()) | Estimate: 1002714.745231455
Estimation mode: True
| BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
Sketch Unions Theta Sketch unions make use of a separate union object. The union will accept input sketches with different values of $k$.For this example, we will create a sketch with distinct values that partially overlap those in `sk1`. | offset = int(3 * n / 4)
sk2 = update_theta_sketch(k+1)
for i in range(0, n):
sk2.update(i + offset)
print(sk2) | ### Update Theta sketch summary:
lg nominal size : 13
lg current size : 14
num retained keys : 12488
resize factor : 8
sampling probability : 1
seed hash : 37836
ordered? : false
theta (fraction) : 0.0123336
theta (raw 64-bit) : 113757656857900... | BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
We can now feed the sketches into the union. As constructed, the exact number of unique values presented to the two sketches is $\frac{7}{4}n$. | union = theta_union(k)
union.update(sk1)
union.update(sk2)
result = union.get_result()
print("Union estimate as % of true value: ", round(100*result.get_estimate()/(1.75*n), 4)) | Union estimate as % of true value: 99.6787
| BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
Sketch Intersections Beyond unions, theta sketches also support intersctions through the use of an intersection object. These set intersections can have vastly superior error bounds than the classic inclusion-exclusion rule used with sketches like HLL. | intersection = theta_intersection()
intersection.update(sk1)
intersection.update(sk2)
print("Has result: ", intersection.has_result())
result = intersection.get_result()
print(result) | Has result: True
### Compact Theta sketch summary:
num retained keys : 1668
seed hash : 37836
ordered? : true
theta (fraction) : 0.00654224
theta (raw 64-bit) : 60341508738660257
estimation mode? : true
estimate : 254959
lower bound 95% conf : 242... | BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
In this case, we expect the sets to have an overlap of $\frac{1}{4}n$. | print("Intersection estimate as % of true value: ", round(100*result.get_estimate()/(0.25*n), 4)) | Intersection estimate as % of true value: 101.9834
| BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
Set Subtraction (A-not-B) Finally, we have the set subtraction operation. Unlike `theta_union` and `theta_intersection`, `theta_a_not_b` always takes as input 2 sketches at a time, namely $a$ and $b$, and directly returns the result as a sketch. | anb = theta_a_not_b()
result = anb.compute(sk1, sk2)
print(result) | ### Compact Theta sketch summary:
num retained keys : 4892
seed hash : 37836
ordered? : true
theta (fraction) : 0.00654224
theta (raw 64-bit) : 60341508738660257
estimation mode? : true
estimate : 747756
lower bound 95% conf : 726670
upper bound... | BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
By using the same two sketches as before, the expected result here is $\frac{3}{4}n$. | print("A-not-B estimate as % of true value: ", round(100*result.get_estimate()/(0.75*n), 4)) | A-not-B estimate as % of true value: 99.7008
| BSL-1.0 | python/jupyter/ThetaSketchNotebook.ipynb | tdoehmen/datasketches-cpp |
SVM | X_train, X_test, Y_train, Y_test = train_test_split(X_train_transform, sentiment, test_size=0.3)
clf = SVC().fit(X_train, Y_train)
predicted = clf.predict(X_test)
print(classification_report(Y_test, predicted))
kf = KFold(n_splits=10)
clf = SVC()
lista = []
for train_index, test_index in kf.split(X_train_transform):
... | 0.3835125448028674
0.45878136200716846
0.4121863799283154
0.43727598566308246
0.4659498207885305
0.44802867383512546
0.44086021505376344
0.4748201438848921
0.44964028776978415
0.48201438848920863
Média: 0.44530698022227383 Std: 0.028021649950196455
| MIT | Tash-PT/RNN_tash.ipynb | letisousa/SentimentAnalysisUpdates |
RL | X_train, X_test, Y_train, Y_test = train_test_split(X_train_transform, sentiment, test_size=0.3)
clf = LogisticRegression(max_iter=1000).fit(X_train, Y_train)
predicted = clf.predict(X_test)
print(classification_report(Y_test, predicted))
kf = KFold(n_splits=10)
clf = LogisticRegression(max_iter=1000)
lista = []
for ... | _____no_output_____ | MIT | Tash-PT/RNN_tash.ipynb | letisousa/SentimentAnalysisUpdates |
CONV1D | model = tf.keras.Sequential([
vectorize_layer,
tf.keras.layers.Embedding(
input_dim=len(vectorize_layer.get_vocabulary()),
output_dim=64,
mask_zero=True),
tf.keras.layers.Conv1D(32,6, activation='relu'),
tf.keras.layers.MaxPooling1D(2),
tf.keras.layers.Flatten(),
... | Fold: 0 Ultimo valor acc: 0.41577062010765076
Fold: 1 Ultimo valor acc: 0.379928320646286
Fold: 2 Ultimo valor acc: 0.40143370628356934
Fold: 3 Ultimo valor acc: 0.3476702570915222
Fold: 4 Ultimo valor acc: 0.4444444477558136
Fold: 5 Ultimo valor acc: 0.379928320646286
Fold: 6 Ultimo valor acc: 0.37992832... | MIT | Tash-PT/RNN_tash.ipynb | letisousa/SentimentAnalysisUpdates |
BDR | model = tf.keras.Sequential([
vectorize_layer,
tf.keras.layers.Embedding(
input_dim=len(vectorize_layer.get_vocabulary()),
output_dim=64,mask_zero=True),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(50)),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.D... | _____no_output_____ | MIT | Tash-PT/RNN_tash.ipynb | letisousa/SentimentAnalysisUpdates |
LSTM | model = tf.keras.Sequential([
vectorize_layer,
tf.keras.layers.Embedding(
input_dim=len(vectorize_layer.get_vocabulary()),
output_dim=64,mask_zero=True),
tf.keras.layers.LSTM(50, activation='relu' ,return_sequences=True),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.LSTM(1... | INFO:tensorflow:Reloading Oracle from existing project .\text_classifier\oracle.json
INFO:tensorflow:Reloading Tuner from .\text_classifier\tuner0.json
INFO:tensorflow:Oracle triggered exit
Epoch 1/10
61/61 [==============================] - 6s 96ms/step - loss: 0.6423 - accuracy: 0.3564 - val_loss: 0.6409 - val_accura... | MIT | Tash-PT/RNN_tash.ipynb | letisousa/SentimentAnalysisUpdates |
Training an Encrypted Neural NetworkIn this tutorial, we will walk through an example of how we can train a neural network with CrypTen. This is particularly relevant for the Feature Aggregation, Data Labeling and Data Augmentation use cases. We will focus on the usual two-party setting and show how we can train an ac... | import crypten
import torch
crypten.init()
torch.set_num_threads(1)
%run ./mnist_utils.py --option features --reduced 100 --binary | _____no_output_____ | MIT | tutorials/Tutorial_7_Training_an_Encrypted_Neural_Network.ipynb | mh739025250/CrypTen |
Next, we'll define the network architecture below, and then describe how to train it on encrypted data in the next section. | import torch.nn as nn
import torch.nn.functional as F
#Define an example network
class ExampleNet(nn.Module):
def __init__(self):
super(ExampleNet, self).__init__()
self.conv1 = nn.Conv2d(1, 16, kernel_size=5, padding=0)
self.fc1 = nn.Linear(16 * 12 * 12, 100)
self.fc2 = nn.Linear(1... | _____no_output_____ | MIT | tutorials/Tutorial_7_Training_an_Encrypted_Neural_Network.ipynb | mh739025250/CrypTen |
Encrypted TrainingAfter all the material we've covered in earlier tutorials, we only need to know a few additional items for encrypted training. We'll first discuss how the training loop in CrypTen differs from PyTorch. Then, we'll go through a complete example to illustrate training on encrypted data from end-to-end.... | # Define source argument values for Alice and Bob
ALICE = 0
BOB = 1
# Load Alice's data
data_alice_enc = crypten.load_from_party('/tmp/alice_train.pth', src=ALICE)
# We'll now set up the data for our small example below
# For illustration purposes, we will create toy data
# and encrypt all of it from source ALICE
x_sm... | Epoch: 0 Loss: 0.3058
Epoch: 1 Loss: 0.2807
| MIT | tutorials/Tutorial_7_Training_an_Encrypted_Neural_Network.ipynb | mh739025250/CrypTen |
A Complete ExampleWe now put these pieces together for a complete example of training a network in a multi-party setting. As in Tutorial 3, we'll assume Alice has the rank 0 process, and Bob has the rank 1 process; so we'll load and encrypt Alice's data with `src=0`, and load and encrypt Bob's data with `src=1`. We'll... | import crypten.mpc as mpc
import crypten.communicator as comm
# Convert labels to one-hot encoding
# Since labels are public in this use case, we will simply use them from loaded torch tensors
labels = torch.load('/tmp/train_labels.pth')
labels = labels.long()
labels_one_hot = label_eye[labels]
@mpc.run_multiprocess(... | torch.Size([100, 28, 20])
torch.Size([100, 28, 8])
| MIT | tutorials/Tutorial_7_Training_an_Encrypted_Neural_Network.ipynb | mh739025250/CrypTen |
We see that the average batch loss decreases across the epochs, as we expect during training.This completes our tutorial. Before exiting this tutorial, please clean up the files generated using the following code. | import os
filenames = ['/tmp/alice_train.pth',
'/tmp/bob_train.pth',
'/tmp/alice_test.pth',
'/tmp/bob_test.pth',
'/tmp/train_labels.pth',
'/tmp/test_labels.pth']
for fn in filenames:
if os.path.exists(fn): os.remove(fn) | _____no_output_____ | MIT | tutorials/Tutorial_7_Training_an_Encrypted_Neural_Network.ipynb | mh739025250/CrypTen |
Line Continuation Add a backslash in the code below, so it is a one-line code. Observe the change in the result. | 15 + 31\
- 26 | _____no_output_____ | MIT | Python basics practice/Python 3 (5)/Line Continuation - Exercise_Py3.ipynb | rachithh/data-science |
Add a default legend to LayerIn this example, a default Legend with a title, description, and footer is added to the map.For more information, run `help(Layer)` or `help(Legend)`. | from cartoframes.auth import set_default_credentials
from cartoframes.viz import Map, Layer, Legend
set_default_credentials('cartoframes')
Map(
Layer(
'global_power_plants',
legend=Legend(
'default',
title='Global Power Plants',
description='Power plant locations... | _____no_output_____ | BSD-3-Clause | examples/layers/add_default_legend_layer.ipynb | jorisvandenbossche/cartoframes |
Vertex pipelines**Learning Objectives:**Use components from `google_cloud_pipeline_components` to create a Vertex Pipeline which will 1. train a custom model on Vertex AI 1. create an endpoint to host the model 1. upload the trained model, and 1. deploy the uploaded model to the endpoint for serving OverviewThi... | !pip3 install --user google-cloud-pipeline-components==0.1.1 --upgrade | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
Restart the kernelAfter you install the additional packages, you need to restart the notebook kernel so it can find the packages. Import libraries and define constants | import os
from datetime import datetime
import kfp
from google.cloud import aiplatform
from google_cloud_pipeline_components import aiplatform as gcc_aip
from kfp.v2 import compiler
from kfp.v2.dsl import component
from kfp.v2.google import experimental | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
Check the versions of the packages you installed. The KFP SDK version should be >=1.6. | print("KFP SDK version: {}".format(kfp.__version__)) | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
Set your environment variablesNext, we'll set up our project variables, like GCP project ID, the bucket and region. Also, to avoid name collisions between resources created, we'll create a timestamp and append it onto the name of resources we create in this lab. | # Change below if necessary
PROJECT = !gcloud config get-value project # noqa: E999
PROJECT = PROJECT[0]
BUCKET = PROJECT
REGION = "us-central1"
TIMESTAMP = datetime.now().strftime("%Y%m%d%H%M%S")
PIPELINE_ROOT = f"gs://{BUCKET}/pipeline_root"
print(PIPELINE_ROOT) | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
We'll save pipeline artifacts in a directory called `pipeline_root` within our bucket. Validate access to your Cloud Storage bucket by examining its contents. It should be empty at this stage. | !gsutil ls -la gs://{BUCKET}/pipeline_root | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
Give your default service account storage bucket accessThis pipeline will read `.csv` files from Cloud storage for training and will write model checkpoints and artifacts to a specified bucket. So, we need to give our default service account `storage.objectAdmin` access. You can do this by running the command below in... | @component
def training_op(input1: str):
print("VertexAI pipeline: {}".format(input1)) | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
Now, you define the pipeline. The `experimental.run_as_aiplatform_custom_job` method takes as args the component defined above, and the list of `worker_pool_specs`— in this case one— with which the custom training job is configured. See [full function code here](https://github.com/kubeflow/pipelines/blob/master/sdk/p... | # Output directory and job_name
OUTDIR = f"gs://{BUCKET}/taxifare/trained_model_{TIMESTAMP}"
MODEL_DISPLAY_NAME = f"taxifare_{TIMESTAMP}"
PYTHON_PACKAGE_URIS = f"gs://{BUCKET}/taxifare/taxifare_trainer-0.1.tar.gz"
MACHINE_TYPE = "n1-standard-16"
REPLICA_COUNT = 1
PYTHON_PACKAGE_EXECUTOR_IMAGE_URI = (
"us-docker.pk... | _____no_output_____ | Apache-2.0 | notebooks/building_production_ml_systems/labs/3_kubeflow_pipelines_vertex.ipynb | paras301/asl-ml-immersion |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.