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 |
|---|---|---|---|---|---|
Re-define the test function so it accounts for the average cross-correlation and auto-correlation from source and target datasets | def test(dataset_name, model_root, crop_size=1):
image_root = os.path.join('dataset', dataset_name)
if dataset_name == 'mnist_m':
test_list = os.path.join(image_root, 'mnist_m_test_labels.txt')
dataset = GetLoader(
data_root=os.path.join(image_root, 'mnist_m_test'),
dat... | _____no_output_____ | MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Training | dataloader_source = torch.utils.data.DataLoader(
dataset=dataset_source,
batch_size=batch_size,
shuffle=True,
num_workers=8)
dataloader_target = torch.utils.data.DataLoader(
dataset=dataset_target,
batch_size=batch_size,
shuffle=True,
num_workers=8)
class CNNModel(nn.Module):
def __... | ============ Summary =============
Accuracy of the mnist dataset: 0.990200
Accuracy of the mnist_m dataset: 0.734141
Corresponding model was saved into ./out_ex3_cnn_da/mnist_mnistm_model_epoch_best.pth
| MIT | ex3_cnn_da.ipynb | swag-kaust/dda_pytorch |
Swow On and Free Scenes | from plot_helpers import *
plt.style.use('fivethirtyeight')
casi_data = PixelClassifier(CASI_DATA, CLOUD_MASK, VEGETATION_MASK)
hillshade = RasterFile(HILLSHADE, band_number=1).band_values()
snow_on_diff_data = RasterFile(SNOW_ON_DIFF, band_number=1)
band_values_snow_on_diff = snow_on_diff_data.band_values()
band_val... | _____no_output_____ | MIT | notebooks/Lidar_comparison_AGU_2019/ERW_snow_on.ipynb | jomey/raster_compare |
Snow Pixels comparison | band_values_snow_free_diff.mask = casi_data.snow_surfaces(band_values_snow_free_diff_mask)
band_values_snow_on_diff.mask = casi_data.snow_surfaces(band_values_snow_on_diff_mask)
ax = box_plot_compare(
[
band_values_snow_free_diff,
band_values_snow_on_diff,
],
[
'SfM Bare Ground\n- L... | _____no_output_____ | MIT | notebooks/Lidar_comparison_AGU_2019/ERW_snow_on.ipynb | jomey/raster_compare |
Stable Ground | lidar_data = RasterFile(LIDAR_SNOW_DEPTH, band_number=1)
band_values_lidar = lidar_data.band_values()
sfm_data = RasterFile(SFM_SNOW_DEPTH, band_number=1)
band_values_sfm = sfm_data.band_values()
band_values_lidar.mask = casi_data.stable_surfaces(band_values_lidar.mask)
band_values_sfm.mask = casi_data.stable_surfaces... | _____no_output_____ | MIT | notebooks/Lidar_comparison_AGU_2019/ERW_snow_on.ipynb | jomey/raster_compare |
This tutorial provides simple examples to learn how to use the functions provided by Preprocesspack package. First we are going to load the modules needed. | from preprocesspack import utils, Attribute, DataSet, graphics | _____no_output_____ | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
First we are going to create an Attribute object. There are several ways of creating an object. In this example we have created three Attributes. | attr=Attribute.Attribute(name="age",vector=[34,16,78,90,12])
attrContinuous=Attribute.Attribute(name="mark",vector=[1.2,3.4,6.7,8.9,4.7])
attrPass=Attribute.Attribute(name="pass",vector=[0,0,1,1,0])
attr.printAttribute() | age
34
16
78
90
12
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
To create a DataSet we can add a previously defined attribute or pass a vector. The name of each column will be the attribute name. | ds=DataSet.DataSet([],name="Students")
ds.addAttribute(attr)
ds.addAttribute(attrContinuous)
ds.addAttribute(attrPass)
ds.printDataSet() | age mark pass
34 1.2 0
16 3.4 0
78 6.7 1
90 8.9 1
12 4.7 0
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
From now on the tutorial will focus in how to use the preprocesspack in an external DataSet. We will use a DataSet called wine data that includes the information (alcohol quantity, color intensity, magnesium...) of two wine types. In this step we have loaded the data from a csv file using loadDataSet function. This fun... | wineData=DataSet.loadDataSet("wine_data_reduced.csv")
wineData.printDataSet() | Class Alcohol Malid ac Ash Alcalini Magnesiu Total p
0 14.23 1.71 2.43 15.6 127 2.8
0 13.2 1.78 2.14 11.2 100 2.65
0 13.16 2.36 2.67 18.6 101 2.8
0 14.37 1.95 2.5 16.8 113 3.85
0 13.24 2.59 2.87 21.0 118 2.8
0 14.2 1.76 2.45 15.2 112 3.27
0 14.39 1.87 2.45 ... | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
The first step with this DataSet will be to discretize the Alcohol and Magnesium columns of the data, as it can be easily noticed that both can be divided into three intervals. DataSet and Attribute objects can be discretized using the function discretize. This function computes two types of discretization: on the one ... |
wineData=wineData.discretize(3,"EW",[1,5])
wineData=wineData.discretize(5,"EF",[6])
wineData.printDataSet() | 8
16
24
32
40
Class Alcohol Malid ac Ash Alcalini Magnesiu Total p
0 (13.773333333333333, inf) 1.71 2.43 15.6 (126.66666666666666, inf) (2.8, 3.5)
0 (12.716666666666667, 13.773333333333333) 1.78 2.14 11.2 (-inf, 102.33333333333333) (-inf, 2.8)
0 (12.716666666666667, 13.773333333333333) 2.36... | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
Single attributes can also be discretized: | attr=Attribute.Attribute(name="age",vector=[34,16,78,90,12])
age_category=attr.discretize(2,"EW")
age_category.printAttribute()
| age
(-inf, 51.0)
(-inf, 51.0)
(51.0, inf)
(51.0, inf)
(-inf, 51.0)
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
The function normalize is used to normalize the data or an attribute. When applied to a DataSet, columns parameter indicate to which columns the normalization have to be applied. In this case I will apply it to the following columns: 2,3,4,6. | wineDataNormalized=wineData.normalize([2,3,4,6])
wineDataNormalized.printDataSet() | Class Alcohol Malid ac Ash Alcalini Magnesiu Total p
0 (13.773333333333333, inf) 1.71 2.43 15.6 (126.66666666666666, inf) (2.8, 3.5)
0 (12.716666666666667, 13.773333333333333) 1.78 2.14 11.2 (-inf, 102.33333333333333) (-inf, 2.8)
0 (12.716666666666667, 13.773333333333333) 2.36 2.67 18.6 ... | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
If the columns parameter is empty and the normalize function is applied to the hole DataSet it will return the original attribute if applied to categorical attributes and will normalize the rest. | wineDataNormalized=wineData.normalize()
wineDataNormalized.printDataSet() | Class Alcohol Malid ac Ash Alcalini Magnesiu Total p
0 (13.773333333333333, inf) 1.71 2.43 15.6 (126.66666666666666, inf) (2.8, 3.5)
0 (12.716666666666667, 13.773333333333333) 1.78 2.14 11.2 (-inf, 102.33333333333333) (-inf, 2.8)
0 (12.716666666666667, 13.773333333333333) 2.36 2.67 18.6 ... | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
Single attributes can also be normalized. If the attribute is categorical the result will be the original attribute | attrNorm=attrContinuous.normalize()
attrNorm.printAttribute()
attrNorm=age_category.normalize()
attrNorm.printAttribute()
| mark
0.0
1.8333333333333335
4.583333333333334
6.416666666666667
2.916666666666667
age
(-inf, 51.0)
(-inf, 51.0)
(51.0, inf)
(51.0, inf)
(-inf, 51.0)
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
To standardize the data or an attribute the function standardize can be used. When applied to a DataSet, columns parameter indicate to which columns the normalization have to be applied. In this case I will apply it to the following columns: 2,3,4,6. | wineDataStandardized=wineData.standardize([2,3,4,6])
wineDataStandardized.printDataSet() | Class Alcohol Malid ac Ash Alcalini Magnesiu Total p
0 (13.773333333333333, inf) 1.71 2.43 15.6 (126.66666666666666, inf) (2.8, 3.5)
0 (12.716666666666667, 13.773333333333333) 1.78 2.14 11.2 (-inf, 102.33333333333333) (-inf, 2.8)
0 (12.716666666666667, 13.773333333333333) 2.36 2.67 18.6 ... | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
If the columns parameter is empty and the standardize function is applied to the hole DataSet it will return the original attribute if applied to categorical attributes and will standardize the rest. | wineDataStandardized=wineData.standardize()
wineDataStandardized.printDataSet() | Class Alcohol Malid ac Ash Alcalini Magnesiu Total p
0 (13.773333333333333, inf) 1.71 2.43 15.6 (126.66666666666666, inf) (2.8, 3.5)
0 (12.716666666666667, 13.773333333333333) 1.78 2.14 11.2 (-inf, 102.33333333333333) (-inf, 2.8)
0 (12.716666666666667, 13.773333333333333) 2.36 2.67 18.6 ... | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
Single attributes can also be standardized. If the attribute is categorical the result will be the original attribute | attrStd=attrContinuous.standardize()
attrStd.printAttribute()
attrStd=age_category.standardize()
attrStd.printAttribute()
| mark
-1.4248840017881383
-0.5955864346098569
0.6483599161575655
1.4776574833358471
-0.10554696309541775
age
(-inf, 51.0)
(-inf, 51.0)
(51.0, inf)
(51.0, inf)
(-inf, 51.0)
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
Entropy function computes the entropy of an Attribute or a complete DataSet. In the case of continuous variables it returns None. The entropy of a given DataSet can be plotted using the entropyPlot function. In the following example we have computed the entropy of the Wine Data dataset, as there are only 4 categorical ... | print(str(wineData.entropy()))
graphics.entropyPlot(wineData) | [0.9995708393473224, 1.5788720570183736, None, None, None, 1.3247497144200895, 1.4552137931890252]
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
The entropy of single attributes can also be computed. If the attribute is not categorical the result will be None. | print(attrContinuous.entropy())
print (age_category.entropy()) | None
0.9709505944546686
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
The package also includes a function to compute the variance of a DataDet or an Attribute. The variance function returns a vector with the variance of each column of the DataSet or a value in the case of the Attribute. If the attribute is a factor it will return None. | print(wineData.variance()) | [0.2498512790005949, None, 0.37029541939321836, 0.10231171921475313, 13.642629387269485, None, None]
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
The variance function can also be applied to Attributes. | print(attrContinuous.variance())
print (age_category.variance()) | 7.0376
None
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
In order to analyze the relation between the data, the correlation function computes the correlation between the Attribute pairs of a DataSet. It calculates the correlation matrix between continuous variables and the mutual information between categorical ones. In the case where one of the variables is categorical and ... | print(wineDataStandardized.correlation()) | [[ 1. 0.40036882 -0.360096 -0.52998158 0.34937507 0.0582239
0.10514007]
[ 0.40036882 1.09439071 0.10264858 0.12943356 0.0694872 0.02751501
0.1561628 ]
[-0.360096 0.10264858 1. 0.48744897 0.17908969 0.12763826
0.10179586]
[-0.52998158 0.12943356 0.48744897 1. 0.3... | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
With the correlationPlot function the correlation can be displayed graphically. The plot type used for that is a HeatMap that is darker where the correlation between the Attributes is higher. | graphics.correlationPlot(wineDataStandardized) | _____no_output_____ | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
Another useful function of this package is the filter function. This function removes from the data the attributes with a correlation above the given threshold. If a function is passed through FUN parameter is given the filter function will apply the function to the data and remove the attributes that have a higher sco... | filteredWineData=wineDataStandardized.filter(0.4)
filteredWineData.printDataSet() | Alcohol Malid ac Alcalini Magnesiu Total p
(13.773333333333333, inf) 1.71 15.6 (126.66666666666666, inf) (2.8, 3.5)
(12.716666666666667, 13.773333333333333) 1.78 11.2 (-inf, 102.33333333333333) (-inf, 2.8)
(12.716666666666667, 13.773333333333333) 2.36 18.6 (-inf, 102.33333333333333) (2.8, 3.5)
(13.... | MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
In the following example the attributes with a variance higher than 2 will be removed. If we compute the variance we see that the attributes that have to be removed are the fifth (Alcalinity of ash) and the 11th one (Color intensity). | import numpy as np
print(wineData.variance())
filteredWineData=wineData.filter(13,np.mean)
filteredWineData.printDataSet() | [None, 0.37029541939321836, 13.642629387269485, None, None]
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
Using the RocAuc function the area behind the ROC curve can be calculated. The RocAuc function takes as parameters: a DataSet, a variable and a class index and returns the area behind the ROC curve. In order to visualize the curve, the function RocPlot plots the Roc curve of the given variable index. In the example the... | print(ds.rocAuc(1,2))
graphics.rocPlot(ds,1,2) | -0.6666666666666667
| MIT | .ipynb_checkpoints/Tutorial-checkpoint.ipynb | nuriale207/preprocesspack |
Modelling CpG islands with Hidden Markov Models Table of Contents1 Introduction1.1 General1.2 Viterbi, Forward/Backward Algorithm2 Imports3 Matrices4 Forward Algorithm5 Backward Algorithm6 Test Sequence7 Test Sequence M... | from matplotlib.patches import Rectangle
import re
import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
transitions = np.zeros((2, 2)) # +- / +-
emissions = np.zeros((4, 2)) # +- / ACTG
initiations = np.zeros((1, 2)) # +- / Probability | _____no_output_____ | MIT | Jupyter Notebooks/CpG islands Hidden Markov Model.ipynb | thierrygrimm/CpGIslandHMM |
Matrices | sequences = pd.read_csv('Sequences.txt', header=None)[0]
keys = pd.read_csv('keys.txt', header=None)[0]
keys_ohe = [x.replace('+', "1").replace('-', "0") for x in keys] # binary
totals = [60278, 29119]
# Transition Array
for i in range(2):
for x in range(2):
query = str(i)+str(x)
transitions[i][x]... | Transitions: -+ / -+
[[0.9871429 0.0128571 ]
[0.02558467 0.97441533]]
Emissions: ATGC/-+
[[0.25910751 0.14164113]
[0.26115618 0.14501192]
[0.24023989 0.35263875]
[0.23949642 0.36070821]]
Initiations: -+/Probabilites
[0.442, 0.558]
| MIT | Jupyter Notebooks/CpG islands Hidden Markov Model.ipynb | thierrygrimm/CpGIslandHMM |
Using Viterbi algorithm we find the most likely assignment of CpG islands in the“Test_sequence”. Forward Algorithm | def forward(sequence, initmat, a, e):
states = [0, 1]
seqlen = len(sequence)
f = [[0]*seqlen, [0]*seqlen]
ptr = [[0]*seqlen]
nucleotide = {"A": 0, "T": 1, "G": 2, "C": 3}
for k in states:
f[k][0] = initmat[k]*e[k][nucleotide[sequence[0]]]
for i in range(1, seqlen):
for k in s... | _____no_output_____ | MIT | Jupyter Notebooks/CpG islands Hidden Markov Model.ipynb | thierrygrimm/CpGIslandHMM |
Backward Algorithm | def backward(sequence, initmat, a, e):
states = [0, 1]
seqlen = len(sequence)
b = [[0]*seqlen, [0]*seqlen]
nucleotide = {"A": 0, "T": 1, "C": 2, "G": 3}
for k in states:
b[k][-1] = 1
for i in np.arange(seqlen-2, -1, -1):
# -1 for index shift, -1 for second last column
... | _____no_output_____ | MIT | Jupyter Notebooks/CpG islands Hidden Markov Model.ipynb | thierrygrimm/CpGIslandHMM |
Test Sequence | test_sequence="AACAATAATTTTGTTCTCCAATATAATCATCGACGCGTCGCGACGCGCGGGGGCGCCGGGTGACCCTATACTTCACTTGAATGCCATCCG"
states = [0,1]
start_p = [0.558, 0.442]
trans_p = [[0.9871429, 0.0128571], [0.02558467, 0.97441533]]
emit_p = [[0.25910751, 0.26115618, 0.24023989, 0.23949642],
[0.14164113, 0.14501192, 0.35263875, 0.360... | _____no_output_____ | MIT | Jupyter Notebooks/CpG islands Hidden Markov Model.ipynb | thierrygrimm/CpGIslandHMM |
For every base of the “Test_sequence” calculate the probability to be in a CpG island. Use Forward and Backward algorithms. Calculate the probability of the “Test_sequence” using Forward and Backward algorithms. Obtained values should be the same. Plot the result: x-axis defines the position of the base, the y-axis def... | f1 = forward(test_sequence, start_p, trans_p, emit_p)
b1 = backward(test_sequence, start_p, trans_p, emit_p)
probs = np.multiply(f1, b1) / np.sum(f1, axis=0)[-1]
island = ["-"]*len(test_sequence)
state=np.argmax(probs1,axis=0)
for i in range(len(test_sequence)):
if state[i]==1:
island[i]="+"
p... | _____no_output_____ | MIT | Jupyter Notebooks/CpG islands Hidden Markov Model.ipynb | thierrygrimm/CpGIslandHMM |
Test Sequence Modification Change a single letter of the “Test_sequence” from G to T (red): | test_sequence2="AACAATAATTTTGTTCTCCAATATAATCATCGACGCGTCGCGACTCGCGGGGGCGCCGGGTGACCCTATACTTCACTTGAATGCCATCCG"
f2 = forward(test_sequence2, start_p, trans_p, emit_p)
b2 = backward(test_sequence2, start_p, trans_p, emit_p)
probs2 = np.multiply(f2, b2) / np.sum(f2, axis=0)[-1]
island2 = ["-"]*len(test_sequence2)
state2=np.... | _____no_output_____ | MIT | Jupyter Notebooks/CpG islands Hidden Markov Model.ipynb | thierrygrimm/CpGIslandHMM |
Dependencies | !pip install --quiet efficientnet
import warnings, time
from kaggle_datasets import KaggleDatasets
from sklearn.model_selection import KFold
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from tensorflow.keras import optimizers, Sequential, losses, metrics, Model
from tensorflow.ker... | _____no_output_____ | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Hardware configuration | # TPU or GPU detection
# Detect hardware, return appropriate distribution strategy
strategy, tpu = set_up_strategy()
AUTO = tf.data.experimental.AUTOTUNE
REPLICAS = strategy.num_replicas_in_sync
print(f'REPLICAS: {REPLICAS}')
# Mixed precision
from tensorflow.keras.mixed_precision import experimental as mixed_precis... | Running on TPU grpc://10.0.0.2:8470
REPLICAS: 8
| MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Model parameters | BATCH_SIZE = 64 * REPLICAS #32 * REPLICAS
LEARNING_RATE = 3e-5 * REPLICAS # 1e-5 * REPLICAS
EPOCHS_CL = 5
EPOCHS = 15
HEIGHT = 512
WIDTH = 512
HEIGHT_DT = 512
WIDTH_DT = 512
CHANNELS = 3
N_CLASSES = 5
N_FOLDS = 5
FOLDS_USED = 1
ES_PATIENCE = 5 | _____no_output_____ | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Load data | database_base_path = '/kaggle/input/cassava-leaf-disease-classification/'
train = pd.read_csv(f'{database_base_path}train.csv')
print(f'Train samples: {len(train)}')
GCS_PATH = KaggleDatasets().get_gcs_path(f'cassava-leaf-disease-tfrecords-center-{HEIGHT_DT}x{WIDTH_DT}') # Center croped and resized (50 TFRecord)
GCS_P... | Train samples: 21397
GCS: train images: 21395
| MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Augmentation | def data_augment(image, label):
# p_rotation = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_pixel_1 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
p_pixel_2 = tf.random.unif... | _____no_output_____ | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Auxiliary functions | # CutOut
def data_augment_cutout(image, min_mask_size=(int(HEIGHT * .1), int(HEIGHT * .1)),
max_mask_size=(int(HEIGHT * .125), int(HEIGHT * .125))):
p_cutout = tf.random.uniform([], 0, 1.0, dtype=tf.float32)
if p_cutout > .85: # 10~15 cut outs
n_cutout = tf.random.uniform([... | _____no_output_____ | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Training data samples (with augmentation) | # train_dataset = get_dataset(FILENAMES_COMP, ordered=True, augment=True)
# train_iter = iter(train_dataset.unbatch().batch(20))
# display_batch_of_images(next(train_iter))
# display_batch_of_images(next(train_iter)) | _____no_output_____ | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Model | def encoder_fn(input_shape):
inputs = L.Input(shape=input_shape, name='input_image')
base_model = efn.EfficientNetB5(input_tensor=inputs,
include_top=False,
weights='noisy-student',
pooling=None)
... | _____no_output_____ | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Learning rate schedule | lr_start = 1e-8
lr_min = 1e-6
lr_max = LEARNING_RATE
num_cycles = 1
warmup_epochs = 3
hold_max_epochs = 0
total_epochs = EPOCHS
step_size = (NUM_TRAINING_IMAGES//BATCH_SIZE)
hold_max_steps = hold_max_epochs * step_size
total_steps = total_epochs * step_size
warmup_steps = warmup_epochs * step_size
def lrfn(total_step... | 615 total steps and 41 steps per epoch
Learning rate schedule: 1e-08 to 0.00024 to 1e-06
| MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Training | skf = KFold(n_splits=N_FOLDS, shuffle=True, random_state=seed)
oof_pred = []; oof_labels = []; oof_names = []; oof_folds = []; history_list = []; oof_embed = []
for fold,(idxT, idxV) in enumerate(skf.split(np.arange(15))):
if fold >= FOLDS_USED:
break
if tpu: tf.tpu.experimental.initialize_tpu_system(t... |
FOLD: 1
TRAIN: [ 0 2 3 4 5 7 9 10 11 12 13 14] VALID: [1 6 8]
Pre-training the encoder using "Supervised Contrastive" Loss
Downloading data from https://github.com/qubvel/efficientnet/releases/download/v0.0.1/efficientnet-b5_noisy-student_notop.h5
115261440/115255328 [==============================] - 3s 0us/ste... | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Model loss graph | for fold, history in enumerate(history_list):
print(f'\nFOLD: {fold+1}')
plot_metrics(history, acc_name='output_sparse_categorical_accuracy') |
FOLD: 1
| MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Model evaluation | y_true = np.concatenate(oof_labels)
y_pred = np.concatenate(oof_pred)
folds = np.concatenate(oof_folds)
names = np.concatenate(oof_names)
acc = accuracy_score(y_true, y_pred)
print(f'Overall OOF Accuracy = {acc:.3f}')
df_oof = pd.DataFrame({'image_id':names, 'fold':fold,
'target':y_true, 'pred... | Overall OOF Accuracy = 0.882
| MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Confusion matrix | fig, ax = plt.subplots(1, 1, figsize=(20, 12))
cfn_matrix = confusion_matrix(y_true, y_pred, labels=range(len(CLASSES)))
cfn_matrix = (cfn_matrix.T / cfn_matrix.sum(axis=1)).T
df_cm = pd.DataFrame(cfn_matrix, index=CLASSES, columns=CLASSES)
ax = sns.heatmap(df_cm, cmap='Blues', annot=True, fmt='.2f', linewidths=.5).set... | _____no_output_____ | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Visualize embeddings outputs | y_true = np.concatenate(oof_labels)
y_pred = np.concatenate(oof_pred)
y_embeddings = np.concatenate(oof_embed)
visualize_embeddings(y_embeddings, y_true) | _____no_output_____ | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Visualize predictions | # train_dataset = get_dataset(TRAINING_FILENAMES, ordered=True)
# x_samp, y_samp = dataset_to_numpy_util(train_dataset, 18)
# y_samp = np.argmax(y_samp, axis=-1)
# x_samp_1, y_samp_1 = x_samp[:9,:,:,:], y_samp[:9]
# samp_preds_1 = model.predict(x_samp_1, batch_size=9)
# display_9_images_with_predictions(x_samp_1, samp... | _____no_output_____ | MIT | Model backlog/Models/Train/87-cassava-leaf-effnetb5-scl-2020-2-aux-512x512.ipynb | dimitreOliveira/Cassava-Leaf-Disease-Classification |
Stringhe 4 - iterazione e funzioni [Scarica zip esercizi](../_static/generated/strings.zip)[Naviga file online](https://github.com/DavidLeoni/softpython-it/tree/master/strings) Che fare- scompatta lo zip in una cartella, dovresti ottenere qualcosa del genere: ```strings strings1.ipynb strings1-sol.ipynb ... | # scrivi qui
# versione con len, più veloce perchè python assieme ad una stringa mantiene sempre in memoria
# il numero della lunghezza immediatamente disponibile
def lung1(stringa):
return len(stringa)
# versione con contatore, più lenta
def lung2(parola):
contatore = 0
for lettera in parola:
c... | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
contin✪ Scrivi la funzione `contin(parola, stringa)`, che RITORNA `True` se `parola` contiene la `stringa` indicata, altrimenti RITORNA `False` - Usa l'operatore `in````python>>> x = contin('carpenteria', 'ent')>>> xTrue>>> y = contin('carpenteria', 'zent')>>> yFalse``` | # scrivi qui
def contin(parola, stringa):
return stringa in parola | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
invertilet✪ Scrivi la funzione `invertilet(primo, secondo)` che prende in input due stringhe di lunghezza maggiore di 3, e RESTITUISCE una nuova stringa in cui le parole sono concatenate e separate da uno spazio, le ultime lettere delle due parole sono invertite. Questo significa che passando in input 'ciao' e 'world... | # scrivi qui
def invertilet(primo,secondo):
if len(primo) <= 3 or len(secondo) <=3:
print("errore!")
else:
return primo[:-1] + secondo[-1] + " " + secondo[:-1] + primo[-1]
| _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
nspazio✪ Scrivi la funzione `nspazio` che data una stringa in input, RITORNA una nuova stringa incui l’n-esimo carattere è uno spazio. Per esempio, data la stringa 'largamente' e il carattere all'indice 5, il programma deve RITORNARE `'larga ente'`. Nota: se il numero dovesse essere troppo grande (i.e., la parola ha 6... | # scrivi qui
def nspazio(parola, indice):
if indice >= len(parola):
print("errore!")
return parola[:indice]+' '+parola[indice+1:]
#nspazio("largamente", 5) | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
inifin✪ Scrivi un programma in Python prende una stringa, e se la stringa ha una lunghezza maggiore di 4, il programma STAMPA le prime e le ultime due lettere. Altrimenti, nel caso in cui la lunghezza della stringa sia minore di 4, STAMPA `voglio almeno 4 caratteri`. Per esempio, passando alla funzione `"ciaomondo"`, ... | # scrivi qui
def inifin(stringa):
if len(stringa) >= 4:
print(stringa[:2] + stringa[-2:])
else:
print("Voglio almeno 4 caratteri")
| _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
scambiaScrivere una funzione che data una stringa, inverte il primo e l’ultimo carattere, e STAMPA il risultato.Quindi, data la stringa “mondo”, il programma stamperà “oondm”```python>>> scambia('mondo')oondm``` | # scrivi qui
def scambia(stringa):
print(stringa[-1] + stringa[1:-1] + stringa[0]) | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
Esercizi con eccezioni e test**ATTENZIONE: Gli esercizi seguenti richiedono di conoscere:**[Controllo di flusso](https://it.softpython.org/control-flow)[Funzioni](https://it.softpython.org/functions/functions-sol.html)**e anche**: [Eccezioni e test con assert](https://it.softpython.org/errors-and-testing/errors-and-te... | def halet(parola, lettera):
#jupman-raise
indice = 0 # inizializziamo indice
while indice < len(parola):
if parola[indice] == lettera:
return True # abbiamo trovato il carattere, possiamo interrompere la ricerca
indice += 1 # è come scrivere indice = indice + 1
# se a... | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
conta✪ RITORNA il numero di occorrenze di lettera in parolaNOTA: NON VOGLIO UNA STAMPA, VOGLIO CHE *RITORNI* IL VALORE! - Usare ciclo for in |
def conta(parola, lettera):
#jupman-raise
occorrenze = 0
for carattere in parola:
# print("carattere corrente = ", carattere) # le print di debug sono ammesse
if carattere == lettera:
# print("trovata occorrenza !") # le print di debug sono ammesse
occorrenze +... | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
contiene_minuscola✪ Esercizio ripreso dall' Esercizio 4 del libro Pensare in Python Capitolo Stringheleggere in fondo qua: https://davidleoni.github.io/ThinkPythonItalian/html/thinkpython2009.html - RITORNA True se la parola contiene almeno una lettera minuscola- RITORNA False altrimenti- Usare ciclo `while` |
def contiene_minuscola(s):
#jupman-raise
i = 0
while i < len(s):
if s[i] == s[i].lower():
return True
i += 1
return False
#/jupman-raise
# INIZIO TEST - NON TOCCARE !
# se hai scritto tutto il codice giusto, ed esegui la cella, python non dovrebbe lanciare As... | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
dialetto✪✪ Esiste un dialetto in cui tutte le “a” devono per forza essere precedute da una “g”. Nel caso una parola dovesse contenere “a” _non_ preceduta da una “g”, possiamo dire con certezza che questa parola non fa parte di quel dialetto. Scrivere una funzione che data una parola, RITORNI `True` se la parola rispet... |
def dialetto(parola):
#jupman-raise
n = 0
for i in range(0,len(parola)):
if parola[i] == "a":
if i == 0 or parola[i - 1] != "g":
return False
return True
#/jupman-raise
# INIZIO TEST - NON TOCCARE !
# se hai scritto tutto il codice giusto, ed esegui la ce... | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
contavoc ✪✪ Data una stringa, scrivere una funzione che conti il numero di vocali. Se il numero di vocali è pari RITORNA il numero di vocali, altrimenti solleva l'eccezione `ValueError` ```python >>> conta_vocali("asso") 2>>> conta_vocali("ciao")---------------------------------------------------------... |
def contavoc(parola):
#jupman-raise
n_vocali = 0
vocali = ["a","e","i","o","u"]
for lettera in parola:
if lettera.lower() in vocali:
n_vocali = n_vocali + 1
if n_vocali % 2 == 0:
return n_vocali
else:
raise ValueError("Vocali dispari !")
#/jupman-raise... | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
palindroma✪✪✪ Una parola è palindroma quando è esattamente la stessa se letta al contrarioScrivi una funzione che RITORNA `True` se una parola è palindroma, `False` altrimenti* assumi che la stringa vuota sia palindromaEsempio: ```python>>> x = palindroma('radar')>>> xTrue>>> x = palindroma('scatola')>>> xFalse``` |
def palindroma(parola):
#jupman-raise
for i in range(len(parola) // 2):
if parola[i] != parola[len(parola)- i - 1]:
return False
return True # nota che è FUORI dal for: superati tutti i controlli,
# possiamo concludere che la parola è palindroma
... | _____no_output_____ | CC-BY-4.0 | strings/strings4-sol.ipynb | DavidLeoni/softpython- |
Unit 5 - Financial Planning | %%capture
# Initial imports
import os
import requests
import pandas as pd
from dotenv import load_dotenv
import alpaca_trade_api as tradeapi
from MCForecastTools import MCSimulation
# Load .env enviroment variables
load_dotenv() | _____no_output_____ | ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
Part 1 - Personal Finance Planner | # Set monthly household income
monthly_income = 12000 | _____no_output_____ | ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
Collect Crypto Prices Using the requests Library | # Current amount of crypto assets
my_btc = 1.2
my_eth = 5.3
# Crypto API URLs
btc_url = "https://api.alternative.me/v2/ticker/Bitcoin/?convert=USD"
eth_url = "https://api.alternative.me/v2/ticker/Ethereum/?convert=USD"
requests.get(btc_url)
btc_url_data = requests.get(btc_url)
btc_data = btc_url_data.json()
requests... | The current value of your 1.2 BTC is $18422.15
The current value of your 5.3 ETH is $2369.84
| ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
Collect Investments Data Using Alpaca: SPY (stocks) and AGG (bonds) | # Current amount of shares
my_agg = 200
my_spy = 50
# Set Alpaca API key and secret
alpaca_api_key = os.getenv("ALPACA_API_KEY")
alpaca_secret_key = os.getenv("ALPACA_SECRET_KEY")
# Create the Alpaca API object
alpaca = tradeapi.REST(
alpaca_api_key,
alpaca_secret_key,
api_version="v2"
)
# Set timeframe ... | The current value of your 50 SPY shares is $17134.50
The current value of your 200 AGG shares is $23503.00
| ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
Savings Health Analysis | # Create savings DataFrame
shares = my_spy_value + my_agg_value
crypto = my_btc_value + my_eth_value
savings = [['shares',shares],['crypto', crypto]]
df_savings = pd.DataFrame(savings, columns =['','amount'])
df_savings.set_index(df_savings[''], inplace=True)
# Use the `drop` function to drop specific columns
df_sav... | Congratulations! You have enough money in your emergency fund.
| ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
Part 2 - Retirement PlanningMonte Carlo Simulation | # Set start and end dates of five years back from today.
# Sample results may vary from the solution based on the time frame chosen
start_date1 = pd.Timestamp('2015-10-21', tz='America/New_York').isoformat()
end_date1 = pd.Timestamp('2020-10-21', tz='America/New_York').isoformat()
# Get 5 years' worth of historical da... | count 500.000000
mean 11.345167
std 7.313115
min 1.943399
25% 6.058662
50% 9.757410
75% 14.528162
max 55.313315
95% CI Lower 2.754306
95% CI Upper 31.080523
Name: 7560, dtype: float64
| ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
Given an initial investment of $20,000, what is the expected portfolio return in dollars at the 95% lower and upper confidence intervals? | # Set initial investment
initial_investment = 20000
# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $20,000
ci_lower = round(tbl[8]*20000,2)
ci_upper = round(tbl[9]*20000,2)
# Print results
print(f"There is a 95% chance that an initial investment of ${initi... | There is a 95% chance that an initial investment of $20000 in the portfolio over the next 30 years will end within in the range of $55086.12 and $621610.45
| ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
How would a 50% increase in the initial investment amount affect the expected portfolio return in dollars at the 95% lower and upper confidence intervals | # Set initial investment
initial_investment1 = 20000 * 1.5
# Use the lower and upper `95%` confidence intervals to calculate the range of the possible outcomes of our $30,000
ci_lower1 = round(tbl[8]*(20000*1.5),2)
ci_upper1 = round(tbl[9]*(20000*1.5),2)
# Print results
print(f"There is a 95% chance that an initial i... | There is a 95% chance that an initial investment of $30000.0 in the portfolio over the next 30 years will end within in the range of $82629.18 and $932415.68
| ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
Optional Challenge - Early RetirementFive Years Retirement Option | # Configuring a Monte Carlo simulation to forecast 5 years cumulative returns
start_date5 = pd.Timestamp('2015-10-21', tz='America/New_York').isoformat()
end_date5 = pd.Timestamp('2020-10-21', tz='America/New_York').isoformat()
ticker5 = ["AGG", "SPY"]
five_stock_data = alpaca.get_barset(
ticker5,
timefram... | There is a 95% chance that an initial investment of $60000 in the portfolio over the next 5 years will end within in the range of $52671.88 and $142928.62
| ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
Ten Years Retirement Option | # Configuring a Monte Carlo simulation to forecast 10 years cumulative returns
start_date_10 = pd.Timestamp('2015-10-21', tz='America/New_York').isoformat()
end_date_10 = pd.Timestamp('2020-10-21', tz='America/New_York').isoformat()
ticker_10 = ["AGG", "SPY"]
ten_stock_data = alpaca.get_barset(
ticker_10,
... | There is a 95% chance that an initial investment of $60000 in the portfolio over the next 10 years will end within in the range of $62241.22 and $254734.34
| ADSL | financial_planning.ipynb | kary2003/5_financial_planning |
Indexing in NumPy np.where vs masking * np.where returns just the indices where the equivalent mask is true * this is useful if you need the actual indices (maybe for counts) * otherwise the shorthand notation (masking) is perhaps easier * np.where returns a tuple Why do I care?You may need to work directly in... | import numpy as np
%matplotlib inline
x = np.arange(5)
print(np.where(x < 3))
print(x < 3) | (array([0, 1, 2]),)
[ True True True False False]
| BSD-3-Clause | archive/python/indexing_in_numpy.ipynb | ajrichards/bayesian-examples |
Chaining logic statements | x = np.arange(10)
y1 = np.intersect1d(np.where(x > 3),np.where(x<7))
y2 = np.where((x > 3) & (x < 7))
y3 = np.where(np.logical_and(x > 3, x < 7))
y4 = x[(x > 3) & (x < 7)]
print(y1,y2,y3,y4) | [4 5 6] (array([4, 5, 6]),) (array([4, 5, 6]),) [4 5 6]
| BSD-3-Clause | archive/python/indexing_in_numpy.ipynb | ajrichards/bayesian-examples |
Random helpful things in NumPy | a = np.array(['a','b','c','c'])
#a = np.sort(np.unique(a))
b = np.array(['c','d','e','c','f'])
mask1a = np.in1d(a,b)
mask1b = [np.where(b==i)[0].tolist() for i in a]
mask2a = np.in1d(b,a)
mask2b = [np.where(a==i)[0].tolist() for i in b]
print("1")
print(mask1a)
print(mask1b)
print("2")
print(mask2a)
print(mask2b) | 1
[False False True True]
[[], [], [0, 3], [0, 3]]
2
[ True False False True False]
[[2, 3], [], [], [2, 3], []]
| BSD-3-Clause | archive/python/indexing_in_numpy.ipynb | ajrichards/bayesian-examples |
How does one array compare to another?This example is also the real reason to read this notebook.```pythona = np.array(['a','b','c'])b = np.array(['c','d','e','c','f'])``` * Where do we find elements of a in b? * Where do we find elements of b in a? * If you can use np.in1d [np.in1d](http://docs.scipy.org/doc/... | ## Get rid of nans
x = np.array([[1., 2., np.nan, 3., np.nan, np.nan]])
x[~np.isnan(x)]
## carry around indices
labels = np.array(['x' + str(i)for i in range(10)])
x = np.random.randint(1,14,10)
sortedInds = np.argsort(x)
print("sorted labels: %s"%labels[sortedInds])
## make x have exactly 5 evenly spaced points in t... | _____no_output_____ | BSD-3-Clause | archive/python/indexing_in_numpy.ipynb | ajrichards/bayesian-examples |
Bayesian Optimisation Verification | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.colors import LogNorm
from scipy.interpolate import interp1d
from scipy import interpolate
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel
from scipy im... | _____no_output_____ | MIT | BO_trials/BO_log_scale (2).ipynb | michelleliu1027/Bayesian_PV |
Trial on TiOx/SiOxTempeature vs. S10_HF | #import normal data sheet at 85 C (time:0~5000s)
address = 'data/degradation.xlsx'
x_normal = []
y_normal = []
df = pd.read_excel(address,sheet_name = 'normal data',usecols = [0],names = None,nrows = 5000)
df_85 = df.values.tolist()
df = pd.read_excel(address,sheet_name = 'normal data',usecols = [3],names = None,nrows... | -1.0178925921332458
-1.0178925921332458
[ 1 10 32 100 316 618 1000 3162]
| MIT | BO_trials/BO_log_scale (2).ipynb | michelleliu1027/Bayesian_PV |
How to create Data objectsThe SciDataTool python module has been created to **ease the handling of scientific data**, and considerately simplify plot commands. It unifies the extraction of relevant data (e.g. slices), whether they are stored in the time/space or in the frequency domain. The call to Fourier Transform f... | # Add SciDataTool to the Python path
import sys
sys.path.append('..')
# Import useful packages
from os.path import join
from numpy import pi, squeeze
from pandas import ExcelFile, read_excel
# Import SciDataTool modules
from SciDataTool import Data1D, DataTime
# Import scientific data
from Tests import DATA_DIR
xls_... | _____no_output_____ | Apache-2.0 | Tutorials/tuto1_Create.ipynb | helene-t/SciDataTool |
Your `Data`objects have been successfully created. Other features of the `SciDataTool` package are also available:- reduce storage if an axis is regularly spaced- reduce storage if the field presents a symmetry along one of its axes- store a field in the frequency domain- specifiy normalizationsThese functionalities ar... | from SciDataTool import DataLinspace
#---------------------------------------------------------------
# Create Data objects
Angle = DataLinspace(
name="angle",
unit="rad",
symmetries={},
initial=0,
final=2*pi,
number=2016,
)
#-------------... | _____no_output_____ | Apache-2.0 | Tutorials/tuto1_Create.ipynb | helene-t/SciDataTool |
3. How to reduce storage if a field presents a symmetry/periodicityIf a signal shows a **symmetry** or a **periodicity** along one or several of its axes, it is possible to store only the relevant part of the signal, and save the information necessary to rebuild it within the optional attribute `symmetries`. A repetin... | time_reduced = time[0:time.size//3]
field_reduced = field[0:time.size//3,:]
#---------------------------------------------------------------
# Create Data objects
Time_reduced = Data1D(name="time", unit="s", symmetries={"time": {"period": 3}}, values=time_reduced)
Br_reduced = DataTime(
name="Airgap radial... | _____no_output_____ | Apache-2.0 | Tutorials/tuto1_Create.ipynb | helene-t/SciDataTool |
4. How to store a field in the frequency domainIf one prefers to store data in the frequency domain, for example because most postprocessings will handle spectra, or because a small number of harmonics allow to reduce storage, the `DataFreq` class can be used.The definition is similar to the `DataTime` one, with the d... | from SciDataTool import DataFreq
# Import scientific data
freqs = read_excel(xls_file, sheet_name="freqs", header=None, nrows=1, squeeze=True).to_numpy()
wavenumber = read_excel(xls_file, sheet_name="wavenumber", header=None, nrows=1, squeeze=True).to_numpy()
field_fft2 = read_excel(xls_file, sheet_name="Br_fft2", hea... | _____no_output_____ | Apache-2.0 | Tutorials/tuto1_Create.ipynb | helene-t/SciDataTool |
5. How to specify normalizations (axes or field)If you plan to **normalize** your field or its axes during certain postprocessings (but not all), you might want to store the normalizations values. To do so, you can use the `normalizations` attribute, which is a dictionaray:- for a normalization of the **field**, use `... | #---------------------------------------------------------------
Br = DataTime(
name="Airgap radial flux density",
unit="T",
symbol="B_r",
axes=[Time, Angle],
normalizations={"ref": 0.8, "elec_order": 60},
values=field,
)
Br.normalizations[... | _____no_output_____ | Apache-2.0 | Tutorials/tuto1_Create.ipynb | helene-t/SciDataTool |
6. How to store a field with multiple componentsIt is more efficient to store all the **components** of a same field (e.g. $x$, $y$, $z$ components of a vector field, phases of a signal, etc.) in the same `Data` object. To do so, the `is_components` key can be used to easily recognize it, and strings can be used as va... | from numpy import roll, array
fieldB = roll(field, 100, axis=0)
fieldC = roll(field, 200, axis=0)
new_field = array([field, fieldB, fieldC])
#---------------------------------------------------------------
Phases = Data1D(name="phases", unit="", values=["Phase A","Phase B","Phase C"], is_components=True)
Br = DataTim... | _____no_output_____ | Apache-2.0 | Tutorials/tuto1_Create.ipynb | helene-t/SciDataTool |
**On my honor I have neither given nor received any unauthorized aid.** **Your name here** Test 2On this test we are going use a dataset that researchers collected about 649 high school students in Portugal, and attempt to determine how their grades are affected by several of the variables that they collected informat... | library(dplyr)
library(ggplot2) | _____no_output_____ | MIT | Test 2 Ver 1/Test 2.ipynb | mbardoe/DataScience |
We will load the data using the command: | student<-read.csv("student-por.csv") | _____no_output_____ | MIT | Test 2 Ver 1/Test 2.ipynb | mbardoe/DataScience |
Dataset studentThe student dataset looks at the relationship between variables describing students lives and their performance in Portuguese class. | Attribute | Explanation||-----------|------------||age|student's age (numeric: from 15 to 22) ||studytime|hours studied weekly ||Walc| Alcoholic drinks consumed weekly... | str(student) | 'data.frame': 649 obs. of 5 variables:
$ age : int 18 17 15 15 16 16 16 17 15 15 ...
$ studytime: int 2 2 2 3 2 2 2 2 2 2 ...
$ Walc : int 1 1 3 1 2 2 1 1 1 1 ...
$ absences : int 4 2 6 0 0 6 0 2 0 0 ...
$ G3 : int 11 11 12 14 13 13 13 13 17 13 ...
| MIT | Test 2 Ver 1/Test 2.ipynb | mbardoe/DataScience |
Task 1Create a scatterplot that shows the relationship between G3 and Walc. Task 2 Create a linear model that predicts the G3 based on the Walc. **Write a markdown cell that gives the equation that predicts G3 from Walc. Does your calculation indicate that Walc is a useful predictor for G3?** Task 3**Create a scatte... | _____no_output_____ | MIT | Test 2 Ver 1/Test 2.ipynb | mbardoe/DataScience | |
MODISMODIS Terra: https://lpdaac.usgs.gov/products/mod11c1v006/MODIS Acqua: https://lpdaac.usgs.gov/products/myd11c1v061/Docs: https://lpdaac.usgs.gov/documents/118/MOD11_User_Guide_V6.pdf | ! wget https://e4ftl01.cr.usgs.gov/MOLA/MYD11C1.061/2018.04.19/MYD11C1.A2018109.061.2021330052306.hdf -O /network/group/aopp/predict/TIP016_PAXTON_RPSPEEDY/ML4L/MODIS.hdf
import xarray as xr
import rioxarray as rxr
modis_xarray= rxr.open_rasterio('/network/group/aopp/predict/TIP016_PAXTON_RPSPEEDY/ML4L/MODIS.hdf',mask... | _____no_output_____ | MIT | notebooks/legacy/legacy/Explore_raw_MODIS_data.ipynb | tomkimpson/ML4L |
ODE solverIn this notebook, we show some examples of solving an ODE model. For the purposes of this example, we use the Scipy solver, but the syntax remains the same for other solvers | %pip install pybamm -q # install PyBaMM if it is not installed
import pybamm
import tests
import numpy as np
import os
import matplotlib.pyplot as plt
from pprint import pprint
os.chdir(pybamm.__path__[0]+'/..')
# Create solver
ode_solver = pybamm.ScipySolver() | Note: you may need to restart the kernel to use updated packages.
| BSD-3-Clause | examples/notebooks/solvers/ode-solver.ipynb | deepakdinesh1123/PyBaMM |
Integrating ODEs In PyBaMM, a model is solved by calling a solver with `solve`. This sets up the model to be solved, and then calls the method `_integrate`, which is specific to each solver. We begin by setting up and discretising a model | # Create model
model = pybamm.BaseModel()
u = pybamm.Variable("u")
v = pybamm.Variable("v")
model.rhs = {u: -v, v: u}
model.initial_conditions = {u: 2, v: 1}
model.variables = {"u": u, "v": v}
# Discretise using default discretisation
disc = pybamm.Discretisation()
disc.process_model(model); | _____no_output_____ | BSD-3-Clause | examples/notebooks/solvers/ode-solver.ipynb | deepakdinesh1123/PyBaMM |
Now the model can be solved by calling `solver.solve` with a specific time vector at which to evaluate the solution | # Solve ########################
t_eval = np.linspace(0, 5, 30)
solution = ode_solver.solve(model, t_eval)
################################
# Extract u and v
t_sol = solution.t
u = solution["u"]
v = solution["v"]
# Plot
t_fine = np.linspace(0,t_eval[-1],1000)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13,4))
ax1.... | _____no_output_____ | BSD-3-Clause | examples/notebooks/solvers/ode-solver.ipynb | deepakdinesh1123/PyBaMM |
Note that, where possible, the solver makes use of the mass matrix and jacobian for the model. However, the discretisation or solver will have created the mass matrix and jacobian algorithmically, using the expression tree, so we do not need to calculate and input these manually. The solution terminates at the final si... | solution.termination | _____no_output_____ | BSD-3-Clause | examples/notebooks/solvers/ode-solver.ipynb | deepakdinesh1123/PyBaMM |
EventsIt is possible to specify events at which a solution should terminate. This is done by adding events to the `model.events` dictionary. In the following example, we solve the same model as before but add a termination event when `v=-2`. | # Create model
model = pybamm.BaseModel()
u = pybamm.Variable("u")
v = pybamm.Variable("v")
model.rhs = {u: -v, v: u}
model.initial_conditions = {u: 2, v: 1}
model.events.append(pybamm.Event('v=-2', v + 2)) # New termination event
model.variables = {"u": u, "v": v}
# Discretise using default discretisation
disc = pyba... | _____no_output_____ | BSD-3-Clause | examples/notebooks/solvers/ode-solver.ipynb | deepakdinesh1123/PyBaMM |
Now the solution terminates because the event has been reached | solution.termination
print("event time: ", solution.t_event, "\nevent state", solution.y_event.flatten()) | event time: [3.78510677]
event state [-0.99995359 -2. ]
| BSD-3-Clause | examples/notebooks/solvers/ode-solver.ipynb | deepakdinesh1123/PyBaMM |
ReferencesThe relevant papers for this notebook are: | pybamm.print_citations() | [1] Joel A. E. Andersson, Joris Gillis, Greg Horn, James B. Rawlings, and Moritz Diehl. CasADi – A software framework for nonlinear optimization and optimal control. Mathematical Programming Computation, 11(1):1–36, 2019. doi:10.1007/s12532-018-0139-4.
[2] Charles R. Harris, K. Jarrod Millman, Stéfan J. van der Walt, R... | BSD-3-Clause | examples/notebooks/solvers/ode-solver.ipynb | deepakdinesh1123/PyBaMM |
初始化 | import sys,os
root_path = os.path.abspath('../../../../')
sys.path.append(root_path)
root_path
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import src.features.factors.consolidate_factor as cf
import src.visualization.plotting as pt | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
整理数据 | fp = root_path + "/xxx.parquet" # 需要用到的其它类型的数据
mf = pd.read_parquet(fp)
md_fp = root_path + "/data/example/IF/md.parquet" # 需要用到的行情数据
md = pd.read_parquet(md_fp)
df = pd.concat([mf, md], axis=1).dropna(axis=0) # 将数据源进行整合
df['return'] = df['close'].diff() # 基准收益 | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
生成因子 设置因子的类型、名称、参数值 | factor_type = 'tmom'
factor_signature = 'xxx'
param_signatures = [560, 720, 960, 1200, 1800]
raw_factor_name = f"factor_{factor_type}_{factor_signature}"
raw_factor_name
def factor_tmom_xxx(df: pd.DataFrame, w) -> pd.Series:
"""
最好在这里规范描述因子逻辑,以便后期整理
"""
df['factor'] = df['return'].rolling(w).mean() / df... | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
开启一个循环,用以检验因子在不同参数下的表现 | # set signal shift
sig_shift = 1
compare_df, compare_df_2 = pd.DataFrame(), pd.DataFrame()
for i in param_signatures:
factor = factor_tmom_xxx(df, i)
signal = np.sign(factor)
ret_cumsum_df = pd.DataFrame((df['return'] * signal.shift(sig_shift)).cumsum(), columns=[i])
ret_df = pd.DataFrame((df['return'] ... | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
选取你认为表现比较好的因子,将因子函数固化 | param_signature = 1200
factor_name = f"factor_{factor_type}_{factor_signature}_{param_signature}"
factor_name | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
现在,你的因子函数应该有固定的参数,而非传入参数。 | def factor_tmom_xxx_1200(df: pd.DataFrame):
"""
衡量北向资金净买入量在1200期内的投票结果
"""
df['factor'] = df['return'].rolling(w).mean() / df['return'].rolling(w).max() # 生成因子
return df['factor']
factor = factor_tmom_xxx_1200(df) | _____no_output_____ | MIT | notebook/Template.ipynb | danni2019/JAB |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.