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
Does Python know about your error before it runs your code? Python is what is called an interpreted language. Compiled languages examine your entire program at compile time, and are able to warn you about a whole class of errors prior to execution. In contrast, Python interprets your script line by line as it executes...
# Print string and error to see the running order print("This will be printed") print("This will cause an error") print("This will NOT be printed")
This will be printed This will cause an error This will NOT be printed
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Exercise: Your First Program Generations of programmers have started their coding careers by simply printing "Hello, world!". You will be following in their footsteps.In the code cell below, use the print() function to print out the phrase: Hello, world!
# Write your code below and press Shift+Enter to execute print('Hello, World!')
Hello, World!
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Double-click __here__ for the solution.<!-- Your answer is below:print("Hello, world!")--> Now, let's enhance your code with a comment. In the code cell below, print out the phrase: Hello, world! and comment it with the phrase Print the traditional hello world all in one line of code.
# Write your code below and press Shift+Enter to execute print('Hello, World!')
Hello, World!
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Double-click __here__ for the solution.<!-- Your answer is below:print("Hello, world!") Print the traditional hello world--> Types of objects in Python Python is an object-oriented language. There are many different types of objects in Python. Let's start with the most common object types: strings, integers and floa...
# Integer 21 # Float 3.14 # String "Hello, Python 101!"
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
You can get Python to tell you the type of an expression by using the built-in type() function. You'll notice that Python refers to integers as int, floats as float, and character strings as str.
# Type of 12 type(12) # Type of 2.14 type(2.14) # Type of "Hello, Python 101!" type("Hello, Python 101!")
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
In the code cell below, use the type() function to check the object type of 12.0.
# Write your code below. Don't forget to press Shift+Enter to execute the cell type(12.0)
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Double-click __here__ for the solution.<!-- Your answer is below:type(12.0)--> Integers Here are some examples of integers. Integers can be negative or positive numbers: We can verify this is the case by using, you guessed it, the type() function:
# Print the type of -1 type(-1) # Print the type of 4 type(4) # Print the type of 0 type(0)
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Floats Floats represent real numbers; they are a superset of integer numbers but also include "numbers with decimals". There are some limitations when it comes to machines representing real numbers, but floating point numbers are a good representation in most cases. You can learn more about the specifics of floats fo...
# Print the type of 1.0 type(1.0) # Notice that 1 is an int, and 1.0 is a float # Print the type of 0.5 type(0.5) # Print the type of 0.56 type(0.56) # System settings about float type sys.float_info
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Converting from one object type to a different object type You can change the type of the object in Python; this is called typecasting. For example, you can convert an integer into a float (e.g. 2 to 2.0).Let's try it:
# Verify that this is an integer type(2)
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Converting integers to floatsLet's cast integer 2 to float:
# Convert 2 to a float float(2) # Convert integer 2 to a float and check its type type(float(2))
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
When we convert an integer into a float, we don't really change the value (i.e., the significand) of the number. However, if we cast a float into an integer, we could potentially lose some information. For example, if we cast the float 1.1 to integer we will get 1 and lose the decimal information (i.e., 0.1):
# Casting 1.1 to integer will result in loss of information int(1.1)
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Converting from strings to integers or floats Sometimes, we can have a string that contains a number within it. If this is the case, we can cast that string that represents a number into an integer using int():
# Convert a string into an integer int('1')
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
But if you try to do so with a string that is not a perfect match for a number, you'll get an error. Try the following:
# Convert a string into an integer with error # int('1 or 2 people') int('1')
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
You can also convert strings containing floating point numbers into float objects:
# Convert the string "1.2" into a float float('1.2')
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
[Tip:] Note that strings can be represented with single quotes ('1.2') or double quotes ("1.2"), but you can't mix both (e.g., "1.2'). Converting numbers to strings If we can convert strings to numbers, it is only natural to assume that we can convert numbers to strings, right?
# Convert an integer to a string str(1)
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
And there is no reason why we shouldn't be able to make floats into strings as well:
# Convert a float to a string str(1.2)
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Boolean data type Boolean is another important type in Python. An object of type Boolean can take on one of two values: True or False:
# Value true True
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Notice that the value True has an uppercase "T". The same is true for False (i.e. you must use the uppercase "F").
# Value false False
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
When you ask Python to display the type of a boolean object it will show bool which stands for boolean:
# Type of True type(True) # Type of False type(False)
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
We can cast boolean objects to other data types. If we cast a boolean with a value of True to an integer or float we will get a one. If we cast a boolean with a value of False to an integer or float we will get a zero. Similarly, if we cast a 1 to a Boolean, you get a True. And if we cast a 0 to a Boolean we will get a...
# Convert True to int int(True) # Convert 1 to boolean bool(1) # Convert 0 to boolean bool(0) # Convert True to float float(False)
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Exercise: Types What is the data type of the result of: 6 / 2?
# Write your code below. Don't forget to press Shift+Enter to execute the cell print(6/2)
3.0
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Double-click __here__ for the solution.<!-- Your answer is below:type(6/2) float--> What is the type of the result of: 6 // 2? (Note the double slash //.)
# Write your code below. Don't forget to press Shift+Enter to execute the cell print(6//2)
3
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Double-click __here__ for the solution.<!-- Your answer is below:type(6//2) int, as the double slashes stand for integer division --> Expression and Variables Expressions Expressions in Python can include operations among compatible types (e.g., integers and floats). For example, basic arithmetic operations like add...
# Addition operation expression 43 + 60 + 16 + 41
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
We can perform subtraction operations using the minus operator. In this case the result is a negative number:
# Subtraction operation expression 50 - 60
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
We can do multiplication using an asterisk:
# Multiplication operation expression 5 * 5
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
We can also perform division with the forward slash:
# Division operation expression 25 / 5 # Division operation expression 25 / 6
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
As seen in the quiz above, we can use the double slash for integer division, where the result is rounded to the nearest integer:
# Integer division operation expression 25 // 5 # Integer division operation expression 25 // 6
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Exercise: Expression Let's write an expression that calculates how many hours there are in 160 minutes:
# Write your code below. Don't forget to press Shift+Enter to execute the cell z = 160//60 print(z, 'Hours')
2 Hours
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Double-click __here__ for the solution.<!-- Your answer is below:160/60 Or 160//60--> Python follows well accepted mathematical conventions when evaluating mathematical expressions. In the following example, Python adds 30 to the result of the multiplication (i.e., 120).
# Mathematical expression 30 + 2 * 60
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
And just like mathematics, expressions enclosed in parentheses have priority. So the following multiplies 32 by 60.
# Mathematical expression (30 + 2) * 60
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Variables Just like with most programming languages, we can store values in variables, so we can use them later on. For example:
# Store value into variable x = 43 + 60 + 16 + 41
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
To see the value of x in a Notebook, we can simply place it on the last line of a cell:
# Print out the value in variable print(x)
160
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
We can also perform operations on x and save the result to a new variable:
# Use another variable to store the result of the operation between variable and value y = x / 60 y
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
If we save a value to an existing variable, the new value will overwrite the previous value:
# Overwrite variable with new value x = x / 60 x
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
It's a good practice to use meaningful variable names, so you and others can read the code and understand it more easily:
# Name the variables meaningfully total_min = 43 + 42 + 57 # Total length of albums in minutes total_min # Name the variables meaningfully total_hours = total_min / 60 # Total length of albums in hours total_hours
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
In the cells above we added the length of three albums in minutes and stored it in total_min. We then divided it by 60 to calculate total length total_hours in hours. You can also do it all at once in a single expression, as long as you use parenthesis to add the albums length before you divide, as shown below.
# Complicate expression total_hours = (43 + 42 + 57) / 60 # Total hours in a single expression total_hours
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
If you'd rather have total hours as an integer, you can of course replace the floating point division with integer division (i.e., //). Exercise: Expression and Variables in Python What is the value of x where x = 3 + 2 * 2
# Write your code below. Don't forget to press Shift+Enter to execute the cell x = 3 + 2 * 2 x
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Double-click __here__ for the solution.<!-- Your answer is below:7--> What is the value of y where y = (3 + 2) * 2?
# Write your code below. Don't forget to press Shift+Enter to execute the cell y = (3 + 2) * 2 y
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
Double-click __here__ for the solution.<!-- Your answer is below:10--> What is the value of z where z = x + y?
# Write your code below. Don't forget to press Shift+Enter to execute the cell z = x + y z
_____no_output_____
MIT
PY0101EN_1_1_Types.ipynb
NikkiRufiansya/ML-Courses
prepare general parametersparameters are saved in json file. json file has advantage that it is saved in the text format and therefore it can be easily opened, visualised and changed without python
import datetime import json import numpy as np import os import lib.helper as hl region_type = 'hippocamp' current_dir = os.getcwd() dir_morpho_vertical = os.path.join(current_dir, 'data/vertical')# where your vertical morphologies are saved results_dir = os.path.join(current_di...
Created new DEFAULT .json file: /home/maria/maja/code/lfp-paper/data/results/2018_12_5_14_1_all.json
CC-BY-4.0
set_general_params.py.ipynb
maikia/ulfp-paper
SVM with queue imbalance
df_res = {} for s in stocks: df_res_temp = pd.read_csv('res_{}_prev_queue_imbalance.csv'.format(s)) df_res_temp = df_res_temp[df_res_temp['features'] == 'queue_imbalance'] df_res_temp = df_res_temp[df_res_temp['method'] == 'svm_sigmoid'] df_res_temp['stock'] = [s for i in range(len(df_res_temp))] df...
_____no_output_____
MIT
overview_val10/overview_all_three_svm-sigmoid.ipynb
vevurka/mt-lob
Qonto - Get positions
import naas_drivers # Enter your credentials user_id = 'YOUR_USER_ID' api_key = 'YOUR_API_KEY' # Get bank positions df_positions = qonto.connect(user_id, api_key).positions.get() df_positions
_____no_output_____
BSD-3-Clause
Qonto/Qonto_Get_positions.ipynb
gagan3012/awesome-notebooks
1. Let’s attempt to predict the survival of a horse based on various observed medical conditions. Load the data from ‘horses.csv’ and observe whether it contains missing values.[Hint: Pandas dataframe has a method isnull] 2. This dataset contains many categorical features, replace them with label encoding.[Hint: Refer...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns dfhorses = pd.read_csv('horse.csv') dfhorses.shape dfhorses.info() dfhorses.sample(10) dfhorses.isna().sum() dfhorses.outcome.unique() dfhorses['rectal_temp'].fillna(dfhorses['rectal_temp'].mean(), inplace= True) dfhorses.count...
_____no_output_____
MIT
Cls4-Supervised Learning - 1/Supervised1 - Case Study 2 - Solution.ipynb
tuhinssam/MLResources
Same value
import evidence as evi datum1 = evi.Evidence(3.12) datum1.add_reference({'database':'DOI', 'id':'XXX'}) datum2 = evi.Evidence(3.12) datum2.add_reference({'database':'PubMed', 'id':'YYY'}) datum3 = evi.Evidence(3.12) datum3.add_reference({'database':'PubMed', 'id':'ZZZ'}) datum4 = evi.Evidence(6.58) datum4.add_refere...
_____no_output_____
MIT
docs/contents/same_value.ipynb
dprada/evidence
Accumulation Test
relevantColumns = ['id', 'serverTime', 'playerId', 'type', 'section'] df = df100.loc[:,relevantColumns] part131 = df131.loc[:,relevantColumns] part132 = df132.loc[:,relevantColumns] df = pd.concat([df, part131, part132]) df
_____no_output_____
CC0-1.0
tests/accumulation.ipynb
CyberCRI/herocoli-metrics-redwire
第五周 函数和代码 5.1 函数的定义与使用 5.2 实例7:七段数码管绘制 5.3 代码复用与函数递归 5.4 模块4:PyInstaller库的使用 5.5 科赫雪花小包裹 5.1 函数的定义与使用- 函数的理解与定义 - 函数是一段代码的表示,是具有一定功能的、可重复使用的语句组,是一种功能的抽象 - 两个作用: - 降低编程难度 - 代码复用 - ``` def(): return ``` - 函数定义时,所指定的参数是一种占位符 - 函数定义后,如果不经过调用,不会被执行 - 函数...
#计算n! def fact(n): s=1 for i in range(1,n+1): s*=i return s n = input() b=fact(int(n)) print(b)
3628800
MIT
week5.ipynb
ali820/leanringPython
- 函数的使用及调用过程 - 函数只有被调用,才会被执行- 函数的参数传递 - 无论函数有没有参数,都要保留括号 - 可选参数:函数定义时可以为某些参数指定默认值,构成可选参数 - ``` def(,): return ``` - 可选参数一定要在必选参数后面 - 可变参数的传递:函数定义时可以设计可变数量参数,既不确定参数总数量 - ``` def(,*b): return ``` - 函数调用时,参数可以...
#可选参数:计算n!//m def fact(n,m=1): #m是可选参数 s=1 for i in range(1,n+1): s*=i return s//m b=fact(10,5) #位置传递 c=fact(m=5,n=10) #名称传递 print(b,c) #可变参数:计算n!//m def fact(n,*b): #*b为可变参数 s=1 for i in range(1,n+1): s*=i for item in b: s*=item return s print(fact(3)) print(fa...
6 144 5400
MIT
week5.ipynb
ali820/leanringPython
- 函数的返回值 - 函数可以返回0或者多个结果,也可以不返回
#可选参数:计算n!//m def fact(n,m=1): #m是可选参数 s=1 for i in range(1,n+1): s*=i return s,m,s//m #返回三个值 b=fact(10,5) #位置传递 c=fact(m=5,n=10) #名称传递 x,y,z = fact(10,5) #返回的三个值分别赋给xyz print(b,c) print(x,y,z)
(3628800, 5, 725760) (3628800, 5, 725760) 3628800 5 725760
MIT
week5.ipynb
ali820/leanringPython
- 局部变量和全局变量 - 局部变量是函数内部使用的变量 1. 局部变量和全局变量是不同变量- 局部变量是函数内部的占位符,可以与全局变量重名但是不相同- 函数运算结束后,局部变量被释放- 可以使用`global`保留字在函数内部使用全局变量
n,s=10,100 #此处n,s是全局变量 def fact(n): #fact函数中的n,s是局部变量 s=1 for i in range(1,n+1): s*=i return s print(fact(n),s) #n,s是全局变量 n,s=10,100 #此处n,s是全局变量 def fact(n): #fact函数中的n,s是局部变量 global s #声明是全局变量 for i in range(1,n+1): s*=i return s print(fact(n),s) #n,s是全局变量
362880000 362880000
MIT
week5.ipynb
ali820/leanringPython
2. 局部变量为组合数据类型且未创建,等同于全局变量
ls=['F','f'] #创建全局变量s def func(a): ls.append(a) #此处ls是列表类型,未真实创建则等同于全局变量 return func('C') #全局变量ls被修改 print(ls) ls=['F','f'] #创建全局变量s def func(a): ls = [] #此处ls是列表类型,真实创建ls是局部变量,函数运行完成就被释放 ls.append(a) return func('C') #局部变量ls被修改 print(ls)
['F', 'f']
MIT
week5.ipynb
ali820/leanringPython
- lambda函数 - lambda函数返回函数名作为结果 1. lambda函数是一种匿名函数,即没有名字的函数 2. 使用lambda保留字定义,函数名是返回结果 3. lambda函数用于定义简单的、能够在一行内表示的函数 ``` =lambda: ``` - 谨慎使用lambda函数 - lambda函数主要用作一些特定函数或方法的参数 - lambda函数有固定的使用方式
# f = lambda x,y:x+y print(f(10,15))
25
MIT
week5.ipynb
ali820/leanringPython
5.2 实例7:七段数码管绘制- 交通灯的显示等 1. 绘制三个数字的数码管 - 七段数码管由7个基本线条组成 - 七段数码管可以有固定顺序 - 不同数字显示不同的线条 2. 获得一串数字,绘制对应数码管 3. 获得当前时间,绘制对应数码管
#SevenDigitsDrawV1.py import turtle as t def drawLine(draw): #绘制单段数码管 t.pendown() if draw else t.penup() t.fd(40) t.right(90) def drawDigit(digit): #根据数字绘制七段数码管 drawLine(True) if digit in...
_____no_output_____
MIT
week5.ipynb
ali820/leanringPython
5.3 代码复用与函数递归- 把代码当作资源进行抽象: - 代码资源化:程序代码是一种用来表达计算的“资源” - 代码抽象化:使用函数等方法对代码赋予更高级别的定义 - 代码复用:同一份代码在需要时可以被重复使用- 函数和对象是代码复用的两种主要形式 - 函数:将代码命名,在代码层面建立了初步抽象 - 对象:通过属性和方法`.`和`.()`,在函数之上再次组织进行抽象- 模块化设计:分而治之 - 通过函数或对象封装将程序划分为模块及模块间的表达 - 具体包括:主程序、子程序和子程序间的关系 - 是一中分而治之、分层抽象、体系化设计的思想- 紧耦合:两个部分之间交流很多,无法独立存在-...
#n!计算 def fact(n): if n==0: return 1 else: return n*fact(n-1) n=10 print(fact(n)) #字符串反转-递归 # s=input() # s[::-1] def rvs(s): if s == '': return s else: return rvs(s[1:])+s[0] s = 'sdf' rvs(s) #斐波那契数列 def f(n): if n ==1 or n == 2: return 1 else: ...
1:a->c 2:a->b 1:c->b 3:a->c 1:b->a 2:b->c 1:a->c 7 0.00025690000256872736
MIT
week5.ipynb
ali820/leanringPython
5.4 模块4:PyInstaller库的使用- PyInstaller可以将.py源代码文件封装成为可执行文件 - pyinstaller -h:查看帮助 - pyinstaller --clean:清理打包过程的临时文件 - -D,--online:默认值,生成dist文件夹 - -F,--onefile:在dist文件夹中只生成独立打包文件 - -i指定打包程序使用的图标(icon)文件 5.5 科赫雪花小包裹- 科赫曲线:一种迭代的自相似曲线
#KochDrawV1 import turtle as t def koch(size,n): if n == 0: t.fd(size) else: for angle in [0,60,-120,60]: t.left(angle) koch(size/3,n-1) def main(): t.setup(800,400) t.penup() t.goto(-300,-50) t.pendown() t.pensize(2) koch(600,3) t.hideturtle(...
_____no_output_____
MIT
week5.ipynb
ali820/leanringPython
随机密码生成描述补充编程模板中代码,完成如下功能:‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬以整数17为随机数种子,获取用户输入整数N为长度,产生3个长度为N位的密码,密码的每位是一个数字。每个密码单独一行输出。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬产生密码采用random.randint()函数。
import random def genpwd(length): return random.randint(pow(10,length-1),pow(10,length)) length = eval(input()) random.seed(17) for i in range(3): print(genpwd(length))
634 524 926
MIT
week5.ipynb
ali820/leanringPython
连续质数计算描述补充编程模板中代码,完成如下功能:‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬获得用户输入数字N,计算并输出从N开始的5个质数,单行输出,质数间用逗号,分割。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬注意:需要考虑用户输入的数字N可能是浮点数,应对输入取整数;最后一个输出后不用逗号。
def prime(m): count = 1 while(count<=5): isprime = 1 for i in range(2,m): if m%i == 0: isprime = 0 if isprime == 1: if count == 5: print(m,end='') else: print(m,end=',') count+=1 m+=1 ...
13,17,19,23,29
MIT
week5.ipynb
ali820/leanringPython
Crossentropy methodThis notebook will teach you to solve reinforcement learning problems with crossentropy method.
import gym import numpy as np, pandas as pd env = gym.make("Taxi-v2") env.reset() env.render() n_states = env.observation_space.n n_actions = env.action_space.n print("n_states=%i, n_actions=%i"%(n_states, n_actions))
n_states=500, n_actions=6
MIT
week1_intro/.ipynb_checkpoints/crossentropy_method-checkpoint.ipynb
syuntoku14/PracticalRL_coursera_pytorch
Create stochastic policyThis time our policy should be a probability distribution.```policy[s,a] = P(take action a | in state s)```Since we still use integer state and action representations, you can use a 2-dimensional array to represent the policy.Please initialize policy __uniformly__, that is, probabililities of a...
policy = <your code here! Create an array to store action probabilities> assert type(policy) in (np.ndarray,np.matrix) assert np.allclose(policy,1./n_actions) assert np.allclose(np.sum(policy,axis=1), 1)
_____no_output_____
MIT
week1_intro/.ipynb_checkpoints/crossentropy_method-checkpoint.ipynb
syuntoku14/PracticalRL_coursera_pytorch
Play the gameJust like before, but we also record all states and actions we took.
def generate_session(policy,t_max=10**4): """ Play game until end or for t_max ticks. :param policy: an array of shape [n_states,n_actions] with action probabilities :returns: list of states, list of actions and sum of rewards """ states,actions = [],[] total_reward = 0. s = env.res...
_____no_output_____
MIT
week1_intro/.ipynb_checkpoints/crossentropy_method-checkpoint.ipynb
syuntoku14/PracticalRL_coursera_pytorch
Crossentropy method steps (2pts)
def select_elites(states_batch,actions_batch,rewards_batch,percentile=50): """ Select states and actions from games that have rewards >= percentile :param states_batch: list of lists of states, states_batch[session_i][t] :param actions_batch: list of lists of actions, actions_batch[session_i][t] :pa...
_____no_output_____
MIT
week1_intro/.ipynb_checkpoints/crossentropy_method-checkpoint.ipynb
syuntoku14/PracticalRL_coursera_pytorch
Training loopGenerate sessions, select N best and fit to those.
from IPython.display import clear_output def show_progress(batch_rewards, log, percentile, reward_range=[-990,+10]): """ A convenience function that displays training progress. No cool math here, just charts. """ mean_reward, threshold = np.mean(batch_rewards), np.percentile(batch_rewards, pe...
_____no_output_____
MIT
week1_intro/.ipynb_checkpoints/crossentropy_method-checkpoint.ipynb
syuntoku14/PracticalRL_coursera_pytorch
Reflecting on resultsYou may have noticed that the taxi problem quickly converges from <-1000 to a near-optimal score and then descends back into -50/-100. This is in part because the environment has some innate randomness. Namely, the starting points of passenger/driver change from episode to episode.In case CEM fail...
from submit import submit_taxi submit_taxi(generate_session, policy, <EMAIL>, <TOKEN>)
_____no_output_____
MIT
week1_intro/.ipynb_checkpoints/crossentropy_method-checkpoint.ipynb
syuntoku14/PracticalRL_coursera_pytorch
General pruning
need_pruning = True method = 'pruning' methods = [] splits = [] explanations = [] explanations_inv = [] model_accuracies = [] explanation_accuracies = [] explanation_accuracies_inv = [] elapsed_times = [] elapsed_times_inv = [] for split, (train_index, test_index) in enumerate(skf.split(x.cpu().detach().numpy(), y.cpu...
_____no_output_____
Apache-2.0
experiments/old/experiment_07_omalizumab_full.ipynb
pietrobarbiero/logic_explained_networks
LIME
need_pruning = False method = 'lime' methods = [] splits = [] explanations = [] explanations_inv = [] model_accuracies = [] explanation_accuracies = [] explanation_accuracies_inv = [] elapsed_times = [] elapsed_times_inv = [] for seed in range(n_rep): print(f'Seed [{seed+1}/{n_rep}]') model = train_nn(x_tr...
_____no_output_____
Apache-2.0
experiments/old/experiment_07_omalizumab_full.ipynb
pietrobarbiero/logic_explained_networks
Weights
need_pruning = False method = 'weights' methods = [] splits = [] explanations = [] explanations_inv = [] model_accuracies = [] explanation_accuracies = [] explanation_accuracies_inv = [] elapsed_times = [] elapsed_times_inv = [] for split, (train_index, test_index) in enumerate(skf.split(x.cpu().detach().numpy(), y.cp...
_____no_output_____
Apache-2.0
experiments/old/experiment_07_omalizumab_full.ipynb
pietrobarbiero/logic_explained_networks
Psi network
def train_psi_nn(x_train, y_train, need_pruning, seed, device): set_seed(seed) x_train = x_train.to(device) y_train = y_train.to(device).to(torch.float) layers = [ torch.nn.Linear(x_train.size(1), 10), torch.nn.Sigmoid(), torch.nn.Linear(10, 4), torch.nn.Sigmoid(), ...
_____no_output_____
Apache-2.0
experiments/old/experiment_07_omalizumab_full.ipynb
pietrobarbiero/logic_explained_networks
Decision tree
need_pruning = False method = 'decision_tree' methods = [] splits = [] explanations = [] explanations_inv = [] model_accuracies = [] explanation_accuracies = [] explanation_accuracies_inv = [] elapsed_times = [] elapsed_times_inv = [] for split, (train_index, test_index) in enumerate(skf.split(x.cpu().detach().numpy()...
_____no_output_____
Apache-2.0
experiments/old/experiment_07_omalizumab_full.ipynb
pietrobarbiero/logic_explained_networks
Summary
cols = ['model_accuracy', 'explanation_accuracy', 'explanation_accuracy_inv', 'elapsed_time', 'elapsed_time_inv'] mean_cols = [f'{c}_mean' for c in cols] sem_cols = [f'{c}_sem' for c in cols] # pruning df_mean = results_pruning[cols].mean() df_sem = results_pruning[cols].sem() df_mean.columns = mean_cols df_sem.column...
_____no_output_____
Apache-2.0
experiments/old/experiment_07_omalizumab_full.ipynb
pietrobarbiero/logic_explained_networks
Radiative Convective Equilibrium with Simple Physics----------------------------------This demo steps the grey radiation code forward in time to get a radiative equilibriumprofile. The Simple Physics module is available to add a boundary layer andsurface fluxes. The Emanuel convection scheme provides moist convection....
%matplotlib notebook import numpy as np import climt from climt.simple_physics_custom import simple_physics_custom global_time_step = 100. #Initialise radiation kwargs = {} #kwargs['UpdateFreq'] = 3600. rad = climt.radiation(scheme='newgreygas', **kwargs) #Initialise simple physics kwargs = {} #kwargs['qflux'] = F...
_____no_output_____
BSD-3-Clause
lib/examples/CliMT -- Radiative-Convective Equilibrium with Simple Physics.ipynb
CliMT/climt-legacy
---title: "DataFrame object"author: "TACT"date: 2019-04-20description: "-"type: technical_notedraft: false--- The pandas DataFrame object a pandas series represents a single array of values, with an index label for each value.if you want to have more than one series of data that is aligned by a common index, then a ...
import pandas as pd from pandas import DataFrame, Series dates = pd.date_range('2019-05-18', '2019-05-25') temp_chennai = Series([36, 37, 36, 37, 37, 37, 37, 37], index = dates) temp_delhi = Series([34, 39, 41, 41, 41, 41, 41, 42], index = dates) # create a DataFrame from the two...
_____no_output_____
MIT
content/python/pandas/.ipynb_checkpoints/DataFrame_object-checkpoint.ipynb
mmblack4/mynotes
第二类区间型DP: 给定字符串s,找到最长回文子序列的长度s。您可以假设s的最大长度为1000。Example 1: Input: "bbbab" Output: 4 One possible longest palindromic subsequence is "bbbb". Example 2: Input: "cbbd" Output: 2 One possible longest palindromic subsequence is "bb".Constraints: 1、1 <= s.length <= 1000 ...
class Solution: def longestPalindromeSubseq(self, s: str) -> int: s = '0' + s len_s = len(s) dp = [[0] * len_s for _ in range(len_s)] for i in range(1, len_s): dp[1][i] = 1 for sub_len in range(2, len_s + 1): start = 1 whi...
cb 2 1 2 bb 2 2 3 bd 2 3 4 cbb 3 1 3 bbd 3 2 4 cbbd 4 1 4
Apache-2.0
Dynamic Programming/1005/516. Longest Palindromic Subsequence.ipynb
YuHe0108/Leetcode
Install ```AIF360``` with minimum requirements:
!pip install aif360
_____no_output_____
MIT
Code/Adult_non_binary.ipynb
georgeyiasemis/Fairness-Regression
Install packages that we will use:
import aif360 import numpy as np import matplotlib.pyplot as plt import pickle from aif360.algorithms.preprocessing.optim_preproc_helpers.data_preproc_functions \ import load_preproc_data_adult from aif360.algorithms.preprocessing.reweighing import Reweighing from aif360.metrics import ClassificationMetric from ai...
_____no_output_____
MIT
Code/Adult_non_binary.ipynb
georgeyiasemis/Fairness-Regression
Define privileged and unprivileged groups:
# Assume privieleged group is the White Males privileged_groups = [{'sex': 1, 'race': 1}] unprivileged_groups = [{'sex': 1, 'race': 0}, {'sex': 0, 'race': 0}, {'sex': 0, 'race': 1}]
_____no_output_____
MIT
Code/Adult_non_binary.ipynb
georgeyiasemis/Fairness-Regression
Visualise Adult data with respect to the taget label ('Income Binary'; >50k or <=50k) and the sensitive attributes (sex and race):
df = adult_dataset_orig.metadata['params']['df'].copy() # Number of White Men with Income <=50 k white_male_less_50k = sum(df[((df['sex'] == 1.0) & (df['race'] == 1.0))]['Income Binary'] == 0.0) # Number of Nonwhite Men with Income <=50 k nonwhite_male_less_50k = sum(df[((df['sex'] == 1.0) & (df['race'] == 0.0))]['Inc...
Male white <=50k: 19670 white >50k: 9065 Total: 28735 nonwhite <=50k: 3062 nonwhite >50k: 853 Total: 3915 Female white <=50k: 11485 >white 50k: 1542 Total: 13027 nonwhite <=50k: 2938 >nonwhite 50k: 227 Total: 3165 Total: 48842
MIT
Code/Adult_non_binary.ipynb
georgeyiasemis/Fairness-Regression
Split Dataset into training and test data:
ad_train, ad_test = adult_dataset_orig.split([0.75], shuffle=True) # Preprocess data scale_orig = StandardScaler() X_train = scale_orig.fit_transform(ad_train.features) y_train = ad_train.labels.ravel() X_test = scale_orig.transform(ad_test.features) y_test = ad_test.labels.ravel()
_____no_output_____
MIT
Code/Adult_non_binary.ipynb
georgeyiasemis/Fairness-Regression
Reweigh data:
labels = ad_train.labels.ravel() features = ad_train.features[:,:2] WEIGHTS = {} # W_(y,a) = count(Y=y) * count(A=a) / (count(Y=y, A=a) * N) # In total 8 unique weights for Y in range(2): WEIGHTS[Y] = {} for A in [(0,0), (0,1), (1,0), (1,1)]: NY = sum(ad_train.labels.ravel() == Y) NA = sum((ad_t...
_____no_output_____
MIT
Code/Adult_non_binary.ipynb
georgeyiasemis/Fairness-Regression
Create a Logistic Regression class with pytorch:
class LogisticRegression_torch(torch.nn.Module): def __init__(self, input_dim, output_dim): super(LogisticRegression_torch, self).__init__() self.linear = torch.nn.Linear(input_dim, output_dim) def forward(self, x): outputs = torch.sigmoid(self.linear(x)) return outputs GPU = Tr...
_____no_output_____
MIT
Code/Adult_non_binary.ipynb
georgeyiasemis/Fairness-Regression
Plot TPR and NPR for each sensitive class with respect to $\lambda$:
TPR_priv = [] TNR_priv = [] TPR_non_priv1 = [] TNR_non_priv1 = [] TPR_non_priv2 = [] TNR_non_priv2 = [] TPR_non_priv3 = [] TNR_non_priv3 = [] lambdas = [] for l in metrics_rw: lambdas.append(l) TPR_priv.append(metrics_rw[l]['privilaged']['White Male'][0]) TNR_priv.append(metrics_rw[l]['privilaged']['White ...
_____no_output_____
MIT
Code/Adult_non_binary.ipynb
georgeyiasemis/Fairness-Regression
Plot accuracy with respect to $\lambda$:
ACC = [] for l in metrics_rw: ACC.append(metrics_rw[l]['accuracy']) fig, axs = plt.subplots(1, 1, figsize=(6,3)) axs.plot(lambdas, ACC) axs.set_title('Accuracy') axs.set(xlabel='Reg-lambda', ylabel = 'Accuracy')
_____no_output_____
MIT
Code/Adult_non_binary.ipynb
georgeyiasemis/Fairness-Regression
Polynomial RegressionThe problem with our linear model was that it was too simple for the data and resulted in underfitting (high bias). In this part of the exercise, you will address this problem by adding more features.The file ex5data1 contains a data set which includes train set, test set, validation set.The struc...
# import libraries import scipy.io import numpy as np data = scipy.io.loadmat("ex5data1")
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
Now we **extract** `x`, `y`, `xval`, `yval`, `xtest` and `ytest` variables from the .mat file and save them into .csv file for further usage. After running the below code you should see:1. X.csv2. y.csv 3. Xtest.csv4. ytest.csv5. Xval.csv6. yval.csvfiles in your directory.
for i in data: if '__' not in i and 'readme' not in i: np.savetxt((i+".csv"),data[i],delimiter=',')
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
1.B Loading DatasetFirst we import .csv files into pandas dataframes then save them into numpy arrays.
# import library import pandas as pd # saving .csv files to pandas dataframes x_df = pd.read_csv('X.csv',names= ['x']) xtest_df = pd.read_csv('Xtest.csv',names= ['xtest']) xval_df = pd.read_csv('Xval.csv',names= ['xval']) y_df = pd.read_csv('y.csv',names=['y']) ytest_df = pd.read_csv('ytest.csv',names= ['ytest']) yval...
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
Now we convert all **pandas dataframes** to **numpy arrays** for calculations.
# saving x, y, xval, yval, xtest and ytest into numpy arrays x = x_df.iloc[:,:].values xval = xval_df.iloc[:,:].values xtest = xtest_df.iloc[:,:].values y = y_df.iloc[:,:].values yval = yval_df.iloc[:,:].values ytest = ytest_df.iloc[:,:].values # number of examples and number of features m, n = x.shape m_val = xval....
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
1.C Ploting DatasetWe will begin by visualizing the dataset containing historical records on **the change in the water level**, `x`, and **the amount of water flowing out of the dam**, `y`.This dataset is divided into three parts: • A **training set** that your model will learn on: `x`, `y` • A **cross validatio...
# import libraries import matplotlib.pyplot as plt %matplotlib inline plt.scatter(x, y, color='red', marker='x') plt.title('Training Set') plt.xlabel('Change in water level (x)') plt.ylabel('Water flowing out of the dam (y)') plt.grid() plt.show()
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
2. Adding Polynomial FeaturesFor use polynomial regression, our hypothesis has the form:Notice that by defining `x1 = (waterLevel)`, `x2 = (waterLevel)`2, ... , `xp = (waterLevel)`p, we obtain a linear regression model where the features are the various powers of the original value (waterLevel).Now, you will **add mor...
x_poly = None # the output of polu_features p = 8 # order of polynomial features from sklearn.preprocessing import PolynomialFeatures # import libraries def poly_features(x,p): polynomial_features = PolynomialFeatures(degree=8, include_bias=False) x_poly = polynomial_features.fit_transform(x) return x_...
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
Now we add these features to `xtest` and `xval`
xval_poly = poly_features(xval,p) xval_poly_df = pd.DataFrame(xval_poly,columns=None) xval_poly_df.head(3) xtest_poly = poly_features(xtest,p) xtest_poly_df = pd.DataFrame(xtest_poly,columns=None) xtest_poly_df.head(3)
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
2.B Normalize FeaturesIt turns out that if we run the training directly on the projected data, will not work well as the **features** would be **badly scaled** (e.g., an example with **x = 40 will now have a feature x8 = 408 = 6.5 × 1012**). Therefore, you will need to use **feature normalization**.`feature_normalize(...
def feature_normalize(x, xtest, xval): sigma = x.std() mean = x.mean() x_norm = (x-mean)/sigma xtest_norm = (xtest-mean)/sigma xval_norm = (xval-mean)/sigma return (x_norm, xtest_norm, xval_norm) x_poly_norm, xtest_poly_norm, xval_poly_norm = feature_normalize(x_poly,xtest_poly, xval_poly) print...
x_poly_norm : mean= -1.850371707708594e-17, std=0.9999999999999999. xval_poly_norm : mean= 0.044848630228004685, std=1.2247731967735336. xtest_poly_norm : mean= 0.1606768875137592, std=2.5245490041714636.
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
Look at this [link](https://stackoverflow.com/questions/40405803/mean-of-data-scaled-with-sklearn-standardscaler-is-not-zero) if you have any question why after using **scaling**, we still do not have **mean = 0** and **std = 1**.Actually the values are zero.
# add 1's to the features of x as bias x_poly_norm = np.append(np.ones(shape=(m,1)),x_poly_norm,axis = 1) xval_poly_norm = np.append(np.ones(shape=(xval_poly_norm.shape[0],1)),xval_poly_norm,axis = 1) xtest_poly_norm = np.append(np.ones(shape=(xtest_poly_norm.shape[0],1)),xtest_poly_norm,axis = 1)
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
3. Learning Polynomial RegressionWe will proceed to **train polynomial regression using your linear regression cost function**.Keep in mind that even though **we have polynomial terms** in our feature vector, we are **still solving a linear regression** optimization problem. The **polynomial terms have simply turned i...
def hypothesis(x,theta): return np.dot(x,theta) def linear_reg_cost(theta_flatten, x_flatten, y, lambda_, num_of_samples, num_of_features): x = x_flatten.reshape(num_of_samples, num_of_features) theta = theta_flatten.reshape(n,1) loss = hypothesis(x,theta)-y regularizer = lambda_*np.sum(theta[1:,:]*...
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
3.B Regularized Linear Regression GradientCorrespondingly, the **partial derivative of regularized linear regression’s cost for θj** is defined as: Implementation`linear_reg_grad(x, y, theta, lambda_)` computes the gradient of cost of using `theta` as the parameter for linear regression to fit the data points in `x` ...
def linear_reg_grad(theta_flatten, x_flatten, y, lambda_, num_of_samples, num_of_features): x = x_flatten.reshape(num_of_samples, num_of_features) m,n = x.shape theta = theta_flatten.reshape(n,1) new_theta = np.zeros(shape=(theta.shape)) loss = hypothesis(x,theta)-y gradient = np.dot(x.T,loss) ...
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
3.C Fitting Linear RegressionOnce your cost function and gradient are working correctly, the next part is to **compute the optimal values** of **θ**.This training function uses `fmin_cg` to optimize the cost function. See official doc ImplementationOnce you have implemented the cost and gradient correctly, the `fmin_...
m,n = x_poly_norm.shape lambda_ = 0 theta = np.ones(n) from scipy.optimize import fmin_cg new_theta = fmin_cg(f=linear_reg_cost, x0=theta, fprime=linear_reg_grad, args=(x_poly_norm.flatten(), y, lambda_, m,n)) new_theta
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
3.D Visualization of Fitted ModelFinally, you should also **plot the best fit line**. The best fit line tells us that the model is a good fit to the data because the **data has a non-linear pattern**. While **visualizing the best fit** as shown is **one possible way to debug** your learning algorithm, it is not always...
# import libraries import matplotlib.pyplot as plt %matplotlib inline plt.scatter(x, y, color='red', marker='x', label= 'train data') plt.plot(x.flatten(),np.dot(x_poly_norm,new_theta.reshape(n,1).flatten()), label = 'best fit model') #plt.axis([-40,50,-75,75]) plt.title('Training Set') plt.xlabel('Change in water lev...
_____no_output_____
MIT
Week 6 - Regularized Linear Regression and Bias v.s. Variance/Polynomial Regression.ipynb
Nikronic/Coursera-Machine-Learning
Visualize Results: Downstream Performance - "Fully Observed" ExperimentThis notebook should answer the questions: *Does imputation lead to better downstream performances?* Notebook Structure * Application Scenario 2 - Downstream Performance * Categorical Columns (Classification) * Numerical Columns (Regression)...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import os import pandas as pd import re import seaborn as sns from pathlib import Path from data_imputation_paper.experiment import read_experiment, read_csv_files from data_imputation_paper.plotting import draw_cat_box_plot %matplotlib inlin...
_____no_output_____
Apache-2.0
notebooks/results_downstream_fully_obs.ipynb
se-jaeger/data-imputation-paper
Settings
sns.set(style="whitegrid") sns.set_context('paper', font_scale=1.5) mpl.rcParams['lines.linewidth'] = '2' EXPERIMENT = "fully_observed_fix" EXPERIMENT_PATH = Path(f"../data/experiments/{EXPERIMENT}/") CLF_METRIC = "Classification Tasks" REG_METRIC = "Regression Tasks" DOWNSTREAM_RESULT_TYPE = "downstream_performance...
_____no_output_____
Apache-2.0
notebooks/results_downstream_fully_obs.ipynb
se-jaeger/data-imputation-paper
Import the data
%%time results = read_csv_files(read_experiment(EXPERIMENT_PATH), read_details=False) results.head() na_impute_results = results[ (results["result_type"] == IMPUTE_RESULT_TYPE) & (results["metric"].isin(["F1_macro", "RMSE"])) ] na_impute_results.drop(["baseline", "corrupted", "imputed"], axis=1, inplace=True)...
_____no_output_____
Apache-2.0
notebooks/results_downstream_fully_obs.ipynb
se-jaeger/data-imputation-paper
Robustness: check which imputers yielded `NaN`values
for col in downstream_results.columns: na_sum = downstream_results[col].isna().sum() if na_sum > 0: print("-----" * 10) print(col, na_sum) print("-----" * 10) na_idx = downstream_results[col].isna() print(downstream_results.loc[na_idx, "Imputation Method"]...
_____no_output_____
Apache-2.0
notebooks/results_downstream_fully_obs.ipynb
se-jaeger/data-imputation-paper
Compute Downstream Performance relative to Baseline
clf_row_idx = downstream_results["metric"] == CLF_METRIC reg_row_idx = downstream_results["metric"] == REG_METRIC downstream_results["Improvement"] = (downstream_results["Imputed"] - downstream_results["Corrupted"] ) / downstream_results["Baseline"] downstream_results.loc[reg_row_idx, "Improvement"] = downstream_r...
_____no_output_____
Apache-2.0
notebooks/results_downstream_fully_obs.ipynb
se-jaeger/data-imputation-paper
Application Scenario 2 - Downstream Performance Categorical Columns (Classification)
draw_cat_box_plot( downstream_results, "Improvement", (-0.15, 0.3), FIGURES_PATH, "fully_observed_downstream_boxplot.eps", hue_order=list(rename_imputer_dict.values()), row_order=list(rename_metric_dict.values()) )
_____no_output_____
Apache-2.0
notebooks/results_downstream_fully_obs.ipynb
se-jaeger/data-imputation-paper
Agrupación (groupby) Lo Básico
df = pd.DataFrame({'key1': ['a','a','b','b','a'], 'key2': ['one','two','one','two','one'], 'data1': np.random.randn(5), 'data2': np.random.randn(5)}) df # Calcula la media por cada grupo grouped = df['data1'].groupby(df['key1']) # La columna llave será 'data' ...
_____no_output_____
MIT
Pandas/DataAggregations.ipynb
EstebanBrito/TallerIA-SISI2019