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 |
|---|---|---|---|---|---|
It is important to keep in mind inherent or implied meaning of each axis. In the above example, here are the implied meanings:
*Batch size:* 3
*Depth*: 2
*Width*: 4
*Height*: 5 Indexing (See [here](https://www.tensorflow.org/guide/tensorindexing)) Single-axis indexing
TensorFlow follows standar... | # 6.0 Sample 1-axes tensor
rank_1_tensor = tf.constant([0, 1, 1, 2, 3, 5, 8, 13, 21, 34])
print(rank_1_tensor.numpy())
# 6.2 Indexing with a : slice keeps the axis:
#6.2.1 Everything
rank_1_tensor[:].numpy()
print()
#6.2.2 Before 4:
rank_1_tensor[:4].numpy()
print()
#6.2.3 From 4 to the end
rank_1_ten... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Manipulating shapes | # 7.0 Shape returns a `TensorShape` object
# that shows the size along each axis
x = tf.constant([[1], [2], [3]])
print(x.shape)
| _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
You can reshape a tensor into a new shape. The tf.reshape operation is fast and cheap as the underlying data does not need to be duplicated. | # 7.1 You can reshape a tensor to a new shape.
# Note that you're passing in a list
reshaped = tf.reshape(x, [1, 3])
reshaped.shape
# 7.2 We created this tensor earlier
print(rank_3_tensor) | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
If you flatten a tensor you can see what order it is laid out in memory. | #7.3 A `-1` passed in the `shape` argument
# says "Whatever fits".
print(tf.reshape(rank_3_tensor, [-1])) | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Typically the only reasonable use of tf.reshape is to combine or split adjacent axes (or add/remove 1s).
For this 3x2x5 tensor, reshaping to (3x2)x5 or 3x(2x5) are both reasonable things to do, as the slices do not mix: | # 7.4
print(tf.reshape(rank_3_tensor, [3*2, 5]), "\n")
print(tf.reshape(rank_3_tensor, [3, -1])) | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Reshaping can be a mess
Reshaping will "work" for any new shape with the same total number of elements, but it will not do anything useful if you do not respect the order of the axes. It will be a mess. | # 8.0 Bad examples: don't do this
# Only multiply adjacent indices
# 8.1 You can't reorder axes with reshape.
print(tf.reshape(rank_3_tensor, [2, 3, 5]), "\n")
# 8.2 This is a mess
print(tf.reshape(rank_3_tensor, [5, 6]), "\n")
| _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Broadcasting Broadcasting is a concept borrowed from the equivalent feature in NumPy. In short, under certain conditions, smaller tensors are "stretched" automatically to fit larger tensors when running combined operations on them.
The simplest and most common case is when you attempt to multiply or add a tensor to a... | # 9.0
x = tf.constant([1, 2, 3])
y = tf.constant(2)
z = tf.constant([2, 2, 2])
# 9.1
x * y
x + z | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Likewise, axes with length 1 can be stretched out to match the other arguments. Both arguments can be stretched in the same computation.
In this case a 3x1 matrix is element-wise multiplied by a 1x4 matrix to produce a 3x4 matrix. Note how the leading 1 is optional: The shape of y is [4]. | # 9.2 These are the same computations
x = tf.reshape(x,[3,1])
y = tf.range(1, 5)
# 9.2.1
print(x, "\n")
print(y, "\n")
print(tf.multiply(x, y))
# 9.2.2
x = tf.constant([1, 2, 3])
y = tf.constant(2)
z = tf.constant([2, 2, 2])
# 9.2.3 All of these are the same computation
print(tf.multiply(x, 2))
print(... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Logical operations | # 9.3 Logical operations on tensors
# Pl refer: tf.math
# https://www.tensorflow.org/api_docs/python/tf/math
print(tf.constant([1,2,10]) < 5)
print(tf.constant([True, False, True,True], dtype = tf.bool))
# 9.4 A tensor can be reshaped as per its shape argument
print(tf.constant(np.arange(20), ... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Define custom loss function
Refer: Page 384 of Book by Aurelion | # 10.0 Define a model
import pandas as pd
from tensorflow import keras
from sklearn.datasets import load_boston
# 10.1
X,y = load_boston(return_X_y= True)
X.shape # (506, 13)
# 10.2
model = keras.models.Sequential(
[
keras.layers.Dense(5, ac... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Huber loss
For a comparative picture of loss functions being used in Regression, see [here](https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0). Briefly, if data is noisy, use MAE and if their are more outliers or noise, use huber loss.
Huber loss is less sensitive... | # 10.3 Custom loss function
def huber_loss(y_true,y_pred):
error = y_true - y_pred
is_small_error = tf.abs(error) < 1.0
squared_loss = tf.square(error) / 2.0
linear_loss = tf.abs(error) - 0.5
return tf.where(is_small_error, squared_loss, linear_loss)
# 10.4 Compile and run the model with our loss fu... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Generate random tensors
Refer this [article](https://www.tensorflow.org/guide/random_numbers) | # 11.0 Generate random data using
# Generator object
g1 = tf.random.Generator.from_seed(1)
# 2.0.1 Use object 'g1'
g1.normal([2,3])
print()
# 2.0.2
g1.uniform([1])
print()
# 11.1 Generate random data
# directly
tf.random.uniform([4]) # shape is (4,)
print()
tf.random.uniform([4]).shape
pr... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
tf.data.Dataset API
Understanding Dataset object. The `tf.data.Dataset` API supports writing descriptive and efficient **input pipelines**. Dataset usage follows a common pattern (see [the right-panel here](https://www.tensorflow.org/api_docs/python/tf/data/Dataset) and a colab page with example [here](https://colab.r... | # 1.0 Call libraries
import numpy as np
import tensorflow_datasets as tfds
import tensorflow as tf
import matplotlib.pyplot as plt
import os
# 1.1 More libraries
from tensorflow.keras import utils
from tensorflow.keras import preprocessing
import pathlib
from tensorflow.keras.layers.experimental.preprocessing ... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Dataset objects from numpy-arrays in memory If all data is in memory, to create a `Dataset` object, use `Dataset.from_tensor_slices()` on numpy arrays (in memory). | # 3.0 Download numpy arrays to
# two objects (train,test) in memory
# 3.0.1 First delete any existing folder
!rm -rf /root/.keras/datasets
!ls -la /root/.keras
# 3.0.2 Next download data:
train, test = tf.keras.datasets.fashion_mnist.load_data()
# 3.0.3 Check downloaded files
! ls -la /root/.keras/datase... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Dataset objects from textfiles on disk
Please see this [tutorial](https://www.tensorflow.org/tutorials/load_data/text). We are downloading files from stackoverflow. The file contains questions asked on some subjects. (This section is to be completed.) Consuming CSV file See [Loading CSV Files](../tutorials/load_data/... | # 5.0 Download titanic file 'train.csv'
# from a URL:
import pandas as pd
titanic_file = tf.keras.utils.get_file(
"train.csv",
"https://storage.googleapis.com/tf-datasets/titanic/train.csv"
)... | survived:0
sex:b'male'
age:22.0
n_siblings_spouses:1
parch:0
fare:7.25
class:b'Third'
deck:b'unknown'
embark_town:b'Southampton'
alone:b'n'
| Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
A more scalable approach is to load from disk as necessary. The tf.data module provides methods to extract records from one or more CSV files fron disk.
The `experimental.make_csv_dataset` function is the high level interface for reading sets of csv files. It supports column type inference and many other features, lik... | # 6.2
batch_size = 4
titanic_batches = tf.data.experimental.make_csv_dataset(
titanic_file,
batch_size=batch_size,
label_name="survived"
... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
You can use the select_columns argument if you only need a subset of columns. | # 6.6
titanic_batches = tf.data.experimental.make_csv_dataset(
titanic_file, batch_size=4,
label_name="survived", select_columns=['class', 'fare', 'survived'])
# 6.7
for feature_batch, label_batch in titanic_batches.take(1):
print("'survived': {}".format(label_batch))
for key, value in feature_batch.i... | 'survived': [1 0 0 1]
'fare' : [12.288 8.654 52. 7.142]
'class' : [b'Third' b'Third' b'First' b'Third']
| Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Consuming text files Download file from a url
How to download a file from a URL.
This way any file can also be downloaded from *gdrive* without mounting it. Uses [`get_file()`](https://www.tensorflow.org/api_docs/python/tf/keras/utils/get_file) utility of `tf.keras.utils`. See this [example](https://www.tensorflow.or... | # 7.0 Which files are where:
!ls -la /root/.keras/
!ls -la /root/.keras/datasets
# 7.0.1 Deleting datasets dir
!rm -rf /root/.keras/datasets
# 7.1 Specify file URL from stackoverflow.
# Our file: stack_overflow_16k.tar.gz
data_url = 'https://storage.googleapis.com/download.tensorflow.org/data/stack_ov... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Create a dataset of text-lines | # 8.0 Files in 'train/python' folder
train_dir = "/root/.keras/datasets/train/"
python_files = os.listdir(train_dir + "python")
python_files[:3]
print()
# 8.0.1 Join directory path to file-names
files_with_path = [os.path.join(train_dir, file) for file in python_files]
files_with_path[:4]
# 8.1 tf.data.Dataset... | <bound method _EagerTensorBase.numpy of <tf.Tensor: shape=(), dtype=string, numpy=b'"blank submodule imports using __init__.py i\'m learning blank, and i can\'t figure out how imports in __init__.py work...i understand from the blank tutorial that the __init__.py file initializes a package, and that i can import subpac... | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Downloading data from gdrive | # 8.3 gdrive download: May also download a shared file from gdrive
# No need to mount gdrive
# Download 'archive.csv.zip' from my gdrive:
gdrive_url = "https://drive.google.com/file/d/14gjcWMRJORJ4bQ2QerWaodDpLi5oDcxM/view?usp=sharing"
# 8.3.1 Use keras get_file() utility
dnld_gdrive = utils.get_file(
... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
preprocessing data
The Keras preprocessing layers API allows developers to build Keras-native input processing pipelines. These input processing pipelines can be used as independent preprocessing code in non-Keras workflows, combined directly with Keras models, and exported as part of a Keras SavedModel.
With Keras... | # 9.0 Our stackoverflow training data is here:
train_dir = "/root/.keras/datasets/train"
# 9.0.1 Some constants
batch_size = 32
seed = 42
# 9.1 Create a training dataset object
raw_train_ds = preprocessing.text_dataset_from_directory(
train_dir,
... | Found 8000 files belonging to 4 classes.
| Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Text Vectorization
Once our train, test and validation datasets are ready, we proceed to feed textvectorization layer.
Using `preprocessing.TextVectorization` layer. Its [full syntax](https://www.tensorflow.org/api_docs/python/tf/keras/layers/experimental/preprocessing/TextVectorization) is:
`tf.keras.layers.experi... | from tensorflow.keras.layers.experimental import preprocessing | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Simple **experiment** | data = [
"The title of Rachel Levin’s book, Look Big, is"
"just about the best two words of advice one can"
" give about how to survive most animal encounters."
"In her illustrated service manual, Levin breaks down"
"how to handle 50 different kinds of animals commo... | _____no_output_____ | Apache-2.0 | tf data API.ipynb | harnalashok/deeplearning-sequences |
Zebrafish Double coiling model Below is the block of code to run double coiling models INITIALIZE - Run before running the models to set the parameters | %matplotlib inline
### FIRST, run this code to set the simulation parameters. Then select from the codes below to run different models
#Declare the duration of the simulation
TIME_END = 100000
SKIP = 200
PLOT_INTERVAL = 10000
PLOT_RESULT = True
PRINT_PARAM = False
SAVE_CSV = True
SAVE_ANIM = True
import winsound
dur... | _____no_output_____ | MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
Base Model |
from Double_coiling_model import Double_coil_base
print("Base Model")
test = Double_coil_base(dt = 0.1, stim0 = 35, sigma = 0,
E_glu = 0, E_gly = -58, cv = 1, nIC = 5, nMN = 10, nV0d = 10, nV0v=10, nV2a=10, nMuscle = 10)
#test.setWeightParameters(V0d_IC_syn_weight = 2.0, V0d_MN_syn_weight = 2.0, V0d... | _____no_output_____ | MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
Glycine Null | from Double_coiling_glycine_null import Double_coil_glycine_null
print("Glycine Null Model")
test = Double_coil_glycine_null(dt = 0.1, stim0 = 35, sigma = 0,
E_glu = 0, E_gly = -58, cv = 1, nIC = 5, nMN = 10, nV0d = 10, nV0v=10, nV2a=10, nMuscle = 10)
test.setWeightParameters(V0d_IC_syn_weight=0, V0d... | _____no_output_____ | MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
V0v Overexcitation |
from Double_coiling_with_Tonic_drive_to_IC_overexcitation_of_V0v import Double_coil_with_Tonic_drive_to_IC_overexcitation_of_V0v
print("IC Tonic Drive Model")
test = Double_coil_with_Tonic_drive_to_IC_overexcitation_of_V0v(dt = 0.1, stim0 = 35, sigma = 0.1,
E_glu = 0, E_gly = -58, cv = 1, nIC = 5, n... | _____no_output_____ | MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
V2a KO |
from Double_coiling_V2a_KO import Double_coil_V2a_KO
print("V2a Knockout Model")
test = Double_coil_V2a_KO(dt = 0.1, stim0 = 35, sigma = 0,
E_glu = 0, E_gly = -58, cv = 1, nIC = 5, nMN = 10, nV0d = 10, nV0v=10, nV2a=10, nMuscle = 10)
test.setWeightParameters(V0d_IC_syn_weight = 8, V0d_MN_syn_weight ... | _____no_output_____ | MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
No excitatory Synapse |
from Double_coiling_no_excitatory_syn import Double_coil_no_excitatory_syn
print("No Excitatory Synapse Model")
test = Double_coil_no_excitatory_syn(dt = 0.1, stim0 = 35, sigma = 0,
E_glu = 0, E_gly = -58, cv = 1, nIC = 5, nMN = 10, nV0d = 10, nV0v=10, nV2a=10, nMuscle = 10)
test.setWeightParameters... | _____no_output_____ | MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
V0v to IC Null |
from Double_coiling_V0v_to_IC_null import Double_coil_V0v_to_IC_null
print("V0v to IC null Model")
test = Double_coil_V0v_to_IC_null(dt = 0.1, stim0 = 35, sigma = 0.001,
E_glu = 0, E_gly = -58, cv = 1, nIC = 5, nMN = 10, nV0d = 10, nV0v=10, nV2a=10, nMuscle = 10)
test.setWeightParameters(V0d_IC_syn_... | _____no_output_____ | MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
30 Somites |
from Double_coiling_30_somites import Double_coil_30_somites
print("30 somites Model")
test = Double_coil_30_somites(dt = 0.1, stim0 = 50, sigma = 0,
E_glu = 0, E_gly = -58, cv = 1, nIC = 5, nMN = 30, nV0d = 30, nV0v=30, nV2a=30, nMuscle = 30)
test.setWeightParameters(V0d_IC_syn_weight = 2, V0d_MN_s... | 30 somites Model
| MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
Sigma | from Double_coiling_with_sigmas import Double_coil_with_sigmas
print("Sigma Model")
test = Double_coil_with_sigmas(dt = 0.1, stim0 = 35, sigmaD=0.2, sigmaL = 0, sigmaP = 0, sigmaW=0,
E_glu = 0, E_gly = -58, cv = 1, nIC = 5, nMN = 10, nV0d = 10, nV0v=10, nV2a=10, nMuscle = 10)
test.setWeightParameters... | _____no_output_____ | MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
Chemical and Gap Sigmas | from Double_coiling_with_sigmas_chem_syn_and_gap import Double_coil_with_gap_chem_sigma
print("Chemical and Gap Sigmas")
test = Double_coil_with_gap_chem_sigma(dt = 0.1, stim0 = 35, sigma_chem = 0, sigma_gap = 0,
E_glu = 0, E_gly = -58, cv = 1, nIC = 5, nMN = 10, nV0d = 10, nV0v=10, nV2a=10, nMuscle ... | _____no_output_____ | MIT | Zebrafish spinal locomotor circuit/Version 2/Double coiling model notebook.ipynb | Bui-lab/Code |
Competencia de Kaggle[ir a Kaggle](https://www.kaggle.com/c/rossmann-store-sales/data)[3er puesto](https://github.com/entron/entity-embedding-rossmann) Métrica de la competencia $$\textrm{RMSPE} = \sqrt{\frac{1}{n} \sum_{i=1}^{n} \left(\frac{\hat{y}_i - y_i}{y_i}\right)^2}$$donde:- $y_i$ las ventas de un día particul... | from google.colab import drive
drive.mount('/content/drive') | Mounted at /content/drive
| MIT | 04-rossman/kaggle-rossmann-master/01-data-visualization.ipynb | rocioparra/redes-neuronales |
Importamos dataset La competencia permitía agregar datos externos para realizar la predicción The following tables are available in the datasets:| Archivo | Descripción| Origen de Datos||--------------|--------------------------------------------------------------------|--|| train.csv | training set: infor... | PATH = '/content/drive/My Drive/Colab Notebooks/kaggle-rossmann-master/rossmann/rossmann/'
table_names = ['train', 'store', 'store_states', 'state_names', 'googletrend', 'weather']
train, store, store_states, state_names, googletrend, weather = [pd.read_csv(PATH + fname+'.csv',
... | _____no_output_____ | MIT | 04-rossman/kaggle-rossmann-master/01-data-visualization.ipynb | rocioparra/redes-neuronales |
- Mirar counts que todos tienen la misma cantidad- Ninguno tiene missing- Los tipos tambien es interesante observar | train['StateHoliday'].value_counts()
display(store.head())
display(DataFrameSummary(store).summary()) | _____no_output_____ | MIT | 04-rossman/kaggle-rossmann-master/01-data-visualization.ipynb | rocioparra/redes-neuronales |
Descripción de algunas columnas que quizas no sean tan claras:- `Customers`: La cantidad de clientes por día- `Open`: Indicador si el store estaba abierto o cerrado: 0 = closed, 1 = open- `StateHoliday`: Indica feriado en ese estado. a = public holiday, b = Easter holiday, c = Christmas, 0 = None- `SchoolHoliday`: Inid... | store['StoreType'].value_counts()
store['PromoInterval'].value_counts()
display(store_states.head(20))
display(DataFrameSummary(store_states).summary())
display(state_names.head(20))
display(DataFrameSummary(state_names).summary())
display(googletrend)
display(DataFrameSummary(googletrend).summary())
display(weather)
d... | _____no_output_____ | MIT | 04-rossman/kaggle-rossmann-master/01-data-visualization.ipynb | rocioparra/redes-neuronales |
Creating a Model for Immigration and Outsider LanguageThis notebook starts with a baseline system and then provides users the opportunity to attempt to improve performance with their own custom, complete system. Set-up | %%capture
!pip install datasets
!pip install transformers
import re
from collections import Counter
import datasets
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import accuracy_score, confusion_matrix,... | _____no_output_____ | MIT | Immigration.ipynb | hlab-repo/purity-and-danger |
Getting a test dataset We can start with the Common Crawl news corpus (January 2017 - December 2019). See here for details:https://huggingface.co/datasets/cc_newsThis will constitute our test dataset. Note that the pseudolabels were generated from the beginning of this dataset but that the dataset (of 708,241 news art... | # this could take several minutes
dataset = datasets.load_dataset('cc_news')
dataset
# look at the first 10 samples
for i, s in enumerate(dataset['train']):
print(s)
if i >= 10:
break | {'date': '2017-04-17 00:00:00', 'description': "Officials unsealed court documents Monday (April 17) to reveal details surrounding the first searches of Prince's Paisley Park estate.", 'domain': '1041jackfm.cbslocal.com', 'image_url': 'https://cbs1041jackfm.files.wordpress.com/2017/04/prince-young-and-sad.jpg?w=946', '... | MIT | Immigration.ipynb | hlab-repo/purity-and-danger |
Getting pseudo-labeled data for training`0` represents viral language, `1` immigration language, and `2` a blend of the two. These categorizations are fuzzy and inexact and are not the result of manual annotations. They should be improved upon during the training process (or adjusted manually) when possible. | df = pd.read_csv('https://www.dropbox.com/s/kfbja23kisimedm/immigration.csv?dl=1')
df.head()
X_train, X_valid, y_train, y_valid = train_test_split(df['text'], df['target'], train_size=0.7, random_state=42)
X_valid, y_valid | _____no_output_____ | MIT | Immigration.ipynb | hlab-repo/purity-and-danger |
Baseline 1Let's use Naive Bayes. For the sake of simplicity, I will not add weighting to the classes here (we probably should!), but sklearn wants its weights to correspond to samples in the train dataset (when using the fit method). So you would need to feed in a list of weights the same length as your samples. Think... | vectorizer = TfidfVectorizer()
train_vectorized = vectorizer.fit_transform(X_train)
valid_vectorized = vectorizer.transform(X_valid)
train_vectorized
naive_bayes = MultinomialNB()
naive_bayes.fit(train_vectorized, y_train)
predictions = naive_bayes.predict(valid_vectorized)
predictions
print(f'Accuracy: {accuracy_score... | _____no_output_____ | MIT | Immigration.ipynb | hlab-repo/purity-and-danger |
Baseline 2 | model = BertForSequenceClassification.from_pretrained('bert-large-uncased', num_labels=3)
tokenizer = BertTokenizer.from_pretrained('bert-large-uncased')
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = model.to(device)
# the classes are extremely unbalanced; let's generate weights that we ... | _____no_output_____ | MIT | Immigration.ipynb | hlab-repo/purity-and-danger |
Your Original SystemImprove upon the baselines above. Feel free to copy cells from one of the baselines above, paste it here, and tweak it for improvements. You have several models to select from from sklearn (both for classification and for vectorization of text). And even just trying different architectures for Basl... | _____no_output_____ | MIT | Immigration.ipynb | hlab-repo/purity-and-danger | |
592B, Class 11.2 (11/14). Filtering review | import numpy as np
import matplotlib.pyplot as plt
import scipy.io.wavfile as wavfile
import scipy.signal as signal
from scipy import fftpack
from ipywidgets import interactive
from IPython.display import Audio, display | _____no_output_____ | MIT | class_11-2/592B-F19-class_11-2.ipynb | ling592b-f19/592b-f19-class |
Review question: filtering and "translating" to cepstral analysisRemember this from last week? Here I've chosen a small frequency for `y1` and a higher frequency for `y2`. | def plot_play_summed_sines(f1 = 50, f2 = 880, t_start = 0, t_stop = 1, fs = 2000, xlim_max = 0.01):
x = np.linspace(t_start, t_stop, fs * (t_stop - t_start))
y1 = np.sin(2*np.pi*f1*x)
y2 = np.sin(2*np.pi*f2*x)
plt.xlim(t_start,xlim_max)
plt.plot(x , y1, "-g", label="y1")
plt.plot(x , y2, "... | _____no_output_____ | MIT | class_11-2/592B-F19-class_11-2.ipynb | ling592b-f19/592b-f19-class |
9. Import a time series In this tutorial we are adding a timeseries to the DataStore object. This might be useful if the temperature in one of the calibration baths was measured with an external device. It requires three steps to add the measurement files to the DataStore object:1. Load the measurement files (e.g., cs... | import pandas as pd
import os
from dtscalibration import read_silixa_files | /Users/bfdestombe/anaconda3/envs/dts/lib/python3.7/typing.py:847: FutureWarning: xarray subclass DataStore should explicitly define __slots__
super().__init_subclass__(*args, **kwargs)
| BSD-3-Clause | examples/notebooks/09Import_timeseries.ipynb | bdestombe/python-dts-calibration |
Step 1: load the measurement files | filepath = os.path.join('..', '..', 'tests', 'data',
'external_temperature_timeseries',
'Loodswaternet2018-03-28 02h.csv')
# Bonus:
print(filepath, '\n')
with open(filepath, 'r') as f:
head = [next(f) for _ in range(5)]
print(' '.join(head))
ts = pd.read_csv(filepa... | _____no_output_____ | BSD-3-Clause | examples/notebooks/09Import_timeseries.ipynb | bdestombe/python-dts-calibration |
Now we quickly create a DataStore from xml-files with Stokes measurements to add the external timeseries to | filepath_ds = os.path.join('..', '..', 'tests', 'data', 'double_ended2')
ds = read_silixa_files(directory=filepath_ds,
timezone_netcdf='UTC',
file_ext='*.xml') | 6 files were found, each representing a single timestep
6 recorded vars were found: LAF, ST, AST, REV-ST, REV-AST, TMP
Recorded at 1693 points along the cable
The measurement is double ended
Reading the data from disk
| BSD-3-Clause | examples/notebooks/09Import_timeseries.ipynb | bdestombe/python-dts-calibration |
Step 2: Add the temperature measurements of the external probe to the DataStore.First add the coordinates | ds.coords['time_external'] = ts.index.values | _____no_output_____ | BSD-3-Clause | examples/notebooks/09Import_timeseries.ipynb | bdestombe/python-dts-calibration |
Second we add the measured values | ds['external_probe'] = (('time_external',), ts) | _____no_output_____ | BSD-3-Clause | examples/notebooks/09Import_timeseries.ipynb | bdestombe/python-dts-calibration |
Step 3: Align the time of the external measurements to the Stokes measurement timesWe linearly interpolate the measurements of the external sensor to the times we have DTS measurements | ds['external_probe_dts'] = ds['external_probe'].interp(time_external=ds.time)
print(ds.data_vars) | Data variables:
st (x, time) float64 1.281 -0.5321 ... -43.44 -41.08
ast (x, time) float64 0.4917 1.243 ... -30.14 -32.09
rst (x, time) float64 0.4086 -0.568 ... 4.822e+03
rast (x, time) float64 2.569 -1.603 ... 4.224e+03
tm... | BSD-3-Clause | examples/notebooks/09Import_timeseries.ipynb | bdestombe/python-dts-calibration |
**Model Validation** >[Index predictor](p) >[Cluster comparison](cc) >[Predictand computation and plotting](plv) **After analizing the tailor-made predictor along the hindcast data for the calibration period (1982-2019), the performace of the model will be validated for year 2020, which has not been included in th... | path_val = r'/home/administrador/Documentos/seasonal/seasonal_forecast/validation/'
year_val = 2020
change_sst_resolution_val(path_val,year_val) | Start time: 2021-04-12 09:57:46.179185
End time: 2021-04-12 10:01:47.651739
| MIT | _build/jupyter_execute/j06.ipynb | AndreaPozo/Master_thesis |
**Generation of the index predictor based on the index function obtained at the calibration period.** | xs_val = ds_index_over_time_val(path_val,path_p,year_val)
xs_val | _____no_output_____ | MIT | _build/jupyter_execute/j06.ipynb | AndreaPozo/Master_thesis |
**The fitted Principal Component Analysis for the calibration is used to predict the index principal components in that same temporal-spatial space and the predicted PCs are assigned to the best match unit group from the fitted K-means clustering -> based on the index predictor a DWT is assigned to each day.** | val_bmus = PCA_k_means_val(path_p,path_val,xs_val) | K-means order previously obtained in the calibration period:
[11 27 28 45 16 23 47 19 7 14 0 31 46 30 34 35 15 2 8 33 37 41 5 10
48 4 40 21 3 20 42 29 38 26 32 43 13 17 18 39 25 22 44 9 1 24 6 12
36]
DWTs for the validation period and their counting:
(array([ 6, 8, 9, 12, 15, 17, 18, 24, 25, 26, 27... | MIT | _build/jupyter_execute/j06.ipynb | AndreaPozo/Master_thesis |
**Chronology of the DWTs:** | fig_bmus = plot_bmus_chronology(xs_val,val_bmus,year_val) | _____no_output_____ | MIT | _build/jupyter_execute/j06.ipynb | AndreaPozo/Master_thesis |
**The resulting classification can be seen in the PCs space of the predictor index data. The obtained centroids (black dots), span the wide variability of the data.** | fig = plot_scatter_kmeans(xds_kma_ord, val_bmus, xds_kma_ord.cenEOFs.values, size_l=12, size_h=10); | _____no_output_____ | MIT | _build/jupyter_execute/j06.ipynb | AndreaPozo/Master_thesis |
**Cluster comparison** | fig = plot_bmus_comparison_validation_calibration(xs,xds_kma,xs_val,val_bmus,9,49) | _____no_output_____ | MIT | _build/jupyter_execute/j06.ipynb | AndreaPozo/Master_thesis |
**Predictand computation and plotting** **From the DWT the daily expected mean number of TCs in 8x8º cells in the target area is known for each day and thus maps at different time scales can be computed.** **Daily mean expected number of TCs** | xds_timeline_val,xs_M_val = ds_monthly_probabilities_val(df_2021,val_bmus,xs_val,xs_dwt_counts,xs_dwt_counts_964) | _____no_output_____ | MIT | _build/jupyter_execute/j06.ipynb | AndreaPozo/Master_thesis |
**Monthly aggregated mean expected number of TCs** | xs_M_val
fig_val_year_8 = plot_validation_year(df_2021,xs_M_val,xds_timeline_val,35) | _____no_output_____ | MIT | _build/jupyter_execute/j06.ipynb | AndreaPozo/Master_thesis |
**Whole period aggregated mean expected number of TCs** | fig_val_year_8 = plot_validation_full_season(df_2021,xs_M_val,xds_timeline_val,35) | _____no_output_____ | MIT | _build/jupyter_execute/j06.ipynb | AndreaPozo/Master_thesis |
Parte 1: Iteração de RayleighVimos que podemos iterar um vetor $v$ pela matriz $A$, obtendo a sequência de vetores $A^nv$, por multiplicações sucessivas, e que isso permite encontrar um autovetor. Questão 1Implemente uma função `itera(A,v,tol,debug)` que itera o vetor $v$, normalizando a cada iteração, e que retorna ... | def itera(A,v, tol=1e-12, maxiter=1000, debug=False):
v = np.array(v)
n,m = np.shape(A)
assert n==m, 'A must be square'
def eigenvector_normalizer(A,v,n=29):
answ = []
answ.append(v)
for i in range(0,n):
v_next = A @ answ[-1]
answ.append(v_next/np.lin... | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
Questão 2: ConvergênciaTemos o número de iterações, mas não vimos como o algoritmo "converge" para o autovetor.Assim, use os vetores intermediários e faça um gráfico da evolução do erro entre os $v$'s produzidos e o autovetor $v_\lambda$. | ax = None
v,l,n, vs_intermediarios = itera(A, np.random.rand(4), debug=True)
tam = len(vs_intermediarios)
rng = (0,n)
ks = [([v]*tam)/i for i in vs_intermediarios]
#plt.plot(ks,rng)
ax = plt.gca()
plt.show()
assert ax.title.get_text() != ""
assert len(ax.lines) == 1
ys = ax.lines[0].get_ydata()
assert min(ys) < 1e-1... | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
O que o último assert quer dizer? Compara se o $ys[i]$ é menor que $ys[i-1]$, ou seja, se a lista está convergindo Questão 3: Convergência comparadaPara cada um dos vetores `d1` e `d2` abaixo, considere a matriz $A = \operatorname{diag}(d_i)$ correspondente. | d1 = [1,10,20,30,31,32]
d2 = [1,10,20,29,30,32] | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
Qual é o autovetor com o maior autovalor para $A_1$ e $A_2$? YOUR ANSWER HERE Agora, compare a velocidade de convergência do autovetor usando `itera` para cada uma destas matrizes,fazendo o gráfico do erro entre os vetores gerados para $A_1$ e $A_2$ no mesmo eixo. | ax = []
_,_,_,l_1 = itera(np.diag(d1), np.ones_like(d1), debug=True)
_,_,_,l_2 = itera(np.diag(d2), np.ones_like(d2), debug=True)
# YOUR CODE HERE
raise NotImplementedError()
ax = plt.gca()
plt.show()
assert ax.title.get_text() != ""
assert len(ax.lines) == 2
assert len(ax.legend().texts) == 2 | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
Para qual matriz há convergência mais rápida? Como você explicaria isso? YOUR ANSWER HERE Questão 4: Convergência?Sejam $\theta \in [0,2\pi]$ e $\alpha \in \mathbb{R}$,e considere a matriz $$A(\theta, \alpha) = \begin{bmatrix} \cos(\theta) & \sin(\theta) & 0\\-\sin(\theta) &\cos(\theta) & 0\\0 & 0 & \alpha\\\end{bma... | def make_matrix(theta,alpha):
# YOUR CODE HERE
raise NotImplementedError()
assert np.allclose(make_matrix(0,1),np.eye(3))
assert np.allclose(make_matrix(np.pi,0.5),[[-1,0,0],[0,-1,0],[0,0,0.5]]) | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
Fixando $\theta = \dfrac{\pi}{4}$,faça um gráfico do número de iterações necessários para calcular o maior autovetor,em função de $\alpha \in [0.5,1.5]$. | alphas = np.linspace(0.5,1.5,100)
ax = []
# YOUR CODE HERE
raise NotImplementedError()
ax = plt.gca()
plt.show()
assert ax.title.get_text() != ""
assert len(ax.lines) == 1
assert ax.get_xlabel() != ""
ys = ax.lines[0].get_ydata()
assert 100 > ys.min() > 60
assert ys[55] < 600
assert ys[50] > 900 | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
Agora, faça o gráfico com a estimativa do autovalor, novamente em função de $\alpha$. | ax = []
# YOUR CODE HERE
raise NotImplementedError()
ax = plt.gca()
plt.show()
assert ax.title.get_text() != ""
assert len(ax.lines) == 1
assert ax.get_xlabel() != ""
ys = ax.lines[0].get_ydata()
assert np.all(0.7 <= ys) and np.all(ys <= 1.5) | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
Como explicar a variação no número de iterações? O que isso tem a ver com o autovalor retornado? YOUR ANSWER HERE Parte 2: Generalizando Questão 5: Outra iteração, novos limitesEm vez de iterar $A^n v$, é possível iterar $A^{-n} v$.Assim, em vez de "aumentar" os vetores correspondentes aos autovalores de módulo grande... | def inverse_iteration(A, v, alpha=0, tol=1e-12, maxiter=1000, debug=False):
v = np.array(v)
n,m = np.shape(A)
assert n==m, 'A must be square'
# YOUR CODE HERE
raise NotImplementedError()
A = [[1,2],[2,1]]
ans = np.array([-1,1])/np.sqrt(2)
v, l, n = inverse_iteration(A,[1,2])
assert np.allclose(n... | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
Questão 7: Convergência comparadaFaça o gráfico da velocidade de convergência dos autovetores da iteração inversa aplicada à matriz $A$ acima,para $\alpha \in \{-2,0,2\}$. | np.random.seed(1234)
ax = []
v0 = np.random.rand(2)
# YOUR CODE HERE
raise NotImplementedError()
plt.ylabel('Distance to eigenvector')
ax = plt.gca()
plt.show()
assert ax.title.get_text() != ""
assert len(ax.lines) == 3
assert len(ax.legend().texts) == 3
assert ax.get_xlabel() != ""
ys = [l.get_ydata() for l in a... | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
Qual valor de $\alpha$ levou à convergência mais rápida?Como você explicaria isso? YOUR ANSWER HERE O que mais você observa neste gráfico? YOUR ANSWER HERE Questão 8: Zoom da convergência Agora, repita o mesmo gráfico para $\alpha \in \{2, 2.5, 2.9, 2.99 \}$. | np.random.seed(1234)
ax = []
v0 = np.random.rand(2)
# YOUR CODE HERE
raise NotImplementedError()
plt.ylabel('Distance to eigenvector')
ax = plt.gca()
plt.show()
assert ax.title.get_text() != ""
assert len(ax.lines) == 4
assert len(ax.legend().texts) == 4
assert ax.get_xlabel() != ""
ys = [l.get_ydata() for l in a... | _____no_output_____ | MIT | comp-cientifica-I-2018-2/Teste8.ipynb | mirandagil/university-courses |
Homework 1: Classification With Naive Bayes Problem 1: Diabetes ClassificationPoints: 40A famous collection of data on whether a patient has diabetes, known as the Pima Indians dataset, and originally owned by the National Institute of Diabetes and Digestive and Kidney Diseases can be found at Kaggle. Download this d... | !pip install pandas_profiling
import pandas as pd
import numpy as np
import math
from scipy.stats import norm
import pandas_profiling
import pickle
import matplotlib.pyplot as plt
%matplotlib inline
import warnings
warnings.filterwarnings("ignore") | _____no_output_____ | MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
Load datasetAccess https://www.kaggle.com/kumargh/pimaindiansdiabetescsv, download the dataset, it will download pimaindiansdiabetescsv.zip. Dataset dictionaryFollowing are the datset details as per kaggle.About this fileThis dataset describes the medical records for Pima Indians and whether or not each patient will ... | #pima_indias_diabetes_data = pd.read_csv("/content/gdrive/My Drive/UIUC-MCS-DS/CS498AML/homework_1/1a/data/pima-indians-diabetes.csv")
#pickle.dump(pima_indias_diabetes_data, open( '/content/gdrive/My Drive/UIUC-MCS-DS/CS498AML/homework_1/1a/data/pima_indias_diabetes_data.pkl','wb'))
pima_indias_diabetes_data = pd.rea... | _____no_output_____ | MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
Exploratory Data Analysis Validate dataset | # rename column names
pima_indias_diabetes_data.columns = ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age', 'Class']
pima_indias_diabetes_data.head()
# count number of dataset
print("There are a total of", len(pima_indias_diabetes_data),"data-points")
pima... | (767, 8)
(767, 1)
| MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
There are 767 observations of 8 different features. Analyse label | count_classes = pd.value_counts(pima_indias_diabetes_data['Class'], sort = True).sort_index()
count_classes.plot(kind = 'bar')
plt.title("Pima Indians diabetes class histogram")
plt.xlabel("Class")
plt.ylabel("Frequency")
# 284315 normal transactions (class 0)
# 492 fraud transactions (class 1)
pima_indias_diabetes_d... | _____no_output_____ | MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
There are 500 Pima Indians 0: tested negative for diabetes, 267 :tested positive for diabetes. Data distribution analysis for each feature and class labelPlot the data by each feature | axarr = [[]]*len(pima_indias_diabetes_data_features.columns)
columns = 4
rows = int( np.ceil( len(pima_indias_diabetes_data_features.columns) / columns ) )
f, fig = plt.subplots( figsize=(columns*3.5, rows*2) )
f.suptitle('Data Distributions by Feature and Class', size=16)
for i, col in enumerate(pima_indias_diabetes... | _____no_output_____ | MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
Classify Dataset - Build a simple naive Bayes classifier Split data |
def train_test_split(features, labels, test_size=0.2):
np.random.seed(4)
id = np.random.rand(len(features))>test_size
#print(id)
features_train = features[id]
labels_train = labels[id]
features_test = features[np.invert(id)]
labels_test = labels[np.invert(id)]
return features_train, lab... | _____no_output_____ | MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
Gaussian Naive Bayes classifierIn Gaussian Naive Bayes, continuous values associated with each feature are assumed to be distributed according to a Gaussian distribution. A Gaussian distribution is also called Normal distribution. The likelihood of the features is assumed to be Gaussian, hence, conditional probability... | class GaussianNaiveBayes():
"""The Gaussian Naive Bayes classifier. """
def fit(self,features, labels):
"""
for each label and feature combination we need to calculate the std and mean value from the features & labels.
"""
self.min_std = 0.00000001
self.ntargets= np.unique(labels).... | _____no_output_____ | MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
Compute an estimate of the accuracy of the classifier by averaging over 10 test-train splits. Each split should randomly assign 20% of the data to test, and the rest to train. | print(features.shape)
test_accuracy_iterations =[]
# for 10 iterations
for i in range(10):
features_train, labels_train, features_test, labels_test = train_test_split(features.values,
labels.values, test_size=0.2)
nb = GaussianNaiveBayes()
nb.fit(features_train, labels_train)... | (767, 8)
[0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593]
Average test accuracy 0.7724550898203593
| MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
Validate using scikit learn naive bayes | from sklearn import naive_bayes
test_accuracy_iterations =[]
# for 10 iterations
for i in range(10):
features_train, labels_train, features_test, labels_test = train_test_split(features.values, labels.values, test_size=0.2)
snb = naive_bayes.GaussianNB()
snb.fit(features_train, labels_train)
test_accuracy = s... | [0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593, 0.7724550898203593]
Average test accuracy 0.7724550898203593
| MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
Part 1BNow adjust your code so that, for attribute 3 (Diastolic blood pressure), attribute 4 (Triceps skinfold thickness), attribute 6 (Body mass index), and attribute 8 (Age), it regards a value of 0 as a missing value when estimating the class-conditional distributions, and the posterior. * Compute an estimate of ... | pima_indias_diabetes_data[['BloodPressure','SkinThickness','BMI','Age']]= pima_indias_diabetes_data[['BloodPressure','SkinThickness','BMI','Age']].replace(0, np.NaN)
print(pima_indias_diabetes_data.isnull().sum())
#pima_indias_diabetes_data.dropna(inplace=True)
print(pima_indias_diabetes_data.isnull().sum())
pima_in... | _____no_output_____ | MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
After processing the missing data split data and build new model with new train dataset and test he accuracy. | processed_features = pima_indias_diabetes_data.drop('Class', axis = 1)
processed_labels = pima_indias_diabetes_data['Class']
#scaler = StandardScaler()
#normal_processed_features = scaler.fit_transform(processed_features)
processed_test_accuracy_iterations =[]
# for 10 iterations
for i in range(10):
p_features_train... | [0.7425149700598802, 0.7425149700598802, 0.7425149700598802, 0.7425149700598802, 0.7425149700598802, 0.7425149700598802, 0.7425149700598802, 0.7425149700598802, 0.7425149700598802, 0.7425149700598802]
Average test accuracy for processed data 0.7425149700598802
| MIT | homework 1/1a/homework_1_1a_b.ipynb | sriharshams/cs498aml |
The Knapsack Problem by Stefano Gualandi is licensed under a Creative Commons Attribution 4.0 International License.Based on a work at https://github.com/mathcoding/opt4ds. **NOTE:** Run the following script whenever running this script on a Google Colab. | import shutil
import sys
import os.path
if not shutil.which("pyomo"):
!pip install -q pyomo
assert(shutil.which("pyomo"))
if not (shutil.which("glpk") or os.path.isfile("glpk")):
if "google.colab" in sys.modules:
!apt-get install -y -qq glpk-utils
else:
try:
!conda install ... | _____no_output_____ | MIT | aa2021/notebooks/N-Queens.ipynb | gianlucacovini/opt4ds |
$n$-Queens ProblemThe $n$-Queens puzzle is the problem of placing eight chess queens on an $n \times n$ chessboard so that no two queens threaten each other; thus, a solution requires that no two queens share the same row, column, or diagonal (source: [wikipedia](https://en.wikipedia.org/wiki/Eight_queens_puzzle)). A ... | n = 5
for j in range(-n+2,n-1):
for i in range(1, n+1):
if 0 < j+i <= n:
print(i, j+i, end='\t')
else:
print(' ', end='\t')
print() | _____no_output_____ | MIT | aa2021/notebooks/N-Queens.ipynb | gianlucacovini/opt4ds |
Off Diagonals $_k$Similarly, we can define the off diagonals as follows: | for i in reversed(range(-n+3, n)):
for j in range(1, n):
if 0 < n - j+i <= n:
print(j, n-j+i, end='\t')
else:
print(' ', end='\t')
print() | _____no_output_____ | MIT | aa2021/notebooks/N-Queens.ipynb | gianlucacovini/opt4ds |
Full Model defined in PyomoIf we put all the definitions together, we can solve the $n$-Queens problem with the script below.Please, note the following Pyomo syntax used to define variable $x_{ij}$ over the [RangeSet](https://pyomo.readthedocs.io/en/stable/library_reference/aml/index.htmlpyomo.environ.RangeSet) $I$ an... | # Import the libraries
from pyomo.environ import ConcreteModel, Var, Objective, Constraint, SolverFactory
from pyomo.environ import maximize, Binary, RangeSet, ConstraintList
n = 8
# Create concrete model
model = ConcreteModel()
model.I = RangeSet(1, n)
model.J = RangeSet(1, n)
# Variables
model.x = Var(model.I, m... | _____no_output_____ | MIT | aa2021/notebooks/N-Queens.ipynb | gianlucacovini/opt4ds |
To solve the script, we use a solver factory, specifying the GLPK solver, and we inspect the Solver **status** (infeasible, unbounded, or optimal). | # Solve the model
sol = SolverFactory('glpk').solve(model)
# Basic info about the solution process
for info in sol['Solver']:
print(info) | _____no_output_____ | MIT | aa2021/notebooks/N-Queens.ipynb | gianlucacovini/opt4ds |
We aspect the optimal decision variables (only the positive variables). | # Report solution value
print("Optimal solution value: z =", model.obj())
print("Decision variables:")
for i in model.I:
for j in model.J:
if model.x[i,j]() > 0:
print("x({},{}) = {}".format(i, j, model.x[i,j]())) | _____no_output_____ | MIT | aa2021/notebooks/N-Queens.ipynb | gianlucacovini/opt4ds |
And finally, we print a solution on a simplified chessboard $n\times n$. | print('\nChessboard Solution:')
for i in model.I:
for j in model.J:
if model.x[i,j]() > 0:
print('Q', end=' ')
else:
print('.', end=' ')
print() | _____no_output_____ | MIT | aa2021/notebooks/N-Queens.ipynb | gianlucacovini/opt4ds |
Plotting a solution with a Chessboard | # CREDIT: Solution original appeared on Stackoverflow at:
# https://stackoverflow.com/questions/60608055/insert-queen-on-a-chessboard-with-pyplot
def PlotSolution(n, x, size=6):
import matplotlib.pyplot as plt
import numpy as np
chessboard = np.zeros((n, n))
chessboard[1::2,0::2] = 1
chessboard[0... | _____no_output_____ | MIT | aa2021/notebooks/N-Queens.ipynb | gianlucacovini/opt4ds |
**Title**: Upload kaggle chest X-Ray. **Date**: 12-Oct-2020 **Description**: Pneumonia accounts for over 15% of all deaths of children under 5 years old internationally. Advanced detection of pneumonia could save thousands of lives a year.In 2018 the RSNA Pneumonia Detection Challenge was posted on Kaggle, an o... | %reload_ext autoreload
%autoreload 2
%matplotlib inline | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Requirements:- **Python** (Preferably >= 3.6): - Have admin permissions to create Flywheel Groups and Projects. Install and import dependencies | !pip install pandas pydicom flywheel-sdk tqdm kaggle jupyter ipywidgets
import json
import logging
import os
import re
import time
import zipfile
from getpass import getpass
from pathlib import Path
import flywheel
import pandas as pd
import pydicom
from tqdm.notebook import tqdm
# Instantiate a logger
logging.basicCo... | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Download kaggle datasetThis requires that you have stored your Kaggle credentials in ~/.kaggle/kaggle.json. These can be acquired by creating a kaggle account at kaggle.com and using "Create New API Token" on the user account page. This dataset is currently 3.7 GB and may change in the future. Depending on the bandwid... | !kaggle competitions download -c rsna-pneumonia-detection-challenge | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Initialize ConstantsInitialize path to dowload directory, default session label, and default acquisition label. | ROOT_KAGGLE_DATA = '/path/to/repository/rsna-pneumonia-detection-challenge'
DEFAULT_SESSION_LABEL = 'NA'
DEFAULT_ACQ_LABEL = 'Chest XR' | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Flywheel API Key and ClientGet an API_KEY. More on this in the Flywheel SDK doc [here](https://flywheel-io.gitlab.io/product/backend/sdk/branches/master/python/getting_started.htmlapi-key). | API_KEY = getpass('Enter API_KEY here: ') | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Instantiate the Flywheel API client | fw_client = flywheel.Client(API_KEY if 'API_KEY' in locals() else os.environ.get('FW_KEY')) | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Show Flywheel logging information | log.info('You are now logged in as %s to %s', fw_client.get_current_user()['email'], fw_client.get_config()['site']['api_url']) | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Read the csvThe CSV file consists of the patient id, whether the pnemonia was diagnosed (Target 0/1), and the rectangular region of the image it was found in (x,y,width,height).```patientId,x,y,width,height,Target0004cfab-14fd-4e49-80ba-63a80b6bddd6,,,,,000436515-870c-4b36-a041-de91049b9ab4,264.0,152.0,213.0,379.0,1``... | df = pd.read_csv(Path(ROOT_KAGGLE_DATA) / 'stage_2_train_labels.csv') | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Container helpersImport container helper functions to find existing or create new containers. | from container_helpers import (
find_or_create_group,
find_or_create_project,
find_or_create_subject,
find_or_create_session,
find_or_create_acquisition,
upload_file_to_acquisition
) | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Create the project | # Initialize the group
public_data_group = find_or_create_group(fw_client, 'public_data', 'public_data')
# Initialize the project
project_label = 'kaggle-rsna-pneumonia-detection-challenge'
readme = 'https://www.kaggle.com/c/rsna-pneumonia-detection-challenge/data'
chestxray_project = find_or_create_project(project_lab... | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Iterate through dataframe and uploadIterate through the training data csv to create the container hierarchy for this project:1. find or create each subject encountered a. Encode presence/absence of pneumonia (Target=0/1) and the rectangular region it was found in (box) into a dictionary.2. find or create each session... | for i, row in tqdm(df.iterrows(), total=len(df)):
log.info('Processing Subject %s.', row['patientId'])
# (1) Find or create subject
subject = find_or_create_subject(row['patientId'], chestxray_project)
# (1a) Encode pneumonia status and rectangular region of positive status in dictionary.
if row['Ta... | _____no_output_____ | MIT | import/kaggle_pneumonia_chestxray.ipynb | flywheel-apps/flywheel-tutorials |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.