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
초기화---이 노트북에서는 데이터 폴더에 추론 디렉토리를 추가하게끔 저장소 구조를 갱신합니다.```/lookout-equipment-demo|+-- data/| || +-- inference/| | || | |-- input/| | || | \-- output/| || +-- labelled-data/| | \-- labels.csv| || \-- training-data/| \-- expander/| |-- subsystem-01| | \-- subsyste...
%%sh pip -q install --upgrade pip pip -q install --upgrade awscli boto3 sagemaker aws configure add-model --service-model file://../utils/lookoutequipment.json --service-name lookoutequipment from IPython.core.display import HTML HTML("<script>Jupyter.notebook.kernel.restart()</script>") import boto3 import datetime im...
_____no_output_____
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
파라미터
warnings.filterwarnings('ignore') DATA = os.path.join('..', 'data') RAW_DATA = os.path.join('..', 'dataset') INFER_DATA = os.path.join(DATA, 'inference') os.makedirs(os.path.join(INFER_DATA, 'input'), exist_ok=True) os.makedirs(os.path.join(INFER_DATA, 'output'), exist_ok=True) ROLE_ARN = sagemaker.get_exec...
_____no_output_____
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
추론 스케줄러 생성하기---콘솔의 모델 세부 정보 부분으로 이동하면 추론 스케줄이 아직 없음을 확인할 수 있습니다.![Schedule Starting point](../assets/schedule_start.png) 스케줄러 설정새로운 추론 스케줄을 만들어 보겠습니다. 파라미터 일부는 필수 입력이지만 파라미터 다수는 유연하게 추가 설정할 수 있습니다. 파라미터* 추론을 위해 데이터를 업로드할 빈도로 `DATA_UPLOAD_FREQUENCY`를 설정합니다. 허용되는 값은`PT5M`,`PT10M`,`PT15M`,`PT30M`과`PT1H`입니다. * 이것은 추론 스케...
# 생성하려는 추론 스케줄러의 이름 INFERENCE_SCHEDULER_NAME = 'lookout-demo-model-v1-scheduler' # 본 추론 스케줄러를 생성할 모델의 이름 MODEL_NAME_FOR_CREATING_INFERENCE_SCHEDULER = 'lookout-demo-model-v1' # 필수 입력 파라미터 INFERENCE_DATA_SOURCE_BUCKET = BUCKET INFERENCE_DATA_SOURCE_PREFIX = f'{PREFIX}/input/' INFERENCE_DATA_OUTPUT_BUCKET = BUCKET INFE...
_____no_output_____
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
생략 가능한 파라미터* 데이터 업로드하는데 지연이 예상되는 시간(분)으로 `DATA_DELAY_OFFSET_IN_MINUTES`를 설정합니다. 즉, 데이터 업로드하는 시간에 대한 버퍼입니다.* ``INPUT_TIMEZONE_OFFSET``을 설정합니다. 허용되는 값은 +00:00, +00:30, -01:00, ... +11:30, +12:00, -00:00, -00:30, -01:00, ... -11:30, -12:00입니다.* `TIMESTAMP_FORMAT`을 설정합니다. 허용되는 값은 `EPOCH`, `yyyy-MM-dd-HH-mm-ss` 또는 `yyyyMMd...
DATA_DELAY_OFFSET_IN_MINUTES = None INPUT_TIMEZONE_OFFSET = '+00:00' COMPONENT_TIMESTAMP_DELIMITER = '_' TIMESTAMP_FORMAT = 'yyyyMMddHHmmss'
_____no_output_____
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
추론 스케줄러 생성하기CreateInferenceScheduler API는 스케줄러를 생성**하고** 구동시킵니다. 즉, 즉각적으로 비용이 발생하기 시작합니다. 그러나 기존 스케줄러를 원하는대로 중지하거나 재구동시킬 수 있습니다 (이 노트북의 마지막 부분 참조).
scheduler = lookout.LookoutEquipmentScheduler( scheduler_name=INFERENCE_SCHEDULER_NAME, model_name=MODEL_NAME_FOR_CREATING_INFERENCE_SCHEDULER, region_name=REGION_NAME ) scheduler_params = { 'input_bucket': INFERENCE_DATA_SOURCE_BUCKET, 'input_prefix': INFERENCE_DATA_SOURCE_PREFIX, 'output_buck...
_____no_output_____
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
추론 데이터 준비하기---스케줄러가 모니터링할 S3 입력 위치에 몇 가지 데이터를 준비하고 전송하겠습니다.
# 원본 신호 전체를 불러오겠습니다. all_tags_fname = os.path.join(DATA, 'training-data', 'expander.parquet') table = pq.read_table(all_tags_fname) all_tags_df = table.to_pandas() del table all_tags_df.head()
_____no_output_____
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
태그 설명을 불러옵시다. 본 데이터셋에는 다음 내용을 포함하는 태그 설명 파일이 존재합니다.* `Tag`: 이력 관리 시스템에 고객이 기록한 태그 명 (예컨대 [Honeywell 프로세스 이력 데이터베이스](https://www.honeywellprocess.com/en-US/explore/products/advanced-applications/uniformance/Pages/uniformance-phd.aspx))* `UOM`: 기록한 신호의 측정 단위* `Subsystem`: 해당 센서가 연결된 자산 부속의 ID여기에서 구성 요소 (즉, 하위 시스템 열)의 Lis...
tags_description_fname = os.path.join(RAW_DATA, 'tags_description.csv') tags_description_df = pd.read_csv(tags_description_fname) components = tags_description_df['Subsystem'].unique() tags_description_df.head()
_____no_output_____
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
샘플 추론 데이터셋을 구성하기 위해 원본 시계열 검증 기간에서 마지막 몇 분을 추출합니다.
# 추출하려는 시퀀스 개수 num_sequences = 3 # 스케줄링 빈도 (분): 이 값은 **반드시** # 모델 학습에 사용한 리샘플링 비율에 맞춰 설정해야 합니다. frequency = 5 # 각 시퀀스를 반복합니다. start = all_tags_df.index.max() + datetime.timedelta(minutes=-frequency * (num_sequences) + 1) for i in range(num_sequences): end = start + datetime.timedelta(minutes=+frequency - 1) ...
Extracting data from 2015-11-30 23:45:00 to 2015-11-30 23:49:00: Extracting data from 2015-11-30 23:50:00 to 2015-11-30 23:54:00: Extracting data from 2015-11-30 23:55:00 to 2015-11-30 23:59:00: ===== Polling Inference Scheduler Status ===== Scheduler Status: PENDING Scheduler Status: RUNNING ===== End of Polling Inf...
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
스케줄러가 실행 중이며 추론 기록은 현재 비어 있습니다.![Scheduler created](../assets/schedule_created.png) 추론 결과 얻기--- 추론 실행 결과 나열하기 **스케줄러가 추론을 최초로 실행할 경우 5-15분 정도 걸립니다.** 대기가 끝나면 현재 추론 스케줄러에서 ListInferenceExecution API를 사용할 수 있습니다. 입력 파라미터로 스케줄러 명만 필요합니다.추론 실행 결과를 질의할 기간을 선택할 수 있습니다. 지정하지 않으면 추론 스케줄러에 대한 모든 실행 결과들이 나열됩니다. 시간 범위를 지정하려면 다음...
START_TIME_FOR_INFERENCE_EXECUTIONS = None END_TIME_FOR_INFERENCE_EXECUTIONS = None EXECUTION_STATUS = None execution_summaries = [] while len(execution_summaries) == 0: execution_summaries = scheduler.list_inference_executions( start_time=START_TIME_FOR_INFERENCE_EXECUTIONS, end_time=END_TIME_FOR...
WAITING FOR THE FIRST INFERENCE EXECUTION WAITING FOR THE FIRST INFERENCE EXECUTION FIRST INFERENCE EXECUTED
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
스케줄러를 5분마다 실행하도록 구성했습니다. 몇 분 후 콘솔에서 첫 번째 실행 결과가 입력된 기록을 살펴볼 수 있습니다. ![Inference history](../assets/schedule_inference_history.png) 스케줄러가 시작될 때, 예를 들어 `datetime.datetime (2021, 1, 27, 9, 15)`일 때 입력 위치에서 **단일** CSV 파일을 찾습니다. 여기에는 타임스탬프가 포함된 파일 명이, 말하자면 다음과 같은 파일 명이 존재해야 합니다.* subsystem-01_2021012709**10**00.csv가 검색되고 수집됩...
results_df = scheduler.get_predictions() results_df.to_csv(os.path.join(INFER_DATA, 'output', 'results.csv')) results_df.head()
_____no_output_____
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
추론 스케줄러 운영--- 추론 스케줄러 중단하기**근검 절약해야합니다**. 스케줄러 실행이 Amazon Lookout for Equipment 비용의 주된 원인입니다. 다음 API를 이용하여 현재 실행 중인 추론 스케줄러를 중지시키세요. 그렇게 하면 주기적인 추론 실행이 중지됩니다.
scheduler.stop()
===== Polling Inference Scheduler Status ===== Scheduler Status: STOPPING Scheduler Status: STOPPED ===== End of Polling Inference Scheduler Status =====
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
추론 스케줄러 시작하기다음 API를 사용하여 `STOPPED` 추론 스케줄러를 재시작할 수 있습니다.
scheduler.start()
===== Polling Inference Scheduler Status ===== Scheduler Status: PENDING Scheduler Status: RUNNING ===== End of Polling Inference Scheduler Status =====
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
추론 스케줄러 삭제하기더 이상 사용하지 않는, **중지된** 스케줄러를 삭제할 수 있습니다. 모델 당 하나의 스케줄러만 가질 수 있습니다.
scheduler.stop() scheduler.delete()
===== Polling Inference Scheduler Status ===== Scheduler Status: STOPPING Scheduler Status: STOPPED ===== End of Polling Inference Scheduler Status =====
MIT-0
notebooks/5_inference_scheduling.ipynb
youngmki/lookout-for-equipment-demo
RGBD integrationOpen3D implements a scalable RGBD image integration algorithm. The algorithm is based on the technique presented in [\[Curless1996\]](../reference.htmlcurless1996) and [\[Newcombe2011\]](../reference.htmlnewcombe2011). In order to support large scenes, we use a hierarchical hashing structure introduced...
class CameraPose: def __init__(self, meta, mat): self.metadata = meta self.pose = mat def __str__(self): return 'Metadata : ' + ' '.join(map(str, self.metadata)) + '\n' + \ "Pose : " + "\n" + np.array_str(self.pose) def read_trajectory(filename): traj = [] with op...
_____no_output_____
MIT
examples/python/pipelines/rgbd_integration.ipynb
aaronlhe/Open3D
TSDF volume integrationOpen3D provides two types of TSDF volumes: `UniformTSDFVolume` and `ScalableTSDFVolume`. The latter is recommended since it uses a hierarchical structure and thus supports larger scenes.`ScalableTSDFVolume` has several parameters. `voxel_length = 4.0 / 512.0` means a single voxel size for TSDF v...
volume = o3d.pipelines.integration.ScalableTSDFVolume( voxel_length=4.0 / 512.0, sdf_trunc=0.04, color_type=o3d.pipelines.integration.TSDFVolumeColorType.RGB8) for i in range(len(camera_poses)): print("Integrate {:d}-th image into the volume.".format(i)) color = o3d.io.read_image("../../test_data/R...
_____no_output_____
MIT
examples/python/pipelines/rgbd_integration.ipynb
aaronlhe/Open3D
Extract a meshMesh extraction uses the marching cubes algorithm [\[LorensenAndCline1987\]](../reference.htmllorensenandcline1987).
print("Extract a triangle mesh from the volume and visualize it.") mesh = volume.extract_triangle_mesh() mesh.compute_vertex_normals() o3d.visualization.draw_geometries([mesh], front=[0.5297, -0.1873, -0.8272], lookat=[2.0712, 2.0312, 1.7251], ...
_____no_output_____
MIT
examples/python/pipelines/rgbd_integration.ipynb
aaronlhe/Open3D
Apache Arrow 1 Compare performance of csv, Parquet and Arrow - 1 Change
import pyarrow.parquet as pq import pyarrow as pa import pandas as pd import numpy as np import os import psutil
_____no_output_____
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.1 Load and prepare data One more change
## Read Palmer Station Penguin dataset from GitHub df = pd.read_csv("https://raw.githubusercontent.com/allisonhorst/" "palmerpenguins/47a3476d2147080e7ceccef4cf70105c808f2cbf/" "data-raw/penguins_raw.csv") # Increase dataset to 1m rows and reset index df = df.sample(1_000_000, replace=...
_____no_output_____
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.2 Write to disk
# Write to csv df.to_csv("penguin-dataset.csv") # Write to parquet df.to_parquet("penguin-dataset.parquet") context = pa.default_serialization_context() # Write to Arrow # Convert from pandas to Arrow table = pa.Table.from_pandas(df) # Write out to file writer = pa.RecordBatchFileWriter('penguin-dataset.arrow', tab...
_____no_output_____
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.3 Reading time - calculate average of numeric column 1.3.1 Read csv and calculate mean
%%timeit pd.read_csv("penguin-dataset.csv")["Flipper Length (mm)"].mean()
3.4 s ± 105 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.3.2 Read parquet and calculate mean
%%timeit pd.read_parquet("penguin-dataset.parquet", columns=["Flipper Length (mm)"]).mean()
/Users/ravishankarnair/anaconda3/envs/py36/lib/python3.6/site-packages/pyarrow/pandas_compat.py:708: FutureWarning: .labels was deprecated in version 0.24.0. Use .codes instead. labels = getattr(columns, 'labels', None) or [ /Users/ravishankarnair/anaconda3/envs/py36/lib/python3.6/site-packages/pyarrow/pandas_compat....
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.3.3 Read Arrow using file API
%%timeit with pa.OSFile('penguin-dataset.arrow', 'rb') as source: table = pa.ipc.open_file(source).read_all().column("Flipper Length (mm)") result = table.to_pandas().mean()
133 ms ± 2.73 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.3.4 Read Arrow with memory-mapped API with missing values
%%timeit source = pa.memory_map('penguin-dataset.arrow', 'r') table = pa.ipc.RecordBatchFileReader(source).read_all().column("Flipper Length (mm)") result = table.to_pandas().mean()
6.19 ms ± 82.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.3.5 Read Arrow with memory-mapped API without missing values (zero-copy)
%%timeit source = pa.memory_map('penguin-dataset-nonan.arrow', 'r') table = pa.ipc.RecordBatchFileReader(source).read_all().column("Flipper Length (mm)") result = table.to_pandas().mean()
4.04 ms ± 80.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.4 Memory consumption - read column
# Measure initial memory consumption memory_init = psutil.Process(os.getpid()).memory_info().rss >> 20
_____no_output_____
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.4.1 Read csv
col_csv = pd.read_csv("penguin-dataset.csv")["Flipper Length (mm)"] memory_post_csv = psutil.Process(os.getpid()).memory_info().rss >> 20
_____no_output_____
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.4.2 Read parquet
col_parquet = pd.read_parquet("penguin-dataset.parquet", columns=["Flipper Length (mm)"]) memory_post_parquet = psutil.Process(os.getpid()).memory_info().rss >> 20
_____no_output_____
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.4.3 Read Arrow using file API
with pa.OSFile('penguin-dataset.arrow', 'rb') as source: col_arrow_file = pa.ipc.open_file(source).read_all().column("Flipper Length (mm)").to_pandas() memory_post_arrowos = psutil.Process(os.getpid()).memory_info().rss >> 20
_____no_output_____
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.4.4 Read Arrow with memory-mapped API with missing values
source = pa.memory_map('penguin-dataset.arrow', 'r') table_mmap = pa.ipc.RecordBatchFileReader(source).read_all().column("Flipper Length (mm)") col_arrow_mapped = table_mmap.to_pandas() memory_post_arrowmmap = psutil.Process(os.getpid()).memory_info().rss >> 20
_____no_output_____
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.4.5 Read Arrow with memory-mapped API without missing values (zero-copy)
source = pa.memory_map('penguin-dataset-nonan.arrow', 'r') table_mmap_zc = pa.ipc.RecordBatchFileReader(source).read_all().column("Flipper Length (mm)") col_arrow_mapped_zc = table_mmap_zc.to_pandas() memory_post_arrowmmap_zc = psutil.Process(os.getpid()).memory_info().rss >> 20
_____no_output_____
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
1.4.6 Display memory consupmtion
# Print memory consumption print(f"csv: {memory_post_csv - memory_init}\n" f"Parquet: {memory_post_parquet - memory_post_csv}\n" f"Arrow file API: {memory_post_arrowos - memory_post_parquet}\n" f"Arrow memory-mapped API with NaNs: {memory_post_arrowmmap - memory_post_arrowos}\n" f"Arrow memory-m...
csv: 223 Parquet: -4 Arrow file API: -8 Arrow memory-mapped API with NaNs: 8 Arrow memory-mapped API (zero-copy): 0
Apache-2.0
arrow_performance_comparison_notebook.ipynb
passionbytes/arrowexp
Controlling accesss to attributes * Following blocks are one possible implementation of vectors of `double`s. * Here, member variable `new_name` is in `protected:` part.* Member methods and subclass members can access this variable but from the outside of the class, we cannot access it.* We call it **encapsulation**; ...
import collections class Vector(collections.UserList): def __add__(self, other): # check size assert len(self) == len(other), f"Lengths are different ({len(self)} == {len(other)})" # trying list comprehension return Vector([a + b for a, b in zip(self, other)]) def __radd__(...
_____no_output_____
BSD-3-Clause
02.ipynb
2018pycpp/18pycpp-04
Matrix class example In C++ * Following code blocks present a possible implementation of matrix class in C++.* Please note that to build these files, `vector_double.h` and `vector_double.cpp` files are necessary. ```C++// Begin matrix_double.hinclude include include include include include include "vector_double.h...
import collections import copy class Matrix(collections.UserList): def __init__(self, m=None, n=None, values=None): if m is None: self.m = self.n = 0 self.data = [] elif values is not None: self.m = int(m) # number of rows self.n = int(n) # number of...
_____no_output_____
BSD-3-Clause
02.ipynb
2018pycpp/18pycpp-04
Overview- nb023 ベース- nb034の結果を使う Const
NB = '035' isSmallSet = False if isSmallSet: LENGTH = 7000 else: LENGTH = 500_000 PATH_TRAIN = './../data/input/train_clean.csv' PATH_TEST = './../data/input/test_clean.csv' PATH_SMPLE_SUB = './../data/input/sample_submission.csv' DIR_OUTPUT = './../data/output/' cp = ['#f8b195', '#f67280', '#c06c84', '#6c5b7b...
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
Import everything I need :)
import warnings warnings.filterwarnings('ignore') import time import gc import random import os import itertools import multiprocessing import numpy as np from scipy import signal # from pykalman import KalmanFilter import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from fastprogress import progr...
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
My function
def f1_macro(true, pred): return f1_score(true, pred, average='macro') def get_df_batch(df, batch): idxs = df['batch'] == batch assert any(idxs), 'そのようなbatchはありません' return df[idxs] def get_signal_mv_mean(df, n=3001): signal_mv = np.zeros(len(df)) for bt in df['batch'].unique(): idx...
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
ref: https://www.kaggle.com/martxelo/fe-and-ensemble-mlp-and-lgbm
def calc_gradients(s, n_grads=4): ''' Calculate gradients for a pandas series. Returns the same number of samples ''' grads = pd.DataFrame() g = s.values for i in range(n_grads): g = np.gradient(g) grads['grad_' + str(i+1)] = g return grads def calc_low_pass(s...
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
ref: https://www.kaggle.com/nxrprime/single-model-lgbm-kalman-filter-ii
def Kalman1D(observations,damping=1): # To return the smoothed time series data observation_covariance = damping initial_value_guess = observations[0] transition_matrix = 1 transition_covariance = 0.1 initial_value_guess kf = KalmanFilter( initial_state_mean=initial_value_guess, ...
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
Preparation setting
sns.set()
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
load dataset
df_tr = pd.read_csv(PATH_TRAIN) df_te = pd.read_csv(PATH_TEST)
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
処理のしやすさのために、バッチ番号を振る
batch_list = [] for n in range(10): batchs = np.ones(500000)*n batch_list.append(batchs.astype(int)) batch_list = np.hstack(batch_list) df_tr['batch'] = batch_list batch_list = [] for n in range(4): batchs = np.ones(500000)*n batch_list.append(batchs.astype(int)) batch_list = np.hstack(batch_list) df_t...
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
smallset?
if isSmallSet: print('small set mode') # train batchs = df_tr['batch'].values dfs = [] for i_bt, bt in enumerate(df_tr['batch'].unique()): idxs = batchs == bt _df = df_tr[idxs][:LENGTH].copy() dfs.append(_df) df_tr = pd.concat(dfs).reset_index(drop=True) # test ...
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
Train
# configurations and main hyperparammeters # EPOCHS = 180 EPOCHS = 180 NNBATCHSIZE = 16 GROUP_BATCH_SIZE = 4000 SEED = 321 LR = 0.0015 SPLITS = 6 def seed_everything(seed): random.seed(seed) np.random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) # tf.random.set_seed(seed) # read data def read_da...
Reading Data Started...(Wed May 6 11:15:32 2020) Reading and Normalizing Data Completed Creating Features(Wed May 6 11:15:36 2020) Feature Engineering Started... Feature Engineering Completed... Training Wavenet model with 6 folds of GroupKFold Started...(Wed May 6 11:15:46 2020) Our training dataset shape is (1000,...
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
analysis
df_tr = pd.read_csv(PATH_TRAIN) batch_list = [] for n in range(10): batchs = np.ones(500000)*n batch_list.append(batchs.astype(int)) batch_list = np.hstack(batch_list) df_tr['batch'] = batch_list # group 特徴量を作成 group = group_feat_train(df_tr) df_tr = pd.concat([df_tr, group], axis=1) y = df_tr['open_channels']....
group_score(0): 0.332464 group_score(1): 0.779841 group_score(2): 0.973168 group_score(3): 0.997029 group_score(4): 0.847571
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
可視化
x_idx = np.arange(len(df_tr)) idxs = y != oof failed = np.zeros(len(df_tr)) failed[idxs] = 1 n = 200 b = np.ones(n)/n failed_move = np.convolve(failed, b, mode='same') fig, axs = plt.subplots(2, 1, figsize=(20, 6)) axs = axs.ravel() # fig = plt.figure(figsize=(20, 3)) for i_gr, group in enumerate(sorted(df_tr['group'...
_____no_output_____
MIT
nb/035_submission.ipynb
fkubota/kaggle-University-of-Liverpool-Ion-Switching
Using Interrupts and asyncio for Buttons and SwitchesThis notebook provides a simple example for using asyncio I/O to interact asynchronously with multiple input devices. A task is created for each input device and coroutines used to process the results. To demonstrate, we recreate the flashing LEDs example in the get...
from pynq import PL from pynq.overlays.base import BaseOverlay base = BaseOverlay("base.bit")
_____no_output_____
BSD-3-Clause
Pynq-ZU/base/notebooks/board/asyncio_buttons.ipynb
Xilinx/PYNQ-ZU
Define the flash LED taskNext step is to create a task that waits for the button to be pressed and flash the LED until the button is released. The `while True` loop ensures that the coroutine keeps running until cancelled so that multiple presses of the same button can be handled.
import asyncio async def flash_led(num): while True: await base.buttons[num].wait_for_value_async(1) while base.buttons[num].read(): base.leds[num].toggle() await asyncio.sleep(0.1) base.leds[num].off()
_____no_output_____
BSD-3-Clause
Pynq-ZU/base/notebooks/board/asyncio_buttons.ipynb
Xilinx/PYNQ-ZU
Create the taskAs there are four buttons we want to check, we create four tasks. The function `asyncio.ensure_future` is used to convert the coroutine to a task and schedule it in the event loop. The tasks are stored in an array so they can be referred to later when we want to cancel them.
tasks = [asyncio.ensure_future(flash_led(i)) for i in range(4)]
_____no_output_____
BSD-3-Clause
Pynq-ZU/base/notebooks/board/asyncio_buttons.ipynb
Xilinx/PYNQ-ZU
Monitoring the CPU UsageOne of the advantages of interrupt-based I/O is to minimised CPU usage while waiting for events. To see how CPU usages is impacted by the flashing LED tasks we create another task that prints out the current CPU utilisation every 3 seconds.
import psutil async def print_cpu_usage(): # Calculate the CPU utilisation by the amount of idle time # each CPU has had in three second intervals last_idle = [c.idle for c in psutil.cpu_times(percpu=True)] while True: await asyncio.sleep(3) next_idle = [c.idle for c in psutil.cpu_times...
_____no_output_____
BSD-3-Clause
Pynq-ZU/base/notebooks/board/asyncio_buttons.ipynb
Xilinx/PYNQ-ZU
Run the event loopAll of the blocking wait_for commands will run the event loop until the condition is met. All that is needed is to call the blocking `wait_for_level` method on the switch we are using as the termination condition. While waiting for switch 0 to get high, users can press any push button on the board to...
if base.switches[0].read(): print("Please set switch 0 low before running") else: base.switches[0].wait_for_value(1)
CPU Usage: 0.67%, 11.67% CPU Usage: 0.00%, 0.33% CPU Usage: 0.00%, 0.33% CPU Usage: 0.00%, 0.33% CPU Usage: 0.00%, 0.33% CPU Usage: 0.00%, 0.33%
BSD-3-Clause
Pynq-ZU/base/notebooks/board/asyncio_buttons.ipynb
Xilinx/PYNQ-ZU
Clean upEven though the event loop has stopped running, the tasks are still active and will run again when the event loop is next used. To avoid this, the tasks should be cancelled when they are no longer needed.
[t.cancel() for t in tasks]
_____no_output_____
BSD-3-Clause
Pynq-ZU/base/notebooks/board/asyncio_buttons.ipynb
Xilinx/PYNQ-ZU
Now if we re-run the event loop, nothing will happen when we press the buttons. The process will block until the switch is set back down to the low position.
base.switches[0].wait_for_value(0)
_____no_output_____
BSD-3-Clause
Pynq-ZU/base/notebooks/board/asyncio_buttons.ipynb
Xilinx/PYNQ-ZU
Making Simple Plots Objectives+ Learn how to make a simple 1D plot in Python.+ Learn how to find the maximum/minimum of a function in Python.We will use [Problem 4.B.2](https://youtu.be/w-IGNU2i3F8) of the lecturebook as a motivating example.We find that the moment of the force $\vec{F}$ about point A is:$$\vec{M_A} =...
import numpy as np # for numerical algebra import matplotlib.pyplot as plt # this is where the plotting capabilities are # The following line is need so that the plots are embedded in the Jupyter notebook (remove when not using Jupyter) %matplotlib inline # Define a function that computes the moment magnitude as a fu...
_____no_output_____
MIT
making_simple_plots.ipynb
PurdueMechanicalEngineering/me270
Now, let's put two lines in the same plot.Let's compare the moments when we change $d$ from 2 meters to 3.5 meters.
# We already have M_A for d=2 m (and all other paramters to whichever values we gave them) # Let's copy it: M_As_case_1 = M_As # And let's compute it again for d=3.5 m d = 3.5 # In m M_As_case_2 = M_A(thetas, b, d, F) # Let's plot both of them in the same figure plt.plot(thetas / (2. * np.pi) * 360, M_As_case_1, lw=2, ...
_____no_output_____
MIT
making_simple_plots.ipynb
PurdueMechanicalEngineering/me270
Finally, let's see how we can make interactive plots.We will use the Python module [ipywidgets](https://ipywidgets.readthedocs.io/en/stable/) and in particular the function [ipywidgets.interact](https://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html).
from ipywidgets import interact # Loading the module # Interact needs a function that does the plotting given the parameters. # Let's make it: def make_plots(b=0.5, d=3., F=1.): # X=val defines default values for the function """ Make the plot. """ thetas = np.linspace(0, 2. * np.pi, 100) M_As = M_A...
_____no_output_____
MIT
making_simple_plots.ipynb
PurdueMechanicalEngineering/me270
Let's just check that the function works by calling it a few times:
# With no inputs it should use the default values make_plots() # You can specify all the inputs like this: make_plots(2., 3., 2.) # Or even by name (whatever is not specified gets the default value): make_plots(F=2.3)
_____no_output_____
MIT
making_simple_plots.ipynb
PurdueMechanicalEngineering/me270
Ok. Let's use interact now:
interact(make_plots, b=(0., 5., 0.1), # Range for b: (min, max, increment) d=(0., 5, 0.1), # Range for d F=(0., 2, 0.1) # Range for F );
_____no_output_____
MIT
making_simple_plots.ipynb
PurdueMechanicalEngineering/me270
VacationPy---- Note* Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing.* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps...
# Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import gmaps import os # Import API key from api_keys import g_key
_____no_output_____
ADSL
VacationPy/VacationPy.ipynb
jgmoore10/python-api-challenge
Store Part I results into DataFrame* Load the csv exported in Part I to a DataFrame
city_data = pd.read_csv("../output_data/cities.csv") city_data.head()
_____no_output_____
ADSL
VacationPy/VacationPy.ipynb
jgmoore10/python-api-challenge
Humidity Heatmap* Configure gmaps.* Use the Lat and Lng as locations and Humidity as the weight.* Add Heatmap layer to map.
gmaps.configure(api_key=g_key) locations = city_data[["Lat", "Lng"]].astype(float) humidity = city_data["Humidity"].astype(float) fig = gmaps.figure() heat_layer = gmaps.heatmap_layer(locations, weights = humidity, dissipating = False, max_intensity = 100, point_radius = 1) fig.add_layer(heat_layer) fig
_____no_output_____
ADSL
VacationPy/VacationPy.ipynb
jgmoore10/python-api-challenge
Create new DataFrame fitting weather criteria* Narrow down the cities to fit weather conditions.* Drop any rows will null values.
narrowed_city_df = city_data.loc[(city_data["Humidity"]>=70) & (city_data["Wind Speed"]>=10) & \ (city_data["Cloudiness"] <= 20)].dropna() narrowed_city_df.head()
_____no_output_____
ADSL
VacationPy/VacationPy.ipynb
jgmoore10/python-api-challenge
Hotel Map* Store into variable named `hotel_df`.* Add a "Hotel Name" column to the DataFrame.* Set parameters to search for hotels with 5000 meters.* Hit the Google Places API for each city's coordinates.* Store the first Hotel result into the DataFrame.* Plot markers on top of the heatmap.
hotel_df = narrowed_city_df.reset_index(drop=True) hotel_df["Hotel Name"] = "" hotel_df # geocoordinates target_search = "Hotel" target_radius = 5000 target_type = "Hotels" params={ "radius":target_radius, "types":target_type, "keyword":target_search, "key":g_key } # NOTE: Do not change any of the cod...
_____no_output_____
ADSL
VacationPy/VacationPy.ipynb
jgmoore10/python-api-challenge
BEFORE YOU DO ANYTHING...In the terminal:1. Navigate to __inside__ your ILAS_Python repository.2. __COMMIT__ any un-commited work on your personal computer.3. __PULL__ any changes *you* have made using another computer.4. __PULL__ textbook updates (including homework answers). Control Flow Lesson GoalCompose simple ...
# Time-telling program time = 13.05 # current time work_starts = 8.00 # time work starts work_ends = 17.00 # time work ends lunch_starts = 13.00 # time lunch starts lunch_ends = 14.00 # time lunch ends # variable lunchtime is True if the time is between the start and end of lunchtime lunchtime ...
Is it work time? False Is it lunchtime? True
MIT
3_Control_flow.ipynb
konshte/Python_K
What if we now want our computer program to do something based on these answers?To do this, we need to use *control statements*.Control statements allow us to make decisions in a program.This decision making is known as *control flow*. Control statements are a fundamental part of programming. Here is a control statemen...
# Time-telling program time = 13.05 # current time work_starts = 8.00 # time work starts work_ends = 17.00 # time work ends lunch_starts = 13.00 # time lunch starts lunch_ends = 14.00 # time lunch ends # variable lunchtime is True if the time is between the start and end of lunchtime lunchtime ...
Eat lunch
MIT
3_Control_flow.ipynb
konshte/Python_K
__Remember:__ The program assigns the variables lunchtime and work_time the values `True` or `False`.Therefore when we type: `if lunchtime`the meaning is the same as: `if lunchtime == True` Here is another example, using algebraic operators to modify the value of an initial variable, `x`. The modification of `x` and th...
#The input to the program is variable `x`. x = -10.0 # Initial x value if x > 0.0: print('Initial x is greater than zero') #The program prints a message... x -= 20.0 # ...and modifies `x`. elif x < 0.0: print('Initial x is less than zero') x += 21.0 else: ...
Initial x is less than zero Modified x = 11.0
MIT
3_Control_flow.ipynb
konshte/Python_K
__Note:__ The program uses the short-cut algebraic operators that you learnt to use in the last seminar. __Try it yourself__In the cell code cell above, try:- changing the operations performed on `x`- changing the value of `x` a few times.Re-run the cell to see the different paths the program can follow. Look carefu...
JPY = 1_000_000 # The amount in JPY to be changed into USD cash = False # True if transaction is in cash, otherwise False market_rate = 0.0091 # 1 JPY is worth this many dollars at the market rate # Apply the appropriate reduction depending on the amount being sold if JPY < 10_000: multiplier = 0.9 ...
Amount in JPY sold: 1000000 Amount in USD purchased: 80325700.0 Effective rate: 80.3257
MIT
3_Control_flow.ipynb
konshte/Python_K
__Note:__ - We can use multiple `elif` statements within a control block. - We can use multipe `if` statements. When the program executes and exits a control block, it moves to the next `if` statement. - __Readability:__ Underscores _ are placed between 0s in long numbers to make them easier to read. You DO NOT nee...
for i in range(0, 6): print(i)
0 1 2 3 4 5
MIT
3_Control_flow.ipynb
konshte/Python_K
The first time through, the value of i is equal to 0.The second time through, its value is 1.Each loop the value `i` increases by 1 (0, 1, 2, 3, 4) until the last time when its value is 4. Look carefully at the structure of the `for` loop: - `for` is followed by the condition being checked. - : colon at the end of the...
for i in range(-2, 3): print(i) print('The end of the loop')
-2 -1 0 1 2 The end of the loop
MIT
3_Control_flow.ipynb
konshte/Python_K
The above loop starts from -2 and executes the indented code for each value of i in the range (-2, -1, 0, 1, 2).When the loop has executed the code for the final value `i = 2`, it moves on to the next unindented line of code.
for n in range(4): print("----") print(n, n**2)
---- 0 0 ---- 1 1 ---- 2 4 ---- 3 9
MIT
3_Control_flow.ipynb
konshte/Python_K
The above executes 4 loops.The statement ```pythonfor n in range(4):```says that we want to loop over four integers, starting from 0. Each loop the value `n` increases by 1 (0, 1, 2 3). __Try it yourself__Go back and change the __range__ of input values in the last three cells and observe the change in output. If we w...
for n in range(0, 10, 3): print(n)
0 3 6 9
MIT
3_Control_flow.ipynb
konshte/Python_K
If we want to step backwards rather than forwards we __must__ include the step size:
for n in range(10, 0, -1): print(n)
10 9 8 7 6 5 4 3 2 1
MIT
3_Control_flow.ipynb
konshte/Python_K
For example...
for n in range(10, 0): print(n)
_____no_output_____
MIT
3_Control_flow.ipynb
konshte/Python_K
...does not return any values because there are no values that lie between 10 and 0 when counting in the positive direction from 10. __Try it yourself.__In the cell below write a `for` loop that:- starts at `n = 9`- ends at `n = 3` (and includes `n = 3`)- loops __backwards__ through the range in steps of -3 - prints `...
# For loop for n in range(9, 2, -3): print ("-----") print(n, n**2)
----- 9 81 ----- 6 36 ----- 3 9
MIT
3_Control_flow.ipynb
konshte/Python_K
For loops are useful for performing operations on large data sets.We often encounter large data sets in real-world mathematical problems. A simple example of this is converting multiple values using the same mathematical equation to create a look-up table... Real-world Example: conversion table from degrees Fahrenhei...
print("T_f, T_c") for Tf in range(-100, 200, 20): print(Tf, "\t", round(((Tf - 32) * 5 / 9), 3))
T_f, T_c -100 -73.333 -80 -62.222 -60 -51.111 -40 -40.0 -20 -28.889 0 -17.778 20 -6.667 40 4.444 60 15.556 80 26.667 100 37.778 120 48.889 140 60.0 160 71.111 180 82.222
MIT
3_Control_flow.ipynb
konshte/Python_K
`while` loopsA __`for`__ loop performs an operation a specified number of times. ```python for x in range(5): print(x)``` A __`while`__ loop performs a task *while* a specified statement is true. ```pythonx = 0while x < 5: print(x)``` The structure of a `while` loop is similar to a `for` loop.- `while` is foll...
x = 0 print("Start of while statement") while x < 5: print(x) x += 1 # Increment x print("End of while statement")
Start of while statement 0 1 2 3 4 End of while statement
MIT
3_Control_flow.ipynb
konshte/Python_K
`for` loops are often safer when performing an operation on a set range of values.
x = -2 print("Start of for statement") for y in range(x,5): print(y) print("End of for statement")
Start of for statement -2 -1 0 1 2 3 4 End of for statement
MIT
3_Control_flow.ipynb
konshte/Python_K
Here is another example of a `while` loop.
x = 0.9 while x > 0.001: # Square x (shortcut x *= x) x = x * x print(round(x, 6))
0.81 0.6561 0.430467 0.185302 0.034337 0.001179 1e-06
MIT
3_Control_flow.ipynb
konshte/Python_K
If we use an initial value of $x \ge 1$, an infinite loop will be generted.`x` will increase with each loop, meaning `x` will always be greater than 0.001.e.g. ```pythonx = 2while x > 0.001: x = x * x print(x)``` However, using a `for` loop is a less appropriate solution in this case.We may not know beforehand ho...
x = 0.9 if x < 1: while x > 0.001: # Square x (shortcut x *= x) x = x * x print(round(x, 6)) else: print("x is greater than one, infinite loop avoided")
0.81 0.6561 0.430467 0.185302 0.034337 0.001179 1e-06
MIT
3_Control_flow.ipynb
konshte/Python_K
__Try it for yourself:__In the cell above change the value of x to above or below 1.Observe the output. __Try it for yourself:__In the cell below: - Create a variable,`x`, with the initial value 50 - Each loop: 1. print x 1. reduce the value of x by half - Exit the loop when `x` < 3
# While loop
_____no_output_____
MIT
3_Control_flow.ipynb
konshte/Python_K
`break` and `continue`. `break`Sometimes we want to break out of a `for` or `while` loop. For example in a `for` loop we can check if something is true, and then exit the loop prematurely, e.g
for x in range(10): print(x) if x == 5: print("Time to break out") break
0 1 2 3 4 5 Time to break out
MIT
3_Control_flow.ipynb
konshte/Python_K
Let's look at how we can use this in a program... The following program __finds prime numbers__.__Prime number:__ A positive integer, greater than 1, that has no positive divisors other than 1 and itself (2, 3, 5, 11, 13, 17....)The program checks (integer) numbers, `n` up to a limit `N` and prints the prime numbers. ...
N = 50 # Check numbers up 50 for primes (excludes 50) # Loop over all numbers from 2 to 50 (excluding 50) for n in range(2, N): # Assume that n is prime n_is_prime = True # Check if n divided by (any number in the range 2 to n) returns a remainder equal to 0 for m in range(2, n): #...
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
MIT
3_Control_flow.ipynb
konshte/Python_K
Notice that our program contains a second `for` loop. For each value of n, it loops through incrementing values of m in the range (2 to n):```python Check if n can be divided by m m ranges from 2 to n (excluding n)for m in range(2, n):```before incrementing to the next value of n.We call this a *nested* loop.The indent...
N = 50 # for loop 1 for n in range(2, N): n_is_prime = True # for loop 2 for m in range(2, n): if n % m == 0: n_is_prime = False if n_is_prime: print(n)
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
MIT
3_Control_flow.ipynb
konshte/Python_K
As n gets larger, dividing it by *every* number in the range (2, n) becomes more and more inefficient. A `break` statement allows us to exit the loop as soon as a remainder equal to zero is returned (indicating that n is not a prime number). In the program below, a break statement is added.As soon as a number is found...
N = 55 # for loop 1 for n in range(2, N): # for loop 2 for m in range(2, n): if n % m == 0: break else: # if n is prime print(n)
3 5 5 5 7 7 7 7 7 9 11 11 11 11 11 11 11 11 11 13 13 13 13 13 13 13 13 13 13 13 15 17 17 17 17 17 17 17 17 17 17 17 17 17 17 17 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 19 21 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 23 25 25 25 27 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 29 ...
MIT
3_Control_flow.ipynb
konshte/Python_K
`continue`Sometimes, instead of stopping the loop we want to go to the next iteration in a loop, skipping the remaining code.For this we use `continue`. The example below loops over 20 numbers (0 to 19) and checks if the number is divisible by 4. If the number is not divisible by 4:- it prints a message - it moves ...
for j in range(1, 20): if j % 4 == 0: # Check remainer of j/4 continue # continue to next value of j print(j, "is not a multiple of 4")
1 is not a multiple of 4 2 is not a multiple of 4 3 is not a multiple of 4 5 is not a multiple of 4 6 is not a multiple of 4 7 is not a multiple of 4 9 is not a multiple of 4 10 is not a multiple of 4 11 is not a multiple of 4 13 is not a multiple of 4 14 is not a multiple of 4 15 is not a multiple of 4 17 is not a mul...
MIT
3_Control_flow.ipynb
konshte/Python_K
To compare, if we used `break` instead of `continue`:
for j in range(1, 20): if j % 4 == 0: # Check remainer of j/4 break # continue to next value of j print(j, "is not a multiple of 4")
1 is not a multiple of 4 2 is not a multiple of 4 3 is not a multiple of 4
MIT
3_Control_flow.ipynb
konshte/Python_K
__Try it yourself__We can use a `for` loop to perform an operation on each character of a string.```Pythonstring = "string"for i in range(len(sting)): print(sting[i])``` In the cell below, loop through the characters of the string.Use `continue` to only print the letters of the word *sting*.
# Print the letters of the word sting string = "string"
_____no_output_____
MIT
3_Control_flow.ipynb
konshte/Python_K
Review ExercisesHere are a series of engineering problems for you to practise each of the new Python skills that you have learnt today. Review Exercise: `while` loops.In the cell below, write a while loop that with each loop:- prints the value of `x`- then decreases the value of x by 0.5as long as `x` remains positiv...
x = 4 while x > 0: print(x) x -= 0.5 # Example Solution while (x > 0): print(x) x -= 0.5
_____no_output_____
MIT
3_Control_flow.ipynb
konshte/Python_K
Review Exercise: `for` loopsIn the cell below, write a `for` loop to print the even numbers from 2 to 100, inclusive.
# for loop to print the even numbers from 2 to 20, inclusive. for n in range (2, 21): print (n) # Example Solution for i in range(2, 21, 2): print(i)
_____no_output_____
MIT
3_Control_flow.ipynb
konshte/Python_K
Review Excercise: `for` loops and `if` statementsIn the cell below, write a for loop to alternately print `Red` then `Blue` 3 times. i.e. Red Blue Red Blue Red Blue
# Alternately print Red and Blue for n in range (1, 7): if n % 2 == 0: print("red") elif # Example Solution colour = "Red" for n in range(6): print(colour) if colour == "Red": colour = "Blue" else: colour = "Red"
_____no_output_____
MIT
3_Control_flow.ipynb
konshte/Python_K
Review Exercise: `continue`In the cell below, loop through the characters of the string.Use `continue` to only print the letters of the word *sing*.Hint: Refer to __Logical Operators__ (Seminar 2). Jump to continue
# Print the letters of the word sing string = "string" # Example Solution string = "string" for i in range(len(string)): if string[i] == "r" or string[i] == "t": continue print(string[i])
_____no_output_____
MIT
3_Control_flow.ipynb
konshte/Python_K
Review Exercise: `for` loops and `if`, `else` and `continue` statements.__(A)__ In the cell below, use a for loop to print the square roots of the first 25 odd positive integers. (Remember, the square root of a number, $x$ can be found by $x^{1/2}$)__(B)__ If the number generated is greater than 3 and smaller than 5, ...
# square roots of the first 25 odd positive integers # Example Solution for x in range(1, 50, 2): if((x ** (1/2) > 3) and (x ** (1/2) < 5)): print("skip") continue print(x ** (1/2))
_____no_output_____
MIT
3_Control_flow.ipynb
konshte/Python_K
Prove that for integers $a,\;b,\;\dots$(1) $(a, b) = 1, \; c | a, \; d | a \implies (c, d) = 1$Suppose $(c, d) = e > 1$. Then $e | c$ and $c | a$ implies $e | a$; similarly $e | b$ so $(a, b) > 1$, a contradiction, and therefore $(c, d) = 1$. $\;\;\;\boxdot$(2) $(a, b) = (a, c) = 1 \implies (a, bc) = 1$(3) $(a, b) = 1 ...
def pf(n): pfn, i = [], 2 while i * i < n: while n%i == 0: pfn.append(i); n = n / i i = i + 1 pfn.append(int(n)) return pfn def npf(n): return len(pf(n)) def isprime(n): if npf(n) == 1: return True return False for a in range(3): s = a * 10 + 5 t = s*s*s*s + 4 if ...
629 factors are [17, 37] 50629 factors are [197, 257] 390629 factors are [577, 677]
MIT
T1_chapter1_exercises.ipynb
robfatland/boojum
... ...(20) Let $d = (826, 1890)$. Use the Euclidean algorithm to compute $d$, then express $d$ as a linear combination of 826 and 1890Solution$1890 = 826 \cdot 2 + 238$$826 = 238 \cdot 3 + 112$$238 = 112 \cdot 2 + 14$$112 = 14 \cdot 8 + 0$$d = 14$$d = u \cdot 826 + v \cdot 1890$ or equivalently $1 = u \cdot 59 + v \cd...
254*826-111*1890
_____no_output_____
MIT
T1_chapter1_exercises.ipynb
robfatland/boojum
Table of Contents1&nbsp;&nbsp;Plot Validation and Train loss2&nbsp;&nbsp;Extract relevant Data to df2.1&nbsp;&nbsp;Get best result2.2&nbsp;&nbsp;Consider Outliers3&nbsp;&nbsp;Results by model3.1&nbsp;&nbsp;Remove Duplicates4&nbsp;&nbsp;Each variable plotted against loss:5&nbsp;&nbsp;Investigate "band" in loss-model plo...
%load_ext autoreload %autoreload 2 %cd .. import os import sys from notebooks import utils from matplotlib import pyplot as plt %matplotlib inline import seaborn as sns sns.set() #import pipeline # parent_dir = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) # sys.path.append(parent_dir) #to import pipeline %ls...
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
Plot Validation and Train loss
ylim = (0, 3000) ylim2 = (70,100) utils.plot_results_loss_epochs(results, ylim1=ylim, ylim2=ylim2)
(2, 3)
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
Extract relevant Data to dfUse minimum validation loss as criterion. In theory (if we had it) it would be better to use DA MAE
df_res = utils.create_res_df(results) df_res_original = df_res.copy() #save original (in case you substitute out) df_res
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
Get best result
df_res["valid_loss"].idxmin() print(df_res.loc[df_res["valid_loss"].idxmin()]) df_res.loc[df_res["valid_loss"].idxmin()]["path"]
model CLIC valid_loss 397.938 activation prelu latent_dims ?? num_layers ?? total_channels None channels/layer ?? augmentation ...
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
Consider Outliers
#consider third experiment run (lots of outliers) df3 = df_res[df_res["path"].str.contains("CAE_zoo3")] df_outlier = df_res[df_res["valid_loss"] > 150000] df_outlier
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
Results by model
relu = df_res[df_res.activation == "relu"] lrelu = df_res[df_res.activation == "lrelu"] plt.scatter('model', "valid_loss", data=relu, marker="+", color='r') plt.scatter('model', "valid_loss", data=lrelu, marker="+", color='g') plt.ylabel("Loss") plt.xlabel("Model") plt.ylim(16000, 70000) plt.legend(labels=["relu", ...
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
It turns out that there are lots of duplicates in the above data (as a result of a bug in my code that was giving all models the same number of channels). So remove duplicates and go again: Remove Duplicates
#remove duplicates columns = list(df_res_original.columns) columns.remove("model") columns.remove("path") print(columns) df_res_new = df_res_original.loc[df_res_original.astype(str).drop_duplicates(subset=columns, keep="last").index] #df_res_new = df_res_original.drop_duplicates(subset=columns, keep="last") df_res_new....
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation