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
Load and prepare data
df = tl.load_data('./data/For Naomi.csv') #read in data from file df = tl.prepare_data(df,'消費日期','交易筆數') # select 'ds' and 'y' df1 = tl.group_by_date(df, 'M','2015-01-01','2020-08-31') # group by date df1.shape
_____no_output_____
MIT
ARIMA_monthly_rev_driver.ipynb
naomiyjchen/sales-forecast-time-series
Split data for testing and spliting
df_tr, df_tst = tl.train_test_split(df1,'2018-12-31','2019-12-31')
train shape (48, 3) test shape (12, 3)
MIT
ARIMA_monthly_rev_driver.ipynb
naomiyjchen/sales-forecast-time-series
Set parameters for ARIMA model
params = {'start_p': 1, 'max_p': 16, 'd':None, #'max_d':2, 'start_q': 1, 'max_q': 3, 'start_P': 1, 'max_P': 5, 'D': None, #'max_D': 1, #'start_Q': 1, #'max_Q': 5, ...
_____no_output_____
MIT
ARIMA_monthly_rev_driver.ipynb
naomiyjchen/sales-forecast-time-series
Model Training
Arima = arima.Arima_Impl(df_tr) Arima.find_best_orders( print_summary = False, **params) Arima.sm_train()
Performing stepwise search to minimize aic ARIMA(1,1,1)(1,0,1)[12] intercept : AIC=1076.860, Time=0.09 sec ARIMA(0,1,0)(0,0,0)[12] intercept : AIC=1085.102, Time=0.02 sec ARIMA(1,1,0)(1,0,0)[12] intercept : AIC=1074.386, Time=0.03 sec ARIMA(0,1,1)(0,0,1)[12] intercept : AIC=1075.752, Time=0.03 sec ARIMA(0,...
MIT
ARIMA_monthly_rev_driver.ipynb
naomiyjchen/sales-forecast-time-series
Predict the data and calculate MAPE
Arima.predict(12,'predicted_revenue') df_pred = tl.make_dataframe(Arima.predictions.values, df_tst) #prepare data for plotting print('MAPE: ', tl.mean_absolute_percentage_error(Arima.predictions, df_tst['y']))
MAPE: 0.059292462335839374
MIT
ARIMA_monthly_rev_driver.ipynb
naomiyjchen/sales-forecast-time-series
Prediction Evaluation
tl.plot_predict_and_actual(df_pred, df_tr) tl.plot_predict_vs_actual(df_pred, df_tst, 'M', '2018-12-31','2019-12-31')
(12, 2) (12, 3)
MIT
ARIMA_monthly_rev_driver.ipynb
naomiyjchen/sales-forecast-time-series
Biomass C content estimationBiomass is presented in the paper on a dry-weight basis. As part of the biomass calculation, we converted biomass in carbon-weight basis to dry-weight basis by multiplying by a conversion factor. Conversion factor calculation The conversion factor was calculated based on C content estimat...
# Upload C content data from Tang et al., units [mg/g] c_content = pd.read_excel("C_content_Tang.xlsx") c_content # Save parameters to unumpy arrays cleaf = unumpy.uarray(list(c_content['leaf']), list(c_content['leaf std'])) cstem = unumpy.uarray(list(c_content['stem'].fillna(0)), list(c_content['stem std'].fillna(0))...
_____no_output_____
MIT
C_content/biomass_C_content_estimation.ipynb
milo-lab/anthropogenic_mass
For each biome, we calculate the weighted average C content according to the mass fraction of each plant compartment. Information on plants compartmental mass composition was obtained from [Poorter et al.](https://nph.onlinelibrary.wiley.com/doi/full/10.1111/j.1469-8137.2011.03952.x).
# Upload compartmental mass composition, from Poorter et al., classified according to Tang et al. biomes compart_comp = pd.read_excel("compartment_comp_Poorter.xlsx") compart_comp # Save parameters to unumpy arrays fleaf = unumpy.uarray(list(compart_comp['leaf']), list(compart_comp['leaf std'])) fstem = unumpy.uarr...
_____no_output_____
MIT
C_content/biomass_C_content_estimation.ipynb
milo-lab/anthropogenic_mass
Next, we calculate the plants conversion factor, according to the mass fraction of each biome, which was calculated by the corresponding mass of each of the biome categories, derived from [Erb et al.](https://doi.org/10.1038/nature25138).
# Upload biomes biomass, from Erb et al., classified according to Tang et al. biomes mbiome = pd.read_excel('biome_mass_Erb.xlsx') mbiome # Save to unumpy array mbiomes = unumpy.uarray(list(mbiome['biomass [Gt C]']), list(mbiome['biomass std'])) # Calculate the overall conversion factor cplants_factor = 1000/np.su...
_____no_output_____
MIT
C_content/biomass_C_content_estimation.ipynb
milo-lab/anthropogenic_mass
In the overall carbon-weight to dry-weight conversion factor, we also accounted the C content of non-plant biomass, which was based on estimates from [Heldal et al.](https://aem.asm.org/content/50/5/1251.short) and [von Stockar](https://www.sciencedirect.com/science/article/pii/S0005272899000651). We used the current e...
# Upload non plant C content data, units [g/g] cnon_plant = pd.read_excel('C_content_non_plant.xlsx') cnon_plant # Calculate conversion factors cnon_plant_factor = ufloat(np.average(cnon_plant['C content']) ,np.std(cnon_plant['C content'], ddof = 1)) cfactor = (cplants_factor*0.9) +(0.1*(1/cnon_plant_factor)) cfacto...
Our best estimate of the C content conversion factor is: 2.25, with uncertainty (±1 standard deviation): 0.13
MIT
C_content/biomass_C_content_estimation.ipynb
milo-lab/anthropogenic_mass
TPU or GPU detection
# Detect hardware, return appropriate distribution strategy try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case. print('Running on TPU ', tpu.master()) except ValueError: tpu = Non...
Running on TPU grpc://10.0.0.2:8470 REPLICAS: 8
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Competition data accessTPUs read data directly from Google Cloud Storage (GCS). This Kaggle utility will copy the dataset to a GCS bucket co-located with the TPU. If you have multiple datasets attached to the notebook, you can pass the name of a specific dataset to the get_gcs_path function. The name of the dataset is...
GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with "!gsutil ls $GCS_DS_PATH"
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Configuration
IMAGE_SIZE = [512, 512] # at this size, a GPU will run out of memory. Use the TPU BATCH_SIZE = 16 * strategy.num_replicas_in_sync SEED = 42 FOLDS = 3 GCS_PATH_SELECT = { # available image sizes 192: GCS_DS_PATH + '/tfrecords-jpeg-192x192', 224: GCS_DS_PATH + '/tfrecords-jpeg-224x224', 331: GCS_DS_PATH + '/...
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Visualization utilitiesdata -> pixels, nothing of much interest for the machine learning practitioner in this section.
# numpy and matplotlib defaults np.set_printoptions(threshold=15, linewidth=80) def batch_to_numpy_images_and_labels(data): images, labels = data numpy_images = images.numpy() numpy_labels = labels.numpy() if numpy_labels.dtype == object: # binary string in this case, these are image ID strings ...
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Datasets
def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32) / 255.0 # convert image to floats in [0, 1] range image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU return image def read_labeled_tfrecord(example): LABELE...
Dataset: 10976 training images, 5488 validation images, 7382 unlabeled test images
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Enhanced Data Augmentation
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): # returns 3x3 transformmatrix which transforms indicies # CONVERT DEGREES TO RADIANS rotation = math.pi * rotation / 180. shear = math.pi * shear / 180. # ROTATION MATRIX c1 = tf.math.cos(rotation) ...
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Model Selector
#selecting which models will be trained and used in inference. Options: Ensamble, Model No. MODEL_SELECT = 'Model1' EPOCHS = 15
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Model 1DenseNet201
def get_model1(): with strategy.scope(): dn201 = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3]) dn201.trainable = True # Full Training model1 = tf.keras.Sequential([ dn201, tf.keras.layers.GlobalAveragePooling2D...
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Model 2Efficient Net B7
def get_model2(): with strategy.scope(): enb7 = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3]) enb7.trainable = True # Full Training model2 = tf.keras.Sequential([ enb7, tf.keras.layers.GlobalAveragePooling2D(), ...
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Callbacks
LR_START = 0.0001 LR_MAX = 0.00005 * strategy.num_replicas_in_sync LR_MIN = 0.00001 LR_RAMPUP_EPOCHS = 3 LR_SUSTAIN_EPOCHS = 0 LR_EXP_DECAY = .8 def lrfn(epoch): if epoch < LR_RAMPUP_EPOCHS: lr = np.random.random_sample() * LR_START # Using random learning rate for initial epochs. elif epoch < LR_RAMPU...
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Custom Training Fuction
def train_cross_validate(folds = 5): histories = [] models = [] kfold = KFold(folds, shuffle = True, random_state = SEED) for f, (trn_ind, val_ind) in enumerate(kfold.split(TRAINING_FILENAMES)): print(); print('#'*25) print('### FOLD',f+1) print('#'*25) train_dataset = lo...
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Training
histories, models = train_and_predict(folds = FOLDS) for h in range(len(histories)): display_training_curves(histories[h].history['loss'], histories[h].history['val_loss'], 'loss', 211) display_training_curves(histories[h].history['sparse_categorical_accuracy'], histories[h].history['val_sparse_categorical_accu...
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
Confusion matrix
all_labels = []; all_prob = []; all_pred = [] kfold = KFold(FOLDS, shuffle = True, random_state = SEED) for j, (trn_ind, val_ind) in enumerate( kfold.split(TRAINING_FILENAMES) ): print('Inferring fold',j+1,'validation images...') VAL_FILES = list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[val_...
_____no_output_____
Apache-2.0
flower-classification-ensemble.ipynb
Sebastian-Koenig/Flower-Classification-with-TPUs
A Simple Pair Trading Strategy**_Please go through the "building strategies" notebook before looking at this notebook._**Let's build a aimple pair trading strategy to show how you can trade multiple symbols in a strategy. We will trade 2 stocks, Coca-Cola (KO) and Pepsi (PEP)1. We will buy KO and sell PEP when the p...
import math import datetime import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.stats import os from types import SimpleNamespace import pyqstrat as pq pq.set_defaults() # Set some display defaults to make dataframes and plots easier to look at try: ko_file = os.path.dirname(os.pa...
_____no_output_____
BSD-3-Clause
pyqstrat/notebooks/pair_trading_strategy.ipynb
alexanu/pyqstrat
Lets compute the ratio of the two prices and add it to the market data. Since the two price series have the exact same timestamps, we can simply divide the two close price series
ratio = ko_prices.c / pep_prices.c
_____no_output_____
BSD-3-Clause
pyqstrat/notebooks/pair_trading_strategy.ipynb
alexanu/pyqstrat
Next, lets create an indicator for the zscore, and plot it.
def zscore_indicator(symbol, timestamps, indicators, strategy_context): # simple moving average ratio = indicators.ratio r = pd.Series(ratio).rolling(window = 130) mean = r.mean() std = r.std(ddof = 0) zscore = (ratio - mean) / std zscore = np.nan_to_num(zscore) return zscore ko_zscore = zs...
_____no_output_____
BSD-3-Clause
pyqstrat/notebooks/pair_trading_strategy.ipynb
alexanu/pyqstrat
Now lets create the signal that will tell us to get in when the zscore is +/-1 and get out when its less than +/- 0.5. We use a signal value of 2 to figure out when to go long, and -2 to figure out when to go short. A value of 1 means get out of a long position, and -1 means get out of a short position. We also plot...
def pair_strategy_signal(contract_group, timestamps, indicators, parent_signals, strategy_context): zscore = indicators.zscore signal = np.where(zscore > 1, 2, 0) signal = np.where(zscore < -1, -2, signal) signal = np.where((zscore > 0.5) & (zscore < 1), 1, signal) signal = np.where((zscore < -0.5) ...
_____no_output_____
BSD-3-Clause
pyqstrat/notebooks/pair_trading_strategy.ipynb
alexanu/pyqstrat
Finally we create the trading rule and market simulator functions
def pair_trading_rule(contract_group, i, timestamps, indicators, signal, account, strategy_context): timestamp = timestamps[i] curr_pos = account.position(contract_group, timestamp) signal_value = signal[i] risk_percent = 0.1 orders = [] symbol = contract_group.name contract =...
_____no_output_____
BSD-3-Clause
pyqstrat/notebooks/pair_trading_strategy.ipynb
alexanu/pyqstrat
Lets run the strategy, plot the results and look at the returns
def get_price(contract, timestamps, i, strategy_context): if contract.symbol == 'KO': return strategy_context.ko_price[i] elif contract.symbol == 'PEP': return strategy_context.pep_price[i] raise Exception(f'Unknown symbol: {symbol}') strategy_context = SimpleNamespace(ko_price = ko_prices....
_____no_output_____
BSD-3-Clause
pyqstrat/notebooks/pair_trading_strategy.ipynb
alexanu/pyqstrat
Introduction **Code not tidied, but should work OK** Neural Network
import numpy as np import matplotlib.pyplot as plt import pdb
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
**Sigmoid**
def sigmoid(x): return 1/(1+np.exp(-x)) def sigmoid_der(x): return sigmoid(x) * (1 - sigmoid(x))
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
**Hyperbolic Tangent**
def tanh(x): return np.tanh(x) def tanh_der(x): return 1.0 - np.tanh(x)**2
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
**Mean Squared Error**
def mse(x, y, Wxh, Whh, Who): y_hat = forward(x, Wxh, Whh, Who) return 0.5 * np.mean((y-y_hat)**2)
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
**Forward Pass**
def forward(x, Wxh, Whh, Who): assert x.ndim==3 and x.shape[1:]==(4, 3) x_t0 = x[:,0,:] x_t1 = x[:,1,:] x_t2 = x[:,2,:] x_t3 = x[:,3,:] s_init = np.zeros([len(x), len(Whh)]) # [n_batch, n_hid] z_t0 = s_init @ Whh + x_t0 @ Wxh s_t0 = tanh(z_t0) z_t1 = s_t0 @ Whh + x_t1...
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
**Backpropagation**
def backward(x, y, Wxh, Whh, Who): assert x.ndim==3 and x.shape[1:]==(4, 3) assert y.ndim==2 and y.shape[1:]==(1,) assert len(x) == len(y) # Forward x_t0 = x[:,0,:] x_t1 = x[:,1,:] x_t2 = x[:,2,:] x_t3 = x[:,3,:] s_init = np.zeros([len(x), len(Whh)]) # [n_batch, n_hid...
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
**Train Loop**
def train_rnn(x, y, nb_epochs, learning_rate, Wxh, Whh, Who): losses = [] for e in range(nb_epochs): y_hat, dWxh, dWhh, dWho = backward(x, y, Wxh, Whh, Who) Wxh += -learning_rate * dWxh Whh += -learning_rate * dWhh Who += -learning_rate * dWho ...
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
Example: Count Letter 'a' **Create Dataset**
# Encoding: 'a'=[0,0,1] 'b'=[0,1,0] 'c'=[1,0,0] # < ----- 4x time steps ----- > x_train = np.array([ [ [0, 1, 0], [0, 1, 0], [1, 0, 0], [0, 1, 0] ], # 'bbcb' [ [1, 0, 0], [0, 1, 0], [1, 0, 0], [0, 1, 0] ], # 'cbcb' ^ [ [0,...
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
Train
np.random.seed(0) W_xh = 0.1 * np.random.randn(3, 2) # Wxh.shape: [n_in, n_hid] W_hh = 0.1 * np.random.randn(2, 2) # Whh.shape: [n_hid, n_hid] W_ho = 0.1 * np.random.randn(2, 1) # Who.shape: [n_hid, n_out] losses = train_rnn(x_train, y_train, 3000, 0.1, W_xh, W_hh, W_ho) y_hat = forward(x_train, W_xh, W_hh, W_ho).ro...
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
Gradient Check
def numerical_gradient(x, y, Wxh, Whh, Who): dWxh = np.zeros_like(Wxh) dWhh = np.zeros_like(Whh) dWho = np.zeros_like(Who) eps = 1e-4 for r in range(len(Wxh)): for c in range(Wxh.shape[1]): Wxh_pls = Wxh.copy() Wxh_min = Wxh.copy() Wxh_pl...
_____no_output_____
MIT
NumpyNN/1010_Char_RNN_Unfolded.ipynb
marcinbogdanski/ai-sketchpad
Operations and Expressions Boolean Operator
x=1 y=2 print(x>y) print(y) print(10>11) print(10==10) #Using bool() function print(bool("Hello")) print(bool(15)) print(bool("false")) print(bool(0))
True True True False
Apache-2.0
Operations_and_Expressions.ipynb
LouisFeraer/CPEN21A-ECE-2-1
Function can return Boolean
def myFunction():return True print(myFunction())
True
Apache-2.0
Operations_and_Expressions.ipynb
LouisFeraer/CPEN21A-ECE-2-1
You try
print (10>9) a=6 b=7 print(a==b) print(a!=a)
True False False
Apache-2.0
Operations_and_Expressions.ipynb
LouisFeraer/CPEN21A-ECE-2-1
Arithmetic operators
print(10+5) print(10-5) print(10*5) print(10/5) print(10%5) #modulo division, reminder print(10//5) #floor division print(10//3) #floor division
15 5 50 2.0 0 2 3
Apache-2.0
Operations_and_Expressions.ipynb
LouisFeraer/CPEN21A-ECE-2-1
Bitwise Operators
a=60 #0011 1100 b=13 #0000 1101 print(a&b) print(a|b) print(a^b) print(~a) print(a<<1) #0011 1100 print(a<<2) #0011 1100 print(b>>1) #0000 1101 print(b>>2)
12 61 49 -61 120 240 6 3
Apache-2.0
Operations_and_Expressions.ipynb
LouisFeraer/CPEN21A-ECE-2-1
Python Assignment Operators
a++3 #Same Asa=a+3 #Same Asa=60, a=63 print(a)
60
Apache-2.0
Operations_and_Expressions.ipynb
LouisFeraer/CPEN21A-ECE-2-1
Logical Operator
#and logical operator a=True b=False print(a and b) print(a or b) print(not(a or b)) print(a is b) a is not b
False
Apache-2.0
Operations_and_Expressions.ipynb
LouisFeraer/CPEN21A-ECE-2-1
Basic plotting
import pandas as pd oo = pd.read_csv('data/olympics.csv',skiprows=4) oo.head() import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
Plot types What were the different sports in the first olympics? Plot them using different graphs.
fo = oo[oo.Edition == 1896] fo.head()
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
Line plot
fo.Sport.value_counts().plot(kind='line');
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
Bar plot
fo.Sport.value_counts().plot(kind='bar');
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
Horizontal bar plot
fo.Sport.value_counts().plot(kind='barh');
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
Pie chart
fo.Sport.value_counts().plot(kind='pie');
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
Plot colors
fo.Sport.value_counts().plot(color='plum') fo.Sport.value_counts().plot(kind='bar',color='maroon');
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
figsize()
fo.Sport.value_counts().plot(figsize=(10,3));
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
Colormaps
fo.Sport.value_counts().plot(kind='pie',colormap='Paired'); fo.Sport.value_counts().plot(kind='bar',color='red');
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
Seaborn basic plotting
import seaborn as sns
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
How many medals have been won by men and women in the history of the Olympics. How many gold, silver and bronze medals were won for each gender?
sns.countplot(x='Medal',data=oo, hue='Gender'); mw = oo[(oo.Edition == 2008) & (oo.NOC == "CHN")] mw.Gender.value_counts().plot(kind="bar") sns.countplot(data=oo, x="Gender", palette='bwr') sns.countplot(x='Medal', data=mw, hue='Gender', palette='bwr', order=['Gold', 'Silver', 'Bronze'])
_____no_output_____
BSD-3-Clause
basics/first/Ch05 Basic plotting.ipynb
febin-varghese/Data-Science
JWST Pipeline Validation Notebook: calwebb_detector1, dark_current unit tests **Instruments Affected**: NIRCam, NIRISS, NIRSpec, MIRI, FGS Table of Contents [Introduction](intro) [JWST Unit Tests](unit) [Defining Terms](terms) [Test Description](description) [Data Description](data_descr) [Imports](imports) [Conv...
import tempfile import pytest import jwst from IPython.display import IFrame
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/dark_current/jwst_dark_current_unit_tests.ipynb
york-stsci/jwst_validation_notebooks
Convenience FunctionsHere we define any convenience functions to help with running the unit tests. [Top of Page](title_ID)
def display_report(fname): '''Convenience function to display pytest report.''' return IFrame(src=fname, width=700, height=600)
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/dark_current/jwst_dark_current_unit_tests.ipynb
york-stsci/jwst_validation_notebooks
Perform TestsBelow we run the unit tests for the Dark Current step. [Top of Page](title_ID)
with tempfile.TemporaryDirectory() as tmpdir: !pytest jwst/dark_current -v --ignore=jwst/associations --ignore=jwst/datamodels --ignore=jwst/stpipe --ignore=jwst/regtest --html=tmpdir/unit_report.html --self-contained-html report = display_report('tmpdir/unit_report.html') report
_____no_output_____
BSD-3-Clause
jwst_validation_notebooks/dark_current/jwst_dark_current_unit_tests.ipynb
york-stsci/jwst_validation_notebooks
Transform points from pitch to texture and vice-versa Matrix P - ProjectionThe P matrix is a 3x4 matrix that given a 3D point in the world reference frame, it is projected into the 2D image in **texture coordinate** reference frame, i.e:\begin{align}\mathbf{pt_{world}} = (x, y, z, 1) \\\mathbf{pt_{pitch}} = (a, b, c) ...
# import what we need import numpy as np import math def rodrigues(r): ''' Rodrigues formula :param r: 1x3 array of rotations about x, y, and z :return: the 3x3 rotation matrix ''' def S(n): Sn = np.array([ [0.0, -n[2], n[1]], [n[2], 0.0, -n[0]], [-n[1...
_____no_output_____
MIT
MatrixP.ipynb
marceljanerfont/MatrixP
Projection matrix P from an individual cameraThe funciton `camera_full_projection_matrix` is only valid for individual cameras. How to get camera parameters: *aspect_ratio, zoom, skew, pan, tilt, roll, Tx, Ty, Tz* You can find camera parameters **`aspect_ratio, zoom, skew, pan, tilt, roll, Tx, Ty, Tz`** in `C:\Automa...
def camera_full_projection_matrix(aspect_ratio, zoom, skew, pan, tilt, roll, Tx, Ty, Tz): """ Creates projection matrix P from camera model parameters :param aspect_ratio: camera aspect ratio = image width / image height :param zoom: camera focal :param skew: :param pan: :param tilt: :pa...
_____no_output_____
MIT
MatrixP.ipynb
marceljanerfont/MatrixP
Individual camera matrix P Testing
# test # test matrixP_from_camera_model camera_model = { "aspect_ratio": 5.333333333, "zoom": 0.45361389, "skew": 0.0, "pan": -2.0953152, "tilt": 108.76381, "roll": 0.0, "Tx": 0.48063888, "Ty": -0.30635475, "Tz": 87.349004} P = camera_full_projection_matrix(**camera_model) P_expected...
[[ 0.85549003 0.91779104 -0.38178799 78.5656145 ] [ -0.21537938 -0.42563356 -2.16061687 29.73643812] [ -0.45199561 0.82127568 -0.34814685 74.498503 ]] world: [-10. 3. 0.] texture: [ 0.89300498 0.37570535] pitch: [-10. 3.] texture: [ 0.89300498 0.37570535] texture: [ 0.89300498 0.37570535] pit...
MIT
MatrixP.ipynb
marceljanerfont/MatrixP
Matrix P for Panorama How to get Panorama camera parameters: *src_width, src_height, zoom, skew, pan, tilt, roll, Tx, Ty, Tz* You can find camera parameters **`zoom, skew, pan, tilt, roll, Tx, Ty, Tz`** in `C:\AutomaticTV\data\virtual_cameras\{id}.xml`. In XML `` tag, for instance:``` 5760 1080 0.45...
def camera_full_projection_matrix_with_crop(aspect_ratio, zoom, skew, pan, tilt, roll, Tx, Ty, Tz, crop_tx, crop_ty, crop_zoom): """ Creates projection matrix P from camera model parameters :param aspect_ratio: camera aspect ratio = dst_width / dst_height :param zoom: camera focal :param skew: :...
_____no_output_____
MIT
MatrixP.ipynb
marceljanerfont/MatrixP
Panorama matrix P Testing
camera_model = { "aspect_ratio": 3.5555555820465088, "zoom": 0.45361389, "skew": 0.0, "pan": -2.0953152, "tilt": 108.76381, "roll": 10.0, "Tx": 0.48063888, "Ty": -0.30635475, "Tz": 87.349004} crop_params = { "src_width": 5760, "src_height": 1080, "offset_x": 0.0, "of...
crop: 0.0, 0.0, 1.5 [[ 6.50936689e-01 5.35590234e-01 -4.89595755e-02 4.40015387e+01] [ 4.30532613e-01 -2.77397706e-01 -2.41672906e+00 4.29333459e+01] [ -3.46188241e-02 9.46219547e-01 -3.21667695e-01 8.73490040e+01]]
MIT
MatrixP.ipynb
marceljanerfont/MatrixP
House Price Prediction With TensorFlow[![open_in_colab][colab_badge]][colab_notebook_link][![open_in_binder][binder_badge]][binder_notebook_link][colab_badge]: https://colab.research.google.com/assets/colab-badge.svg[colab_notebook_link]: https://colab.research.google.com/github/UnfoldedInc/examples/blob/master/notebo...
# If in Colab, install this notebook's required dependencies import sys if "google.colab" in sys.modules: !pip install 'unfolded.map_sdk>=0.6.3' pandas numpy scikit-learn scipy seaborn matplotlib tensorflow
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Imports If you're running this notebook on Binder, you may see a notification like the following when running the next cell.```Could not load dynamic library 'libcudart.so.11.0'; dlerror: libcudart.so.11.0: cannot open shared object file: No such file or directoryIgnore above cudart dlerror if you do not have a GPU se...
from uuid import uuid4 import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.cluster import KMeans from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from tensorflow.keras import Sequential from tensorflow.keras.lay...
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Data Loading For this example we'll use data from Kaggle's [California Housing Prices](https://www.kaggle.com/camnugent/california-housing-prices) dataset under the CC0 license. This dataset contains information about the housing in each census area in California, as of the 1990 census.
dataset_url = "https://raw.githubusercontent.com/UnfoldedInc/examples/master/notebooks/data/housing.csv" housing = pd.read_csv(dataset_url) housing.head()
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Feature Engineering First, let's take a look at the input data and try to visualize different aspects of them in a map. Population Clustering In the next cell we'll create a map that clusters rows of the dataset according to population. Note that since the clustering happens within Unfolded Studio, the clusters are r...
population_in_CA = UnfoldedMap() population_in_CA # Create a persistent dataset ID that we can reference in both add_dataset and add_layer dataset_id = uuid4() population_in_CA.add_dataset( {"uuid": dataset_id, "label": "Population_in_CA", "data": housing}, auto_create_layers=False, ) population_in_CA.add_lay...
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Distances from housing areas to largest cities Next, we want to explore where the housing areas in our dataset are located in comparison to the largest cities in California. For example purposes, we'll take the five largest cities in California and compare our input data against these locations.
# Longitude-latitude pairs for large cities cities = { "Los Angeles": (-118.244, 34.052), "San Diego": (-117.165, 32.716), "San Jose": (-121.895, 37.339), "San Francisco": (-122.419, 37.775), "Fresno": (-119.772, 36.748), }
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Next we need to find the closest city for each row in our data sample. First we'll define a couple functions to help compute the distance between cities and the city closest to a specific point. Then we'll apply these functions on our data.
def distance(lng1, lat1, lng2, lat2): """Vectorized Haversine formula Computes distances between two sets of points. From: https://stackoverflow.com/a/51722117 """ # approximate radius of earth in km R = 6371.009 lat1 = lat1*np.pi/180.0 lng1 = np.deg2rad(lng1) lat2 = np.deg2rad(la...
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Then use the `closest_city` function on our data to create three new columns:
housing[['closest_city_dist', 'closest_city_lng', 'closest_city_lat']] = closest_city( housing['longitude'], housing['latitude'], cities )
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
The map created in the next cell uses the new columns we computed above in relation to the largest cities in California:
distance_to_big_cities = UnfoldedMap() distance_to_big_cities dist_data_id = uuid4() distance_to_big_cities.add_dataset( { "uuid": dist_data_id, "label": "Distance to closest big city", "data": housing, }, auto_create_layers=False, ) distance_to_big_cities.add_layer( { ...
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Data Preprocessing In this next section, we want to prepare our dataset to be used for training a TensorFlow model. First, we'll drop rows with null values, since they're quite rare in the dataset.
pct_null_rows = housing.isnull().any(axis=1).sum() / len(housing) * 100 print(f'{pct_null_rows:.1f}% of rows have null values') housing = housing.dropna()
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
In the model we're training, we want to predict the median house value of an area. Thus we split the columns from our dataset `housing` into a dataset `y` with the column `median_house_value` and a dataset `X` with all other columns.
predicted_column = ['median_house_value'] other_columns = housing.columns.difference(predicted_column) X = housing.loc[:, other_columns] y = housing.loc[:, predicted_column]
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Most of the columns in `X` are numeric, but one is not. `ocean_proximity` is of type `object`, which here is a string.
X.dtypes
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Looking closer, we see that `ocean_proximity` is a categorical string with only five values.
X['ocean_proximity'].value_counts()
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
In order to use this column in our numeric model, we call [`pandas.get_dummies`](https://pandas.pydata.org/docs/reference/api/pandas.get_dummies.html) to create five new boolean columns. Each of these columns contains a `1` if the value of `ocean_proximity` is equal to the value that's now the column name.
X = pd.get_dummies( data=X, columns=["ocean_proximity"], prefix=["ocean_proximity"], drop_first=True )
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Data Splitting In line with standard machine learning practice, we split our dataset into training, validation and test sets. We first take out 20% of our full dataset to use for testing the model after training. Then of the remaining 80%, we take out 75% to use for training the model and 25% to use for validation.
# dividing training data into test, validation and train X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) X_train, X_val, y_train, y_val = train_test_split( X_train, y_train, test_size=0.25, random_state=1 ) # We save a copy of our test data to use after model prediction st...
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Feature Scaling We use standard scaling with mean and standard deviation from our training dataset to avoid data leakage.
# feature standardization scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_val = scaler.transform(X_val) X_test = scaler.transform(X_test)
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Price Prediction Model Next we specify the parameters for the TensorFlow model:
# We use a Sequential model from Keras # https://keras.io/api/models/sequential/ model = Sequential() # Each column from X is an input feature into our model. number_of_features = len(X.columns) # input Layer model.add(Dense(number_of_features, activation="relu", input_dim=number_of_features)) # hidden Layer model.a...
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Training Next we begin model training. Model training can take a long time; the higher the number of epochs, the better the model will be fit, but the longer training will take. Here we default to only 10 epochs because the focus of this notebook is integration with Unfolded Studio, not the machine learning itself.
EPOCHS = 10 # Or uncomment the following line if you're happy to wait longer for a better model fit. # EPOCHS = 70 history = model.fit( X_train, y_train.to_numpy(), batch_size=10, epochs=EPOCHS, verbose=1, validation_data=(X_val, y_val), )
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Evaluation Next we want to find out how well the model was trained:
# summarize history for loss loss_train = history.history["loss"] loss_val = history.history["val_loss"] epochs = range(1, EPOCHS + 1) plt.figure(figsize=(10, 8)) plt.plot(epochs, loss_train, "g", label="Training loss") plt.plot(epochs, loss_val, "b", label="Validation loss") plt.title("Training and Validation loss") p...
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
In the above chart we can see that the training loss and validation loss are quite close to each other. Now we can use our trained model to predict home prices on the _test_ data, which was not used in the training process.
y_pred = model.predict(X_test)
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
We can see that loss function value on the test data is similar to the loss value on the training data
model.evaluate(X_test, y_test)
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Prediction Let's now visualize our housing price predictions using Unfolded Studio. Here we create a dataframe with predicted values obtained from the model.
predict_data = start_values.loc[:, ['longitude', 'latitude']] predict_data["price"] = y_pred
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Visualization The map we create in the next cell depicts the prices we've predicted for houses in each census area in California.
housing_predict_prices = UnfoldedMap() housing_predict_prices price_data_id = uuid4() housing_predict_prices.add_dataset( { "uuid": price_data_id, "label": "Predict housing prices in CA", "data": predict_data, }, auto_create_layers=False, ) housing_predict_prices.add_layer( { ...
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Clustering Model We'll now cluster the predicted data by price levels using the KMeans algorithm.
k = 5 km = KMeans(n_clusters=k, init="k-means++") X = predict_data.loc[:, ["latitude", "longitude", "price"]] # Run clustering and add to prediction dataset dataset predict_data["cluster"] = km.fit_predict(X)
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Visualization Let's show the price clusters in a chart
fig, ax = plt.subplots() sns.scatterplot( x="latitude", y="longitude", data=predict_data, palette=sns.color_palette("bright", k), hue="cluster", size_order=[1, 0], ax=ax, ).set_title(f"Clustering (k={k})")
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
The next map shows the same clusters in a geographic context. Here we can see that house prices are highest for areas close to the largest cities.
unfolded_map_prices = UnfoldedMap() unfolded_map_prices prices_dataset_id = uuid4() unfolded_map_prices.add_dataset( {"uuid": prices_dataset_id, "label": "Prices", "data": predict_data}, auto_create_layers=False, ) unfolded_map_prices.add_layer( { "id": "prices_CA", "type": "point", ...
_____no_output_____
MIT
notebooks/09 - Tensorflow_prediction.ipynb
UnfoldedInc/examples
Lambda School Data Science*Unit 2, Sprint 2, Module 3*--- Before you start: Today is the day you should submit the dataset for your Unit 2 Build Week project. You can review the guidelines and make your submission in the Build Week course for your cohort on Canvas.
%%capture import sys # If you're on Colab: if 'google.colab' in sys.modules: DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Kaggle-Challenge/main/data/' !pip install category_encoders==2.* !pip install pandas-profiling==2.* # If you're working locally: else: DATA_PATH = '../data...
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge
Module Project: Hyperparameter TuningThis sprint, the module projects will focus on creating and improving a model for the Tanazania Water Pump dataset. Your goal is to create a model to predict whether a water pump is functional, non-functional, or needs repair.Dataset source: [DrivenData.org](https://www.drivendata....
def wrangle(fm_path, tv_path=None): if tv_path: df = pd.merge(pd.read_csv(fm_path, na_values=[0, -2.000000e-08]), pd.read_csv(tv_path)).set_index('id') else: df = pd.read_csv(fm_path, na_values=[0, -2.000000e-08],...
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge
**Task 1:** Using the above `wrangle` function to read `train_features.csv` and `train_labels.csv` into the DataFrame `df`, and `test_features.csv` into the DataFrame `X_test`.
df = ... X_test = ...
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge
II. Split Data**Task 2:** Split your DataFrame `df` into a feature matrix `X` and the target vector `y`. You want to predict `'status_group'`.**Note:** You won't need to do a train-test split because you'll use cross-validation instead.
X = ... y = ...
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge
III. Establish Baseline**Task 3:** Since this is a **classification** problem, you should establish a baseline accuracy score. Figure out what is the majority class in `y_train` and what percentage of your training observations it represents.
baseline_acc = ... print('Baseline Accuracy Score:', baseline_acc)
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge
IV. Build Models**Task 4:** Build a `Pipeline` named `clf_dt`. Your `Pipeline` should include:- an `OrdinalEncoder` transformer for categorical features.- a `SimpleImputer` transformer fot missing values.- a `DecisionTreeClassifier` Predictor.**Note:** Do not train `clf_dt`. You'll do that in a subsequent task.
clf_dt = ...
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge
**Task 5:** Build a `Pipeline` named `clf_rf`. Your `Pipeline` should include:- an `OrdinalEncoder` transformer for categorical features.- a `SimpleImputer` transformer fot missing values.- a `RandomForestClassifier` predictor.**Note:** Do not train `clf_rf`. You'll do that in a subsequent task.
clf_rf = ...
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge
V. Check Metrics**Task 6:** Evaluate the performance of both of your classifiers using k-fold cross-validation.
cv_scores_dt = ... cv_scores_rf = ... print('CV scores DecisionTreeClassifier') print(cv_scores_dt) print('Mean CV accuracy score:', cv_scores_dt.mean()) print('STD CV accuracy score:', cv_scores_dt.std()) print('CV score RandomForestClassifier') print(cv_scores_rf) print('Mean CV accuracy score:', cv_scores_rf.mean())...
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge
VI. Tune Model**Task 7:** Choose the best performing of your two models and tune its hyperparameters using a `RandomizedSearchCV` named `model`. Make sure that you include cross-validation and that `n_iter` is set to at least `25`.**Note:** If you're not sure which hyperparameters to tune, check the notes from today's...
model = ...
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge
**Task 8:** Print out the best score and best params for `model`.
best_score = ... best_params = ... print('Best score for `model`:', best_score) print('Best params for `model`:', best_params)
_____no_output_____
MIT
module3-cross-validation/LS_DS_223_assignment.ipynb
tbbcoach/DS-Unit-2-Kaggle-Challenge