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
stage2を結合
# 表記揺れの確認 print(np.sort(train['stage'].unique())) print(np.sort(test['stage'].unique())) # 「mystery~」はイベント時に解放されるステージ、今回のtrain,testデータには無し print(np.sort(stage2['key'].unique())) stage2_r.columns # 結合のため列名変更 stage2_r = stage2.rename(columns = {'key':'stage', 'area':'stage_size2'}) # 必要カラム st2_col = ['stage_size2', # ステー...
stage_size2 0 dtype: int64 stage_size2 0 dtype: int64
MIT
program/lightGBM_base_v0.1.ipynb
tomokoochi/splatoon_competition
weaponを結合
# trainのブキ train_weapon = sorted(list(set(train['A1-weapon'])&set(train['A2-weapon'])&set(train['A3-weapon'])&set(train['A4-weapon'])\ &set(train['B1-weapon'])&set(train['B2-weapon'])&set(train['B3-weapon'])&set(train['B4-weapon']))) print('{}種類'.format(len(train_weapon))) print(train_weapon) # testのブキ test_weapon = so...
_____no_output_____
MIT
program/lightGBM_base_v0.1.ipynb
tomokoochi/splatoon_competition
前処理
# 欠損値埋める def fill_all_null(df, num): for col_name in df.columns[df.isnull().sum()!=0]: df[col_name] = df[col_name].fillna(num) # 訓練データ、テストデータの欠損値を-1で補完 fill_all_null(train_input, -1) fill_all_null(test_input, -1) # ターゲットエンコーディングの関数定義 ## Holdout TSを用いる 変更の余地あり def change_to_target2(train_df,test_df,input_col...
_____no_output_____
MIT
program/lightGBM_base_v0.1.ipynb
tomokoochi/splatoon_competition
データの確認
# 訓練データとテストデータの列を確認 print(train_input.columns) print(test_input.columns)
Index(['A1-level', 'A2-level', 'A3-level', 'A4-level', 'B1-level', 'B2-level', 'B3-level', 'B4-level', 'y', 'stage_size1', 'stage_size2', 'enc_period', 'enc_game-ver', 'enc_lobby-mode', 'enc_lobby', 'enc_mode', 'enc_stage', 'enc_A1-weapon', 'enc_A1-rank', 'enc_A2-weapon', 'enc_A2-rank', 'enc...
MIT
program/lightGBM_base_v0.1.ipynb
tomokoochi/splatoon_competition
学習の準備
# 訓練データを説明変数と目的変数に分割 target = train_input['y'] train_x = train_input.drop('y',axis=1) # LGBMのパラメータを設定 params = { # 二値分類問題 'objective': 'binary', # 損失関数は二値のlogloss #'metric': 'auc', 'metric': 'binary_logloss', # 最大イテレーション回数指定 'num_iterations' : 1000, # early_stopping 回数指定 'early_stopp...
_____no_output_____
MIT
program/lightGBM_base_v0.1.ipynb
tomokoochi/splatoon_competition
学習・予測の実行
# k-分割交差検証を使って学習&予測(K=10) FOLD_NUM = 10 kf = KFold(n_splits=FOLD_NUM, random_state=42) #lgbmのラウンド数を定義 num_round = 10000 #検証時のスコアを初期化 scores = [] #テストデータの予測値を初期化 pred_cv = np.zeros(len(test.index)) for i, (tdx, vdx) in enumerate(kf.split(train_x, target)): print(f'Fold : {i}') # 訓練用データと検証用データに分割...
_____no_output_____
MIT
program/lightGBM_base_v0.1.ipynb
tomokoochi/splatoon_competition
Angle-based Outlier Detector (ABOD)
clf1=ABOD(contamination=outliers_fraction) clf1.fit(X) y_pred1=clf1.predict(X) from sklearn.metrics import confusion_matrix confusion_matrix(y, y_pred1)
_____no_output_____
MIT
outlierdetector_lib.ipynb
eaglewarrior/Anamoly-Detection
Cluster-based Local Outlier Factor (CBLOF)
clf2=CBLOF(contamination=outliers_fraction,check_estimator=False, random_state=random_state) clf2.fit(X) y_pred2=clf2.predict(X) from sklearn.metrics import confusion_matrix confusion_matrix(y, y_pred2)
_____no_output_____
MIT
outlierdetector_lib.ipynb
eaglewarrior/Anamoly-Detection
Feature Bagging
clf3=FeatureBagging(LOF(n_neighbors=35),contamination=outliers_fraction,check_estimator=False,random_state=random_state) clf3.fit(X) y_pred3=clf3.predict(X) from sklearn.metrics import confusion_matrix confusion_matrix(y, y_pred3)
_____no_output_____
MIT
outlierdetector_lib.ipynb
eaglewarrior/Anamoly-Detection
Histogram-base Outlier Detection (HBOS)
clf4=HBOS(alpha=0.1, contamination=0.037, n_bins=10, tol=0.9) clf4.fit(X) y_pred4=clf4.predict(X) from sklearn.metrics import confusion_matrix confusion_matrix(y, y_pred4)
_____no_output_____
MIT
outlierdetector_lib.ipynb
eaglewarrior/Anamoly-Detection
Isolation Forest
clf5=IForest(contamination=outliers_fraction,random_state=random_state) clf5.fit(X) y_pred5=clf5.predict(X) from sklearn.metrics import confusion_matrix confusion_matrix(y, y_pred5)
_____no_output_____
MIT
outlierdetector_lib.ipynb
eaglewarrior/Anamoly-Detection
K Nearest Neighbors (KNN)
clf6=KNN(contamination=outliers_fraction) clf6.fit(X) y_pred6=clf6.predict(X) from sklearn.metrics import confusion_matrix confusion_matrix(y, y_pred6)
_____no_output_____
MIT
outlierdetector_lib.ipynb
eaglewarrior/Anamoly-Detection
Average KNN
clf7=KNN(method='mean',contamination=outliers_fraction) clf7.fit(X) y_pred7=clf7.predict(X) from sklearn.metrics import confusion_matrix confusion_matrix(y, y_pred7)
_____no_output_____
MIT
outlierdetector_lib.ipynb
eaglewarrior/Anamoly-Detection
Exercise 1Add the specified code for each code cell, running the cells _in order_. Create a variable `food` that stores your favorite kind of food. Print or output the variable.
food = "pizza"
_____no_output_____
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Create a variable `restaurant` that stores your favorite place to eat that kind of food.
restaurant = "Delfinos pizza"
_____no_output_____
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Print the message `"I'm going to RESTAURANT for some FOOD"`, replacing the restaurant and food with your variables.
print ("I'm going to " + restaurant + " for some " + food)
I'm going to Delfinos pizza for some pizza
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Create a variable `num_friends` equal to the number of friends you would like to eat with.
num_friends = 5
_____no_output_____
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Print a message `"I'm going with X friends"`, replacing the X with the number of friends.
print ("I'm going with " + str(num_friends) + " friends ")
I'm going with 5 friends
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Create a variable `meal_price`, which is how expensive you think one meal at the restaurant would be. This price should be a `float`.
meal_price = 35.90
_____no_output_____
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Update (re-assign) the `meal_price` variable so it includes a 15% tip—that is, so the price is 15% higher. Output the variable.
meal_price = meal_price * 1.15
_____no_output_____
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Create a variable `total_cost` that has the total estimated cost of the bill for you and all of your friends. Output or print the variable
total_cost = meal_price * num_friends
_____no_output_____
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Create a variable `budget` representing your spending budget for a night out.
budget = 500
_____no_output_____
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Create a variable `max_friends`, which is the maximum number of friends you can invite, at the estimated meal price, while staying within your budget. Output or print this value.- Be carefully that you only invite whole people!
max_friends = int (budget/meal_price)
_____no_output_____
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
Bonus: Create a variable `chorus` that is the string `"FOOD time!"` _repeated_ once for each of the friends you are able to bring. _Hint_ use the **`*`** operator. Print out the variable.
print ("food time!\n " * 5)
food time! food time! food time! food time! food time!
MIT
exercise-1/exercise.ipynb
ajm1813/ch4-python-intro
OPTIMIZATION PHASES List of variables Variable Description Comment $B$ Number of full blocks/pages that need the records $\lceil \frac{|T|}{R} \rceil$; $B \ll |T|$ $R$ Number of r...
import math c_P, c_W, c_V = 10000, 5000, 100000 R_p, R_w, R_v = 12, 10, 20 B_p, B_w, B_v = math.ceil(c_P / R_p), math.ceil(c_W / R_w), math.ceil(c_V / R_v) print("Cardinality of {}: {}, Records: {}, number of Full Blocks: {}".format('P', c_P, R_p, B_p)) print("Cardinality of {}: {}, Records: {}, number of Full Blocks...
Cardinality of P: 10000, Records: 12, number of Full Blocks: 834 Cardinality of W: 5000, Records: 10, number of Full Blocks: 500 Cardinality of V: 100000, Records: 20, number of Full Blocks: 5000
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
Phase 1. Alternatives generation```sqlSELECT DISTINCT w.strengthFROM wines w, producers p, vintages vWHERE v.wineId = w.wineId AND p.prodId = v.prodId AND p.region = "Priorat" AND v.quantity > 100;```Change selection and join arrangement![Phase 1](phase1.svg) Phase 2. Intermediate results estimation`...
c = 100 min_v = 10 max_v = 500 SF_v_prime = (max_v - c) / (max_v - min_v) print("Selectivity factor of V': {} \n".format(SF_v_prime)) C_v_prime = math.floor(SF_v_prime * c_V) print("Cardinality output of V': {} \n".format(C_v_prime)) R_v_len = 5 + 5 B = 500 R_v_prime = math.floor(B / R_v_len) print("V' number of reco...
Selectivity factor of V': 0.8163265306122449 Cardinality output of V': 81632 V' number of records per block : 50 Blocks needed for V': 1633
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**Selection over P: P'**![P: P'](ppprime.svg)Record length of prodId:$$|R_{P'}| = 5$$Selectivity factor of selection:$$\mathrm{SF}(A = c) = \frac{1}{\text{ndist}(A)}$$Where $c = 'Priorat'$ and the query specifies `p.region = 'Priorat'`, then:$$\text{SF}(\text{region} = \text{Priorat}) = \frac{1}{30} = 0.033333$$Output ...
ndist_region = 30 SF_p_prime = 1 / ndist_region print("Selectivity factor of P': {} \n".format(SF_p_prime)) C_p_prime = math.floor(SF_p_prime * c_P) print("Cardinality output of P': {} \n".format(C_p_prime)) R_p_len = 5 B = 500 R_p_prime = math.floor(B / R_p_len) print("P' number of records per block : {} \n".format(...
Selectivity factor of P': 0.03333333333333333 Cardinality output of P': 333 P' number of records per block : 100 Blocks needed for P': 4
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**PT1****Join between W and V': WV'**![WV'](wvprime.svg)Record length of `strength` and `prodId`:$$|R_{WV'}| = 5 + 5$$Selectivity factor$$\text{SF}_{WV'} = \frac{1}{|W|} = \frac{1}{5000} = 0.0002$$Cardinality ouput of WV'$$|WV'| = SF_{WV'} \cdot |W| \cdot |V'| = \frac{1}{5000} \cdot 5000 \cdot 81632 = 81632$$Number of...
SF_wv_prime = 1 / c_W print("Selectivity factor of WV': {} \n".format(SF_wv_prime)) C_wv_prime = math.floor(SF_wv_prime * c_W * C_v_prime) print("Cardinality output of WV': {} \n".format(C_wv_prime)) R_wv_prime_len = 5 + 5 B = 500 R_wv_prime = math.floor(B / R_wv_prime_len) print("WV' number of records per block : {}...
Selectivity factor of WV': 0.0002 Cardinality output of WV': 81632 WV' number of records per block : 50 Blocks needed for WV': 1633
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**Join between WV' and P': WV'P'**![WV'P'](wvprimepprime.svg)Record length for `strength`:$$|R_{WV'P'}| = 5$$Selectivity Factor, assuming quantity and region independent$$\text{SF(WV'} \cdot \text{P')} = \frac{1}{|P'|} \cdot \frac{1}{ndist(\text{region})} = \frac{1}{333 \cdot 30} = 10^{-4}$$Cardinality output$$|WV'P'| ...
SF_wvp_prime = (1 / C_p_prime) * (1 / ndist_region) print("Selectivity factor of WV'P': {} \n".format(SF_wvp_prime)) C_wvp_prime = math.floor(SF_wvp_prime * C_wv_prime * C_p_prime) print("Cardinality output of WV'P': {} \n".format(C_wvp_prime)) R_wvp_prime_len = 5 B = 500 R_wvp_prime = math.floor(B / R_wvp_prime_len)...
Selectivity factor of WV'P': 0.00010010010010010009 Cardinality output of WV'P': 2721 WV'P' number of records per block : 100 Blocks needed for WV'P': 28
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**PT2**![V'P'](vprimepprime.svg)**Join V' and P': V'P'**Assuming independence of variablesRecord length for `wineId`$$|R_{V'P'}| = 5$$Selectivity factor$$\text{SF}_{V'P'} = \frac{1}{ndist(\text{region})} \cdot \frac{1}{|P'|} = \frac{1}{30} \cdot \frac{1}{333} = 10^{-4}$$Output cardinality$$|V'P'| = \text{SF}_{V'P'} \cd...
ndist_region = 30 SF_vp_prime = (1 / ndist_region) * (1 / C_p_prime) print("Selectivity factor of V'P': {} \n".format(SF_vp_prime)) C_vp_prime = math.floor(SF_vp_prime * C_v_prime * C_p_prime) print("Cardinality output of V'P': {} \n".format(C_vp_prime)) R_vp_len = 5 B = 500 R_vp_prime = math.floor(B / R_vp_len) prin...
Selectivity factor of V'P': 0.00010010010010010009 Cardinality output of V'P': 2721 V'P' number of records per block : 100 Blocks needed for V'P': 28
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**Join between W and V'P': WV'P'**![WV'P'](wvprimepprime2.svg)Record length for WV'P'$$|R_{WV'P'}| = 5$$Selectivity Factor for WV'P'$$\text{SF} = \frac{1}{|W|} = \frac{1}{5000} = 0.0002$$Cardinality Output$$|WV'P'| = SF \cdot |W| \cdot |V'P'| = 10^{-4} \cdot 5000 \cdot 2721 = 2721$$Number of records per block$$R_{WV'P'...
SF_wv_pr_p_pr = 1 / c_W print("Selectivity factor of WV'P': {} \n".format(SF_wv_pr_p_pr)) C_wv_pr_p_pr = math.floor(SF_wv_pr_p_pr * c_W * C_vp_prime) print("Cardinality output of WV'P': {} \n".format(C_wv_pr_p_pr)) R_wv_pr_p_pr_len = 5 B = 500 R_wv_pr_p_pr = math.floor(B / R_wv_pr_p_pr_len) print("WV'P' number of rec...
Selectivity factor of WV'P': 0.0002 Cardinality output of WV'P': 2721 WV'P' number of records per block : 100 Blocks needed for WV'P': 28
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**PT1/PT2****Final result = O**Record length$$|R_O| = 5$$Output cardinality$$|O| = \text{ndist}(\text{strength}) = 100$$Number of records$$R_O = \lfloor \frac{B}{|R_O|} \rfloor = \lfloor \frac{500}{5} \rfloor = 100$$Blocks needed$$B_O = \lceil \frac{|O|}{R_O} \rceil = \lceil \frac{100}{100} \rceil = 1$$
ndist_strength = 100 C_o = ndist_strength print("Cardinality output of O: {} \n".format(C_o)) R_o_len = 5 B = 500 R_o = math.floor(B / R_o_len) print("O number of records per block : {} \n".format(R_o)) B_o = math.ceil(C_o / R_o) print("Blocks needed for O: {} \n".format(B_o))
Cardinality output of O: 100 O number of records per block : 100 Blocks needed for O: 1
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**Map result**![Phase 2](phase2.svg) Phase 3. Cost estimation for each algorithmRecall:$$u = \frac{2}{3} \cdot 2(75) = 100$$**AP1/AP2****Selection over V: V'**Recall that for Vintages is clustered by wineId and prodIdAvailable access paths: No index$$\text{cost}_{\text{scan}}(V') = \lceil 1.5 B_{V} \rceil \cdot D = \l...
load = 2/3 d = 75 u = load * (2 * d) h = math.ceil(math.log(c_P, u)) - 1 D = 1 print("load is: {}\nd is: {}\nu is: {}\nh is: {}\nD is: {}\n".format(load, d, u, h, D)) cost_scan_p = math.ceil(1.5 * B_p) * D cost_bplus_p = (h * D) + ((C_p_prime / u) * D) + (C_p_prime * D) print("Cost of scan is: {} \nCost of B+ is: {}".f...
load is: 0.6666666666666666 d is: 75 u is: 100.0 h is: 1 D is: 1 Cost of scan is: 1251 Cost of B+ is: 337.33
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**PT1****Join over W and V': WV'**Available algorithms: Block Nested Loops (BML), Row Nested Loops (RML) and Sort-Match (SM)*Block Nested Loops*Recall:$$M = 4$$$\lceil 1.5 B_{W} \rceil < B_{V'}$ we use the commutative property of joins$$\begin{align}\text{cost}_{\text{BML}}(WV') & = \lceil 1.5 B_{W} \rceil + \lceil \fr...
print("B_p' is {}\nB_wv' is {}".format(B_p_prime, B_wv_prime)) (2 * B_wv_prime * math.ceil(math.log(B_wv_prime, 2))) + (2 * B_p_prime * math.ceil(math.log(B_p_prime, 2))) + B_wv_prime + B_p_prime
_____no_output_____
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**PT2****Join between V' and P': V'P'Available algorithms: BNL and SM.*Block Nested Loops*$B_{P'} < B_{V'}$ we use the commutative property of joins$$\begin{align}\text{cost}_{\text{BML}}(V'P') & = B_{P'} + \lceil \frac{B_{P'}}{M} \rceil \cdot B_{V'} \\& = 4 + \lceil \frac{4}{4} \rceil \cdot 1633 \\& = 1637\end{align}$...
print("B_p' is {}\nB_v' is {}".format(B_p_prime, B_v_prime))
B_p' is 4 B_v' is 1633
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
**Join between W and V'P': WV'P'**Available algorithms: Block Nested Loops (BML), Row Nested Loops (RML) and Sort-Match (SM)*Block Nested Loops*$B_{V'P'} < \lceil 1.5 B_{W} \rceil$ we use the commutative property of joins$$\begin{align}\text{cost}_{\text{BML}}(WV'P') & = B_{V'P'} + \lceil \frac{B_{V'P'}}{M} \rceil \cdo...
print("B_v'p' is {}\n1.5*B_w is {}\n|V'P'| is {}".format(B_vp_prime, math.ceil(1.5*B_w), C_vp_prime)) 28 + math.ceil(28/4) * 750 28+(2721*(math.ceil(math.log(5000, 100)) - 1 + 1)) Cost_v_prime = 1633 + 7500 Cost_p_prime = 4 + 337 Cost_wv = 1633 + 2383 Cost_vp = 28 + 1637 Cost_wvp_pt1 = 28 + 1637 Cost_wvp_pt2 = 28 + 105...
Total cost of: PT1: 15408 PT2: 12478
MIT
ADSDB/Optimization-Costs.ipynb
MiguelHeCa/miri-notes
Спортивный анализ данных. Платформа Kaggle Урок 1. Введение в спортивный анализ данных, Exploration Data Analysis Домашняя работа к уроку 1 Ссылка на наборы данных: https://drive.google.com/file/d/1j8zuKbI-PW5qKwhybP4S0EtugbPqmeyX/view?usp=sharing Задание 1 Сделать базовый анализ данных: вывести размерность датасет...
# В работе. Как-то все наложилось. Надеюсь на этой неделе все нагнать. # Посмотрел. Очень серьезный курс, темы сложные. Зря его вынесли во вне четверти.
_____no_output_____
MIT
webinar_1/Lesson 1.ipynb
superbe/KagglePlatform
Задание 2 Сделать базовый анализ целевой переменной, сделать выводы;
# В работе
_____no_output_____
MIT
webinar_1/Lesson 1.ipynb
superbe/KagglePlatform
Задание 3 Построить распределение признаков в зависимости от значения целевой переменной и распределение признаков для обучающей и тестовой выборки (если машина не позволяет построить распределение для всех признаков, то выполнить задание для признаков var_0, var_1, var_2, var_5, var_9, var_10, var_13, var_20, var_26,...
# В работе
_____no_output_____
MIT
webinar_1/Lesson 1.ipynb
superbe/KagglePlatform
Задание 4 Построить распределение основных статистики признаков (среднее, стандартное отклонение) в разрезе целевой переменной и распределение основных статистик обучающей и тестовой выборки, сделать выводы;
# В работе
_____no_output_____
MIT
webinar_1/Lesson 1.ipynb
superbe/KagglePlatform
Задание 5 Построить распределение коэффициентов корреляции между признаками. Есть ли зависимость между признаками (будем считать, что связь между признаками отсутствует, если коэффициент корреляции < 0.2)?
# В работе
_____no_output_____
MIT
webinar_1/Lesson 1.ipynb
superbe/KagglePlatform
Задание 6 Выявить 10 признаков, которые обладают наибольшей нелинейной связью с целевой переменной.
# В работе
_____no_output_____
MIT
webinar_1/Lesson 1.ipynb
superbe/KagglePlatform
Задание 7 Провести анализ идентичности распределения признаков на обучающей и тестовой выборках, сделать выводы.
# В работе
_____no_output_____
MIT
webinar_1/Lesson 1.ipynb
superbe/KagglePlatform
Euler Problem 206=================Find the unique positive integer whose square has the form 1_2_3_4_5_6_7_8_9_0,where each "&95;" is a single digit.
from itertools import product for a, b, c, d in product(range(10), repeat=4): N = 10203040596979899 N += a*10**15 + b*10**13 + c*10**11 + d*10**9 sqrtN = int(N**0.5) s = str(sqrtN**2) if s[0:17:2] == '123456789': print(sqrtN * 10) break
1389019170
MIT
Euler 206 - Concealed square.ipynb
Radcliffe/project-euler
BLU15 - Model CSI Intro:It often happens that your data distribution changes with time. More than that, sometimes you don't know how a model was trained and what was the original training data. In this learning unit we're going to try to identify whether an existing model meets our expectations and redeploy it. Pro...
import joblib import pandas as pd import json import joblib import pickle from sklearn.metrics import precision_score, recall_score, roc_auc_score from sklearn.metrics import confusion_matrix import requests import matplotlib.pyplot as plt import matplotlib.image as mpimg from sklearn.metrics import precision_recall_cu...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
Let's start from sending all those requests and comparing the model prediction results with the target values. The model is already prepared to convert our observations to the format its expecting, the only thing we need to change is making department and intervention location names lowercase, and we're good to extract...
# lowercaes departments and location names df['Department Name'] = df['Department Name'].apply(lambda x: str(x).lower()) df['InterventionLocationName'] = df['InterventionLocationName'].apply(lambda x: str(x).lower()) url = "http://127.0.0.1:5000/predict" headers = {'Content-Type': 'application/json'} def send_request(i...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
**NOTE:** We could also load the model and make predictions locally (without using the api), but:1. I wanted to show you how you might send requests in a similar situation2. If you have a running API and some model file, you always need to understand how the API works (if it makes any kind of data preprocessing), which...
confusion_matrix(df['ContrabandIndicator'], df['prediction'])
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
If you're not familiar with confusion matrixes, **here is an explanation of the values:** These values don't seem to be good. Let's once again take a look on the client's requirements and see if we still meet them: > A minimum 50% success rate for searches (when a car is searched, it should be at least 50% likely that...
def verify_success_rate_above(y_true, y_pred, min_success_rate=0.5): """ Verifies the success rate on a test set is above a provided minimum """ precision = precision_score(y_true, y_pred, pos_label=True) is_satisfied = (precision >= min_success_rate) return is_satisfied, precisi...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
![No please](./media/no_please.jpg) > The largest possible amount of contraband found, given the constraints above.As the client says, their model recall was 0.893. And what now?
def verify_amount_found(y_true, y_pred): """ Verifies the amout of contraband found in the test dataset - a.k.a the recall in our test set """ recall = recall_score(y_true, y_pred, pos_label=True) return recall verify_amount_found(df['ContrabandIndicator'], df['prediction'])
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
Okay, relax, it happens. Let's start from checking different thresholds. Maybe the selected threshold was to specific and doesn't work anymore. What about 0.25?
threshold = 0.25 df['prediction'] = [1 if p >= threshold else 0 for p in df['proba']] verify_success_rate_above(df['ContrabandIndicator'], df['prediction'], 0.5) verify_amount_found(df['ContrabandIndicator'], df['prediction'])
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
Okay, let's try the same technique to identify the best threshold as they originally did. Maybe we find something good enough. It's not a good idea to verify such things on the test data, but we're going to use it just to confirm the model's performance, not to select the threshold.
precision, recall, thresholds = precision_recall_curve(df['ContrabandIndicator'], df['proba']) precision = precision[:-1] recall = recall[:-1] fig=plt.figure() ax1 = plt.subplot(211) ax2 = plt.subplot(212) ax1.hlines(y=0.5,xmin=0, xmax=1, colors='red') ax1.plot(thresholds,precision) ax2.plot(thresholds,recall) ax1.get_...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
So what do we see? There is some threshold value (around 0.6) that gives us precision >= 0.5. But the threshold is so big, that the recall at this point is really-really low. Let's calculate the exact values:
min_index = [i for i, prec in enumerate(precision) if prec >= 0.5][0] print(min_index) thresholds[min_index] precision[min_index] recall[min_index]
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
Before we move on, we need to understand why this happens, so that we can decide what kind of action to perform. Let's try to analyze the changes in data and discuss different things we might want to do.
old_df = pd.read_csv('./data/train_searched.csv') old_df.head()
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
We're going to apply the same changes to the dataset as in the original model notebook unit to understand what was the original data like and how the current dataset differs.
old_df = old_df[(old_df['VehicleSearchedIndicator']==True)] # lowercaes departments and location names old_df['Department Name'] = old_df['Department Name'].apply(lambda x: str(x).lower()) old_df['InterventionLocationName'] = old_df['InterventionLocationName'].apply(lambda x: str(x).lower()) train_features = old_df.col...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
Looks like we got a bit more contraband now, and it's already a good sign:if the training data had a different target feature distribution than the test set, the model's predictions might have a different distribution as well. It's a good practice to have the same target feature distribution both in training and test s...
new_department_names = df['Department Name'].unique() old_department_names = old_df['Department Name'].unique() unknown_departments = [department for department in new_department_names if department not in old_department_names] len(unknown_departments) df[df['Department Name'].isin(unknown_departments)].shape
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
So we have 10 departments that the original model was not trained on, but they are only 23 rows from the test set. Let's repeat the same thing for the Intervention Location names
new_location_names = df['InterventionLocationName'].unique() old_location_names = old_df['InterventionLocationName'].unique() unknown_locations = [location for location in new_location_names if location not in old_location_names] len(unknown_locations) df[df['InterventionLocationName'].isin(unknown_locations)].shape[0...
unknown locations: 5.3 %
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
Alright, a bit more of unknown locations. We don't know if the feature was important for the model, so these 5.3% of unknown locations might be important or not.But it's worth keeping it in mind. **Here are a few ideas of what we could try to do:**1. Reanalyze the filtered locations, e.g. filter more rare ones.2. Creat...
common_departments = df['Department Name'].value_counts().head(20).index departments_new = df[df['Department Name'].isin(common_departments)] departments_old = old_df[old_df['Department Name'].isin(common_departments)] pd.crosstab(departments_new['ContrabandIndicator'], departments_new['Department Name'], normalize="co...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
We can clearly see that some departments got a huge difference in the contraband indicator.E.g. Bridgeport used to have 93% of False contrabands, and now has only 62%.Similar situation with Danbury and New Haven. Why? Hard to say. There are really a lot of variables here. Maybe the departments got instructed on how to ...
common_location = df['InterventionLocationName'].value_counts().head(20).index locations_new = df[df['InterventionLocationName'].isin(common_location)] locations_old = old_df[old_df['InterventionLocationName'].isin(common_location)] pd.crosstab(locations_new['ContrabandIndicator'], locations_new['InterventionLocationNa...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
What do we see? First of all, the InterventionLocationName and the Department Name are often same.It sounds pretty logic, as probably policeman's usually work in the area of their department. But we could try to create a feature saying whether InterventionLocationName is equal to the Department Name.Or maybe we could j...
pd.crosstab(df['ContrabandIndicator'], df['InterventionReasonCode'], normalize="columns") pd.crosstab(old_df['ContrabandIndicator'], old_df['InterventionReasonCode'], normalize="columns")
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
There are some small changes, but they don't seem to be significant. Especially that all the 3 values have around 33% of Contraband.Time for officers:
df['ReportingOfficerIdentificationID'].value_counts() filter_values(df, 'ReportingOfficerIdentificationID', 2)['ReportingOfficerIdentificationID'].nunique()
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
Well, looks like there are a lot of unique values for the officer id (1166 for 2000 records), and there are not so many common ones (only 206 officers have more than 2 rows in the dataset) so it doesn't make much sense to analyze it. Let's quickly go throw the rest of the columns:
df.columns rest = ['ResidentIndicator', 'SearchAuthorizationCode', 'StatuteReason', 'SubjectEthnicityCode', 'SubjectRaceCode', 'SubjectSexCode','TownResidentIndicator'] for col in rest: display(pd.crosstab(df['ContrabandIndicator'], df[col], normalize="columns")) display(pd.crosstab(old_df['Con...
_____no_output_____
MIT
S06 - DS in the Real World/BLU15 - Model CSI/BLU15 - Learning Unit - Model CSI.ipynb
LDSSA/batch4-students
Reviewing Automated Machine Learning ExplanationsAs machine learning becomes more and more and more prevelant, the predictions made by models have greater influence over many aspects of our society. For example, machine learning models are an increasingly significant factor in how banks decide to grant loans or doctor...
import azureml.core from azureml.core import Workspace # Load the workspace from the saved config file ws = Workspace.from_config() print('Ready to use Azure ML {} to work with {}'.format(azureml.core.VERSION, ws.name))
_____no_output_____
MIT
09A - Reviewing Automated Machine Learning Explanations.ipynb
LucaSavio/DP100
Run an Automated Machine Learning ExperimentTo reduce time in this lab, you'll run an automated machine learning experiment with only three iterations.Note that the **model_explainability** configuration option is set to **True**.
import pandas as pd from azureml.train.automl import AutoMLConfig from azureml.core.experiment import Experiment from azureml.widgets import RunDetails from azureml.core.compute import ComputeTarget, AmlCompute from azureml.core.compute_target import ComputeTargetException from azureml.core import Dataset cluster_name...
_____no_output_____
MIT
09A - Reviewing Automated Machine Learning Explanations.ipynb
LucaSavio/DP100
View Feature ImportanceWhen the experiment has completed in the widget above, click the run that produced the best result to see its details. Then scroll to the bottom of the visualizations to see the relative feature importance.You can also view feature importance for the best model produced by the experiment by usin...
from azureml.contrib.interpret.explanation.explanation_client import ExplanationClient from azureml.core.run import Run # Wait for the best model explanation run to complete model_explainability_run_id = automl_run.get_properties().get('ModelExplainRunId') print(model_explainability_run_id) if model_explainability_run...
_____no_output_____
MIT
09A - Reviewing Automated Machine Learning Explanations.ipynb
LucaSavio/DP100
Classifying Fashion-MNISTNow it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 97% ...
import torch from torchvision import datasets, transforms import helper # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) # Download and load the training data trainset = datasets.FashionMNIST('~/.pyt...
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Solution).ipynb
sizigia/deep-learning-v2-pytorch
Here we can see one of the images.
image, label = next(iter(trainloader)) helper.imshow(image[0,:]);
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Solution).ipynb
sizigia/deep-learning-v2-pytorch
Building the networkHere you should define your network. As with MNIST, each image is 28x28 which is a total of 784 pixels, and there are 10 classes. You should include at least one hidden layer. We suggest you use ReLU activations for the layers and to return the logits or log-softmax from the forward pass. It's up t...
from torch import nn, optim import torch.nn.functional as F # TODO: Define your network architecture here class Classifier(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 128) self.fc3 = nn.Linear(128, 64) self.fc4 =...
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Solution).ipynb
sizigia/deep-learning-v2-pytorch
Train the networkNow you should create your network and train it. First you'll want to define [the criterion](http://pytorch.org/docs/master/nn.htmlloss-functions) (something like `nn.CrossEntropyLoss` or `nn.NLLLoss`) and [the optimizer](http://pytorch.org/docs/master/optim.html) (typically `optim.SGD` or `optim.Adam...
# TODO: Create the network, define the criterion and optimizer model = Classifier() criterion = nn.NLLLoss() optimizer = optim.Adam(model.parameters(), lr=0.003) # TODO: Train the network here epochs = 5 for e in range(epochs): running_loss = 0 for images, labels in trainloader: log_ps = model(images) ...
_____no_output_____
MIT
intro-to-pytorch/Part 4 - Fashion-MNIST (Solution).ipynb
sizigia/deep-learning-v2-pytorch
Einstein Tensor calculations using Symbolic module
import numpy as np import pytest import sympy from sympy import cos, simplify, sin, sinh, tensorcontraction from einsteinpy.symbolic import EinsteinTensor, MetricTensor, RicciScalar sympy.init_printing()
_____no_output_____
Apache-2.0
EinsteinPy/Einstein Tensor symbolic calculation.ipynb
IsaacW4/Advanced-GR
Defining the Anti-de Sitter spacetime Metric
syms = sympy.symbols("t chi theta phi") t, ch, th, ph = syms m = sympy.diag(-1, cos(t) ** 2, cos(t) ** 2 * sinh(ch) ** 2, cos(t) ** 2 * sinh(ch) ** 2 * sin(th) ** 2).tolist() metric = MetricTensor(m, syms)
_____no_output_____
Apache-2.0
EinsteinPy/Einstein Tensor symbolic calculation.ipynb
IsaacW4/Advanced-GR
Calculating the Einstein Tensor (with both indices covariant)
einst = EinsteinTensor.from_metric(metric) einst.tensor()
_____no_output_____
Apache-2.0
EinsteinPy/Einstein Tensor symbolic calculation.ipynb
IsaacW4/Advanced-GR
Ex1 - Filtering and Sorting Data This time we are going to pull data directly from the internet.Special thanks to: https://github.com/justmarkham for sharing the dataset and materials. Step 1. Import the necessary libraries
import pandas as pd
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solutions.ipynb
duongv/pandas_exercises
Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv). Step 3. Assign it to a variable called chipo.
url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv' chipo = pd.read_csv(url, sep = '\t')
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solutions.ipynb
duongv/pandas_exercises
Step 4. How many products cost more than $10.00?
# clean the item_price column and transform it in a float prices = [float(value[1 : -1]) for value in chipo.item_price] # reassign the column with the cleaned prices chipo.item_price = prices # delete the duplicates in item_name and quantity chipo_filtered = chipo.drop_duplicates(['item_name','quantity']) # select o...
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solutions.ipynb
duongv/pandas_exercises
Step 5. What is the price of each item? print a data frame with only two columns item_name and item_price
# delete the duplicates in item_name and quantity # chipo_filtered = chipo.drop_duplicates(['item_name','quantity']) chipo[(chipo['item_name'] == 'Chicken Bowl') & (chipo['quantity'] == 1)] # select only the products with quantity equals to 1 # chipo_one_prod = chipo_filtered[chipo_filtered.quantity == 1] # select on...
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solutions.ipynb
duongv/pandas_exercises
Step 6. Sort by the name of the item
chipo.item_name.sort_values() # OR chipo.sort_values(by = "item_name")
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solutions.ipynb
duongv/pandas_exercises
Step 7. What was the quantity of the most expensive item ordered?
chipo.sort_values(by = "item_price", ascending = False).head(1)
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solutions.ipynb
duongv/pandas_exercises
Step 8. How many times were a Veggie Salad Bowl ordered?
chipo_salad = chipo[chipo.item_name == "Veggie Salad Bowl"] len(chipo_salad)
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solutions.ipynb
duongv/pandas_exercises
Step 9. How many times people orderd more than one Canned Soda?
chipo_drink_steak_bowl = chipo[(chipo.item_name == "Canned Soda") & (chipo.quantity > 1)] len(chipo_drink_steak_bowl)
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solutions.ipynb
duongv/pandas_exercises
window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); Start-to-Finish Example: Unit Testing `GiRaFFE_NRPy`: $A_k$ to $B^i$ Author: Patrick Nelson This module Validates the A-to-B routine for `GiRaFFE`.**Notebook Status:** Val...
import shutil, os, sys # Standard Python modules for multiplatform OS-level functions # First, we'll add the parent directory to the list of directories Python will check for modules. nrpy_dir_path = os.path.join("..") if nrpy_dir_path not in sys.path: sys.path.append(nrpy_dir_path) from outputC import *...
_____no_output_____
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Step 1.a: Polynomial vector potential \[Back to [top](toc)\]$$\label{polynomial}$$We will start with the simplest case - testing the second-order solver. In second-order finite-differencing, we use a three-point stencil that can exactly differentiate polynomials up to quadratic. So, we will use cubic functions three v...
if not Use_Gaussian_Data: is_gaussian = par.Cparameters("int",thismodule,"is_gaussian",0) par.set_parval_from_str("reference_metric::CoordSystem","Cartesian") rfm.reference_metric() x = rfm.xxCart[0] y = rfm.xxCart[1] z = rfm.xxCart[2] AD[0] = a*x**3 + b*y**3 + c*z**3 + d*y**2 + e*z**2 + f...
_____no_output_____
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Step 1.b: Gaussian vector potential \[Back to [top](toc)\]$$\label{gaussian}$$Alternatively, we might want to use different functions for the vector potential. Here, we'll give some 3D Gaussians:\begin{align}A_x &= a e^{-((x-b)^2+(y-c)^2+(z-d)^2)} \\A_y &= f e^{-((x-g)^2+(y-h)^2+(z-l)^2)} \\A_z &= m e^{-((x-n)^2+(y-o)...
if Use_Gaussian_Data: is_gaussian = par.Cparameters("int",thismodule,"is_gaussian",1) par.set_parval_from_str("reference_metric::CoordSystem","Cartesian") rfm.reference_metric() x = rfm.xxCart[0] y = rfm.xxCart[1] z = rfm.xxCart[2] AD[0] = a * sp.exp(-((x-b)**2 + (y-c)**2 + (z-d)**2)) ...
_____no_output_____
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Step 1.c: The magnetic field $B^i$ \[Back to [top](toc)\]$$\label{magnetic}$$Next, we'll let NRPy+ compute derivatives analytically according to $$B^i = \frac{[ijk]}{\sqrt{\gamma}} \partial_j A_k.$$ Then we can carry out two separate tests to verify the numerical derivatives. First, we will verify that when we let the...
par.set_parval_from_str("reference_metric::CoordSystem","Cartesian") rfm.reference_metric() x = rfm.xxCart[0] y = rfm.xxCart[1] z = rfm.xxCart[2] gammaDD[0][0] = a*x**3 + b*y**3 + c*z**3 + d*y**2 + e*z**2 + sp.sympify(1) gammaDD[1][1] = g*x**3 + h*y**3 + l*z**3 + m*x**2 + n*z**2 + sp.sympify(1) gammaDD[2][2] = p*x**3 ...
Output C function calculate_metric_gfs() to file Validation/calculate_metric_gfs.h
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
We also should write a function that will use the analytic formulae for $B^i$.
B_analyticU_to_print = [\ lhrh(lhs=gri.gfaccess("out_gfs","B_analyticU0"),rhs=B_analyticU[0]),\ lhrh(lhs=gri.gfaccess("out_gfs","B_analyticU1"),rhs=B_analyticU[1]),\ lhrh(lhs=gri.gfaccess("out_gfs","B_analyticU2"),rhs=B_analyticU[2]),\ ...
Output C function calculate_exact_BU() to file Validation/calculate_exact_BU.h
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Step 1.d: The vector potential $A_k$ \[Back to [top](toc)\]$$\label{vector_potential}$$We'll now write a function to set the vector potential $A_k$. This simply uses NRPy+ to generate most of the code from the expressions we wrote at the beginning. Then, we'll need to call the function from the module `GiRaFFE_NRPy_A2...
AD_to_print = [\ lhrh(lhs=gri.gfaccess("out_gfs","AD0"),rhs=AD[0]),\ lhrh(lhs=gri.gfaccess("out_gfs","AD1"),rhs=AD[1]),\ lhrh(lhs=gri.gfaccess("out_gfs","AD2"),rhs=AD[2]),\ ] desc = "Calculate the vector potential" name = "calculate_AD" outCfunction( outfi...
Output C function calculate_AD() to file Validation/calculate_AD.h
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Step 1.e: Set free parameters in the code \[Back to [top](toc)\]$$\label{free_parameters}$$We also need to create the files that interact with NRPy's C parameter interface.
# Step 3.d.i: Generate declare_Cparameters_struct.h, set_Cparameters_default.h, and set_Cparameters[-SIMD].h # par.generate_Cparameters_Ccodes(os.path.join(out_dir)) # Step 3.d.ii: Set free_parameters.h with open(os.path.join(out_dir,"free_parameters.h"),"w") as file: file.write(""" // Override parameter defaults ...
_____no_output_____
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Step 2: `A2B_unit_test.c`: The Main C Code \[Back to [top](toc)\]$$\label{mainc}$$Now that we have our vector potential and analytic magnetic field to compare against, we will start writing our unit test. We'll also import common C functionality, define `REAL`, the number of ghost zones, and the faces, and set the sta...
%%writefile $out_dir/A2B_unit_test.c // These are common packages that we are likely to need. #include "stdio.h" #include "stdlib.h" #include "math.h" #include "string.h" // Needed for strncmp, etc. #include "stdint.h" // Needed for Windows GCC 6.x compatibility #include <time.h> // Needed to set a random seed. #def...
Overwriting Validation//A2B_unit_test.c
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
We'll now define the gridfunction names.
%%writefile -a $out_dir/A2B_unit_test.c // Let's also #define the NRPy+ gridfunctions #define AD0GF 0 #define AD1GF 1 #define AD2GF 2 #define NUM_EVOL_GFS 3 #define GAMMADD00GF 0 #define GAMMADD01GF 1 #define GAMMADD02GF 2 #define GAMMADD11GF 3 #define GAMMADD12GF 4 #define GAMMADD22GF 5 #define B_ANALYTICU0GF 6 #defi...
Appending to Validation//A2B_unit_test.c
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Now, we'll handle the different A2B codes. There are several things to do here. First, we'll add `include`s to the C code so that we have access to the functions we want to test, as generated above. We will choose to do this in the subfolder `A2B` relative to this tutorial.
%%writefile -a $out_dir/A2B_unit_test.c #include "A2B/driver_AtoB.h" // This file contains both functions we need. #include "calculate_exact_BU.h" #include "calculate_AD.h" #include "calculate_metric_gfs.h"
Appending to Validation//A2B_unit_test.c
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Now, we'll write the main method. First, we'll set up the grid. In this test, we cannot use only one point. As we are testing a three-point stencil, we can get away with a minimal $3 \times 3 \times 3$ grid. Then, we'll write the A fields. After that, we'll calculate the magnetic field two ways.
%%writefile -a $out_dir/A2B_unit_test.c int main(int argc, const char *argv[]) { paramstruct params; #include "set_Cparameters_default.h" // Let the last argument be the test we're doing. 1 = coarser grid, 0 = finer grid. int do_quadratic_test = atoi(argv[4]); // Step 0c: Set free parameters, over...
Appending to Validation//A2B_unit_test.c
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Step 2.a: Compile and run the code \[Back to [top](toc)\]$$\label{compile_run}$$Now that we have our file, we can compile it and run the executable.
import time print("Now compiling, should take ~2 seconds...\n") start = time.time() cmd.C_compile(os.path.join(out_dir,"A2B_unit_test.c"), os.path.join(out_dir,"A2B_unit_test")) end = time.time() print("Finished in "+str(end-start)+" seconds.\n\n") print("Now running...\n") start = time.time() !./Validation/A2B_unit_...
Now compiling, should take ~2 seconds... Compiling executable... Executing `gcc -Ofast -fopenmp -march=native -funroll-loops Validation/A2B_unit_test.c -o Validation/A2B_unit_test -lm`... Finished executing in 0.6135389804840088 seconds. Finished compilation. Finished in 0.6216833591461182 seconds. Now running... d...
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Step 3: Code validation: Verify that relative error in numerical solution converges to zero at the expected order \[Back to [top](toc)\]$$\label{convergence}$$Now that we have shown that when we use a quadratic vector potential, we get roundoff-level agreement (which is to be expected, since the finite-differencing us...
import numpy as np import matplotlib.pyplot as plt Data1 = np.loadtxt("out1-numer.txt") Data2 = np.loadtxt("out7-numer.txt") # print("Convergence test: All should be approximately 2\n") # convergence = np.log(np.divide(np.abs(Data1),np.abs(Data2)))/np.log(2) # for i in range(len(convergence[:,0])): # print(converg...
Face | Res | L2 norm | Conv. Order Int | Dx | 0.0000005 | -- -- | Dx/2 | 0.0000001 | 2.03057 -x | Dx | 0.0000008 | -- -- | Dx/2 | 0.0000002 | 2.08857 +x | Dx | 0.0000008 | -- -- | Dx/2 | 0.0000002 | 2.08857 -y | Dx | 0.0000008 | -- -- | Dx/2 | 0.0000002 | 1.64224 +y | Dx | 0.0000016 | ...
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
Step 4: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](toc)\]$$\label{latex_pdf_output}$$The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial direct...
!jupyter nbconvert --to latex --template latex_nrpy_style.tplx --log-level='WARN' Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb !pdflatex -interaction=batchmode Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.tex !pdflatex -interaction=batchmode Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.tex !pdfl...
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=pdflatex) restricted \write18 enabled. entering extended mode This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=pdflatex) restricted \write18 enabled. entering extended mode This is pdfTeX, Ve...
BSD-2-Clause
in_progress/Tutorial-Start_to_Finish_UnitTest-GiRaFFE_NRPy-A2B.ipynb
Steve-Hawk/nrpytutorial
http://www.yr.no/place/Norway/Telemark/Vinje/Haukeliseter/climate.month12.html
import matplotlib.pyplot as plt import matplotlib.dates as dates import numpy as np import csv import pandas as pd import datetime from datetime import date import calendar %matplotlib inline year = np.arange(2000,2017, 1) T_av = [-4.1,\ -8.2,\ -10.7,\ -4.3,\ -4.1,\ -5.5,\ -0...
_____no_output_____
MIT
yr_Dec_clim_2000_2016.ipynb
franzihe/Python_Masterthesis
DB2 Jupyter Notebook ExtensionsVersion: 2021-08-23 This code is imported as a Jupyter notebook extension in any notebooks you create with DB2 code in it. Place the following line of code in any notebook that you want to use these commands with:&37;run db2.ipynbThis code defines a Jupyter/Python magic command called `%...
# # Set up Jupyter MAGIC commands "sql". # %sql will return results from a DB2 select statement or execute a DB2 command # # IBM 2021: George Baklarz # Version 2021-07-13 # from __future__ import print_function from IPython.display import HTML as pHTML, Image as pImage, display as pdisplay, Javascript as Javascript f...
_____no_output_____
Apache-2.0
db2.ipynb
Db2-DTE-POC/Db2-Openshift-11.5.4
OptionsThere are four options that can be set with the **`%sql`** command. These options are shown below with the default value shown in parenthesis.- **`MAXROWS n (10)`** - The maximum number of rows that will be displayed before summary information is shown. If the answer set is less than this number of rows, it wil...
def setOptions(inSQL): global _settings, _display cParms = inSQL.split() cnt = 0 while cnt < len(cParms): if cParms[cnt].upper() == 'MAXROWS': if cnt+1 < len(cParms): try: _settings["maxrows"] = int(cParms[cnt+1]) ex...
_____no_output_____
Apache-2.0
db2.ipynb
Db2-DTE-POC/Db2-Openshift-11.5.4
SQL HelpThe calling format of this routine is:```sqlhelp()```This code displays help related to the %sql magic command. This help is displayed when you issue a %sql or %%sql command by itself, or use the %sql -h flag.
def sqlhelp(): global _environment if (_environment["jupyter"] == True): sd = '<td style="text-align:left;">' ed1 = '</td>' ed2 = '</td>' sh = '<th style="text-align:left;">' eh1 = '</th>' eh2 = '</th>' sr = '<tr>' er = '</tr>' ...
_____no_output_____
Apache-2.0
db2.ipynb
Db2-DTE-POC/Db2-Openshift-11.5.4
Connection HelpThe calling format of this routine is:```connected_help()```This code displays help related to the CONNECT command. This code is displayed when you issue a %sql CONNECT command with no arguments or you are running a SQL statement and there isn't any connection to a database yet.
def connected_help(): sd = '<td style="text-align:left;">' ed = '</td>' sh = '<th style="text-align:left;">' eh = '</th>' sr = '<tr>' er = '</tr>' if (_environment['jupyter'] == True): helpConnect = """ <h3>Connecting to Db2</h3> <p>The CONNECT c...
_____no_output_____
Apache-2.0
db2.ipynb
Db2-DTE-POC/Db2-Openshift-11.5.4
Prompt for Connection InformationIf you are running an SQL statement and have not yet connected to a database, the %sql command will prompt you for connection information. In order to connect to a database, you must supply:- Database name - Host name (IP address or name)- Port number- Userid- Password- Secure socketTh...
# Prompt for Connection information def connected_prompt(): global _settings _database = '' _hostname = '' _port = '' _uid = '' _pwd = '' _ssl = '' print("Enter the database connection details (Any empty value will cancel the connection)") _database = input("Enter the...
_____no_output_____
Apache-2.0
db2.ipynb
Db2-DTE-POC/Db2-Openshift-11.5.4
Connect Syntax ParserThe parseConnect routine is used to parse the CONNECT command that the user issued within the %sql command. The format of the command is:```parseConnect(inSQL)```The inSQL string contains the CONNECT keyword with some additional parameters. The format of the CONNECT command is one of:```CONNECT RE...
# Parse the CONNECT statement and execute if possible def parseConnect(inSQL,local_ns): global _settings, _connected _connected = False cParms = inSQL.split() cnt = 0 _settings["ssl"] = "" while cnt < len(cParms): if cParms[cnt].upper() == 'TO': if cnt+...
_____no_output_____
Apache-2.0
db2.ipynb
Db2-DTE-POC/Db2-Openshift-11.5.4