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
Define the parameter for the photometer reading
Y_e = ufloat(2673.3,1.) Y_e
_____no_output_____
CC0-1.0
empir19nrm02/Jupyter/IBudgetMETAS.ipynb
AndersThorseth/empir19nrm02
Define the parameter for the distance measurement
d=ufloat(25.0000, 0.0025) d
_____no_output_____
CC0-1.0
empir19nrm02/Jupyter/IBudgetMETAS.ipynb
AndersThorseth/empir19nrm02
The Model
I=k_e*Y_e*d**2 I [h, result_vecotr] = uncLib_PlotHist(I, xLabel='Luminous intensity / cd') print('Mean: {}, I0: {}, I1: {}'.format(result_vecotr[0], result_vecotr[1], result_vecotr[2])) h=uncLib_PlotHist(k_e, xLabel='calibration factor / lx/LSB')
_____no_output_____
CC0-1.0
empir19nrm02/Jupyter/IBudgetMETAS.ipynb
AndersThorseth/empir19nrm02
Prediction of 2017 World Series winner given data 1905 dataset.
import pandas as pd tot1905 = pd.read_csv("../clean_data/1905ML.csv") tot1905 = tot1905.drop({"Unnamed: 0", "H", "HR", "BB", "SB", "HA", "HRA", "BBA", "SOA", "E"}, axis=1) tot1905 tot2017 = pd.read_csv("../clean_data/2017ML.csv") tot2017 = tot2017.drop({"Unnamed: 0", "WSWIN"}, axis=1) tot2017 # Create a function to con...
WS Probability = 0.000567750444291 R 818 ERA 3.3 WP 0.63 Name: 7, dtype: object WS Probability = 0.000386572498575 R 770 ERA 3.38 WP 0.642 Name: 13, dtype: object WS Probability = 0.000337225795312 R 858 ERA 3.72 WP 0.562 Name: 18, dtype: object WS Probability = 0.0002947...
MIT
world_series_prediction-master/ML/Logistic--2017.ipynb
kchhajed1/baseball_predictions
Calculating the distance between the Customer's city and the Seller's city
from pyspark.sql import SparkSession, functions as F import math spark = SparkSession.builder.getOrCreate() orders_items_df = spark.read \ .option('escape', '\"') \ .option('quote', '\"') \ .csv('./dataset/olist_order_items_dataset.csv', header=True, multiLine=True, in...
_____no_output_____
MIT
hypothesis_25.ipynb
IuriSly/DnA-POC-olist
Grouping data
data_df = orders_df.filter(F.col('order_status') == 'delivered').join(customers_df, 'customer_id') data_df = orders_items_df.join(data_df, 'order_id') \ .join(sellers_df, 'seller_id') \ .select('customer_state', 'customer_city', 'customer_zip_code_prefix', 'seller_zip_...
+-------------------+-------------------+-------------------+-------------------+-------------+ | customer_lat| customer_lng| seller_lat| seller_lng|freight_value| +-------------------+-------------------+-------------------+-------------------+-------------+ | -23.50648246805157|-47.4220680...
MIT
hypothesis_25.ipynb
IuriSly/DnA-POC-olist
Calculating distance
def d(c_lat, c_lng, s_lat, s_lng): radius = 6371 # km dlat = math.radians(s_lat-c_lat) dlon = math.radians(s_lng-c_lng) a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(c_lat)) \ * math.cos(math.radians(s_lat)) * math.sin(dlon/2) * math.sin(dlon/2) c = 2 * math.atan2(math.sqr...
_____no_output_____
MIT
hypothesis_25.ipynb
IuriSly/DnA-POC-olist
SCOPUS journal Data analysis of Indian Research About: The main aim of this data analysis is to identify the ongoing research in Indian Universities and Indian Industry. It gives a basic answer about research source and trend with top authors and publication. It also shows the participation of Industry and Universitie...
import sqlite3 import matplotlib.pyplot as plt import operator sqlite_database = '/home/neel/scopus_data/scopus_data.sqlite' conn = sqlite3.connect(sqlite_database) c = conn.cursor() c.execute("SELECT `Title`,`cited_rank` FROM `AI_scopus` ORDER BY `cited_rank` DESC LIMIT 0, 20;") data = c.fetchall() conn.close() top_p...
_____no_output_____
MIT
SCOPUS_data_analysis_Python3x_v1.ipynb
NeelShah18/scopus-analysis-for-indian-researcher
[![Github](https://img.shields.io/github/stars/lab-ml/python_autocomplete?style=social)](https://github.com/lab-ml/python_autocomplete)[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/lab-ml/python_autocomplete/blob/master/notebooks/evaluate.ipynb) Ev...
%%capture !pip install labml labml_python_autocomplete
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Imports
import string import torch from torch import nn from labml import experiment, logger, lab from labml_helpers.module import Module from labml.logger import Text, Style from labml.utils.pytorch import get_modules from labml.utils.cache import cache from labml_helpers.datasets.text import TextDataset from python_autoco...
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
We load the model from a training run. For this demo I'm loading from a run I trained at home.[![View Run](https://img.shields.io/badge/labml-experiment-brightgreen)](https://web.lab-ml.com/run?uuid=39b03a1e454011ebbaff2b26e3148b3d)*If you want to try this on Colab you need to run this on the same space where you run t...
TRAINING_RUN_UUID = '39b03a1e454011ebbaff2b26e3148b3d'
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
We initialize `Configs` object defined in [`train.py`](https://github.com/lab-ml/python_autocomplete/blob/master/python_autocomplete/train.py).
conf = Configs()
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Create a new experiment in evaluation mode. In evaluation mode a new training run is not created.
experiment.evaluate()
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Load custom configurations/hyper-parameters used in the training run.
custom_conf = experiment.load_configs(TRAINING_RUN_UUID) custom_conf
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Set the custom configurations
experiment.configs(conf, custom_conf)
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Set models for saving and loading. This will load `conf.model` from the specified run.
experiment.add_pytorch_models({'model': conf.model})
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Specify which run to load from
experiment.load(TRAINING_RUN_UUID)
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Start the experiment
experiment.start()
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Initialize the `Predictor` defined in [`evaluate.py`](https://github.com/lab-ml/python_autocomplete/blob/master/python_autocomplete/evaluate.py).We load `stoi` and `itos` from cache, so that we don't have to read the dataset to generate them. `stoi` is the map for character to an integer index and `itos` is the map of ...
p = Predictor(conf.model, cache('stoi', lambda: conf.text.stoi), cache('itos', lambda: conf.text.itos))
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Set model to evaluation mode
_ = conf.model.eval()
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
A python prompt to test completion.
PROMPT = """from torch import nn from labml_helpers.module import Module from labml_nn.lstm import LSTM class LSTM(Module): def __init__(self, *, n_tokens: int, embedding_size: int, hidden_size int, n_layers int):"""
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Get a token. `get_token` predicts character by character greedily (no beam search) until it find and end of token character (non alpha-numeric character).
%%time res = p.get_token(PROMPT) print('"' + res + '"')
" super" CPU times: user 950 ms, sys: 34.7 ms, total: 984 ms Wall time: 254 ms
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Try another token
res = p.get_token(PROMPT + res) print('"' + res + '"')
"(LSTM"
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Load a sample python file to test our model
with open(str(lab.get_data_path() / 'sample.py'), 'r') as f: sample = f.read() print(sample[-50:])
ckpoint() if __name__ == '__main__': main()
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Test the model on a sample python file`evaluate` function defined in[`evaluate.py`](https://github.com/lab-ml/python_autocomplete/blob/master/python_autocomplete/evaluate.py)will predict token by token using the `Predictor`, and simulates an editor autocompletion.Colors:* yellow: the token predicted is wrong and the u...
%%time evaluate(p, sample)
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
`accuracy` is the fraction of charactors predicted correctly. `key_strokes` is the number of key strokes required to write the code with help of the model and `length` is the number of characters in the code, that is the number of key strokes required without the model.*Note that this sample is a classic MNIST example,...
anomalies(p, sample)
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
Here we try to autocomplete 100 characters
sample = """import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.utils.data from torchvision import datasets, transforms from labml import lab class Model(nn.Module): """ complete(p, sample, 100)
_____no_output_____
MIT
notebooks/evaluate.ipynb
kalufinnle/python_autocomplete
MLP 208* Operate on 16000 GenCode 34 seqs.* 5-way cross validation. Save best model per CV.* Report mean accuracy from final re-validation with best 5.* Use Adam with a learn rate decay schdule.
NC_FILENAME='ncRNA.gc34.processed.fasta' PC_FILENAME='pcRNA.gc34.processed.fasta' DATAPATH="" try: from google.colab import drive IN_COLAB = True PATH='/content/drive/' drive.mount(PATH) DATAPATH=PATH+'My Drive/data/' # must end in "/" NC_FILENAME = DATAPATH+NC_FILENAME PC_FILENAME = DATAPA...
_____no_output_____
MIT
Workshop/MLP_208.ipynb
ShepherdCode/ShepherdML
Build model
def compile_model(model): adam_default_learn_rate = 0.001 schedule = tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate = adam_default_learn_rate*10, #decay_steps=100000, decay_rate=0.96, staircase=True) decay_steps=10000, decay_rate=0.99, staircase=True) # learn r...
_____no_output_____
MIT
Workshop/MLP_208.ipynb
ShepherdCode/ShepherdML
Load and partition sequences
# Assume file was preprocessed to contain one line per seq. # Prefer Pandas dataframe but df does not support append. # For conversion to tensor, must avoid python lists. def load_fasta(filename,label): DEFLINE='>' labels=[] seqs=[] lens=[] nums=[] num=0 with open (filename,'r') as infile: ...
_____no_output_____
MIT
Workshop/MLP_208.ipynb
ShepherdCode/ShepherdML
Make K-mers
def make_kmer_table(K): npad='N'*K shorter_kmers=[''] for i in range(K): longer_kmers=[] for mer in shorter_kmers: longer_kmers.append(mer+'A') longer_kmers.append(mer+'C') longer_kmers.append(mer+'G') longer_kmers.append(mer+'T') short...
_____no_output_____
MIT
Workshop/MLP_208.ipynb
ShepherdCode/ShepherdML
Cross validation
def do_cross_validation(X,y,given_model): cv_scores = [] fold=0 splitter = ShuffleSplit(n_splits=SPLITS, test_size=0.1, random_state=37863) for train_index,valid_index in splitter.split(X): fold += 1 X_train=X[train_index] # use iloc[] for dataframe y_train=y[train_index] ...
_____no_output_____
MIT
Workshop/MLP_208.ipynb
ShepherdCode/ShepherdML
Train on RNA lengths 200-1Kb
MINLEN=200 MAXLEN=1000 print("Load data from files.") nc_seq=load_fasta(NC_FILENAME,0) pc_seq=load_fasta(PC_FILENAME,1) train_set=pd.concat((nc_seq,pc_seq),axis=0) nc_seq=None pc_seq=None print("Ready: train_set") #train_set print ("Compile the model") model=build_model(MAXLEN) print ("Summarize the model") print(model...
_____no_output_____
MIT
Workshop/MLP_208.ipynb
ShepherdCode/ShepherdML
JAXの乱数生成について調べてみたけどよくわからない> JAXにおける乱数生成について調べたけどよくわからない- toc: true - badges: true- comments: true- categories: [Python, JAX, DeepLearning]- image: images/jax-samune.png JAX流行ってますね。JAXについての詳しい説明は、[たくさんの記事](https://www.google.com/search?q=jax%E3%81%A8%E3%81%AF)や[https://github.com/google/jax](https://github.com/google/j...
import numpy as np # numpy x = np.random.rand() print('x:', x) for i in range(10): x = np.random.rand() print('x:', x)
x: 0.7742336894342167 x: 0.45615033221654855 x: 0.5684339488686485 x: 0.018789800436355142 x: 0.6176354970758771 x: 0.6120957227224214 x: 0.6169339968747569 x: 0.9437480785146242 x: 0.6818202991034834 x: 0.359507900573786
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
バラバラの結果が出てきました。これを固定するには、このようなコードを書きます。
for i in range(10): np.random.seed(0) x = np.random.rand() print('x:', x)
x: 0.5488135039273248 x: 0.5488135039273248 x: 0.5488135039273248 x: 0.5488135039273248 x: 0.5488135039273248 x: 0.5488135039273248 x: 0.5488135039273248 x: 0.5488135039273248 x: 0.5488135039273248 x: 0.5488135039273248
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
ところでnumpyでは、`np.random.get_state()` で乱数生成器の状態が確認できます。
np.random.seed(0) state = np.random.get_state() print(state[0]) print('[', *state[1][:10], '...') print(*state[1][-10:], ']') np.random.seed(20040304) state = np.random.get_state() print(state[0]) print('[', *state[1][:10], '...') print(*state[1][-10:], ']')
MT19937 [ 20040304 3876245041 2868517820 934780921 2883411521 496831348 4198668490 1502140500 1427494545 3747657433 ... 744972032 1872723303 3654422950 1926579586 2599193113 3757568530 3621035041 2338180567 2885432439 2647019928 ]
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
逆に言えば、Numpyの乱数生成はグローバルな一つの状態に依存しています。このことは次のような弊害を生みます。 並列実行と実行順序、再現性 簡単なゲームを作ってみます。 関数`a`, `b`が乱数を生成するので、大きい数を返した方が勝ちというゲームです。
a = lambda : np.random.rand() b = lambda : np.random.rand() def battle(): if a() > b(): return 'A' else: return 'B' for i in range(10): print('winner is', battle(), '!')
winner is B ! winner is A ! winner is B ! winner is A ! winner is A ! winner is A ! winner is B ! winner is B ! winner is B ! winner is A !
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
また実行すれば、結果は変化します。
for i in range(10): print('winner is', battle(), '!')
winner is B ! winner is A ! winner is A ! winner is B ! winner is B ! winner is B ! winner is A ! winner is A ! winner is A ! winner is B !
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
ではこの結果の再現性を持たせるにはどうすればいいでしょうか。簡単な例はこうなります。
res1 = [] np.random.seed(0) for i in range(10): res1.append(battle()) # もう一回 res2 = [] np.random.seed(0) for i in range(10): res2.append(battle()) print('1 | 2') print('=====') for i in range(10): print(res1[i], '|', res2[i])
1 | 2 ===== B | B A | A B | B B | B A | A A | A B | B B | B B | B B | B
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
というわけで同じ結果が得られました。しかし、この結果には落とし穴があります。関数`battle`の動作をもう少し詳しく確認してみましょう。`a`と`b`が呼び出されるタイミングを確認してみます。
def a(): print('a is called!') return np.random.rand() def b(): print('b is called!') return np.random.rand() for i in range(5): battle() print('======')
a is called! b is called! ====== a is called! b is called! ====== a is called! b is called! ====== a is called! b is called! ====== a is called! b is called! ======
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
このように、aはbより常に先に呼び出されます。ここまでだと何の問題もないように見えますが、実際にはそうではありません。このコードを高速に動作させたい、つまり並列化を行う時にはどうなるでしょうか。関数`a`, `b`に依存関係はありませんから、これらを並列に動作させても問題ないように感じます。ですが、実際には `a`, `b`が返す関数は呼び出し順序に依存しています!従って、このままではせっかく`np.random.seed`をしても意味がなくなってしまいます。 JAXの乱数生成では、JAXにおける乱数生成を確認してみます。先ほどまでで述べたように、次のような条件を満たす乱数生成器を実装したいです。- 再現性があること- 並列化でき...
key = jax.random.PRNGKey(0) key
_____no_output_____
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
keyは単に二つの実数値からなるオブジェクトで、これを用いることによって、JAXでは乱数を生成します。
jax.random.normal(key)
_____no_output_____
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
そして、keyが同じであれば同じ値が生成されます。
print(key, jax.random.normal(key)) print(key, jax.random.normal(key)) print(key, jax.random.normal(key)) print(key, jax.random.normal(key)) print(key, jax.random.normal(key)) print(key, jax.random.normal(key)) print(key, jax.random.normal(key)) print(key, jax.random.normal(key)) print(key, jax.random.normal(key))
[0 0] -0.20584235 [0 0] -0.20584235 [0 0] -0.20584235 [0 0] -0.20584235 [0 0] -0.20584235 [0 0] -0.20584235 [0 0] -0.20584235 [0 0] -0.20584235 [0 0] -0.20584235
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
とはいえこれだけだとひとつの数字しか得ることができません。もっとたくさんの乱数が欲しくなった際には、`jax.random.split`を用います。
key1, key2 = jax.random.split(key) print(key, '->', key1, key2)
[0 0] -> [4146024105 967050713] [2718843009 1272950319]
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
`jax.random.split`によって、ひとつのkeyから2つのkeyが作り出されます。このkeyによって、また新しい乱数を生み出します。  ちなみに、この二つのkeyは等価ですが、慣例的に二つ目を新しい乱数生成につかい、一つ目はまた新しいkeyを使うために用いられるようです。(以下のコードを参照)
# 慣例的に二つ目をsub_keyとして新しい乱数生成に、一つ目をまた新しい乱数を作るために使用する(下のように書くことでsplit元の古いkeyも削除できる。keyが残ると誤って同じ乱数を作ってしまうので注意が必要。) key, sub_key = jax.random.split(key) key, subsub_key = jax.random.split(key)
_____no_output_____
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
また、同じkeyから分割されたkeyは、常に等しくなります。
def check_split(seed): key = jax.random.PRNGKey(seed) key, sub_key = jax.random.split(key) print(key, '->', key, sub_key) check_split(0) check_split(0) check_split(0) print('=============================================================================') check_split(2004) check_split(2004) check_split(2004)
[4146024105 967050713] -> [4146024105 967050713] [2718843009 1272950319] [4146024105 967050713] -> [4146024105 967050713] [2718843009 1272950319] [4146024105 967050713] -> [4146024105 967050713] [2718843009 1272950319] ============================================================================= [2965909967 23466...
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
また、一度に何個にもsplitできます。例えば1つのkeyから次のようにして10個のkeyを得ることができます。
# 何個にもsplitできる。 key = jax.random.PRNGKey(0) key, *sub_keys = jax.random.split(key, num=10) key sub_keys
_____no_output_____
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
sequential-equivalent Numpyではsequential-equivalentが保障されています。(適切な訳語がわからない)簡単にいうと、まとめてN個の乱数を取得することと、ひとつひとつ乱数を取得して連結したものは等価である、ということが保障されています。(以下のコードを見るとわかりやすいです)
# ひとつずつ np.random.seed(0) print(np.array([np.random.rand() for i in range(10)])) print('================================================') # まとめて np.random.seed(0) print(np.random.rand(10))
[0.5488135 0.71518937 0.60276338 0.54488318 0.4236548 0.64589411 0.43758721 0.891773 0.96366276 0.38344152] ================================================ [0.5488135 0.71518937 0.60276338 0.54488318 0.4236548 0.64589411 0.43758721 0.891773 0.96366276 0.38344152]
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
ところがJAXではその限りではありません。JAXで10個の配列を取得する方法としては、- keyを10個用意する- ひとつのkeyから10個作るということが考えられます。
# やり方 1: keyを10個用意 key = jax.random.PRNGKey(0) key, *sub_keys = jax.random.split(key, 11) print(np.array([jax.random.normal(sub_key) for sub_key in sub_keys])) # やり方 2: ひとつのkeyから10個作る key = jax.random.PRNGKey(0) print(np.array(jax.random.normal(key, shape=(10,))))
[-0.372111 0.2642311 -0.18252774 -0.7368198 -0.44030386 -0.15214427 -0.6713536 -0.59086424 0.73168874 0.56730247]
Apache-2.0
_notebooks/2021-11-14-jax-random.ipynb
abap34/my-website
Lumped Elements Circuits In this notebook, we construct various network from basic lumped elements (resistor, capacitor, inductor), with the 'classic' and the `Circuit` approach. Generally the `Circuit` approach is more verbose than the 'classic' way for building a circuit. However, as the circuit complexity increases...
import numpy as np # for np.allclose() to check that S-params are similar import skrf as rf rf.stylely()
_____no_output_____
BSD-3-Clause
doc/source/examples/circuit/Lumped Element Circuits.ipynb
nmaterise/scikit-rf
LC Series Circuit In this section we reproduce a simple equivalent model of a capacitor $C$, as illustrated by the figure below:
# reference LC circuit made in Designer LC_designer = rf.Network('designer_capacitor_30_80MHz_simple.s2p') # scikit-rf: manually connecting networks line = rf.media.DefinedGammaZ0(frequency=LC_designer.frequency, z0=50) LC_manual = line.inductor(24e-9) ** line.capacitor(70e-12) # scikit-rf: using Circuit builder port1...
_____no_output_____
BSD-3-Clause
doc/source/examples/circuit/Lumped Element Circuits.ipynb
nmaterise/scikit-rf
A More Advanced Equivalent Model In this section we reproduce an equivalent model of a capacitor $C$, as illustrated by the figure below:
# Reference results from ANSYS Designer LCC_designer = rf.Network('designer_capacitor_30_80MHz_adv.s2p') # scikit-rf: usual way, but this time this is more tedious to deal with connection and port number freq = LCC_designer.frequency line = rf.media.DefinedGammaZ0(frequency=freq, z0=50) elements1 = line.resistor(1e-2) ...
_____no_output_____
BSD-3-Clause
doc/source/examples/circuit/Lumped Element Circuits.ipynb
nmaterise/scikit-rf
Pass band filter Below we construct a pass-band filter, from an example given in [Microwaves101](https://www.microwaves101.com/encyclopedias/lumped-element-filter-calculator):
# Reference result calculated from Designer passband_designer = rf.Network('designer_bandpass_filter_450_550MHz.s2p') # scikit-rf: the filter by cascading all lumped-elements freq = passband_designer.frequency passband_manual = line.shunt_capacitor(25.406e-12) ** line.shunt_inductor(4.154e-9) ** \ li...
_____no_output_____
BSD-3-Clause
doc/source/examples/circuit/Lumped Element Circuits.ipynb
nmaterise/scikit-rf
Boosting: HyperparametersImport [`GradientBoostingClassifier`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html) and [`GradientBoostingRegressor`](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html) from `sklearn` and expl...
from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor print(GradientBoostingClassifier()) print(GradientBoostingRegressor())
GradientBoostingClassifier(criterion='friedman_mse', init=None, learning_rate=0.1, loss='deviance', max_depth=3, max_features=None, max_leaf_nodes=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_...
MIT
ml_algorithms/06_Boosting/06_03/End/06_03.ipynb
joejoeyjoseph/playground
Simulations: Dynamic learning with two learners, one oracle, and *heuristic evidence-weighting function* This notebook provides code to simulate 1D boundary learning in two agents learning from each other and from an "oracle" that always tells the truth. Each agent receives labels from the other agent (based on her cu...
get.pwt <- function(d, s=24, o=5, p=1){ #Computes the proportion of weight given to a source #based on the distance between learner and source boundary # #d = vector of distances between learner and source boundary for n sources #s = slope of HEW curve #o = offsetof HEW curve---distances less th...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Here is what the weighting function looks like with default parameters from experiment 2, where s = 24 and o = 5:
plot(0:150, get.pwt(0:150, s=24, o=5), type = "l", lwd = 3, pch = 16, ylab = "Source weight", xlab = "Source distance", ylim = c(0,1))
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Other possible weighting functions Here we define some other weighting functions to investigate group learning dynamics under different hypotheses about weighting. Equal weight to both sources This function can be used in place of get.pwt to simulate learning where both sources always get equal weight.
get.samewt <-function(d, s=NA, o=NA, p=NA){ #Returns a vector of 0.5 for each element of d #essentially always giving the same .5 weight to each source #All parameters ignored except d, only included to work with other code ############# out<-rep(.5, times=length(d)) out }
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Rectified linear weighting This function returns the weight of a source based on a linear decline of the source's distance from the learner's curent boundary, rectified at 0 and 1.
get.rlwt <- function(d, s=0.01, o=4.5,p=0){ #Rectified linear weighting function #d = vector of distances for sources to be weighted #o = offset; distances less than this get weight 1 #s = slope, rate at which weight diminishes with distance #p = proportion shrinkage from 1 and 0. #Returns vecto...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Here is what the rectified weighting function looks like. $o$ shifts it left/right, $s$ changes the slope.
plot(0:300, get.rlwt(0:300, s=.005, o=4.5, p=.0), type="l", ylim = c(0,1), ylab="Source weight", xlab="Source distance")
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Sigmoid This returns a source weight as the sigmoid of its distance from the learner's source. Like HEW and rectified linear, the function is bounded at ${0,1}$.
get.sigwt <- function(d, s=1, o=4.5,p=NA){ #Sigmoidal weighting function #d = vector of distances for sources to be weighted #o = offset, shifts sigmoid left/right #s = slope of sigmoid #p = for compatibility, not used #Returns vector of weights, one for each element in d ############# d...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Here is the plot:
plot(0:300, get.sigwt(0:300, s=.05, o=-3), type="l", ylim = c(0,1), ylab="Source weight", xlab="Source distance")
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Update the learner's current boundary according to evidence-weighting function. Note that different results obtain depending on whether you use the curve to compute the close source weight first or the far source weight first. Both lead to stable states where learners disagree, but Experiment 2 shows that a source wit...
update.bound <- function(i, s1, s2, r = 1, weightfirst ="c", closebig=T, f = get.pwt, fpars=c(24, 5, 1)){ ############## #Updates learner's current boundary accourding to nonlinear weighting function # #i=learner's initial boundary #s1, s2 = source 1 and 2 boundaries #r = rate of boundary change...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Simulate two learners and one static source This simulation involves two learners and one oracle, as reported in the main paper. The following function generates the sequence of belief-states occupied by each learner over the course of learning, given their starting states, the ground truth, one of the evidence-weight...
dynamic.sim <- function(l1, l2, static, nsteps=100, r=1, f = get.pwt, fpars=c(25,5,1)){ #Simulates two learners, learning from each other and from one static source #l1, l2, static = initial boundaries for learners 1 and 2 and static source #nsteps = number of learning steps to simulate #r = updating r...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Plot simulations for a grid of possible initial learning boundaries in the pair The code below runs the 2-learer simulation several times, with the two learners each beginning with a belief about the category boundary lying somewhere between 0 and 300. For each pair of initial beliefs, it computes how the beliefs cha...
gridpts <- 20 #Number of grid points in each dimension gtruth <- 150 #Location of ground-truth boundary niter <- 200 #Number of learning iterations uprate <- 0.1 #Proportional rate at which beliefs are updated on each iteration upfunc <- get.pwt #Function for computing source weights upfunc.pars <- c(24,5,1) #Paramete...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
As you can see, when learner beliefs begin in the upper left or lower right quadrants, they converge on the truth. These are cases where each learner begins on a different side of the ground truth--so the oracle and the other source are always pulling in the same direction. The two learners do not perfectly agree until...
firstbound <- 150 #Expected initial boundary newbound <- update.bound(150, 165, 50, fpars = c(25,4.5,1), weightfirst = "d") #new boundary after updating weight bshift <- newbound - firstbound #expected amount of shift dwt <- get.pwt(100) #expected weight given to far source print(round(c(firstbound, newbound, bshift, d...
[1] 150.00 141.14 -8.86 0.20
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
So given an initial boundary at 150 and sources at 165 and 50, the weighting curve from Experiment 2 predicts a final boundary around 141, with a total shift of about 9 units toward the distal source. The observed shift wa 14 +/- 7.5 units toward the far source, a confidence interval that includes this prediction. The ...
tmp <- rep(0, times = 100) #vector of zeros to contain predictions for one model #for(i1 in c(1:100)) tmp[i1] <- update.bound(100, 150-i1, 150+i1, fpars = c(24,5,1)) #Create empy plot plot(0,0, type = "n", xaxt = "n", xlab = "Source location", pch = 16, ylab = "Shift toward midpoint", ylim = c(-10,100), xlim = c...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
The result shows that quantitative predictions about the amount of shift vary quite a bit with the parameters of the trust weighting function, especially as the sources grow further toward the poles. But all parameterizations yield the same U-shape: when the sources are closer to the midpoint than is the learner's init...
plot(0,0,type = "n", xlim = c(0,150), ylim = c(0,1), xlab = "Distance of source", ylab = "Source weight") for(i1 in c(100:5)) lines(0:150, get.pwt(0:150, i1, 5, 1), col = rainbow(100)[i1-15], lwd = 5) lines(0:150, get.pwt(0:150, 24,5,1), col=1, lwd = 5)
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Effects of social connections amongst learning pairs In the above simulation of dynamic learners we considered pairs of learners with many different initial beliefs, each learning from the other and from a static oracle. What happens in a group of learners, where the two sources for any single learner are selected acc...
get.srcs <- function(l, s, p = "r", r=NA){ #Function to get two source distances for a learner based on a policy #l = learner's current boundary #s = current boundary for all sources #p = policy for choosing 2 sources: #r = random #s = two most similar #m = mixed ie most similar ...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Check to make sure the code works
get.srcs(5, 1:10, p="n", r=2)
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Functions to simulate a population The following code populates a matrix (out) in which columns indicate learners/sources and rows indicate learning epochs. For each epoch and learner, the code selects two sources according to some policy, as determined by the get.srcs function. The learner then updates her boundary a...
sim.pop <- function(l=c(1:10)*14, o=150, nsteps=300, rate=.1, policy="r", exrad=5){ init<-c(l, o) #Initial boundaries for learners and oracles nl <- length(l) #number of learners no <- length(o) #number of oracles ns <- length(init) #total number of sources out <- matrix(0, nsteps+1, ns) #Initialize...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
The following code plots the change in learner boundaries over time generated by the preceding code.
plot.popsim <- function(d, nl=10){ no <- dim(d)[2] - nl #Number of oracles nsteps <- dim(d)[1] -1 #Plot initial boundaries and frame: plot(rep(0, times = nl), d[1,1:nl], pch=16, col = 3, xlim = c(0,nsteps), ylim = c(0,300), ylab = "Boundary", xlab = "Time") #Add lines showing how each learn...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Below code runs simulation with two oracles at 150 and random initial beliefs sampled from 10-200. Change the policy parameter to one of the above to see the result of different source-selection policies.
n <- 10 #Number of simulated agents no <- 2 #Number of oracles gt <- 150 #ground truth provided by oracles ibspan <- 100 #Maximum span of initial learner belief distribution ibshift <- 140 #Shift from 0 of initial learner belief distribution p <- "m" #Policy for selecting sources, one of: #r = random s = two ...
_____no_output_____
MIT
Models/AgentBasedModels.ipynb
ttrogers/frigo-chen-rogers
Copyright 2019 The TensorFlow Hub Authors.Licensed under the Apache License, Version 2.0 (the "License");
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
_____no_output_____
Apache-2.0
site/ja/hub/tutorials/tf2_arbitrary_image_stylization.ipynb
phoenix-fork-tensorflow/docs-l10n
任意画風の高速画風変換 TensorFlow.org で表示 Google Colab で実行 GitHub でソースを表示 ノートブックをダウンロード TF Hub モデルを見る [magenta](https://github.com/tensorflow/magenta/tree/master/magenta/models/arbitrary_image_stylization) と次の発表のモデルコードに基づきます。[Exploring the structure of a real-time, arbitrary neural artistic stylization netw...
import functools import os from matplotlib import gridspec import matplotlib.pylab as plt import numpy as np import tensorflow as tf import tensorflow_hub as hub print("TF Version: ", tf.__version__) print("TF-Hub version: ", hub.__version__) print("Eager mode enabled: ", tf.executing_eagerly()) print("GPU available:...
_____no_output_____
Apache-2.0
site/ja/hub/tutorials/tf2_arbitrary_image_stylization.ipynb
phoenix-fork-tensorflow/docs-l10n
使用する画像を取得しましょう。
# @title Load example images { display-mode: "form" } content_image_url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Golden_Gate_Bridge_from_Battery_Spencer.jpg/640px-Golden_Gate_Bridge_from_Battery_Spencer.jpg' # @param {type:"string"} style_image_url = 'https://upload.wikimedia.org/wikipedia/common...
_____no_output_____
Apache-2.0
site/ja/hub/tutorials/tf2_arbitrary_image_stylization.ipynb
phoenix-fork-tensorflow/docs-l10n
TF-Hub モジュールをインポートする
# Load TF-Hub module. hub_handle = 'https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2' hub_module = hub.load(hub_handle)
_____no_output_____
Apache-2.0
site/ja/hub/tutorials/tf2_arbitrary_image_stylization.ipynb
phoenix-fork-tensorflow/docs-l10n
画風に使用する Hub モジュールのシグネチャは、次のとおりです。```outputs = hub_module(content_image, style_image) stylized_image = outputs[0]```上記の `content_image`、`style_image`、および `stylized_image` は、形状 `[batch_size, image_height, image_width, 3]` の 4-D テンソルです。現在の例では 1 つの画像のみを提供するためバッチの次元は 1 ですが、同じモジュールを使用して、同時に複数の画像を処理することができます。画像の入力と出力の値範囲は [0,...
# Stylize content image with given style image. # This is pretty fast within a few milliseconds on a GPU. outputs = hub_module(tf.constant(content_image), tf.constant(style_image)) stylized_image = outputs[0] # Visualize input images and the generated stylized image. show_n([content_image, style_image, stylized_image...
_____no_output_____
Apache-2.0
site/ja/hub/tutorials/tf2_arbitrary_image_stylization.ipynb
phoenix-fork-tensorflow/docs-l10n
複数の画像で試してみる
# @title To Run: Load more images { display-mode: "form" } content_urls = dict( sea_turtle='https://upload.wikimedia.org/wikipedia/commons/d/d7/Green_Sea_Turtle_grazing_seagrass.jpg', tuebingen='https://upload.wikimedia.org/wikipedia/commons/0/00/Tuebingen_Neckarfront.jpg', grace_hopper='https://storage.googleap...
_____no_output_____
Apache-2.0
site/ja/hub/tutorials/tf2_arbitrary_image_stylization.ipynb
phoenix-fork-tensorflow/docs-l10n
Data seems imbalance hence need to be balanced basis resampling techniques.
def date_q(date): """ Convert Date to Quarter when separated with / """ qdate = date.strip().split('/')[1:] qdate1 = qdate[0] if qdate1 in ['01','02','03']: return (str('Q1' + '-' + qdate[1])) if qdate1 in ['04','05','06']: return (str('Q2' + '-' + qdate[1])) if qdate1 i...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
EDA for merged file
campaign_data_DATE = campaign_data.copy() campaign_data_DATE.head() campaign_data_DATE['start_date_q'] = campaign_data_DATE['start_date'].map(lambda x: date_q(x)) campaign_data_DATE['end_date_q'] = campaign_data_DATE['end_date'].map(lambda x: date_q(x)) campaign_data_DATE.head() campaign_data_DATE.drop(['start_date',...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Lets have a look for Customer Id's in terms of using coupons most and least number of times.
''' Customer ids using coupons at least once with their demographic details ''' a = pd.DataFrame(train_data_merge_EDA[(train_data_merge_EDA['redemption_status']==1)]) b = pd.DataFrame(a.groupby('customer_id')['redemption_status'].sum()).reset_index() b.columns = ['customer_id','redeem_count'] b.sort_values(by='redeem_...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Hypothesis to test:1. Is age_range of 36 to 55 is mostly using coupons???2. Is Marital Status as Married are to redeem coupon???3. Is couple (family size of 2) are using coupons mostly???4. Is people not on rent are mostly using coupons???5. Is no_of_children irrelevant to redeem coupon???6. Is income bracket of 5 are ...
''' 1. Is age_range of 36 to 55 is mostly using coupons??? ''' d = pd.DataFrame(train_data_merge_EDA.groupby(['age_range'])['redemption_status'].sum()).reset_index() d.columns = ['age_range','tot_redeem'] d['percent'] = round(d['tot_redeem']/(d['tot_redeem'].sum())*100,2) display (d) %matplotlib notebook train_data_mer...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference : Out of the age demographic data available, age range of 36 to 55 are mostly redeeming coupons.
''' 2. Is Marital Status as Married are to redeem coupon??? ''' e = pd.DataFrame(train_data_merge_EDA.groupby(['marital_status'])['redemption_status'].sum()).reset_index() e.columns = ['marital_status','tot_redeem'] e['percent'] = round(e['tot_redeem']/(e['tot_redeem'].sum())*100,2) display (e) %matplotlib notebook tr...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference : As most of the customers haven't mentioned their marital status it is difficult to support that Married customer redeem more. But basis available data, we could see Married people are mostly using coupons to redeem. So at this stage I could think of giving more weightage to a person which has discloses mari...
''' 3. Is couple (family size of 2) are using coupons mostly??? ''' f = pd.DataFrame(train_data_merge_EDA.groupby(['family_size'])['redemption_status'].sum()).reset_index() f.columns = ['family_size','tot_redeem'] f['percent'] = round(f['tot_redeem']/(f['tot_redeem'].sum())*100,2) display (f) %matplotlib notebook trai...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference : Considering family size of 2 or more as a married couple (and transforming that ratio on to Marital Status data of Unspecified), then we could make an assumption over here that Married couple are mostly using the coupons to redeem.
''' 4. Is people not on rent are mostly using coupons??? ''' g = pd.DataFrame(train_data_merge_EDA.groupby(['rented'])['redemption_status'].sum()).reset_index() g.columns = ['rented','tot_redeem'] g['percent'] = round(g['tot_redeem']/(g['tot_redeem'].sum())*100,2) display (g) %matplotlib notebook train_data_merge_EDA....
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference : Maximum people have provided status as not rented so we could assume here more weightage to such customers as they have shown greater tendency towards redemption of the coupons.
''' 5. Is no_of_children irrelevant to redeem coupon??? ''' h = pd.DataFrame(train_data_merge_EDA.groupby(['no_of_children'])['redemption_status'].sum()).reset_index() h.columns = ['no_of_children','tot_redeem'] h['percent'] = round(h['tot_redeem']/(h['tot_redeem'].sum())*100,2) display (h) %matplotlib notebook train_...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference : Since most of the customers preferred not to disclose on number of children, at this point we can assume that this field has no significance with redemption of coupons.
''' 6. Is income bracket of 5 are using coupons mostly??? ''' j = pd.DataFrame(train_data_merge_EDA.groupby(['income_bracket'])['redemption_status'].sum()).reset_index() j.columns = ['income_bracket','tot_redeem'] j['percent'] = round(j['tot_redeem']/(j['tot_redeem'].sum())*100,2) display (j) %matplotlib notebook trai...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference : Assuming 5 as mid income group, customers in this group clearly shows behaviour towards redemption of coupon. Let's explore from Coupon's perspective, in terms of most redeemed and attributes associated with coupons
''' Coupon ids getting redeemed very often and attributes associated with it ''' k = pd.DataFrame(a.groupby('coupon_id')['redemption_status'].sum()).reset_index() k.columns = ['coupon_id','redeem_count'] k.sort_values(by='redeem_count',ascending=False,inplace=True) print ('Top 5 Coupon ids redeemed') display (k.head()...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Basis visualization for top 5 coupons redeemed, we could look for trend towards1. brand 56 is the top selling, let's verify if specific brand shows tendency towards coupon redemption???2. Verify brand type shows tendency towards coupon redemption???3. Verify category shows tendency towards coupon redemption???4. Verify...
''' 1. verify if specific brand shows tendency towards coupon redemption??? ''' m = pd.DataFrame(l1[(l1['brand']==56)|(l1['brand']==133)|(l1['brand']==1337)|(l1['brand']==544)|(l1['brand']==681)][['brand','brand_type','category']]) m.drop_duplicates(subset=['brand','brand_type','category'], keep='first', inplace=True) ...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference: For brand 56, there is a wide range of category available under the umbrella of Food products and displays greater tendency towards coupon redemption as well. Even rest other top 4 brands as well belong to general food product category under Grocery.
''' 2. Verify brand type shows tendency towards coupon redemption??? ''' m1 = pd.DataFrame(train_data_merge_EDA.groupby(['brand_type'])['redemption_status'].sum()).reset_index() m1.columns = ['brand_type','tot_redeem'] m1['percent'] = round(m1['tot_redeem']/(m1['tot_redeem'].sum())*100,2) display (m1) %matplotlib note...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference: Coupon redemption percentage seems high when associated with an Established brand type.
''' 3. Verify category shows tendency towards coupon redemption??? ''' m2 = pd.DataFrame(train_data_merge_EDA.groupby(['category'])['redemption_status'].sum()).reset_index() m2.columns = ['category','tot_redeem'] m2['percent'] = round(m2['tot_redeem']/(m2['tot_redeem'].sum())*100,2) m2.sort_values(by='tot_redeem',asce...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference : Grocery, Packaged Meat, Pharmaceutical, Natural Prodcut, Dairy & Juice and Meat are the category seems more associated with coupon redemption.
''' 4. Verify campaign type shows tendency towards coupon redemption??? ''' m3 = pd.DataFrame(train_data_merge_EDA.groupby(['campaign_type'])['redemption_status'].sum()).reset_index() m3.columns = ['campaign_type','tot_redeem'] m3['percent'] = round(m3['tot_redeem']/(m3['tot_redeem'].sum())*100,2) display (m3) %matplo...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference : Campaign type of X seems to have more associated with coupon redemption. Let's explore coupon redemption trend basis campaign start date and transaction date
n = pd.DataFrame(train_data_merge_EDA.groupby(['start_date_q','end_date_q'])['redemption_status'].sum()).reset_index() n.columns = ['start_date_q','end_date_q','tot_redeem'] n['percent'] = round(n['tot_redeem']/(n['tot_redeem'].sum())*100,2) n.sort_values(by='tot_redeem',ascending=False,inplace=True) display (n) %matpl...
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Inference : Campaign started between Q2-13 to Q3-13 foolwed by Q1-13 to Q2-13, seems experience more association towards coupon redemption trend. So we could assume over here campaign spanned across early quarters of year seem to more association with coupon redemption.
n1 = pd.DataFrame(train_data_merge_EDA.groupby(['tran_date_q'])['redemption_status'].sum()).reset_index() n1.columns = ['tran_date_q','tot_redeem'] n1['percent'] = round(n1['tot_redeem']/(n1['tot_redeem'].sum())*100,2) n1.sort_values(by='tot_redeem',ascending=False,inplace=True) display (n1)
_____no_output_____
MIT
Hackathon_ML Sample Problems/Amex Dataset/ML on Amex Dataset_EDA.ipynb
girishvankudre/hackathon_ml_sample
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
MIT
Informatics/Deep Learning/TensorFlow - deeplearning.ai/3. NLP/Course_3_Week_1_Lesson_1.ipynb
MarcosSalib/Cocktail_MOOC
Mask R-CNN - Train on Custom DatasetThis notebook shows how to train Mask R-CNN on your own dataset. You'd still need a GPU, though, because the network backbone is a Resnet101, which would be too slow to train on a CPU. On a GPU, you can start to get okay-ish results in a few minutes, and good results in less than an...
import os import sys import random import math import re import time import numpy as np import cv2 import matplotlib import matplotlib.pyplot as plt from config import Config import utils import model as modellib import visualize from model import log %matplotlib inline # Root directory of the project ROOT_DIR = os...
c:\users\yaroslav_strontsitsk\appdata\local\continuum\anaconda3\envs\maskrcnn\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import reg...
MIT
train_t_shirts.ipynb
lumstery/maskrcnn
Configurations
class ShapesConfig(Config): """Configuration for training on the toy shapes dataset. Derives from the base Config class and overrides values specific to the toy shapes dataset. """ # Give the configuration a recognizable name NAME = "clothes" # Train on 1 GPU and 8 images per GPU. We can pu...
Configurations: BACKBONE_SHAPES [[32 32] [16 16] [ 8 8] [ 4 4] [ 2 2]] BACKBONE_STRIDES [4, 8, 16, 32, 64] BATCH_SIZE 8 BBOX_STD_DEV [0.1 0.1 0.2 0.2] DETECTION_MAX_INSTANCES 100 DETECTION_MIN_CONFIDENCE 0.7 DETECTION_NMS_THRESHOLD ...
MIT
train_t_shirts.ipynb
lumstery/maskrcnn
Notebook Preferences
def get_ax(rows=1, cols=1, size=8): """Return a Matplotlib Axes array to be used in all visualizations in the notebook. Provide a central point to control graph sizes. Change the default size attribute to control the size of rendered images """ _, ax = plt.subplots(rows, cols, figsize=(...
_____no_output_____
MIT
train_t_shirts.ipynb
lumstery/maskrcnn
DatasetLoad a datasetExtend the Dataset class and add a method to load the shapes dataset, `load_images()`, and override the following methods:* load_image()* load_mask()* image_reference()
class ShapesDataset(utils.Dataset): def load_images(self, count, prefix): """Load the requested number of images. count: number of images to load. """ # Add classes self.add_class("clothes", 1, "t-shirt") # Add images for i in range(count): ...
_____no_output_____
MIT
train_t_shirts.ipynb
lumstery/maskrcnn
Ceate Model
# Create model in training mode model = modellib.MaskRCNN(mode="training", config=config, model_dir=MODEL_DIR) # Which weights to start with? init_with = "coco" # imagenet, coco, or last if init_with == "imagenet": model.load_weights(model.get_imagenet_weights(), by_name=True) elif init_...
_____no_output_____
MIT
train_t_shirts.ipynb
lumstery/maskrcnn