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
3 Lowest HDI Countries
ax = africa_low.loc[africa_low['Country']=='Niger'].plot(x='Year', y= 'TFR', kind='scatter', c = 'cornflowerblue', label = 'Niger') africa_low.loc[africa_low['Country']=='Central African Republic'].plot(x='Year', y= 'TFR', kind='scatter', c = 'mediumblue', ax=ax, label = 'Central African Republic') africa_low.loc[afr...
_____no_output_____
MIT
Python Analysis/Visualisations/Code/Visualisation_TFR_and_FLPR_of_Highest_and_Lowest_HDI_countries.ipynb
ChangHuaHua/QM2-Group-12
Hyperparameter tuning with Amazon SageMaker and Deep Graph Library with PyTorch backend_**Creating a Hyperparameter tuning job for a DGL network**_______ Contents1. [Background](Background) 2. [Setup](Setup) 3. [Tune](Train) 4. [Wrap-up](Wrap-up) BackgroundThis example notebook shows how to generate knowledge gra...
import sagemaker from sagemaker import get_execution_role from sagemaker.session import Session # Setup session sess = sagemaker.Session() # S3 bucket for saving code and model artifacts. # Feel free to specify a different bucket here if you wish. bucket = sess.default_bucket() # Location to put your custom code. cu...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/dgl_kge/kge_pytorch_hypertune.ipynb
P15241328/amazon-sagemaker-examples
Now we'll import the Python libraries we'll need.
import boto3 from sagemaker.tuner import IntegerParameter, CategoricalParameter, ContinuousParameter, HyperparameterTuner
_____no_output_____
Apache-2.0
sagemaker-python-sdk/dgl_kge/kge_pytorch_hypertune.ipynb
P15241328/amazon-sagemaker-examples
TuneSimilar to training a single training job in Amazon SageMaker, you define the training estimator passing in the code scripts, IAM role, (per job) hardware configuration, and any hyperparameters you're not tuning.
from sagemaker.pytorch import PyTorch ENTRY_POINT = 'train.py' CODE_PATH = './' account = sess.boto_session.client('sts').get_caller_identity()['Account'] region = sess.boto_session.region_name params = {} params['dataset'] = 'FB15k' params['model'] = 'DistMult' params['batch_size'] = 1024 params['neg_sample_size'] ...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/dgl_kge/kge_pytorch_hypertune.ipynb
P15241328/amazon-sagemaker-examples
After you define your estimator, specify the hyperparameters you want to tune and their possible values. You have three different types of hyperparameters. * Categorical parameters need to take one value from a discrete set. Define this by passing the list of possible values to CategoricalParameter(list) * Continuous...
hyperparameter_ranges = {'lr': ContinuousParameter(0.01, 0.1), 'gamma': ContinuousParameter(400, 600)}
_____no_output_____
Apache-2.0
sagemaker-python-sdk/dgl_kge/kge_pytorch_hypertune.ipynb
P15241328/amazon-sagemaker-examples
Next, specify the objective metric that you want to tune and its definition. This includes the regular expression needed to extract that metric from the Amazon CloudWatch logs of the training job.You can capture evalution results such as MR, MRR and Hit10.
metric = [] mr_metric = {'Name': 'final_MR', 'Regex':"Test average MR at \[\S*\]: (\S*)"} mrr_metric = {'Name': 'final_MRR', 'Regex':"Test average MRR at \[\S*\]: (\S*)"} hit10_metric = {'Name': 'final_Hit10', 'Regex':"Test average HITS@10 at \[\S*\]: (\S*)"} metric.append(mr_metric) metric.append(mrr_metric) metric.ap...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/dgl_kge/kge_pytorch_hypertune.ipynb
P15241328/amazon-sagemaker-examples
Now, create a HyperparameterTuner object, which you pass. * The training estimator you created above * The hyperparameter ranges * Objective metric name and definition * Number of training jobs to run in-total and how many training jobs should be run simultaneously. More parallel jobs will finish tuning sooner, but may...
task_tags = [{'Key':'ML Task', 'Value':'DGL'}] tuner = HyperparameterTuner(estimator, objective_metric_name='final_MR', objective_type='Minimize', hyperparameter_ranges=hyperparameter_ranges, metric_definitio...
_____no_output_____
Apache-2.0
sagemaker-python-sdk/dgl_kge/kge_pytorch_hypertune.ipynb
P15241328/amazon-sagemaker-examples
And finally, you can start the tuning job by calling .fit().
tuner.fit()
_____no_output_____
Apache-2.0
sagemaker-python-sdk/dgl_kge/kge_pytorch_hypertune.ipynb
P15241328/amazon-sagemaker-examples
Run a quick check of the hyperparameter tuning jobs status to make sure it started successfully and is InProgress.
boto3.client('sagemaker').describe_hyper_parameter_tuning_job( HyperParameterTuningJobName=tuner.latest_tuning_job.job_name)['HyperParameterTuningJobStatus']
_____no_output_____
Apache-2.0
sagemaker-python-sdk/dgl_kge/kge_pytorch_hypertune.ipynb
P15241328/amazon-sagemaker-examples
You can also run the notebook in [COLAB](https://colab.research.google.com/github/deepmipt/DeepPavlov/blob/master/examples/classification_tutorial.ipynb).
!pip3 install deeppavlov
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Classification on DeepPavlov **Task**:Intent recognition on SNIPS dataset: https://github.com/snipsco/nlu-benchmark/tree/master/2017-06-custom-intent-engines that has already been recomposed to `csv` format and can be downloaded from http://files.deeppavlov.ai/datasets/snips_intents/train.csvFastText English word embe...
from deeppavlov.core.data.utils import simple_download #download train data file for SNIPS simple_download(url="http://files.deeppavlov.ai/datasets/snips_intents/train.csv", destination="./snips/train.csv") ! head -n 15 snips/train.csv
text,intents Add another song to the Cita RomГЎntica playlist. ,AddToPlaylist add clem burke in my playlist Pre-Party R&B Jams,AddToPlaylist Add Live from Aragon Ballroom to Trapeo,AddToPlaylist add Unite and Win to my night out,AddToPlaylist Add track to my Digster Future Hits,AddToPlaylist add the piano bar to ...
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
DatasetReaderRead data using `BasicClassificationDatasetReader` из DeepPavlov
from deeppavlov.dataset_readers.basic_classification_reader import BasicClassificationDatasetReader # read data from particular columns of `.csv` file dr = BasicClassificationDatasetReader().read( data_path='./snips/', train='train.csv', x = 'text', y = 'intents' )
2019-02-12 12:14:23.376 WARNING in 'deeppavlov.dataset_readers.basic_classification_reader'['basic_classification_reader'] at line 96: Cannot find snips/valid.csv file 2019-02-12 12:14:23.376 WARNING in 'deeppavlov.dataset_readers.basic_classification_reader'['basic_classification_reader'] at line 96: Cannot find snips...
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
We don't have a ready train/valid/test split.
# check train/valid/test sizes [(k, len(dr[k])) for k in dr.keys()]
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
DatasetIteratorUse `BasicClassificationDatasetIterator` to split `train` on `train` and `valid` and to generate batches of samples.
from deeppavlov.dataset_iterators.basic_classification_iterator import BasicClassificationDatasetIterator # initialize data iterator splitting `train` field to `train` and `valid` in proportion 0.8/0.2 train_iterator = BasicClassificationDatasetIterator( data=dr, field_to_split='train', # field that will be sp...
2019-02-12 12:14:23.557 INFO in 'deeppavlov.dataset_iterators.basic_classification_iterator'['basic_classification_iterator'] at line 73: Splitting field <<train>> to new fields <<['train', 'valid']>>
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Let's look into training samples.
# one can get train instances (or any other data type including `all`) x_train, y_train = train_iterator.get_instances(data_type='train') for x, y in list(zip(x_train, y_train))[:5]: print('x:', x) print('y:', y) print('=================')
x: Is it freezing in Offerman, California? y: ['GetWeather'] ================= x: put this song in the playlist Trap Land y: ['AddToPlaylist'] ================= x: show me a textbook with a rating of 2 and a maximum rating of 6 that is current y: ['RateBook'] ================= x: Will the weather be okay in Northern Lu...
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Data preprocessing We will be using lowercasing and tokenization as data preparation. DeepPavlov also contains several other preprocessors and tokenizers. Lowercasing `str_lower` lowercases texts.
from deeppavlov.models.preprocessors.str_lower import str_lower str_lower(['Is it freezing in Offerman, California?'])
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Tokenization`NLTKTokenizer` can split string to tokens.
from deeppavlov.models.tokenizers.nltk_moses_tokenizer import NLTKMosesTokenizer tokenizer = NLTKMosesTokenizer() tokenizer(['Is it freezing in Offerman, California?'])
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Let's preprocess all `train` part of the dataset.
train_x_lower_tokenized = str_lower(tokenizer(train_iterator.get_instances(data_type='train')[0]))
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
VocabularyNow we are ready to use `vocab`. They are very usefull for:* extracting class labels and converting labels to indices and vice versa,* building of characters or tokens vocabularies.
from deeppavlov.core.data.simple_vocab import SimpleVocabulary # initialize simple vocabulary to collect all appeared in the dataset classes classes_vocab = SimpleVocabulary( save_path='./snips/classes.dict', load_path='./snips/classes.dict') classes_vocab.fit((train_iterator.get_instances(data_type='train')[1]...
2019-02-12 12:14:25.35 INFO in 'deeppavlov.core.data.simple_vocab'['simple_vocab'] at line 89: [saving vocabulary to /home/vimary/ipavlov/Pilot/examples/tutorials/snips/classes.dict]
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Let's see what classes the dataset contains and their indices in the vocabulary.
list(classes_vocab.items()) # also one can collect vocabulary of textual tokens appeared 2 and more times in the dataset token_vocab = SimpleVocabulary( save_path='./snips/tokens.dict', load_path='./snips/tokens.dict', min_freq=2, special_tokens=('<PAD>', '<UNK>',), unk_token='<UNK>') token_vocab.fi...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
FeaturizationThis part contains several possible ways of featurization of text samples. One can chose any appropriate vectorizer/embedder according to available resources and given task.Bag-of-words (BoW) and TF-IDF vectorizers converts text samples to vectors (one vector per sample) while fastText, GloVe, fastText we...
import numpy as np from deeppavlov.models.embedders.bow_embedder import BoWEmbedder # initialize bag-of-words embedder giving total number of tokens bow = BoWEmbedder(depth=token_vocab.len) # it assumes indexed tokenized samples bow(token_vocab(str_lower(tokenizer(['Is it freezing in Offerman, California?'])))) # all 8...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
TF-IDF VectorizerMatches a vector to each text sample: text -> vector $v$ from $R^N$ where $N$ is a vocabulary size.$TF-IDF(token, document) = TF(token, document) * IDF(token, document)$$TF$ is a term frequency:$TF(token, document) = \frac{n_{token}}{\sum_{k}n_k}.$$IDF$ is a inverse document frequency:$IDF(token, all\...
from deeppavlov.models.sklearn import SklearnComponent # initialize TF-IDF vectorizer sklearn component with `transform` as infer method tfidf = SklearnComponent( model_class="sklearn.feature_extraction.text:TfidfVectorizer", infer_method="transform", save_path='./tfidf_v0.pkl', load_path='./tfidf_v0.pk...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
GloVe embedder[GloVe](https://nlp.stanford.edu/projects/glove/) is an unsupervised learning algorithm for obtaining vector representations for words. Training is performed on aggregated global word-word co-occurrence statistics from a corpus, and the resulting representations showcase interesting linear substructures ...
from deeppavlov.models.embedders.glove_embedder import GloVeEmbedder
Using TensorFlow backend.
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Let's download GloVe embedding file
simple_download(url="http://files.deeppavlov.ai/embeddings/glove.6B.100d.txt", destination="./glove.6B.100d.txt") embedder = GloVeEmbedder(load_path='./glove.6B.100d.txt', dim=100, pad_zero=True) # output shape is (batch_size x max_num_tokens_in_the_batch x embedding_dim) embed...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Mean GloVe embedder Embedder returns a vector per token while we want to get a vector per text sample. Therefore, let's calculate mean vector of embeddings of tokens. For that we can either init `GloVeEmbedder` with `mean=True` parameter (`mean=false` by default), or pass `mean=true` while calling function (this way `...
# output shape is (batch_size x embedding_dim) embedded_batch = embedder(str_lower(tokenizer(['Is it freezing in Offerman, California?'])), mean=True) len(embedded_batch), embedded_batch[0].shape
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
GloVe weighted by TF-IDF embedderOne of the possible ways to combine TF-IDF vectorizer and any token embedder is to weigh token embeddings by TF-IDF coefficients (therefore, `mean` set to True is obligatory to obtain embeddings of interest while it still **by default** returns embeddings of tokens.
from deeppavlov.models.embedders.tfidf_weighted_embedder import TfidfWeightedEmbedder weighted_embedder = TfidfWeightedEmbedder( embedder=embedder, # our GloVe embedder instance tokenizer=tokenizer, # our tokenizer instance mean=True, # to return one vector per sample vectorizer=tfidf # our TF-IDF v...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Models
from deeppavlov.metrics.accuracy import sets_accuracy # get all train and valid data from iterator x_train, y_train = train_iterator.get_instances(data_type="train") x_valid, y_valid = train_iterator.get_instances(data_type="valid")
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Models in python SklearnComponent classifier on Tfidf-features in python
# initialize sklearn classifier, all parameters for classifier could be passed cls = SklearnComponent( model_class="sklearn.linear_model:LogisticRegression", infer_method="predict", save_path='./logreg_v0.pkl', load_path='./logreg_v0.pkl', C=1, mode='train') # fit sklearn classifier and save it ...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
KerasClassificationModel on GloVe embeddings in python
from deeppavlov.models.classifiers.keras_classification_model import KerasClassificationModel from deeppavlov.models.preprocessors.one_hotter import OneHotter from deeppavlov.models.classifiers.proba2labels import Proba2Labels # Intialize `KerasClassificationModel` that composes CNN shallow-and-wide network # (name he...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
SklearnComponent classifier on GloVe weighted by TF-IDF embeddings in python
# initialize sklearn classifier, all parameters for classifier could be passed cls = SklearnComponent( model_class="sklearn.linear_model:LogisticRegression", infer_method="predict", save_path='./logreg_v1.pkl', load_path='./logreg_v1.pkl', C=1, mode='train') # fit sklearn classifier and save it ...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Let's free our memory from embeddings and models
embedder.reset() cls.reset()
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Models from configs
from deeppavlov import build_model from deeppavlov import train_model
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
SklearnComponent classifier on Tfidf-features from config
logreg_config = { "dataset_reader": { "class_name": "basic_classification_reader", "x": "text", "y": "intents", "data_path": "./snips" }, "dataset_iterator": { "class_name": "basic_classification_iterator", "seed": 42, "split_seed": 23, "field_to_split": "train", "split_fields"...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
KerasClassificationModel on GloVe embeddings from config
cnn_config = { "dataset_reader": { "class_name": "basic_classification_reader", "x": "text", "y": "intents", "data_path": "snips" }, "dataset_iterator": { "class_name": "basic_classification_iterator", "seed": 42, "split_seed": 23, "field_to_split": "train", "split_fields": [ ...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
SklearnComponent classifier on GloVe weighted by TF-IDF embeddings from config
logreg_config = { "dataset_reader": { "class_name": "basic_classification_reader", "x": "text", "y": "intents", "data_path": "snips" }, "dataset_iterator": { "class_name": "basic_classification_iterator", "seed": 42, "split_seed": 23, "field_to_split": "train", "split_fields"...
_____no_output_____
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Bonus: pre-trained CNN model in DeepPavlov Download model files (`wiki.en.bin` 8Gb embeddings): ! python -m deeppavlov download intents_snips_big Evaluate metrics on validation set (no test set provided): ! python -m deeppavlov evaluate intents_snips_big Or one can use model from python code:
from pathlib import Path import deeppavlov from deeppavlov import build_model, evaluate_model from deeppavlov.download import deep_download config_path = Path(deeppavlov.__file__).parent.joinpath('configs/classifiers/intents_snips_big.json') # let's download all the required data - model files, embeddings, vocabulari...
2018-12-13 18:45:33.675 WARNING in 'deeppavlov.dataset_readers.basic_classification_reader'['basic_classification_reader'] at line 97: Cannot find /home/dilyara/.deeppavlov/downloads/snips/valid.csv file 2018-12-13 18:45:33.675 WARNING in 'deeppavlov.dataset_readers.basic_classification_reader'['basic_classification_re...
Apache-2.0
examples/classification_tutorial.ipynb
ayeffkay/DeepPavlov
Auto MPG data
dataset_path = '/Users/mehdi/.keras/datasets/auto-mpg.data' # read using pandas column_names = ['MPG','Cylinders','Displacement','Horsepower','Weight', 'Acceleration', 'Model Year', 'Origin'] raw_dataset = pd.read_csv(dataset_path, names=column_names, na_values = "?", comment='\t',...
_____no_output_____
MIT
notebooks/trunk/regression-v2.ipynb
mehdirezaie/LSSutils
The aim of this notebook is to explore the following questions: - [ ] Does CSR ongevellan have similar numbers as the incident data that has been provided by RWS - [ ] Is there a common key between the 2 datasets such that we can beef up RWS using Ongavellen.
rws = pd.read_sql('select * from rws_schema.ongevallen_raw;', con=conn) csr = pd.read_sql('select * from rws_schema.incidents;', con=conn) csr.head() rws.columns csr.columns csr.inc_type.value_counts(normalize=True) csr.loc[:,'inc_start'] = pd.to_datetime(csr.inc_start) csr.loc[:,'date'] = csr.inc_start.apply(lambda x...
_____no_output_____
MIT
notebooks/EDA - Incident data from CSR vs Ongevallen from RWS.ipynb
G-Simeone/Learning_Accident_Occurence_on_Dutch_Highways
Do they have a common key?
# what are the common columns c = set(csr.columns) r = set(rws.columns) c.intersection(r) r.intersection(c)
_____no_output_____
MIT
notebooks/EDA - Incident data from CSR vs Ongevallen from RWS.ipynb
G-Simeone/Learning_Accident_Occurence_on_Dutch_Highways
Because column names have been edited in english, so there is no direct intersection
csr.loc[csr.inc_type=='Ongeval'] rws.head() csr.shape pd.to_numeric(rws.id_jaar.map(lambda x: x.split('.')[0])).describe()
_____no_output_____
MIT
notebooks/EDA - Incident data from CSR vs Ongevallen from RWS.ipynb
G-Simeone/Learning_Accident_Occurence_on_Dutch_Highways
Non Numerical datanon_numerical_data = train.select_dtypes(include="object")non_numerical_data.head(3)train.head()
#Numerical data numerical_data = train.select_dtypes(exclude="object") numerical_data.head(3) train.head() #Sub every empty postion with smtg numericals = train.select_dtypes(include=[np.number]).columns.tolist() numericals.remove("TomorrowRainForecast") #Get categoricals categoricals = train.select_dtypes(exclude=[np...
_____no_output_____
MIT
Binary-Classification/it will rain tomorrow/notebooks/Binary Classification-Random Forest.ipynb
mamonteiro-brg/Lisbon-Data-Science-Academy
Parcels Experiment:Expanding the polyline code to release particles at density based on local velocity normal to section._(Based on an experiment originally designed by Christina Schmidt.)__(Runs on GEOMAR Jupyter Server at https://schulung3.geomar.de/user/workshop007/lab)_ To do- Check/ask how OceanParcels deals wit...
%matplotlib inline from parcels import ( AdvectionRK4_3D, ErrorCode, FieldSet, JITParticle, ParticleSet, Variable ) # from operator import attrgetter from datetime import datetime, timedelta import numpy as np from pathlib import Path import matplotlib.pyplot as plt import cmocean as co import...
INFO: Compiled ParcelsRandom ==> /tmp/parcels-62665/libparcels_random_657e0035-5181-471b-9b3b-09640069ddf8.so
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Experiment settings (user input) ParametersThese can be set in papermill
# OSNAP multiline details sectionPathname = '../data/external/' sectionFilename = 'osnap_pos_wp.txt' sectionname = 'osnap' # location of input data path_name = '/data/iAtlantic/ocean-only/VIKING20X.L46-KKG36107B/nemo/output/' experiment_name = 'VIKING20X.L46-KKG36107B' data_resolution = '1m' w_name_extension = '_repai...
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Derived variables
# times t_0 = datetime.fromisoformat(t_0_str) # using monthly mean fields. Check dates. t_start = datetime.fromisoformat(t_start_str) # RNG seed based on release day (days since 1980-01-03) RNG_seed = int((t_start - t_0).total_seconds() / (60*60*24)) # names of files to load fname_U = f'1_{experiment_name}_{data_res...
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Construct input / output paths etc.
mesh_mask = mask_path / mesh_mask_filename
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Load input datasets
def fieldset_defintions( list_of_filenames_U, list_of_filenames_V, list_of_filenames_W, list_of_filenames_T, mesh_mask ): ds_mask = xr.open_dataset(mesh_mask) filenames = {'U': {'lon': (mesh_mask), 'lat': (mesh_mask), 'depth': list_of_filenames_W[0]...
[PosixPath('/gxfs_work1/geomar/smomw355/model_data/ocean-only/VIKING20X.L46-KKG36107B/nemo/output/1_VIKING20X.L46-KKG36107B_5d_19800101_19801231_grid_U.nc'), PosixPath('/gxfs_work1/geomar/smomw355/model_data/ocean-only/VIKING20X.L46-KKG36107B/nemo/output/1_VIKING20X.L46-KKG36107B_5d_19810101_19811231_grid_U.nc'), Posix...
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Create Virtual Particles add a couple of simple plotting routines
def plot_section_sdist(): plt.figure(figsize=(10,5)) u = np.array([p.uvel for p in pset]) * degree2km * 1000.0 * np.cos(np.radians(pset.lat)) v = np.array([p.vvel for p in pset]) * degree2km * 1000.0 section_index = np.searchsorted(lonlat.lon,pset.lon)-1 u_normal = v * lonlatdiff.costheta[section_i...
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Create a set of particles with random initial positionsWe seed the RNG to be reproducible (and to be able to quickly create a second equivalent experiment with differently chosen compatible initial positions), and create arrays of random starting times, lats, lons, depths, and speed parameters (see kernel definitions ...
lonlat = xr.Dataset(pd.read_csv(sectionPath / sectionFilename,delim_whitespace=True)) lonlat.lon.attrs['long_name']='Longitude' lonlat.lat.attrs['long_name']='Latitude' lonlat.lon.attrs['standard_name']='longitude' lonlat.lat.attrs['standard_name']='latitude' lonlat.lon.attrs['units']='degrees_east' lonlat.lat.attrs['u...
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Seed particles uniform random along OSNAP section
np.random.seed(RNG_seed) # define time of release for each particle relative to t0 # can start each particle at a different time if required # here all start at time t_start. times = [] lons = [] lats = [] depths = [] # for subsect in range(lonlatdiff.length.shape[0]): for subsect in range(start_vertex,end_vertex): ...
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Build particle set
%%time pset = ParticleSet( fieldset=fieldset, pclass=SampleParticle, lat=lat, lon=lon, # speed_param=speed_param, depth=depth, time=time # repeatdt = repeatdt ) print(f"Created {len(pset)} particles.") # display(pset[:5]) # display(pset[-5:])
Created 2643886 particles.
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Compose custom kernelWe'll create three additional kernels:- One Kernel adds velocity sampling- One Kernel adds temperature sampling- One kernel adds salinity samplingThen, we combine the builtin `AdvectionRK4_3D` kernel with these additional kernels.
def velocity_sampling(particle, fieldset, time): '''Sample velocity.''' (particle.uvel,particle.vvel) = fieldset.UV[time, particle.depth, particle.lat, particle.lon] def temperature_sampling(particle, fieldset, time): '''Sample temperature.''' particle.temp = fieldset.T[time, particle.dep...
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Be able to handle errors during integrationWe have restricted our domain so in principle, particles could reach undefined positions.In that case, we want to just delete the particle (without forgetting its history).
def DeleteParticle(particle, fieldset, time): particle.delete() recovery_cases = { ErrorCode.ErrorOutOfBounds: DeleteParticle, ErrorCode.Error: DeleteParticle, ErrorCode.ErrorInterpolation: DeleteParticle }
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Run with runtime=0 to initialise fields
%%time # with dask.config.set(**{'array.slicing.split_large_chunks': False}): pset.execute( custom_kernel, runtime=0, # dt=timedelta(minutes=0), # output_file=outputfile, recovery=recovery_cases ) plot_section_sdist()
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Trim unwanted points from ParticleSetUse initialised fields to remove land points. We test `temp == 0.0` (the mask value over land).
t = np.array([p.temp for p in pset]) # u = np.array([p.uvel for p in pset]) # v = np.array([p.vvel for p in pset]) pset.remove_indices(np.argwhere(t == 0).flatten()) # pset.remove(np.argwhere(x * y * z == 0).flatten()) print(len(pset)) plot_section_sdist()
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Test velocity normal to section Velocity conversions from degrees lat/lon per second to m/s
u = np.array([p.uvel for p in pset]) v = np.array([p.vvel for p in pset]) u=u * degree2km * 1000.0 * np.cos(np.radians(pset.lat)) v=v * degree2km * 1000.0
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
normal velocities
section_index = np.searchsorted(lonlat.lon,pset.lon)-1 u_normal = v * lonlatdiff.costheta[section_index].data - u * lonlatdiff.sintheta[section_index].data abs(u_normal).max()
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
remove particles randomly with probability proportional to normal speed
u_random = np.random.rand(len(u_normal))*max_current pset.remove_indices(np.argwhere(abs(u_normal) < u_random).flatten()) print(len(pset)) plot_section_sdist()
_____no_output_____
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Prepare outputWe define an output file and specify the desired output frequency.
# output_filename = 'Parcels_IFFForwards_1m_June2016_2000.nc' npart = str(len(pset)) output_filename = 'tracks_randomvel_mxl_'+sectionname+direction+year_str+month_str+day_str+'_N'+npart+'_D'+days+'_Rnd'+ seed+'.nc' outfile = outpath / output_filename print(outfile) outputfile = pset.ParticleFile( name=outfile, ...
../data/raw/tracks_randomvel_mxl_osnap_backward_20191020_N59894_D3650_Rnd14535.nc
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Execute the experimentWe'll evolve particles, log their positions and variables to the output buffer and finally export the output to a the file. Run the experiment
%%time # with dask.config.set(**{'array.slicing.split_large_chunks': False}): pset.execute( custom_kernel, runtime=timedelta(days=runtime_in_days), dt=timedelta(minutes=dt_in_minutes), output_file=outputfile, recovery=recovery_cases ) # outputfile.export() outputfile.close() conda list p...
Package Version ----------------------------- -------------------------- alembic 1.5.5 ansiwrap 0.8.4 anyio 2.2.0 appdirs 1.4.4 argon2-cffi 20.1.0 asciitree 0.3.3 ...
MIT
notebooks/executed/037_afox_RunParcels_TS_MXL_Multiline_Randomvel_Papermill_executed_2019-10-20.ipynb
alanfox/spg_fresh_blob_202104
Plotly - Create Candlestick chart **Tags:** plotly chart candlestick trading dataviz Input Import libraries
import plotly.graph_objects as go import pandas as pd from datetime import datetime
_____no_output_____
BSD-3-Clause
Plotly/Create Candlestick chart.ipynb
vivard/awesome-notebooks
Model Read a csv and map the plot
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') fig = go.Figure(data=[go.Candlestick(x=df['Date'], open=df['AAPL.Open'], high=df['AAPL.High'], low=df['AAPL.Low'], close=df['AAPL.Close'])])
_____no_output_____
BSD-3-Clause
Plotly/Create Candlestick chart.ipynb
vivard/awesome-notebooks
Output Display result
fig.show()
_____no_output_____
BSD-3-Clause
Plotly/Create Candlestick chart.ipynb
vivard/awesome-notebooks
The idea is to do random patches but try out different methodologies regarding the sampling procedure. First, in the form of weighted samples where ideas from Breiman's Paper (pasting) and Adaboost can be used.Second, in the form of weighted features with respect to correlation (chi square, best of k?) between the sele...
from sklearn.cross_validation import cross_val_score from sklearn.ensemble import BaggingClassifier from sklearn.neighbors import KNeighborsClassifier import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import itertools import sklearn from sklearn.linear_model import LogisticRe...
_____no_output_____
MIT
RANDOM PATCHES WITH NON-UNIFORM SAMPLING.ipynb
kbogas/Cascada
CutMix Callback> Callback to apply [CutMix](https://arxiv.org/pdf/1905.04899.pdf) data augmentation technique to the training data. From the [research paper](https://arxiv.org/pdf/1905.04899.pdf), `CutMix` is a way to combine two images. It comes from `MixUp` and `Cutout`. In this data augmentation technique:> patches...
#export class CutMix(Callback): "Implementation of `https://arxiv.org/abs/1905.04899`" run_after,run_valid = [Normalize],False def __init__(self, alpha=1.): self.distrib = Beta(tensor(alpha), tensor(alpha)) def before_fit(self): self.stack_y = getattr(self.learn.loss_func, 'y_int', False) ...
_____no_output_____
Apache-2.0
nbs/74_callback.cutmix.ipynb
hanshin-back/fastai
How does the batch with `CutMix` data augmentation technique look like? First, let's quickly create the `dls` using `ImageDataLoaders.from_name_re` DataBlocks API.
path = untar_data(URLs.PETS) pat = r'([^/]+)_\d+.*$' fnames = get_image_files(path/'images') item_tfms = [Resize(256, method='crop')] batch_tfms = [*aug_transforms(size=224), Normalize.from_stats(*imagenet_stats)] dls = ImageDataLoaders.from_name_re(path, fnames, pat, bs=64, item_tfms=item_tfms, ...
_____no_output_____
Apache-2.0
nbs/74_callback.cutmix.ipynb
hanshin-back/fastai
Next, let's initialize the callback `CutMix`, create a learner, do one batch and display the images with the labels. `CutMix` inside updates the loss function based on the ratio of the cutout bbox to the complete image.
cutmix = CutMix(alpha=1.) with Learner(dls, resnet18(), loss_func=CrossEntropyLossFlat(), cbs=cutmix) as learn: learn.epoch,learn.training = 0,True learn.dl = dls.train b = dls.one_batch() learn._split(b) learn('before_batch') _,axs = plt.subplots(3,3, figsize=(9,9)) dls.show_batch(b=(cutmix.x,cutm...
_____no_output_____
Apache-2.0
nbs/74_callback.cutmix.ipynb
hanshin-back/fastai
Using `CutMix` in Training
learn = cnn_learner(dls, resnet18, loss_func=CrossEntropyLossFlat(), cbs=cutmix, metrics=[accuracy, error_rate]) # learn.fit_one_cycle(1)
_____no_output_____
Apache-2.0
nbs/74_callback.cutmix.ipynb
hanshin-back/fastai
Export -
#hide from nbdev.export import notebook2script notebook2script()
Converted 00_torch_core.ipynb. Converted 01_layers.ipynb. Converted 01a_losses.ipynb. Converted 02_data.load.ipynb. Converted 03_data.core.ipynb. Converted 04_data.external.ipynb. Converted 05_data.transforms.ipynb. Converted 06_data.block.ipynb. Converted 07_vision.core.ipynb. Converted 08_vision.data.ipynb. Converted...
Apache-2.0
nbs/74_callback.cutmix.ipynb
hanshin-back/fastai
Installing required packages
from IPython.display import clear_output !pip install --upgrade pip !pip install findspark !pip install pyspark clear_output(wait=False)
_____no_output_____
MIT
3_VectorAssembler_example.ipynb
edsonlourenco/pyspark_ml_examples
Importing global objects
import findspark, pyspark from pyspark.sql import SparkSession from pyspark import SparkFiles
_____no_output_____
MIT
3_VectorAssembler_example.ipynb
edsonlourenco/pyspark_ml_examples
Global SettingsNeeded for environments not Databricks
findspark.init() spark = SparkSession.builder.getOrCreate()
_____no_output_____
MIT
3_VectorAssembler_example.ipynb
edsonlourenco/pyspark_ml_examples
Reading data source
url = 'https://raw.githubusercontent.com/edsonlourenco/public_datasets/main/Carros.csv' spark.sparkContext.addFile(url) csv_cars = SparkFiles.get("Carros.csv") df_cars = spark.read.csv(csv_cars, header=True, inferSchema=True, sep=';')
_____no_output_____
MIT
3_VectorAssembler_example.ipynb
edsonlourenco/pyspark_ml_examples
Checking **data**
df_cars.orderBy('Consumo').show(truncate=False)
+-------+---------+-----------+---------------+----+-----+---------+-----------+-------+-----------+---+ |Consumo|Cilindros|Cilindradas|RelEixoTraseiro|Peso|Tempo|TipoMotor|Transmissao|Marchas|Carburadors|HP | +-------+---------+-----------+---------------+----+-----+---------+-----------+-------+-----------+---+ |15 ...
MIT
3_VectorAssembler_example.ipynb
edsonlourenco/pyspark_ml_examples
Transform VectorAssembler Importing **VectorAssembler** class
from pyspark.ml.feature import VectorAssembler
_____no_output_____
MIT
3_VectorAssembler_example.ipynb
edsonlourenco/pyspark_ml_examples
Doing transformation and creating features column
vectas = VectorAssembler(inputCols=[ "Consumo", "Cilindros", "Cilindradas", "RelEixoTraseiro", "Peso", "...
+--------------------+ | features| +--------------------+ |[15.0,8.0,301.0,3...| |[21.0,6.0,160.0,3...| |[21.0,6.0,160.0,3...| |[26.0,4.0,1203.0,...| |[104.0,8.0,472.0,...| |[104.0,8.0,460.0,...| |[133.0,8.0,350.0,...| |[143.0,8.0,360.0,...| |[147.0,8.0,440.0,...| |[152.0,8.0,2758.0...| |[152.0,8.0,304.0,......
MIT
3_VectorAssembler_example.ipynb
edsonlourenco/pyspark_ml_examples
Export
#default_exp templ from nbdev.export import notebook2script notebook2script()
Converted om.ipynb. Converted pspace.ipynb. Converted templ.ipynb.
Apache-2.0
templ.ipynb
mirkoklukas/nbx
Additional dependenciesYou will need to have tensorflow keras pydot and graphviz in your OS installed and added to the path ```bashpython -m pip install pydot``````bashyay graphviz ```bashsudo apt install python-pydot python-pydot-ng graphviz```
import os import sys import time import warnings warnings.filterwarnings("ignore") os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import numpy as np import pandas as pd from pyspark.sql import SparkSession packages = [ 'JohnSnowLabs:spark-nlp: 2.4.2' ] spark = SparkSession \ .builder \ .appName("ML SQL sessio...
_____no_output_____
Apache-2.0
tutorials/jupyter/8- Sarcasm Classifiers (GloVe and CNN).ipynb
nabinkhadka/spark-nlp-workshop
Train your Unet with membrane datamembrane data is in folder membrane/, it is a binary classification task.The input shape of image and mask are the same :(batch_size,rows,cols,channel = 1) Train with data generator
data_gen_args = dict(rotation_range=0.2, width_shift_range=0.05, height_shift_range=0.05, shear_range=0.05, zoom_range=0.05, horizontal_flip=True, fill_mode='nearest') myGene = trainGenerator(2,'data/...
_____no_output_____
MIT
trainUnet.ipynb
chitrakumarsai/Semantic-segmentation---Unet-
Train with npy file
#imgs_train,imgs_mask_train = geneTrainNpy("data/membrane/train/aug/","data/membrane/train/aug/") #model.fit(imgs_train, imgs_mask_train, batch_size=2, nb_epoch=10, verbose=1,validation_split=0.2, shuffle=True, callbacks=[model_checkpoint])
_____no_output_____
MIT
trainUnet.ipynb
chitrakumarsai/Semantic-segmentation---Unet-
test your model and save predicted results
testGene = testGenerator("data/membrane/test") model = unet() model.load_weights("unet_membrane.hdf5") results = model.predict_generator(testGene,30,verbose=1) saveResult("data/membrane/test",results)
C:\Users\xuhaozhi\Documents\Study\unet\model.py:34: UserWarning: The `merge` function is deprecated and will be removed after 08/2017. Use instead layers from `keras.layers.merge`, e.g. `add`, `concatenate`, etc. merge6 = merge([drop4,up6], mode = 'concat', concat_axis = 3) C:\SoftWare\Anaconda2\envs\python3\lib\site...
MIT
trainUnet.ipynb
chitrakumarsai/Semantic-segmentation---Unet-
**Note: Please use the [pyEOF](https://pyeof.readthedocs.io/en/latest/installation.html) environment for this script** This script is used to implement EOF, REOF and k-means clustering to get regions
from pyEOF import * import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt import gc import warnings import pickle from matplotlib.ticker import MaxNLocator from tqdm import tqdm from sklearn.cluster import KMeans import cartopy.crs as ccrs import cartopy.feature as cfeature warning...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
plot the time series of the mean PM2.5 We decided to use April and August as the testing data
mask = xr.open_dataset(mask_path) ds = sel_extent(xr.open_dataset(ds_path)).where(mask["mask"]) ds["PM25"].groupby('time.month').mean(dim=["lon","lat","time"]).plot() plt.show()
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
get the data and implement EOFsBased on the results, we will select 4 PCs (n=4) and implemented varimax rotated EOFs (REOFs)
n=28 # remove months "4" (April) and "8" (August), to be consistant with training data ds = ds.sel(time=ds.time.dt.month.isin([1,2,3, 5,6,7, 9,10,11,12])) df = ds["PM25"].to_dataframe().reset_index() # get df from ds # process the data fo...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
implement REOFs
n=4 # implement REOF pca = df_eof(df_data,pca_type="varimax",n_components=n) eofs = pca.eofs(s=2, n=n) eofs_ds = eofs.stack(["lat","lon"], dropna=False).to_xarray() pcs = pca.pcs(s=2, n=n) evf = pca.evf(n=n) df = pd.DataFrame({"n":np.arange(1,n+1), "evf":pca.evf(n)*100.0, "accum"...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
weighted EOFs loading
eofs_w = pd.DataFrame(data = (eofs.values * evf.reshape(n,1)), index = eofs.index, columns = eofs.columns) eofs_w_ds = eofs_w.stack(["lat","lon"], dropna=False).to_xarray() fig = plt.figure(figsize=(10,2)) for i in range(1,n+1): ax = fig.add_subplot(1,4,i) eofs_w_ds[...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
implement k-Means
# get the index which is not "nan" placeholder_idx = np.argwhere(~np.isnan((eofs_w.values)[0])).reshape(-1) # get the matrix without missing values: locations (row) * EOFs (columns) m = eofs_w.values[:,placeholder_idx].transpose() # clustering and calculate the Sum_of_squared_distances Sum_of_squared_distances = [] K ...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
we select n_cluster = 6 to further the analysis
n_cluster = 6 fig = plt.figure(figsize=(8,3)) ax = fig.add_subplot(121) ax.plot(K, Sum_of_squared_distances, 'bx-') ax.plot(n_cluster,Sum_of_squared_distances[n_cluster-2],"rx") ax.set_xlabel('number of clusters') ax.set_ylabel('sum of squared distances') # ax.set_title('Elbow method for optimal number of clusters') ...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
use n_cluster = 6 to implement the clusters
clusters = KMeans(n_clusters=n_cluster, random_state=66).fit_predict(m) df_f = eofs.copy() df_f.loc[str(n+1),:] = np.nan df_f.iloc[n,placeholder_idx] = clusters ds_f = df_f.stack(["lat","lon"], dropna=False).to_xarray() fig = plt.figure(figsize=(3,3)) ax = fig.add_subplot(111, projection=ccrs.PlateCarree()) ax.set_ex...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
save the clusters masks
fig = plt.figure(figsize=(2*n_cluster,2)) for i in range(n_cluster): ax = fig.add_subplot(1,n_cluster,i+1) ds_f["mask_"+str(i)] = ds_regions.where(ds_regions==i).notnull().squeeze() ds_f["mask_"+str(i)].plot(ax=ax,cbar_kwargs={"label":""}) ax.set_title("mask_"+str(i)) plt.tight_layout() plt.show() mask...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
save the regional masks
cluster_mask = xr.open_dataset("./data/cluster_mask_"+str(n_cluster)+".nc",engine="scipy") fig = plt.figure(figsize=(2*n_cluster,2)) for i in range(n_cluster): ax = fig.add_subplot(1,n_cluster,i+1) ds.mean(dim="time").where(cluster_mask["mask_"+str(i)])["PM25"].plot(ax=ax,cbar_kwargs={"label":""}) ax.set_ti...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
save and load the regional mask
# save the regional mask cluster_mask.to_netcdf("./data/r_mask.nc",engine="scipy") # load the regional mask test = xr.open_dataset("./data/r_mask.nc",engine="scipy") fig = plt.figure(figsize=(n_cluster*2,2)) for i in range(len(loc_name)): ax = fig.add_subplot(1,n_cluster,i+1) ds.mean(dim="time").where(test[loc...
_____no_output_____
MIT
1_get_regions_eof_reofs.ipynb
zzheng93/code_DSI_India_AutoML
![image.png](attachment:image.png) Link Prediction - IntroductionIn this Notebook we are going to examine the process of using Amazon Neptune ML feature to perform link prediction in a property graph. Note: This notebook take approximately 1 hour to complete[Neptune ML](https://docs.aws.amazon.com/neptune/latest/user...
import neptune_ml_utils as neptune_ml neptune_ml.check_ml_enabled()
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
If the check above did not say that this cluster is ready to run Neptune ML jobs then please check that the cluster meets all the pre-requisites defined [here](https://docs.aws.amazon.com/neptune/latest/userguide/machine-learning.htmlmachine-learning-overview). Load the dataThe first step in building a Neptune ML model...
s3_bucket_uri="s3://<INSERT S3 BUCKET OR PATH>" # remove trailing slashes s3_bucket_uri = s3_bucket_uri[:-1] if s3_bucket_uri.endswith('/') else s3_bucket_uri
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Now that you have provided an S3 bucket, run the cell below which will download and format the MovieLens data into a format compatible with Neptune's bulk loader.
response = neptune_ml.prepare_movielens_data(s3_bucket_uri)
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
This process only takes a few minutes and once it has completed you can load the data using the `%load` command in the cell below.
%load -s {response} -f csv -p OVERSUBSCRIBE --run
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Check to make sure the data is loadedOnce the cell has completed, the data has been loaded into the cluster. We verify the data loaded correctly by running the traversals below to see the count of nodes by label: Note: The numbers below assume no other data is in the cluster
%%gremlin g.V().groupCount().by(label).unfold()
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
If our nodes loaded correctly then the output is:* 19 genres* 1682 movies* 100000 rating* 943 usersTo check that our edges loaded correctly we check the edge counts:
%%gremlin g.E().groupCount().by(label).unfold()
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
If our edges loaded correctly then the output is:* 100000 about* 2893 included_in* 100000 rated* 100000 wrote Preparing for exportWith our data validated let's remove a few `rated` vertices so that we can build a model that predicts these missing connections. In a normal scenario, the data you would like to predict is...
%%gremlin g.V('user_1').outE('rated')
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Now let's remove these edges to simulate them missing from our data.
%%gremlin g.V('user_1').outE('rated').drop()
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook
Checking our data again we see that the edges have now been removed.
%%gremlin g.V('user_1').outE('rated')
_____no_output_____
ISC
src/graph_notebook/notebooks/04-Machine-Learning/Neptune-ML-03-Introduction-to-Link-Prediction-Gremlin.ipynb
zacharyrs/graph-notebook