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 data
fold_set = pd.read_csv('../input/aptos-split-oldnew/5-fold.csv') X_train = fold_set[fold_set['fold_2'] == 'train'] X_val = fold_set[fold_set['fold_2'] == 'validation'] test = pd.read_csv('../input/aptos2019-blindness-detection/test.csv') # Preprocecss data test["id_code"] = test["id_code"].apply(lambda x: x + ".png") ...
Number of train samples: 18697 Number of validation samples: 733 Number of test samples: 1928
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Model parameters
# Model parameters model_path = '../working/effNetB4_img256_noBen_fold3.h5' FACTOR = 4 BATCH_SIZE = 8 * FACTOR EPOCHS = 20 WARMUP_EPOCHS = 5 LEARNING_RATE = 1e-3/2 * FACTOR WARMUP_LEARNING_RATE = 1e-3/2 * FACTOR HEIGHT = 256 WIDTH = 256 CHANNELS = 3 TTA_STEPS = 5 ES_PATIENCE = 5 LR_WARMUP_EPOCHS = 5 STEP_SIZE = len(X_t...
_____no_output_____
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Pre-procecess images
old_data_base_path = '../input/diabetic-retinopathy-resized/resized_train/resized_train/' new_data_base_path = '../input/aptos2019-blindness-detection/train_images/' test_base_path = '../input/aptos2019-blindness-detection/test_images/' train_dest_path = 'base_dir/train_images/' validation_dest_path = 'base_dir/validat...
_____no_output_____
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Data generator
datagen=ImageDataGenerator(rescale=1./255, rotation_range=360, horizontal_flip=True, vertical_flip=True) train_generator=datagen.flow_from_dataframe( dataframe=X_train, directory=train_dest...
_____no_output_____
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Model
def create_model(input_shape): input_tensor = Input(shape=input_shape) base_model = EfficientNetB4(weights=None, include_top=False, input_tensor=input_tensor) base_model.load_weights('../input/efficientnet-keras-weights-b0b5/efficientnet-b4_im...
_____no_output_____
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Train top layers
model = create_model(input_shape=(HEIGHT, WIDTH, CHANNELS)) for layer in model.layers: layer.trainable = False for i in range(-2, 0): model.layers[i].trainable = True metric_list = ["accuracy"] optimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE) model.compile(optimizer=optimizer, loss='mean_squared_error', ...
Epoch 1/5 - 282s - loss: 1.2568 - acc: 0.3093 - val_loss: 1.4649 - val_acc: 0.4148 Epoch 2/5 - 269s - loss: 1.0960 - acc: 0.3228 - val_loss: 1.2900 - val_acc: 0.2810 Epoch 3/5 - 267s - loss: 1.0743 - acc: 0.3280 - val_loss: 1.3244 - val_acc: 0.2967 Epoch 4/5 - 266s - loss: 1.0808 - acc: 0.3231 - val_loss: 1.2172 - ...
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Fine-tune the model
for layer in model.layers: layer.trainable = True checkpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True, save_weights_only=True) es = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, restore_best_weights=True, verbose=1) cosine_lr = WarmUpCosineDecaySch...
_____no_output_____
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Model loss graph
plot_metrics(history) # Create empty arays to keep the predictions and labels df_preds = pd.DataFrame(columns=['label', 'pred', 'set']) train_generator.reset() valid_generator.reset() # Add train predictions and labels for i in range(STEP_SIZE_TRAIN + 1): im, lbl = next(train_generator) preds = model.predict(i...
_____no_output_____
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Model Evaluation Confusion Matrix Original thresholds
plot_confusion_matrix((train_preds['label'], train_preds['predictions']), (validation_preds['label'], validation_preds['predictions']))
_____no_output_____
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Quadratic Weighted Kappa
evaluate_model((train_preds['label'], train_preds['predictions']), (validation_preds['label'], validation_preds['predictions']))
Train Cohen Kappa score: 0.738 Validation Cohen Kappa score: 0.899 Complete set Cohen Kappa score: 0.746
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Apply model to test set and output predictions
preds = apply_tta(model, test_generator, TTA_STEPS) predictions = [classify(x) for x in preds] results = pd.DataFrame({'id_code':test['id_code'], 'diagnosis':predictions}) results['id_code'] = results['id_code'].map(lambda x: str(x)[:-4]) # Cleaning created directories if os.path.exists(train_dest_path): shutil.rm...
_____no_output_____
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
Predictions class distribution
fig = plt.subplots(sharex='col', figsize=(24, 8.7)) sns.countplot(x="diagnosis", data=results, palette="GnBu_d").set_title('Test') sns.despine() plt.show() results.to_csv('submission.csv', index=False) display(results.head())
_____no_output_____
MIT
Model backlog/EfficientNet/EfficientNetB4/5-Fold/274 - EfficientNetB4-Reg-Img256 Old&New Fold3.ipynb
ThinkBricks/APTOS2019BlindnessDetection
# To keep the page organized do all imports here from sqlalchemy import create_engine import pandas as pd from scipy import stats # Database credentials postgres_user = 'dabc_student' postgres_pw = '7*.8G9QH21' postgres_host = '142.93.121.174' postgres_port = '5432' postgres_db = 'kickstarterprojects' # use the crede...
_____no_output_____
CC-BY-3.0
ksStatsPy.ipynb
tastiz/story_scape.html
Translate `dzn` to `smt2` for z3 Check Versions of Tools
import os import subprocess my_env = os.environ.copy() output = subprocess.check_output(f'''/home/{my_env['USER']}/optimathsat/bin/optimathsat -version''', shell=True, universal_newlines=True) output output = subprocess.check_output(f'''/home/{my_env['USER']}/minizinc/build/minizinc --version''', shell=True, universal...
_____no_output_____
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
First generate the FlatZinc files using the MiniZinc tool. Make sure that a `smt2` folder is located inside `./minizinc/share/minizinc/`. Else, to enable OptiMathSAT's support for global constraints download the [smt2.tar.gz](http://optimathsat.disi.unitn.it/data/smt2.tar.gz) package and unpack it there using```zshtar ...
output = subprocess.check_output(f'''ls -la /home/{my_env['USER']}/minizinc/share/minizinc/smt2/''', shell=True, universal_newlines=True) print(output)
total 292 drwxr-xr-x 2 jovyan jovyan 4096 Jan 15 2018 . drwxr-xr-x 11 jovyan jovyan 4096 Jul 11 12:34 .. -rw-r--r-- 1 jovyan jovyan 328 Nov 13 2017 alldifferent_except_0.mzn -rw-r--r-- 1 jovyan jovyan 382 Nov 13 2017 all_different_int.mzn -rw-r--r-- 1 jovyan jovyan 396 Nov 13 2017 all_different_set.mzn -rw-r...
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
Transform `dzn` to `fzn` Using a `mzn` Model Then transform the desired `.dzn` file to `.fzn` using a `Mz.mzn` MiniZinc model. First list all `dzn` files contained in the `dzn_path` that should get processed.
import os dzn_files = [] dzn_path = f'''/home/{my_env['USER']}/data/dzn/''' for filename in os.listdir(dzn_path): if filename.endswith(".dzn"): dzn_files.append(filename) len(dzn_files)
_____no_output_____
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
Model $Mz_1$
import sys fzn_path = f'''/home/{my_env['USER']}/data/fzn/smt2/Mz1-noAbs/''' minizinc_base_cmd = f'''/home/{my_env['USER']}/minizinc/build/minizinc \ -Werror \ --compile --solver org.minizinc.mzn-fzn \ --search-dir /home/{my_env['USER']}/minizinc/share/minizinc/smt2/ \ /home/{my_env['USER']}/models/mzn...
(278/278) Translating /home/jovyan/data/dzn/R028.dzn to /home/jovyan/data/fzn/smt2/Mz1-noAbs/R028-dzn.fzn
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
Model $Mz_2$
import sys fzn_path = f'''/home/{my_env['USER']}/data/fzn/smt2/Mz2-noAbs/''' minizinc_base_cmd = f'''/home/{my_env['USER']}/minizinc/build/minizinc \ -Werror \ --compile --solver org.minizinc.mzn-fzn \ --search-dir /home/{my_env['USER']}/minizinc/share/minizinc/smt2/ \ /home/{my_env['USER']}/models/mzn...
(278/278) Translating /home/jovyan/data/dzn/R028.dzn to /home/jovyan/data/fzn/smt2/Mz2-noAbs/R028-dzn.fzn
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
Translate `fzn` to `smt2` The generated `.fzn` files can be used to generate a `.smt2` files using the `fzn2smt2.py` script from this [project](https://github.com/PatrickTrentin88/fzn2omt).**NOTE**: Files `R001` (no cables) and `R002` (one one-sided cable) throw an error while translating. $Mz_1$
import os fzn_files = [] fzn_path = f'''/home/{my_env['USER']}/data/fzn/smt2/Mz1-noAbs/''' for filename in os.listdir(fzn_path): if filename.endswith(".fzn"): fzn_files.append(filename) len(fzn_files) smt2_path = f'''/home/{my_env['USER']}/data/smt2/z3/Mz1-noAbs/''' fzn2smt2_base_cmd = f'''/home/{my_env['...
(278/278) Translating /home/jovyan/data/fzn/smt2/Mz1-noAbs/R079-dzn.fzn to /home/jovyan/data/smt2/z3/Mz1-noAbs/R079-dzn-fzn.smt2
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
$Mz_2$
import os fzn_files = [] fzn_path = f'''/home/{my_env['USER']}/data/fzn/smt2/Mz2-noAbs/''' for filename in os.listdir(fzn_path): if filename.endswith(".fzn"): fzn_files.append(filename) len(fzn_files) smt2_path = f'''/home/{my_env['USER']}/data/smt2/z3/Mz2-noAbs/''' fzn2smt2_base_cmd = f'''/home/{my_env['...
(278/278) Translating /home/jovyan/data/fzn/smt2/Mz2-noAbs/R079-dzn.fzn to /home/jovyan/data/smt2/z3/Mz2-noAbs/R079-dzn-fzn.smt2
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
Adjust `smt2` Files According to Chapter 5.2- Add lower and upper bounds for the decision variable `pfc`- Add number of cavities as comments for later solution extraction (workaround)
import os import re def adjust_smt2_file(smt2_path: str, file: str, write_path: str): with open(smt2_path+'/'+file, 'r+') as myfile: data = "".join(line for line in myfile) filename = os.path.splitext(file)[0] newFile = open(os.path.join(write_path, filename +'.smt2'),"w+") newFile.write(dat...
_____no_output_____
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
$Mz_1$
import os smt2_files = [] smt2_path = f'''/home/{my_env['USER']}/data/smt2/z3/Mz1-noAbs''' for filename in os.listdir(smt2_path): if filename.endswith(".smt2"): smt2_files.append(filename) len(smt2_files) fix_count = 0 for smt2 in smt2_files: fix_count += 1 print(f'''\r{fix_count}/{len(smt2_files)...
49/278 Fixing file R002-dzn-fzn.smt2 Check R002-dzn-fzn for completeness - data missing? 150/278 Fixing file R001-dzn-fzn.smt2 Check R001-dzn-fzn for completeness - data missing? 278/278 Fixing file R166-dzn-fzn.smt2
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
$Mz_2$
import os smt2_files = [] smt2_path = f'''/home/{my_env['USER']}/data/smt2/z3/Mz2-noAbs''' for filename in os.listdir(smt2_path): if filename.endswith(".smt2"): smt2_files.append(filename) len(smt2_files) fix_count = 0 for smt2 in smt2_files: fix_count += 1 print(f'''\r{fix_count}/{len(smt2_files)...
49/278 Fixing file R002-dzn-fzn.smt2 Check R002-dzn-fzn for completeness - data missing? 150/278 Fixing file R001-dzn-fzn.smt2 Check R001-dzn-fzn for completeness - data missing? 278/278 Fixing file R166-dzn-fzn.smt2
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
Test Generated `smt2` Files Using `z3`This shoud generate the `smt2` file without any error. If this was the case then the `z3` prover can be called on a file by running```zshz3 output/A001-dzn-smt2-fzn.smt2 ```yielding something similar to```zshz3 output/A001-dzn-smt2-fzn.smt2 ...
command = f'''/home/{my_env['USER']}/z3/build/z3 /home/{my_env['USER']}/data/smt2/z3/Mz1-noAbs/A001-dzn-fzn.smt2''' print(command) try: result = subprocess.check_output(command, shell=True, universal_newlines=True) except Exception as e: print(e.output) print(result)
_____no_output_____
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
Test with `smt2` from $Mz_2$
result = subprocess.check_output( f'''/home/{my_env['USER']}/z3/build/z3 \ /home/{my_env['USER']}/data/smt2/z3/Mz2-noAbs/v3/A004-dzn-fzn_v3.smt2''', shell=True, universal_newlines=True) print(result)
_____no_output_____
BSD-3-Clause
translation_toolchain/scripts/TranslateDZN2SMT2_Z3.ipynb
kw90/ctw_translation_toolchain
Cincinnati Salaries- https://data.cincinnati-oh.gov/Efficient-Service-Delivery/City-of-Cincinnati-Employees-w-Salaries/wmj4-ygbf
! pip install sodapy ! pip install pandas import pandas as pd from sodapy import Socrata # Unauthenticated client only works with public data sets. Note 'None' # in place of application token, and no username or password: client = Socrata("data.cincinnati-oh.gov", None) # Example authenticated client (needed for non-...
_____no_output_____
MIT
cincinnati_salaries.ipynb
doedotdev/cincinnati-salaries
Welcome to Colaboratory!Colaboratory is a free Jupyter notebook environment that requires no setup and runs entirely in the cloud.With Colaboratory you can write and execute code, save and share your analyses, and access powerful computing resources, all for free from your browser.
#@title Introducing Colaboratory { display-mode: "form" } #@markdown This 3-minute video gives an overview of the key features of Colaboratory: from IPython.display import YouTubeVideo YouTubeVideo('inN8seMm7UI', width=600, height=400)
_____no_output_____
MIT
colaboratory_introduction.ipynb
karlkirschner/2020_Scientific_Programming
Getting StartedThe document you are reading is a [Jupyter notebook](https://jupyter.org/), hosted in Colaboratory. It is not a static page, but an interactive environment that lets you write and execute code in Python and other languages.For example, here is a **code cell** with a short Python script that computes a ...
seconds_in_a_day = 24 * 60 * 60 seconds_in_a_day
_____no_output_____
MIT
colaboratory_introduction.ipynb
karlkirschner/2020_Scientific_Programming
To execute the code in the above cell, select it with a click and then either press the play button to the left of the code, or use the keyboard shortcut "Command/Ctrl+Enter".All cells modify the same global state, so variables that you define by executing a cell can be used in other cells:
seconds_in_a_week = 7 * seconds_in_a_day seconds_in_a_week
_____no_output_____
MIT
colaboratory_introduction.ipynb
karlkirschner/2020_Scientific_Programming
For more information about working with Colaboratory notebooks, see [Overview of Colaboratory](/notebooks/basic_features_overview.ipynb). --- CellsA notebook is a list of cells. Cells contain either explanatory text or executable code and its output. Click a cell to select it. Code cellsBelow is a **code cell**. Once ...
a = 13 a
_____no_output_____
MIT
colaboratory_introduction.ipynb
karlkirschner/2020_Scientific_Programming
Table of Contents1  Leveraging Pre-trained Word Embedding for Text Classification1.1  Data Preparation1.2  Glove1.3  Model1.3.1  Model with Pretrained Embedding1.3.2  Model without Pretrained Embedding1.4  Submission1.5  Summary2 &nbsp...
# code for loading the format for the notebook import os # path : store the current path to convert back to it later path = os.getcwd() os.chdir(os.path.join('..', '..', 'notebook_format')) from formats import load_style load_style(plot_style=False) os.chdir(path) # 1. magic for inline plot # 2. magic to print versi...
Using TensorFlow backend.
MIT
keras/text_classification/keras_pretrained_embedding.ipynb
sindhu819/machine-learning-1
Leveraging Pre-trained Word Embedding for Text Classification There are two main ways to obtain word embeddings:- Learn it from scratch: We specify a neural network architecture and learn the word embeddings jointly with the main task at our hand (e.g. sentiment classification). i.e. we would start off with some rando...
data_dir = 'data' submission_dir = 'submission' input_path = os.path.join(data_dir, 'word2vec-nlp-tutorial', 'labeledTrainData.tsv') df = pd.read_csv(input_path, delimiter='\t') print(df.shape) df.head() raw_text = df['review'].iloc[0] raw_text import re def clean_str(string: str) -> str: string = re.sub(r"\\", ""...
_____no_output_____
MIT
keras/text_classification/keras_pretrained_embedding.ipynb
sindhu819/machine-learning-1
Glove There are many different pretrained word embeddings online. The one we'll be using is from [Glove](https://nlp.stanford.edu/projects/glove/). Others include but not limited to [FastText](https://fasttext.cc/docs/en/crawl-vectors.html), [bpemb](https://github.com/bheinzerling/bpemb).If we look at the project's wi...
import requests from tqdm import tqdm def download_glove(embedding_type: str='glove.6B.zip'): """ download GloVe word vector representations, this step may take a while Parameters ---------- embedding_type : str, default 'glove.6B.zip' Specifying different glove embeddings to download ...
_____no_output_____
MIT
keras/text_classification/keras_pretrained_embedding.ipynb
sindhu819/machine-learning-1
The way we'll leverage the pretrained embedding is to first read it in as a dictionary lookup, where the key is the word and the value is the corresponding word embedding. Then for each token in our vocabulary, we'll lookup this dictionary to see if there's a pretrained embedding available, if there is, we'll use the p...
def get_embedding_lookup(embedding_path) -> Dict[str, np.ndarray]: embedding_lookup = {} with open(embedding_path) as f: for line in f: values = line.split() word = values[0] coef = np.array(values[1:], dtype=np.float32) embedding_lookup[word] = coef ...
number of words found: 19654
MIT
keras/text_classification/keras_pretrained_embedding.ipynb
sindhu819/machine-learning-1
Model To train our text classifier, we specify a 1D convolutional network. Our embedding layer can either be initialized randomly or loaded from a pre-trained embedding. Note that for the pre-trained embedding case, apart from loading the weights, we also "freeze" the embedding layer, i.e. we set its trainable attribu...
def simple_text_cnn(max_sequence_len: int, max_features: int, num_classes: int, optimizer: str='adam', metrics: List[str]=['acc'], pretrained_embedding: np.ndarray=None) -> Model: sequence_input = layers.Input(shape...
_____no_output_____
MIT
keras/text_classification/keras_pretrained_embedding.ipynb
sindhu819/machine-learning-1
Model with Pretrained Embedding
num_classes = 2 model1 = simple_text_cnn(max_sequence_len, max_features, num_classes, pretrained_embedding=pretrained_embedding) model1.summary()
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:66: The name tf.get_default_graph is deprecated. Please use tf.compat.v1.get_default_graph instead. WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:541: The name tf.plac...
MIT
keras/text_classification/keras_pretrained_embedding.ipynb
sindhu819/machine-learning-1
We can confirm whether our embedding layer is trainable by looping through each layer and checking the trainable attribute.
df_model_layers = pd.DataFrame( [(layer.name, layer.trainable, layer.count_params()) for layer in model1.layers], columns=['layer', 'trainable', 'n_params'] ) df_model_layers # time : 70 # test performance : auc 0.93212 start = time.time() history1 = model1.fit(x_train, y_train, validation...
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow_core/python/ops/math_grad.py:1424: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version. Instructions for updating: Use tf.where in 2.0, which has the same broadcast rule as np.where WARNING:tensorflo...
MIT
keras/text_classification/keras_pretrained_embedding.ipynb
sindhu819/machine-learning-1
Model without Pretrained Embedding
num_classes = 2 model2 = simple_text_cnn(max_sequence_len, max_features, num_classes) model2.summary() # time : 86 secs # test performance : auc 0.92310 start = time.time() history1 = model2.fit(x_train, y_train, validation_data=(x_val, y_val), batch_size=128, ...
Train on 20000 samples, validate on 5000 samples Epoch 1/8 20000/20000 [==============================] - 11s 570us/step - loss: 0.5010 - acc: 0.7065 - val_loss: 0.3016 - val_acc: 0.8730 Epoch 2/8 20000/20000 [==============================] - 11s 542us/step - loss: 0.2024 - acc: 0.9243 - val_loss: 0.2816 - val_acc: 0....
MIT
keras/text_classification/keras_pretrained_embedding.ipynb
sindhu819/machine-learning-1
Submission For the submission section, we read in and preprocess the test data provided by the competition, then generate the predicted probability column for both the model that uses pretrained embedding and one that doesn't to compare their performance.
input_path = os.path.join(data_dir, 'word2vec-nlp-tutorial', 'testData.tsv') df_test = pd.read_csv(input_path, delimiter='\t') print(df_test.shape) df_test.head() def clean_text_without_label(df: pd.DataFrame, text_col: str) -> List[str]: texts = [] for raw_text in df[text_col]: text = BeautifulSoup(raw...
generating submission for: pretrained_embedding 25000/25000 [==============================] - 6s 228us/step generating submission for: without_pretrained_embedding 25000/25000 [==============================] - 6s 222us/step (25000, 2)
MIT
keras/text_classification/keras_pretrained_embedding.ipynb
sindhu819/machine-learning-1
04 - Pandas: Working with time series data> *© 2021, Joris Van den Bossche and Stijn Van Hoey (, ). Licensed under [CC BY 4.0 Creative Commons](http://creativecommons.org/licenses/by/4.0/)*---
import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.style.use('ggplot')
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Introduction: `datetime` module Standard Python contains the `datetime` module to handle date and time data:
import datetime dt = datetime.datetime(year=2016, month=12, day=19, hour=13, minute=30) dt print(dt) # .day,... print(dt.strftime("%d %B %Y"))
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Dates and times in pandas The ``Timestamp`` object Pandas has its own date and time objects, which are compatible with the standard `datetime` objects, but provide some more functionality to work with. The `Timestamp` object can also be constructed from a string:
ts = pd.Timestamp('2016-12-19') ts
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Like with `datetime.datetime` objects, there are several useful attributes available on the `Timestamp`. For example, we can get the month (experiment with tab completion!):
ts.month
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
There is also a `Timedelta` type, which can e.g. be used to add intervals of time:
ts + pd.Timedelta('5 days')
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Parsing datetime strings ![](http://imgs.xkcd.com/comics/iso_8601.png) Unfortunately, when working with real world data, you encounter many different `datetime` formats. Most of the time when you have to deal with them, they come in text format, e.g. from a `CSV` file. To work with those data in Pandas, we first have ...
pd.to_datetime("2016-12-09") pd.to_datetime("09/12/2016") pd.to_datetime("09/12/2016", dayfirst=True) pd.to_datetime("09/12/2016", format="%d/%m/%Y")
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
A detailed overview of how to specify the `format` string, see the table in the python documentation: https://docs.python.org/3/library/datetime.htmlstrftime-and-strptime-behavior `Timestamp` data in a Series or DataFrame column
s = pd.Series(['2016-12-09 10:00:00', '2016-12-09 11:00:00', '2016-12-09 12:00:00']) s
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
The `to_datetime` function can also be used to convert a full series of strings:
ts = pd.to_datetime(s) ts
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Notice the data type of this series has changed: the `datetime64[ns]` dtype. This indicates that we have a series of actual datetime values. The same attributes as on single `Timestamp`s are also available on a Series with datetime data, using the **`.dt`** accessor:
ts.dt.hour ts.dt.dayofweek
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
To quickly construct some regular time series data, the [``pd.date_range``](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.date_range.html) function comes in handy:
pd.Series(pd.date_range(start="2016-01-01", periods=10, freq='3H'))
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Time series data: `Timestamp` in the index River discharge example data For the following demonstration of the time series functionality, we use a sample of discharge data of the Maarkebeek (Flanders) with 3 hour averaged values, derived from the [Waterinfo website](https://www.waterinfo.be/).
data = pd.read_csv("data/vmm_flowdata.csv") data.head()
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
We already know how to parse a date column with Pandas:
data['Time'] = pd.to_datetime(data['Time'])
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
With `set_index('datetime')`, we set the column with datetime values as the index, which can be done by both `Series` and `DataFrame`.
data = data.set_index("Time") data
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
The steps above are provided as built-in functionality of `read_csv`:
data = pd.read_csv("data/vmm_flowdata.csv", index_col=0, parse_dates=True)
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
REMEMBER: `pd.read_csv` provides a lot of built-in functionality to support this kind of transactions when reading in a file! Check the help of the read_csv function... The DatetimeIndex When we ensure the DataFrame has a `DatetimeIndex`, time-series related functionality becomes available:
data.index
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Similar to a Series with datetime data, there are some attributes of the timestamp values available:
data.index.day data.index.dayofyear data.index.year
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
The `plot` method will also adapt its labels (when you zoom in, you can see the different levels of detail of the datetime labels):
%matplotlib widget data.plot() # switching back to static inline plots (the default) %matplotlib inline
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
We have too much data to sensibly plot on one figure. Let's see how we can easily select part of the data or aggregate the data to other time resolutions in the next sections. Selecting data from a time series We can use label based indexing on a timeseries as expected:
data[pd.Timestamp("2012-01-01 09:00"):pd.Timestamp("2012-01-01 19:00")]
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
But, for convenience, indexing a time series also works with strings:
data["2012-01-01 09:00":"2012-01-01 19:00"]
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
A nice feature is **"partial string" indexing**, where we can do implicit slicing by providing a partial datetime string.E.g. all data of 2013:
data['2013':]
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Or all data of January up to March 2012:
data['2012-01':'2012-03']
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
EXERCISE: select all data starting from 2012
data['2012':]
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
EXERCISE: select all data in January for all different years
data[data.index.month == 1]
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
EXERCISE: select all data in April, May and June for all different years
data[data.index.month.isin([4, 5, 6])]
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
EXERCISE: select all 'daytime' data (between 8h and 20h) for all days
data[(data.index.hour > 8) & (data.index.hour < 20)]
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
The power of pandas: `resample` A very powerfull method is **`resample`: converting the frequency of the time series** (e.g. from hourly to daily data).The time series has a frequency of 1 hour. I want to change this to daily:
data.resample('D').mean().head()
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Other mathematical methods can also be specified:
data.resample('D').max().head()
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
REMEMBER: The string to specify the new time frequency: http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.htmloffset-aliases These strings can also be combined with numbers, eg `'10D'`...
data.resample('M').mean().plot() # 10D
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
EXERCISE: Plot the monthly standard deviation of the columns
data.resample('M').std().plot() # 'A'
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
EXERCISE: Plot the monthly mean and median values for the years 2011-2012 for 'L06_347'__Note__ Did you know agg to derive multiple statistics at the same time?
subset = data['2011':'2012']['L06_347'] subset.resample('M').agg(['mean', 'median']).plot()
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
EXERCISE: plot the monthly mininum and maximum daily average value of the 'LS06_348' column
daily = data['LS06_348'].resample('D').mean() # daily averages calculated daily.resample('M').agg(['min', 'max']).plot() # monthly minimum and maximum values of these daily averages
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
EXERCISE: Make a bar plot of the mean of the stations in year of 2013
data['2013':'2013'].mean().plot(kind='barh')
_____no_output_____
BSD-3-Clause
_solved/pandas_04_time_series_data.ipynb
jorisvandenbossche/FLAMES-python-data-wrangling
Importing Spark NLP, Spark NLP for Healthcare and Spark OCR
import sparknlp import sparknlp_jsl import sparkocr sparknlp_jsl.version() sparknlp.version() sparkocr.version()
_____no_output_____
Apache-2.0
platforms/sagemaker-studio/SparkNLP_sagemaker.ipynb
fcivardi/spark-nlp-workshop
Retrieving your license
import os, json with open('/license.json', 'r') as f: license_keys = json.load(f) # Defining license key-value pairs as local variables locals().update(license_keys) # Adding license key-value pairs to environment variables os.environ.update(license_keys)
_____no_output_____
Apache-2.0
platforms/sagemaker-studio/SparkNLP_sagemaker.ipynb
fcivardi/spark-nlp-workshop
Add a DNS entry for your Sagemaker instance
!echo "127.0.0.1 $HOSTNAME" >> /etc/hosts
_____no_output_____
Apache-2.0
platforms/sagemaker-studio/SparkNLP_sagemaker.ipynb
fcivardi/spark-nlp-workshop
Start your session
spark = sparkocr.start(secret=os.environ['SPARK_OCR_SECRET'], nlp_secret=['SECRET'])
Spark version: 3.0.2 Spark NLP version: 3.3.1 Spark OCR version: 3.8.0
Apache-2.0
platforms/sagemaker-studio/SparkNLP_sagemaker.ipynb
fcivardi/spark-nlp-workshop
Check everything is good and have fun!
spark
_____no_output_____
Apache-2.0
platforms/sagemaker-studio/SparkNLP_sagemaker.ipynb
fcivardi/spark-nlp-workshop
Demonstrating how to get DonkeyCar Tub files into a PyTorch/fastai DataBlock
from fastai.data.all import * from fastai.vision.all import * from fastai.data.transforms import ColReader, Normalize, RandomSplitter import torch from torch import nn from torch.nn import functional as F from donkeycar.parts.tub_v2 import Tub import pandas as pd from pathlib import Path from malpi.dk.train import prep...
_____no_output_____
MIT
notebooks/DKDataBlock.ipynb
Bleyddyn/malpi
The below code is modified from: https://github.com/cmasenas/fastai_navigation_training/blob/master/fastai_train.ipynb.TODO: Figure out how to have multiple output heads
def test_one_transform(name, inputs, df_all, batch_tfms, item_tfms, epochs, lr): dls = get_data(inputs, df_all=df_all, batch_tfms=batch_tfms, item_tfms=item_tfms) callbacks = [CSVLogger(f"Transform_{name}.csv", append=True)] learn = get_learner(dls) #learn.no_logging() #Try this to block logging when do...
_____no_output_____
MIT
notebooks/DKDataBlock.ipynb
Bleyddyn/malpi
Redis列表实现一次pop 弹出多条数据![](https://kingname-1257411235.cos.ap-chengdu.myqcloud.com/2019-03-03-16-52-34.png)
# 连接 Redis import redis client = redis.Redis(host='122.51.39.219', port=6379, password='leftright123') # 注意: # 这个 Redis 环境仅作为练习之用,每小时会清空一次,请勿存放重要数据。 # 准备数据 client.lpush('test_batch_pop', *list(range(10000))) # 一条一条读取,非常耗时 import time start = time.time() while True: data = client.lpop('test_batch_pop') if n...
循环读取10000条数据,使用 lpop 耗时:112.04084920883179
MIT
视频课件/Redis 的高级用法.ipynb
kingname/SourceCodeofMongoRedis
为什么使用`lpop`读取10000条数据这么慢?因为`lpop`每次只弹出1条数据,每次弹出数据都要连接 Redis 。大量时间浪费在了网络传输上面。 如何实现批量弹出多条数据,并在同一次网络请求中返回?先使用 `lrange` 获取数据,再使用`ltrim`删除被获取的数据。
# 复习一下 lrange 的用法 datas = client.lrange('test_batch_pop', 0, 9) # 读取前10条数据 datas # 学习一下 ltrim 的用法 client.ltrim('test_batch_pop', 10, -1) # 删除前10条数据 # 验证一下数据是否被成功删除 length = client.llen('test_batch_pop') print(f'现在列表里面还剩{length}条数据') datas = client.lrange('test_batch_pop', 0, 9) # 读取前10条数据 datas # 一种看起来正确的做法 def ...
_____no_output_____
MIT
视频课件/Redis 的高级用法.ipynb
kingname/SourceCodeofMongoRedis
这种写法用什么问题在多个进程同时使用 batch_pop_fake 函数的时候,由于执行 lrange 与 ltrim 是在两条语句中,因此实际上会分成2个网络请求。那么当 A 进程刚刚执行完lrange,还没有来得及执行 ltrim 时,B 进程刚好过来执行 lrange,那么 AB 两个进程就会获得相同的数据。等 B 进程获取完成数据以后,A 进程的 ltrim 刚刚抵达,此时Redis 会删除前 n 条数据,然后 B 进程的 ltrim 也到了,再删除前 n 条数据。那么最终导致的结果就是,AB 两个进程同时拿到前 n 条数据,但是却有2n 条数据被删除。 使用 pipeline 打包多个命令到一个请求中pipeline ...
# 真正可用的批量弹出数据函数 def batch_pop_real(key, n): pipe = client.pipeline() pipe.lrange(key, 0, n - 1) pipe.ltrim(key, n, -1) result = pipe.execute() return result[0] # 清空列表并重新添加10000条数据 client.delete('test_batch_pop') client.lpush('test_batch_pop', *list(range(10000))) start = time.time() while True: ...
_____no_output_____
MIT
视频课件/Redis 的高级用法.ipynb
kingname/SourceCodeofMongoRedis
Dataset Los datos son series temporales (casos semanales de Dengue) de distintos distritos de Paraguay
path = "./data/Notificaciones/" filename_read = os.path.join(path,"normalizado.csv") notificaciones = pd.read_csv(filename_read,delimiter=",",engine='python') notificaciones.shape listaMunicp = notificaciones['distrito_nombre'].tolist() listaMunicp = list(dict.fromkeys(listaMunicp)) print('Son ', len(listaMunicp), ' di...
Son 217 distritos ['1RO DE MARZO', '25 DE DICIEMBRE', '3 DE FEBRERO', 'ABAI', 'ACAHAY', 'ALBERDI', 'ALTO VERA', 'ALTOS', 'ANTEQUERA', 'AREGUA', 'ARROYOS Y ESTEROS', 'ASUNCION', 'ATYRA', 'AYOLAS', 'AZOTEY', 'BAHIA NEGRA', 'BELEN', 'BELLA VISTA', 'BENJAMIN ACEVAL', 'BORJA', 'BUENA VISTA', 'CAACUPE', 'CAAGUAZU', 'CAAZAP...
Apache-2.0
AlgoritmosClustering/ExperimentosClusters.ipynb
diegostaPy/UcomSeminario
A continuación tomamos las series temporales que leímos y vemos como quedan
timeSeries = pd.DataFrame() for muni in listaMunicp: municipio=notificaciones['distrito_nombre']==muni notif_x_municp=notificaciones[municipio] notif_x_municp = notif_x_municp.reset_index(drop=True) notif_x_municp = notif_x_municp['incidencia'] notif_x_municp = notif_x_municp.replace('nan', np.nan)....
_____no_output_____
Apache-2.0
AlgoritmosClustering/ExperimentosClusters.ipynb
diegostaPy/UcomSeminario
Análisis de grupos (Clustering) El Clustering o la clusterización es un proceso importante dentro del Machine learning. Este proceso desarrolla una acción fundamental que le permite a los algoritmos de aprendizaje automatizado entrenar y conocer de forma adecuada los datos con los que desarrollan sus actividades. Tien...
#Euclidean def euclidean(x, y): r=np.linalg.norm(x-y) if math.isnan(r): r=1 #print(r) return r #RMSE def rmse(x, y): r=sqrt(mean_squared_error(x,y)) if math.isnan(r): r=1 #print(r) return r #Fast Dynamic time warping def fast_DTW(x, y): r, _ = fastdtw(x, y, dist=eucli...
_____no_output_____
Apache-2.0
AlgoritmosClustering/ExperimentosClusters.ipynb
diegostaPy/UcomSeminario
Determinar el número de clusters a formar La mayoría de las técnicas de clustering necesitan como *input* el número de clusters a formar, para eso lo que se hace es hacer una prueba con diferentes números de cluster y nos quedamos con el que dió menor error en general. Para medir ese error utilizamos **Silhouette scor...
from yellowbrick.cluster import KElbowVisualizer model = AgglomerativeClustering() visualizer = KElbowVisualizer(model, k=(3,20),metric='distortion', timings=False) visualizer.fit(rmse_dist) # Fit the data to the visualizer visualizer.show() # Finalize and render the figure
/home/jbogado/virtualenv_3.5/lib/python3.5/site-packages/sklearn/utils/deprecation.py:144: FutureWarning: The sklearn.metrics.classification module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.metrics. Anything that can...
Apache-2.0
AlgoritmosClustering/ExperimentosClusters.ipynb
diegostaPy/UcomSeminario
Así tenemos que son 9 los grupos que formaremos
k=9
_____no_output_____
Apache-2.0
AlgoritmosClustering/ExperimentosClusters.ipynb
diegostaPy/UcomSeminario
Técnicas de clustering K-means El objetivo de este algoritmo es el de encontrar “K” grupos (clusters) entre los datos crudos. El algoritmo trabaja iterativamente para asignar a cada “punto” (las filas de nuestro conjunto de entrada forman una coordenada) uno de los “K” grupos basado en sus características. Son agrup...
#Experimentos print('Silhouette coefficent') #HAC + euclidean Z = hac.linkage(timeSeries, method='complete', metric=euclidean) clusters = fcluster(Z, k, criterion='maxclust') print("HAC + euclidean distance: ",silhouette_score(euclidean_dist, clusters)) #HAC + rmse Z = hac.linkage(timeSeries, method='complete', metri...
DBSCAN + euclidian distance: 0.8141967832004429 DBSCAN + rmse distance: 0.0 DBSCAN + corr distance: 0.4543067216391177 DBSCAN + scorr distance: 0.005463947798855316 KM + dtw distance: 0.5203731423414103
Apache-2.0
AlgoritmosClustering/ExperimentosClusters.ipynb
diegostaPy/UcomSeminario
Clustering basado en propiedades Otro enfoque en el clustering es extraer ciertas propiedades de nuestros datos y hacer la agrupación basándonos en eso, el procedimiento es igual a como si estuviesemos trabajando con nuestros datos reales.
from tsfresh import extract_features #features extraction extracted_features = extract_features(timeSeries, column_id="indice") extracted_features.shape list(extracted_features.columns.values) n=217 features = pd.DataFrame() Mean=[] Var=[] aCF1=[] Peak=[] Entropy=[] Cpoints=[] for muni in listaMunicp: municipio=no...
DBSCAN + euclidian distance: 0.7327015254414699 DBSCAN + corr distance: 0.0 DBSCAN + scorr distance: 0.982667657643341 KM + dtw distance: 0.6447434480812199
Apache-2.0
AlgoritmosClustering/ExperimentosClusters.ipynb
diegostaPy/UcomSeminario
What is Colaboratory?Colaboratory, or "Colab" for short, allows you to write and execute Python in your browser, with - Zero configuration required- Free access to GPUs- Easy sharingWhether you're a **student**, a **data scientist** or an **AI researcher**, Colab can make your work easier. Watch [Introduction to Colab...
seconds_in_a_day = 24 * 60 * 60 seconds_in_a_day
_____no_output_____
MIT
Welcome_To_Colaboratory.ipynb
user9990/Synthetic-data-gen
To execute the code in the above cell, select it with a click and then either press the play button to the left of the code, or use the keyboard shortcut "Command/Ctrl+Enter". To edit the code, just click the cell and start editing.Variables that you define in one cell can later be used in other cells:
seconds_in_a_week = 7 * seconds_in_a_day seconds_in_a_week
_____no_output_____
MIT
Welcome_To_Colaboratory.ipynb
user9990/Synthetic-data-gen
Colab notebooks allow you to combine **executable code** and **rich text** in a single document, along with **images**, **HTML**, **LaTeX** and more. When you create your own Colab notebooks, they are stored in your Google Drive account. You can easily share your Colab notebooks with co-workers or friends, allowing the...
import numpy as np from matplotlib import pyplot as plt ys = 200 + np.random.randn(100) x = [x for x in range(len(ys))] plt.plot(x, ys, '-') plt.fill_between(x, ys, 195, where=(ys > 195), facecolor='g', alpha=0.6) plt.title("Sample Visualization") plt.show()
_____no_output_____
MIT
Welcome_To_Colaboratory.ipynb
user9990/Synthetic-data-gen
Practice with conditionalsBefore we practice conditionals, let's review:To execute a command when a condition is true, use `if`:```if [condition]: [command]```To execute a command when a condition is true, and execute something else otherwise, use `if/else`:```if [condition]: [command 1]else: [command 2]```To execu...
strawberries = 1 bananas = 0.5 milk = 1 # create a variable ingredients that equals the sum of all our ingredients ingredients = strawberries + bananas + milk # write an if statement that prints out "We have enough ingredients!" if we have at least 4 cups of ingredients if ingredients >= 4: print("We have enough ...
_____no_output_____
CC-BY-4.0
Practices/_Keys/KEY_Practice09_Conditionals.ipynb
ssorbetto/curriculum-notebooks
The code above will let us know if we have enough ingredients for our smoothie. But, if we don't have enough ingredients, the code won't print anything. Our code would be more informative if it also told us when we didn't have enough ingredients. Next, let's write code that also lets us know when we _don't_ have enough...
# write code that prints "We have enough ingredients" if we have at least 4 cups of ingredients # and also prints "We don't have enough ingredients" if we have less than 4 cups of ingredients if ingredients >=4: print("We have enough ingredients!") else: print("We do not have enough ingredients.")
We do not have enough ingredients.
CC-BY-4.0
Practices/_Keys/KEY_Practice09_Conditionals.ipynb
ssorbetto/curriculum-notebooks
It might also be useful to know if we have exactly 4 cups of ingredients. Add to the code above so that it lets us know when we have more than enough ingredients, exactly enough ingredients, or not enough ingredients.
# write code that prints informative messages when we have more than 4 cups of ingredients, # exactly 4 cups of ingredients, or less than 4 cups of ingredients if ingredients > 4: print("we have more than enough ingredients") elif ingredients is 4: print("we have exactly enough ingredients") else: print("we...
we have exactly enough ingredients
CC-BY-4.0
Practices/_Keys/KEY_Practice09_Conditionals.ipynb
ssorbetto/curriculum-notebooks
**Challenge**: Suppose our blender can only fit up to 6 cups inside. Add to the above code so that it also warns us when we have too many ingredients.
# write an if/elif/else style statement that does the following: # prints a message when we have exactly 4 cups of ingredients saying we have exactly the right amount of ingredients # prints a message when we have less than 4 cups of ingredients say we do not have enough # prints a message when we have 4-6 cups of ing...
_____no_output_____
CC-BY-4.0
Practices/_Keys/KEY_Practice09_Conditionals.ipynb
ssorbetto/curriculum-notebooks
Using "method chains" to create more readable code Game of Thrones example - slicing, group stats, and plottingI didn't find an off the shelf dataset to run our seminal analysis from last week, but I found [an analysis](https://www.kaggle.com/dhanushkishore/impact-of-game-of-thrones-on-us-baby-names) that explored if...
#TO USE datadotworld PACKAGE: #1. create account at data.world, then run the next two lines: #2. in terminal/powershell: pip install datadotworld[pandas] # # IF THIS DOESN'T WORK BC YOU GET AN ERROR ABOUT "CCHARDET", RUN: # conda install -c conda-forge cchardet # THEN RERUN: pip install datadotworld[pandas] # #...
_____no_output_____
MIT
content/03/02f_chains-Copy1.ipynb
schemesmith/ledatascifi-2021
Version 11. save a slice of the dataset with the names we want (using `.loc`)2. sometimes a name is used by boys and girls in the same year, so combine the counts so that we have one observation per name per year3. save the dataset and then call a plot function
# restrict by name and only keep years after 2000 somenames = baby_names.loc[( # formating inside this () is just to make it clearer to a reader ( # condition 1: one of these names, | means "or" (baby_names['name'] == "Sansa") | (baby_names['name'] == "Daenerys") | (baby_names['name'] == "Brienne")...
_____no_output_____
MIT
content/03/02f_chains-Copy1.ipynb
schemesmith/ledatascifi-2021
Version 2 - `query` > `loc`, for readabilitySame as V1, but step 1 uses `.query` to slice inside of `.loc`1. save a slice of the dataset with the names we want (using `.query`)2. sometimes a name is used by boys and girls in the same year, so combine the counts so that we have one observation per name per year3. save ...
# use query instead to slice, and the rest is the same somenames = baby_names.query('name in ["Sansa","Daenerys","Brienne","Cersei","Tyrion"] & \ year >= 2000') # this is one string with ' as the string start/end symbol. Inside, I can use # normal quote marks for strings. Also, I can b...
_____no_output_____
MIT
content/03/02f_chains-Copy1.ipynb
schemesmith/ledatascifi-2021
Version 3 - Method chaining!Method chaining: Call the object (`baby_names`) and then keep calling one method on it after another. - Python will call the methods from left to right. - There is no need to store the intermediate dataset (like `somenames` and `somenames_agg` above!) - --> Easier to read and write witho...
baby_names.query('name in ["Sansa","Daenerys","Brienne","Cersei","Tyrion"] & year >= 2000').groupby(['name','year'])['count'].sum().reset_index().pipe((sns.lineplot, 'data'),hue='name',x='year',y='count') plt.axvline(2011, 0,160,color='red') # add a line for when the show debuted
_____no_output_____
MIT
content/03/02f_chains-Copy1.ipynb
schemesmith/ledatascifi-2021
To make this readable, we write a parentheses over multiple lines```( and python knows to execute the code inside as one line)```And as a result, we can write a long series of methods that is comprehensible, and if we want we can even comment on each line:
(baby_names .query('name in ["Sansa","Daenerys","Brienne","Cersei","Tyrion"] & \ year >= 2000') .groupby(['name','year'])['count'].sum() # for each name-year, combine M and F counts .reset_index() # give us the column names back as they were (makes the plot call easy) .pipe((sns.lineplo...
_____no_output_____
MIT
content/03/02f_chains-Copy1.ipynb
schemesmith/ledatascifi-2021