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
Render queries from CARTO
from cartoframes import QueryLayer lines = QueryLayer( ''' WITH capitals as ( select * from populated_places where featurecla like 'Admin-0 capital' ) select pp.cartodb_id, pp.pop_max, ST_MakeLine(c.the_geom,pp.the_geom) as the_geom, ST_MakeLine(c....
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Crazy queriesYou can render fancy queries, more details [here](https://gist.github.com/jsanz/8aeb48a274e3b787ca57)
query = ''' with -- first data data as ( SELECT * FROM jsanz.ne_10m_populated_places_simple_7 WHERE (megacity >= 0.5 AND megacity <= 1) AND featurecla IN ('Admin-0 capital','Admin-1 region capital','Admin-0 region capital','Admin-0 capital alt') ), -- from dubai origin as ( select * from jsanz.ne_10m_popu...
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Create a new table on CARTO
df_spain = df[(df['adm0_a3'] == 'ESP')] df_spain['name'].head() cc.write(df_spain, 'places_spain', overwrite=True) cc.query('SELECT DISTINCT adm0_a3 FROM places_spain')
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Modify schema and data Drop a column
df_spain = df[(df['adm0_a3'] == 'ESP')] df_spain = df_spain.drop('adm0_a3', 1) cc.write(df_spain, 'places_spain', overwrite=True) try: cc.query('SELECT DISTINCT adm0_a3 FROM places_spain') except Exception as e: print(e)
['column "adm0_a3" does not exist']
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Add `València` as an alternate name for the city of `Valencia`
vlc_id = df_spain[df.apply(lambda x: x['name'] == 'Valencia', axis=1)].index.values[0] df_spain = df_spain.set_value(vlc_id,'cityalt','València') # THE FUTURE # cc.sync(df_spain,'places_spain') # THE PRESENT cc.write(df_spain, 'places_spain', overwrite=True) cc.query('''SELECT name,cityalt from places_spain WHERE car...
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Delete the table
cc.delete('places_spain')
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
import pandas as pd import os import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.model_selection import GridSearchCV from sklearn.svm import SVR os.listdir('sample_data') data = pd.read_csv('sample_da...
_____no_output_____
MIT
TrainGridSearch.ipynb
ibnuhajar/TrainingMachineLearning
Predict tags on StackOverflow with linear models In this assignment you will learn how to predict tags for posts from [StackOverflow](https://stackoverflow.com). To solve this task you will use multilabel classification approach. LibrariesIn this task you will need the following libraries:- [Numpy](http://www.numpy.or...
! wget https://raw.githubusercontent.com/hse-aml/natural-language-processing/master/setup_google_colab.py -O setup_google_colab.py import setup_google_colab setup_google_colab.setup_week1() import sys sys.path.append("..") from common.download_utils import download_week1_resources download_week1_resources()
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
GradingWe will create a grader instance below and use it to collect your answers. Note that these outputs will be stored locally inside grader and will be uploaded to platform only after running submitting function in the last part of this assignment. If you want to make partial submission, you can run that cell any t...
from grader import Grader grader = Grader()
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Text preprocessing For this and most of the following assignments you will need to use a list of stop words. It can be downloaded from *nltk*:
import nltk nltk.download('stopwords') from nltk.corpus import stopwords
[nltk_data] Downloading package stopwords to /root/nltk_data... [nltk_data] Unzipping corpora/stopwords.zip.
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
In this task you will deal with a dataset of post titles from StackOverflow. You are provided a split to 3 sets: *train*, *validation* and *test*. All corpora (except for *test*) contain titles of the posts and corresponding tags (100 tags are available). The *test* set is provided for Coursera's grading and doesn't co...
from ast import literal_eval import pandas as pd import numpy as np def read_data(filename): data = pd.read_csv(filename, sep='\t') data['tags'] = data['tags'].apply(literal_eval) return data train = read_data('data/train.tsv') validation = read_data('data/validation.tsv') test = pd.read_csv('data/test.tsv'...
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
As you can see, *title* column contains titles of the posts and *tags* column contains the tags. It could be noticed that a number of tags for a post is not fixed and could be as many as necessary. For a more comfortable usage, initialize *X_train*, *X_val*, *X_test*, *y_train*, *y_val*.
X_train, y_train = train['title'].values, train['tags'].values X_val, y_val = validation['title'].values, validation['tags'].values X_test = test['title'].values
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
One of the most known difficulties when working with natural data is that it's unstructured. For example, if you use it "as is" and extract tokens just by splitting the titles by whitespaces, you will see that there are many "weird" tokens like *3.5?*, *"Flip*, etc. To prevent the problems, it's usually useful to prepa...
import re REPLACE_BY_SPACE_RE = re.compile('[/(){}\[\]\|@,;]') BAD_SYMBOLS_RE = re.compile('[^0-9a-z #+_]') STOPWORDS = set(stopwords.words('english')) def text_prepare(text): """ text: a string return: modified initial string """ text = text.lower() # lowercase text text = re....
Basic tests are passed.
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Run your implementation for questions from file *text_prepare_tests.tsv* to earn the points.
prepared_questions = [] for line in open('data/text_prepare_tests.tsv', encoding='utf-8'): line = text_prepare(line.strip()) prepared_questions.append(line) text_prepare_results = '\n'.join(prepared_questions) grader.submit_tag('TextPrepare', text_prepare_results)
Current answer for task TextPrepare is: sqlite php readonly creating multiple textboxes dynamically self one prefer javascript save php date...
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Now we can preprocess the titles using function *text_prepare* and making sure that the headers don't have bad symbols:
X_train = [text_prepare(x) for x in X_train] X_val = [text_prepare(x) for x in X_val] X_test = [text_prepare(x) for x in X_test] X_train[:3]
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
For each tag and for each word calculate how many times they occur in the train corpus. **Task 2 (WordsTagsCount).** Find 3 most popular tags and 3 most popular words in the train data and submit the results to earn the points.
from collections import Counter # Dictionary of all tags from train corpus with their counts. tags_counts = Counter() #{} # Dictionary of all words from train corpus with their counts. words_counts = Counter() #{} ###################################### ######### YOUR CODE HERE ############# ###########################...
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
We are assuming that *tags_counts* and *words_counts* are dictionaries like `{'some_word_or_tag': frequency}`. After applying the sorting procedure, results will be look like this: `[('most_popular_word_or_tag', frequency), ('less_popular_word_or_tag', frequency), ...]`. The grader gets the results in the following for...
most_common_tags = sorted(tags_counts.items(), key=lambda x: x[1], reverse=True)[:3] most_common_words = sorted(words_counts.items(), key=lambda x: x[1], reverse=True)[:3] grader.submit_tag('WordsTagsCount', '%s\n%s' % (','.join(tag for tag, _ in most_common_tags), ','....
Current answer for task WordsTagsCount is: javascript,c#,java using,php,java...
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Transforming text to a vectorMachine Learning algorithms work with numeric data and we cannot use the provided text data "as is". There are many ways to transform text data to numeric vectors. In this task you will try to use two of them. Bag of wordsOne of the well-known approaches is a *bag-of-words* representation....
most_common_words = sorted(words_counts.items(), key=lambda x: x[1], reverse=True)[:5002] WORDS_TO_INDEX = {p[0]:i for i,p in enumerate(most_common_words[:5])} print(WORDS_TO_INDEX) DICT_SIZE = 5000 WORDS_TO_INDEX = {p[0]:i for i,p in enumerate(most_common_words[:DICT_SIZE])} INDEX_TO_WORDS = {WORDS_TO_INDEX[k]:k for k...
Basic tests are passed.
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Now apply the implemented function to all samples (this might take up to a minute):
from scipy import sparse as sp_sparse X_train_mybag = sp_sparse.vstack([sp_sparse.csr_matrix(my_bag_of_words(text, WORDS_TO_INDEX, DICT_SIZE)) for text in X_train]) X_val_mybag = sp_sparse.vstack([sp_sparse.csr_matrix(my_bag_of_words(text, WORDS_TO_INDEX, DICT_SIZE)) for text in X_val]) X_test_mybag = sp_sparse.vstack(...
X_train shape (100000, 5000) X_val shape (30000, 5000) X_test shape (20000, 5000)
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
As you might notice, we transform the data to sparse representation, to store the useful information efficiently. There are many [types](https://docs.scipy.org/doc/scipy/reference/sparse.html) of such representations, however sklearn algorithms can work only with [csr](https://docs.scipy.org/doc/scipy/reference/generat...
row = X_train_mybag[10].toarray()[0] non_zero_elements_count = np.count_nonzero(row) grader.submit_tag('BagOfWords', str(non_zero_elements_count)) len(row)
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
TF-IDFThe second approach extends the bag-of-words framework by taking into account total frequencies of words in the corpora. It helps to penalize too frequent words and provide better features space. Implement function *tfidf_features* using class [TfidfVectorizer](http://scikit-learn.org/stable/modules/generated/sk...
from sklearn.feature_extraction.text import TfidfVectorizer def tfidf_features(X_train, X_val, X_test): """ X_train, X_val, X_test — samples return TF-IDF vectorized representation of each sample and vocabulary """ # Create TF-IDF vectorizer with a proper parameters choice # Fit ...
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Once you have done text preprocessing, always have a look at the results. Be very careful at this step, because the performance of future models will drastically depend on it. In this case, check whether you have c++ or c in your vocabulary, as they are obviously important tokens in our tags prediction task:
X_train_tfidf, X_val_tfidf, X_test_tfidf, tfidf_vocab = tfidf_features(X_train, X_val, X_test) tfidf_reversed_vocab = {i:word for word,i in tfidf_vocab.items()} print('c++' in tfidf_vocab) print('c#' in tfidf_vocab)
True True
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
If you can't find it, we need to understand how did it happen that we lost them? It happened during the built-in tokenization of TfidfVectorizer. Luckily, we can influence on this process. Get back to the function above and use '(\S+)' regexp as a *token_pattern* in the constructor of the vectorizer. Now, use this tr...
######### YOUR CODE HERE ############# print('c++' in tfidf_vocab) print('c#' in tfidf_vocab)
True True
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
MultiLabel classifierAs we have noticed before, in this task each example can have multiple tags. To deal with such kind of prediction, we need to transform labels in a binary form and the prediction will be a mask of 0s and 1s. For this purpose it is convenient to use [MultiLabelBinarizer](http://scikit-learn.org/sta...
from sklearn.preprocessing import MultiLabelBinarizer mlb = MultiLabelBinarizer(classes=sorted(tags_counts.keys())) y_train = mlb.fit_transform(y_train) y_val = mlb.fit_transform(y_val) y_train[0]
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Implement the function *train_classifier* for training a classifier. In this task we suggest to use One-vs-Rest approach, which is implemented in [OneVsRestClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html) class. In this approach *k* classifiers (= number of tags)...
from sklearn.multiclass import OneVsRestClassifier from sklearn.linear_model import LogisticRegression, RidgeClassifier def train_classifier(X_train, y_train, C = 1.0, penalty = 'l2'): """ X_train, y_train — training data return: trained classifier """ # Create and fit LogisticRegres...
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Train the classifiers for different data transformations: *bag-of-words* and *tf-idf*.
classifier_mybag = train_classifier(X_train_mybag, y_train) classifier_tfidf = train_classifier(X_train_tfidf, y_train)
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Now you can create predictions for the data. You will need two types of predictions: labels and scores.
y_val_predicted_labels_mybag = classifier_mybag.predict(X_val_mybag) y_val_predicted_scores_mybag = classifier_mybag.decision_function(X_val_mybag) y_val_predicted_labels_tfidf = classifier_tfidf.predict(X_val_tfidf) y_val_predicted_scores_tfidf = classifier_tfidf.decision_function(X_val_tfidf)
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Now take a look at how classifier, which uses TF-IDF, works for a few examples:
y_val_pred_inversed = mlb.inverse_transform(y_val_predicted_labels_tfidf) y_val_inversed = mlb.inverse_transform(y_val) for i in range(3): print('Title:\t{}\nTrue labels:\t{}\nPredicted labels:\t{}\n\n'.format( X_val[i], ','.join(y_val_inversed[i]), ','.join(y_val_pred_inversed[i]) ))
Title: odbc_exec always fail True labels: php,sql Predicted labels: Title: access base classes variable within child class True labels: javascript Predicted labels: Title: contenttype application json required rails True labels: ruby,ruby-on-rails Predicted labels: json,ruby-on-rails
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Now, we would need to compare the results of different predictions, e.g. to see whether TF-IDF transformation helps or to try different regularization techniques in logistic regression. For all these experiments, we need to setup evaluation procedure. EvaluationTo evaluate the results we will use several classificati...
from sklearn.metrics import accuracy_score from sklearn.metrics import f1_score from sklearn.metrics import roc_auc_score from sklearn.metrics import average_precision_score from sklearn.metrics import recall_score
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Implement the function *print_evaluation_scores* which calculates and prints to stdout: - *accuracy* - *F1-score macro/micro/weighted* - *Precision macro/micro/weighted*
def print_evaluation_scores(y_val, predicted): ###################################### ######### YOUR CODE HERE ############# ###################################### #print('accuracy') print(f1_score(y_val, predicted, average = 'weighted')) """ #print('f1_score_macro') print(f1_score(...
Bag-of-words 0.6486956090682869 Tfidf 0.6143558163126149
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
You might also want to plot some generalization of the [ROC curve](http://scikit-learn.org/stable/modules/model_evaluation.htmlreceiver-operating-characteristic-roc) for the case of multi-label classification. Provided function *roc_auc* can make it for you. The input parameters of this function are: - true labels - de...
from metrics import roc_auc %matplotlib inline n_classes = len(tags_counts) roc_auc(y_val, y_val_predicted_scores_mybag, n_classes) n_classes = len(tags_counts) roc_auc(y_val, y_val_predicted_scores_tfidf, n_classes)
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
**Task 4 (MultilabelClassification).** Once we have the evaluation set up, we suggest that you experiment a bit with training your classifiers. We will use *F1-score weighted* as an evaluation metric. Our recommendation:- compare the quality of the bag-of-words and TF-IDF approaches and chose one of them.- for the chos...
def EvaluateDifferentModel(C, penalty) : classifier_mybag = train_classifier(X_train_mybag, y_train, C, penalty) classifier_tfidf = train_classifier(X_train_tfidf, y_train, C, penalty) y_val_predicted_labels_mybag = classifier_mybag.predict(X_val_mybag) y_val_predicted_scores_mybag = classifier_mybag.d...
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
When you are happy with the quality, create predictions for *test* set, which you will submit to Coursera.
test_predictions = y_test_predicted_labels_tfidf ######### YOUR CODE HERE ############# test_pred_inversed = mlb.inverse_transform(test_predictions) test_predictions_for_submission = '\n'.join('%i\t%s' % (i, ','.join(row)) for i, row in enumerate(test_pred_inversed)) grader.submit_tag('MultilabelClassification', test_...
Current answer for task MultilabelClassification is: 0 mysql,php 1 javascript 2 3 javascript,jquery 4 android,java 5 php,xml 6 json 7 java,swing 8 pytho...
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Analysis of the most important features Finally, it is usually a good idea to look at the features (words or n-grams) that are used with the largest weigths in your logistic regression model. Implement the function *print_words_for_tag* to find them. Get back to sklearn documentation on [OneVsRestClassifier](http://sc...
def print_words_for_tag(classifier, tag, tags_classes, index_to_words, all_words): """ classifier: trained classifier tag: particular tag tags_classes: a list of classes names from MultiLabelBinarizer index_to_words: index_to_words transformation all_words: all words in the d...
Tag: c Top positive words: c, malloc, scanf, printf, gcc Top negative words: c#, javascript, python, php, java Tag: c++ Top positive words: c++, qt, boost, mfc, opencv Top negative words: c#, javascript, python, php, java Tag: linux Top positive words: linux, ubuntu, c, address, signal Top negative words: method, arr...
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Authorization & SubmissionTo submit assignment parts to Cousera platform, please, enter your e-mail and token into variables below. You can generate token on this programming assignment page. Note: Token expires 30 minutes after generation.
grader.status() STUDENT_EMAIL = "gureddy@microsoft.com"# EMAIL STUDENT_TOKEN = "X6mGG4lxlszGyk9H"# TOKEN grader.status()
You want to submit these parts: Task TextPrepare: sqlite php readonly creating multiple textboxes dynamically self one prefer javascript save php date... Task WordsTagsCount: javascript,c#,java using,php,java... Task BagOfWords: 7... Task MultilabelClassification: 0 mysql,php 1 javascript 2 3 javascript,jquery 4 a...
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
If you want to submit these answers, run cell below
grader.submit(STUDENT_EMAIL, STUDENT_TOKEN)
_____no_output_____
MIT
week1/week1_MultilabelClassification.ipynb
Gurupradeep/Natural-Language-Processing
Medical Image Classification Tutorial with the MedNIST Dataset IntroductionIn this tutorial, we introduce an end-to-end training and evaluation example based on the MedNIST dataset. We'll go through the following steps: Create a dataset for training and testing Use MONAI transforms to pre-process data Use t...
!wget https://www.dropbox.com/s/5wwskxctvcxiuea/MedNIST.tar.gz # unzip the '.tar.gz' file to the current directory import tarfile datafile = tarfile.open('MedNIST.tar.gz') datafile.extractall() datafile.close() import os import numpy as np %matplotlib inline import matplotlib.pyplot as plt from PIL import Image import...
_____no_output_____
Apache-2.0
examples/notebooks/mednist_tutorial.ipynb
erexhepa/MONAI
Read image filenames from the dataset foldersFirst of all, check the dataset files and show some statistics. There are 6 folders in the dataset: Hand, AbdomenCT, CXR, ChestCT, BreastMRI, HeadCT, which should be used as the labels to train our classification model.
data_dir = './MedNIST/' class_names = sorted([x for x in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, x))]) num_class = len(class_names) image_files = [[os.path.join(data_dir, class_names[i], x) for x in os.listdir(os.path.join(data_dir, class_names[i]))] for i in range(nu...
Total image count: 58954 Image dimensions: 64 x 64 Label names: ['AbdomenCT', 'BreastMRI', 'CXR', 'ChestCT', 'Hand', 'HeadCT'] Label counts: [10000, 8954, 10000, 10000, 10000, 10000]
Apache-2.0
examples/notebooks/mednist_tutorial.ipynb
erexhepa/MONAI
Randomly pick images from the dataset to visualize and check
plt.subplots(3, 3, figsize=(8, 8)) for i,k in enumerate(np.random.randint(num_total, size=9)): im = Image.open(image_files_list[k]) arr = np.array(im) plt.subplot(3, 3, i + 1) plt.xlabel(class_names[image_class[k]]) plt.imshow(arr, cmap='gray', vmin=0, vmax=255) plt.tight_layout() plt.show()
_____no_output_____
Apache-2.0
examples/notebooks/mednist_tutorial.ipynb
erexhepa/MONAI
Prepare training, validation and test data listsRandomly select 10% of the dataset as validation and 10% as test.
val_frac = 0.1 test_frac = 0.1 train_x = list() train_y = list() val_x = list() val_y = list() test_x = list() test_y = list() for i in range(num_total): rann = np.random.random() if rann < val_frac: val_x.append(image_files_list[i]) val_y.append(image_class[i]) elif rann < test_frac + val_...
Training count: 47156, Validation count: 5913, Test count: 5885
Apache-2.0
examples/notebooks/mednist_tutorial.ipynb
erexhepa/MONAI
Define MONAI transforms, Dataset and Dataloader to pre-process data
train_transforms = Compose([ LoadPNG(image_only=True), AddChannel(), ScaleIntensity(), RandRotate(range_x=15, prob=0.5, keep_size=True), RandFlip(spatial_axis=0, prob=0.5), RandZoom(min_zoom=0.9, max_zoom=1.1, prob=0.5), ToTensor() ]) val_transforms = Compose([ LoadPNG(image_only=True),...
_____no_output_____
Apache-2.0
examples/notebooks/mednist_tutorial.ipynb
erexhepa/MONAI
Define network and optimizer1. Set learning rate for how much the model is updated per batch.2. Set total epoch number, as we have shuffle and random transforms, so the training data of every epoch is different. And as this is just a get start tutorial, let's just train 4 epochs. If train 10 epochs, the model ...
device = torch.device('cuda:0') model = densenet121( spatial_dims=2, in_channels=1, out_channels=num_class ).to(device) loss_function = torch.nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), 1e-5) epoch_num = 4 val_interval = 1
_____no_output_____
Apache-2.0
examples/notebooks/mednist_tutorial.ipynb
erexhepa/MONAI
Model trainingExecute a typical PyTorch training that run epoch loop and step loop, and do validation after every epoch. Will save the model weights to file if got best validation accuracy.
best_metric = -1 best_metric_epoch = -1 epoch_loss_values = list() metric_values = list() for epoch in range(epoch_num): print('-' * 10) print(f"epoch {epoch + 1}/{epoch_num}") model.train() epoch_loss = 0 step = 0 for batch_data in train_loader: step += 1 inputs, labels = batch_...
_____no_output_____
Apache-2.0
examples/notebooks/mednist_tutorial.ipynb
erexhepa/MONAI
Plot the loss and metric
plt.figure('train', (12, 6)) plt.subplot(1, 2, 1) plt.title('Epoch Average Loss') x = [i + 1 for i in range(len(epoch_loss_values))] y = epoch_loss_values plt.xlabel('epoch') plt.plot(x, y) plt.subplot(1, 2, 2) plt.title('Val AUC') x = [val_interval * (i + 1) for i in range(len(metric_values))] y = metric_values plt.xl...
_____no_output_____
Apache-2.0
examples/notebooks/mednist_tutorial.ipynb
erexhepa/MONAI
Evaluate the model on test datasetAfter training and validation, we already got the best model on validation test. We need to evaluate the model on test dataset to check whether it's robust and not over-fitting. We'll use these predictions to generate a classification report.
model.load_state_dict(torch.load('best_metric_model.pth')) model.eval() y_true = list() y_pred = list() with torch.no_grad(): for test_data in test_loader: test_images, test_labels = test_data[0].to(device), test_data[1].to(device) pred = model(test_images).argmax(dim=1) for i in range(len(p...
precision recall f1-score support Hand 0.9969 0.9928 0.9948 969 AbdomenCT 0.9839 0.9924 0.9881 1046 CXR 0.9948 0.9969 0.9958 961 ChestCT 0.9969 1.0000 0.9985 980 BreastMRI 1.0000 0.9905 0.9952 ...
Apache-2.0
examples/notebooks/mednist_tutorial.ipynb
erexhepa/MONAI
TensorFlow Neural Network Lab In this lab, you'll use all the tools you learned from *Introduction to TensorFlow* to label images of English letters! The data you are using, notMNIST, consists of images of a letter from A to J in differents font.The above images are a few examples of the data you'll be training on. Aft...
import hashlib import os import pickle from urllib.request import urlretrieve import numpy as np from PIL import Image from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelBinarizer from sklearn.utils import resample from tqdm import tqdm from zipfile import ZipFile print('All m...
All modules imported.
MIT
lab.ipynb
bhaveshwadhwani/CarND-TensorFlow-Lab
The notMNIST dataset is too large for many computers to handle. It contains 500,000 images for just training. You'll be using a subset of this data, 15,000 images for each label (A-J).
def download(url, file): """ Download file from <url> :param url: URL to file :param file: Local file path """ if not os.path.isfile(file): print('Downloading ' + file + '...') urlretrieve(url, file) print('Download Finished') # Download the training and test dataset. do...
100%|██████████| 210001/210001 [00:49<00:00, 4284.12files/s] 100%|██████████| 10001/10001 [00:02<00:00, 4503.60files/s]
MIT
lab.ipynb
bhaveshwadhwani/CarND-TensorFlow-Lab
Problem 1The first problem involves normalizing the features for your training and test data.Implement Min-Max scaling in the `normalize()` function to a range of `a=0.1` and `b=0.9`. After scaling, the values of the pixels in the input data should range from 0.1 to 0.9.Since the raw notMNIST image data is in [graysca...
from sklearn.preprocessing import MinMaxScaler # Problem 1 - Implement Min-Max scaling for grayscale image data def normalize_grayscale(image_data): """ Normalize the image data with Min-Max scaling to a range of [0.1, 0.9] :param image_data: The image data to be normalized :return: Normalized image da...
Data cached in pickle file.
MIT
lab.ipynb
bhaveshwadhwani/CarND-TensorFlow-Lab
CheckpointAll your progress is now saved to the pickle file. If you need to leave and comeback to this lab, you no longer have to start from the beginning. Just run the code block below and it will load all the data and modules required to proceed.
%matplotlib inline # Load the modules import pickle import math import numpy as np import tensorflow as tf from tqdm import tqdm import matplotlib.pyplot as plt # Reload the data pickle_file = 'notMNIST.pickle' with open(pickle_file, 'rb') as f: pickle_data = pickle.load(f) train_features = pickle_data['train_da...
_____no_output_____
MIT
lab.ipynb
bhaveshwadhwani/CarND-TensorFlow-Lab
Problem 2For the neural network to train on your data, you need the following float32 tensors: - `features` - Placeholder tensor for feature data (`train_features`/`valid_features`/`test_features`) - `labels` - Placeholder tensor for label data (`train_labels`/`valid_labels`/`test_labels`) - `weights` - Variable Te...
features_count = 784 labels_count = 10 # TODO: Set the features and labels tensors features = tf.placeholder(tf.float32) labels = tf.placeholder(tf.float32) # TODO: Set the weights and biases tensors weights = tf.Variable(tf.truncated_normal((features_count,labels_count))) biases = tf.Variable(tf.zeros(labels_count...
Accuracy function created.
MIT
lab.ipynb
bhaveshwadhwani/CarND-TensorFlow-Lab
Problem 3Below are 3 parameter configurations for training the neural network. In each configuration, one of the parameters has multiple options. For each configuration, choose the option that gives the best acccuracy.Parameter configurations:Configuration 1* **Epochs:** 1* **Batch Size:** * 2000 * 1000 * 500 * 30...
# TODO: Find the best parameters for each configuration epochs = 30 batch_size = 100 learning_rate = 0.2 ### DON'T MODIFY ANYTHING BELOW ### # Gradient Descent optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss) # The accuracy measured against the validation set validation_accuracy = 0....
Epoch 1/30: 100%|██████████| 1425/1425 [00:05<00:00, 241.03batches/s] Epoch 2/30: 100%|██████████| 1425/1425 [00:05<00:00, 241.15batches/s] Epoch 3/30: 100%|██████████| 1425/1425 [00:05<00:00, 241.68batches/s] Epoch 4/30: 100%|██████████| 1425/1425 [00:06<00:00, 237.31batches/s] Epoch 5/30: 100%|██████████| 1425/1...
MIT
lab.ipynb
bhaveshwadhwani/CarND-TensorFlow-Lab
TestSet the epochs, batch_size, and learning_rate with the best learning parameters you discovered in problem 3. You're going to test your model against your hold out dataset/testing data. This will give you a good indicator of how well the model will do in the real world. You should have a test accuracy of at leas...
# TODO: Set the epochs, batch_size, and learning_rate with the best parameters from problem 3 epochs = 30 batch_size = 100 learning_rate = 0.2 ### DON'T MODIFY ANYTHING BELOW ### # The accuracy measured against the test set test_accuracy = 0.0 with tf.Session() as session: session.run(init) batch_cou...
Epoch 1/25: 100%|██████████| 1425/1425 [00:02<00:00, 505.22batches/s] Epoch 2/25: 100%|██████████| 1425/1425 [00:02<00:00, 540.31batches/s] Epoch 3/25: 100%|██████████| 1425/1425 [00:02<00:00, 536.68batches/s] Epoch 4/25: 100%|██████████| 1425/1425 [00:02<00:00, 538.19batches/s] Epoch 5/25: 100%|██████████| 1425/1...
MIT
lab.ipynb
bhaveshwadhwani/CarND-TensorFlow-Lab
Tutorial 6: Dealing with imbalanced dataset using TensorFilterWhen your dataset is imbalanced, training data needs to maintain a certain distribution to make sure minority classes are not ommitted during the training. In FastEstimator, `TensorFilter` is designed for that purpose.`TensorFilter` is a Tensor Operator th...
# Import libraries import numpy as np import tensorflow as tf import fastestimator as fe from fastestimator.op.tensorop import Minmax # Load data and create dictionaries (x_train, y_train), (x_eval, y_eval) = tf.keras.datasets.mnist.load_data() train_data = {"x": np.expand_dims(x_train, -1), "y": y_train} eval_data = ...
_____no_output_____
Apache-2.0
tutorial/t06_TensorFilter_imbalanced_training.ipynb
fastestimator-util/test_nightly
Step 1 - Customize your own Filter...In this example, we will get rid of all images that have a label smaller than 5.
from fastestimator.op.tensorop import TensorFilter # We create our filter in forward function, it's just our condition. class MyFilter(TensorFilter): def forward(self, data, state): pass_filter = data >= 5 return pass_filter # We specify the filter in Pipeline ops list. pipeline = fe.Pipeline(batc...
filtering out all data with label less than 5, the labels of current batch are: tf.Tensor([5 9 6 9 8 8 9 6 5 8 9 6 8 9 5 9 6 7 5 8 7 5 7 5 6 6 9 8 6 5 6 5], shape=(32,), dtype=uint8)
Apache-2.0
tutorial/t06_TensorFilter_imbalanced_training.ipynb
fastestimator-util/test_nightly
... or use a pre-built ScalarFilterIn FastEstimator, if user needs to filter out scalar values with a certain probability, one can use pre-built filter `ScalarFilter`. Let's filter out even numbers labels with 50% probability:
from fastestimator.op.tensorop import ScalarFilter # We specify the list of scalars to filter out and the probability to keep these scalars pipeline = fe.Pipeline(batch_size=32, data=data, ops=[ScalarFilter(inputs="y", filter_value=[0, 2, 4, 6, 8], keep_prob=[0.5, 0.5, 0...
in batch number 0, there are 20 odd labels and 12 even labels in batch number 1, there are 21 odd labels and 11 even labels in batch number 2, there are 20 odd labels and 12 even labels in batch number 3, there are 22 odd labels and 10 even labels in batch number 4, there are 22 odd labels and 10 even labels in batch n...
Apache-2.0
tutorial/t06_TensorFilter_imbalanced_training.ipynb
fastestimator-util/test_nightly
Dataset 1
X1, y1 = importar_dados('datasets/dataset1.txt') exibir_amostras(X=X1, y=y1)
_____no_output_____
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
**Classificador mais adequado**: para este caso, o LDA já é suficiente para atuar bem, mas nada impede que seja escolhido o QDA.
# Bootstrap n_repeticoes = 10 SK_LDA_desempenho = [] ME_LDA_desempenho = [] SK_QDA_desempenho = [] ME_QDA_desempenho = [] for execucao in range(n_repeticoes): # Holdout X_treino, y_treino, X_teste, y_teste = holdout(X=X1, y=y1, teste_parcela=0.30, aleatorio=True, semente=None) # LDA - Scikit-Learn ...
DATASET 1 ------ Acurácias ----- LDA - Scikit: 1.0000 LDA - Próprio: 1.0000 ---------------------- QDA - Scikit: 1.0000 QDA - Próprio: 1.0000
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
Dataset 2
X2, y2 = importar_dados('datasets/dataset2.txt') exibir_amostras(X=X2, y=y2)
_____no_output_____
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
**Classificador mais adequado**: aqui não parece ser possível zerar a taxa de erros, mas é possível observar que o LDA satisfaz a classificação com uma taxa de erros relativamebte baixa.
# Bootstrap n_repeticoes = 10 SK_LDA_desempenho = [] ME_LDA_desempenho = [] SK_QDA_desempenho = [] ME_QDA_desempenho = [] for execucao in range(n_repeticoes): # Holdout X_treino, y_treino, X_teste, y_teste = holdout(X=X2, y=y2, teste_parcela=0.30, aleatorio=True, semente=None) # LDA - Scikit-Learn ...
DATASET 2 ------ Acurácias ----- LDA - Scikit: 0.7714 LDA - Próprio: 0.7429 ---------------------- QDA - Scikit: 0.7571 QDA - Próprio: 0.7571
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
Dataset 3
X3, y3 = importar_dados('datasets/dataset3.txt') exibir_amostras(X=X3, y=y3)
_____no_output_____
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
**Classificador mais adequado**: neste dataset é bastante evidente que há uma intensa sobreposição entre os dados, e o QDA é bem mais conveniente.
# Bootstrap n_repeticoes = 10 SK_LDA_desempenho = [] ME_LDA_desempenho = [] SK_QDA_desempenho = [] ME_QDA_desempenho = [] for execucao in range(n_repeticoes): # Holdout X_treino, y_treino, X_teste, y_teste = holdout(X=X3, y=y3, teste_parcela=0.30, aleatorio=True, semente=None) # LDA - Scikit-Learn ...
DATASET 3 ------ Acurácias ----- LDA - Scikit: 0.4450 LDA - Próprio: 0.4450 ---------------------- QDA - Scikit: 0.8033 QDA - Próprio: 0.8033
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
Dataset 4
X4, y4 = importar_dados('datasets/dataset4.txt') exibir_amostras(X=X4, y=y4)
_____no_output_____
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
**Classificador mais adequado**: aqui também á uma considerável sobreposição das amostras, mas é menos agressiva do que o observado no dataset anterior. Embora não aparente, LDA e QDA exibirão resultados bastante próximos.
# Bootstrap n_repeticoes = 10 SK_LDA_desempenho = [] ME_LDA_desempenho = [] SK_QDA_desempenho = [] ME_QDA_desempenho = [] for execucao in range(n_repeticoes): # Holdout X_treino, y_treino, X_teste, y_teste = holdout(X=X4, y=y4, teste_parcela=0.30, aleatorio=True, semente=None) # LDA - Scikit-Learn ...
DATASET 4 ------ Acurácias ----- LDA - Scikit: 0.7872 LDA - Próprio: 0.7872 ---------------------- QDA - Scikit: 0.7564 QDA - Próprio: 0.7564
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
Dataset 5
X5, y5 = importar_dados('datasets/dataset5.txt') exibir_amostras(X=X5, y=y5)
_____no_output_____
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
**Classificador mais adequado**: este é um caso em que não há qualquer sobreposição. Embora não seja fácil, é possível realizar uma classificação perfeita, com zero erros, utilizando um classificador linear, portanto, o LDA já é suficiente para satisfazer o problema, mas nada impede que o QDA seja utilizado.
# Bootstrap n_repeticoes = 10 SK_LDA_desempenho = [] ME_LDA_desempenho = [] SK_QDA_desempenho = [] ME_QDA_desempenho = [] for execucao in range(n_repeticoes): # Holdout X_treino, y_treino, X_teste, y_teste = holdout(X=X5, y=y5, teste_parcela=0.30, aleatorio=True, semente=None) # LDA - Scikit-Learn ...
DATASET 5 ------ Acurácias ----- LDA - Scikit: 0.9889 LDA - Próprio: 0.9800 ---------------------- QDA - Scikit: 0.9844 QDA - Próprio: 0.9844
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
Dataset 6
X6, y6 = importar_dados('datasets/dataset6.txt') exibir_amostras(X=X6, y=y6)
_____no_output_____
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
**Classificador mais adequado**: neste caso já há sobreposição, o que não permite uma classificação completamente isenta de erros, mas um bom desempenho pode ser alcançado por ambos os classificadores, sem que haja grandes diferenças entre eles.
# Bootstrap n_repeticoes = 10 SK_LDA_desempenho = [] ME_LDA_desempenho = [] SK_QDA_desempenho = [] ME_QDA_desempenho = [] for execucao in range(n_repeticoes): # Holdout X_treino, y_treino, X_teste, y_teste = holdout(X=X6, y=y6, teste_parcela=0.30, aleatorio=True, semente=None) # LDA - Scikit-Learn ...
DATASET 6 ------ Acurácias ----- LDA - Scikit: 0.8222 LDA - Próprio: 0.8089 ---------------------- QDA - Scikit: 0.8156 QDA - Próprio: 0.8156
MIT
ml_prova_7.ipynb
titocaco/disciplina_ml
Búsqueda linealDada un conjunto de datos no ordenados, la búsqueda lineal consiste en recorrer el conjunto de datos desde el inicio al final, moviéndose uno en uno hasta encontrar el elemento o llegar al final del conjunto.datos = [ 4,18,47,2,34,14,78,12,48,21,31,19,1,3,5 ] Búsqueda binariafunciona sobre un conjunto ...
''' Busqueda lineal regresa la posición del elemento 'buscado' si se encuentra dentro de la lista. regresa -1 si el elemento buscado no existe dentro de la lista. ''' def busq_lineal(L, buscado): indice = -1 contador = 0 for idx in range(len(L)): contador += 1 if L[idx] == buscado: indice = idx ...
Que valor quieres buscar: 47 número de comparaciones realizadas = 3 Resultado: 2 Búsqueda lineal en una lista ordenada [1, 2, 3, 4, 5, 12, 14, 18, 19, 21, 31, 34, 47, 48, 78] número de comparaciones realizadas = 13 Resultado: 12 Búsqueda binaria
MIT
7Octubre_daa.ipynb
ibzan79/daa_2021_1
Algèbre linéaire
M = np.random.randint(0,9, [4,3]) print(M) print('\n') N =np.random.randint(0,9, [3,4]) print(N) M.dot(N) N.dot(M) M.T G = np.random.randint(0,9,[3,3]) np.linalg.det(G) np.linalg.inv(G) np.linalg.pinv(G) np.linalg.pinv(M) np.linalg.eig(G)
_____no_output_____
Apache-2.0
numpy_fonctions.ipynb
Michel-Nassalang/python
TP Standardisation (important)
M M.mean(axis=0) P= M - M.mean(axis=0) P S = P/M.std(axis=0) S # standardisation
_____no_output_____
Apache-2.0
numpy_fonctions.ipynb
Michel-Nassalang/python
High Pass Filter Using the Spectral Reversal TechniqueWe can create a high pass filter by using as reference a low pass filter and a technique called **Spectral Reversal**. For this notebook we will use the *Windowed-Sinc Filters* Notebook results, which are pickled in an serialized object called `save_data.pickle`.
import sys sys.path.insert(0, '../') from Common import common_plots from Common import fourier_transform cplots = common_plots.Plot() import pickle import numpy as np import matplotlib.pyplot as plt def get_fourier(x): """ Function that performs the Fourier calculation of a signal x and returns its magnitude ...
_____no_output_____
MIT
12. FIR Filter -Windowed-Sinc Filters/.ipynb_checkpoints/FIR Filter - 2.Spectral Reversal_Solution-checkpoint.ipynb
mriosrivas/DSP_Student_2021
We load the low pass data from the *Windowed-Sinc Filters* Notebook
with open('save_data.pickle', 'rb') as f: data = pickle.load(f) ecg = np.array(data['ecg']) low_pass = np.array(data['low_pass']) low_pass = low_pass/np.sum(low_pass) fft_low_pass = np.array(data['fft_low_pass'])
_____no_output_____
MIT
12. FIR Filter -Windowed-Sinc Filters/.ipynb_checkpoints/FIR Filter - 2.Spectral Reversal_Solution-checkpoint.ipynb
mriosrivas/DSP_Student_2021
To generate the high pass filter, we use the Sprectral Reversal methond, which consist of multiplying the low pass filter response $h_{lp}[n]$ with $(-1)^{-n}$. Therefore the high pass filter response is given by:$$h_{hp}[n] = h_{lp}[n](-1)^{-n}$$
N = low_pass.shape[0] high_pass = low_pass * ((-1) ** np.arange(N)) dft_low_pass_magnitude, dft_low_pass_freq = get_fourier(low_pass) dft_high_pass_magnitude, dft_high_pass_freq = get_fourier(high_pass) plt.rcParams["figure.figsize"] = (15,10) plt.subplot(2,2,1) plt.stem(low_pass, markerfmt='.', use_line_collection=Tr...
_____no_output_____
MIT
12. FIR Filter -Windowed-Sinc Filters/.ipynb_checkpoints/FIR Filter - 2.Spectral Reversal_Solution-checkpoint.ipynb
mriosrivas/DSP_Student_2021
**This frequency response is a “left-right flipped” version of the frequency response of the low-pass filter.**
low_pass_ecg = np.convolve(ecg,low_pass) high_pass_ecg = np.convolve(ecg,high_pass) plt.rcParams["figure.figsize"] = (15,10) plt.subplot(2,2,1) plt.plot(low_pass_ecg) plt.title('Low Pass ECG') plt.grid('on') plt.xlabel('Samples') plt.ylabel('Amplitude') plt.subplot(2,2,2) plt.plot(high_pass_ecg) plt.title('High Pas...
_____no_output_____
MIT
12. FIR Filter -Windowed-Sinc Filters/.ipynb_checkpoints/FIR Filter - 2.Spectral Reversal_Solution-checkpoint.ipynb
mriosrivas/DSP_Student_2021
import pandas as pd
_____no_output_____
MIT
First_try.ipynb
kpflugshaupt/colab
Bubble dissolution : Realtime Acquisition + Preprocessing + Saving Data / SnapshotsBrice : brice.saint-michel@ifsttar.fr Step 1 : Definitions / Initialisations / Automatic thresholding Subroutines : * `analyse_bubble` : checks one bubble (any bubble) for shape and threshold detection * `padding` : pads an image wit...
from pypylon import pylon from bokeh.plotting import show, row, figure, column from bokeh.models import ColumnDataSource, LinearColorMapper from jupyter_bokeh.widgets import BokehModel from bokeh.io import output_notebook import numpy as np import pandas as pd import time import codecs import os from PIL import Image i...
> local_minimum : Found two maxima at : [101 327] / minimum around : 214 time_ref:2021/12/16 11:42:58 zoom:3 pixsize:3.6873156342182885 pixel_format:Mono12 threshold:2434.3444444444444 width:512 height:512 smoothing:10 exposure:100 pixel_fmt:Mono12 max_lum:4095 cameraname:acA1300-60gm reftime:228432030 padsize:16
CC0-1.0
Bubble_Dissolution_Acquisition.ipynb
bsaintmichel/bubbledynamics
Step 2 : FRAME GRABBING LOOP Some bits have been initialised in Step 1, so please run it at least once* Spurious image detection with `spurious` or `spu`* Provide time stamps for each image* Can be restarted if stopped* Handles events (bubble disappearing, appearing, moving, ...)* Try an extra `camera.Close()` if you ...
import traceback from IPython.display import clear_output ############# (Bad) event management routine #########################"" def bubble_event(now_data, ref_data): event_str = '' nbubble_change = np.size(now_data['label']) != np.size(ref_data['label']) chunk_timeout = now_data['frame'][0] - ref_data[...
_____no_output_____
CC0-1.0
Bubble_Dissolution_Acquisition.ipynb
bsaintmichel/bubbledynamics
Temporal-Difference MethodsIn this notebook, you will write your own implementations of many Temporal-Difference (TD) methods.While we have provided some starter code, you are welcome to erase these hints and write your code from scratch.--- Part 0: Explore CliffWalkingEnvWe begin by importing the necessary packages.
import sys import gym import random import numpy as np from collections import defaultdict, deque import matplotlib.pyplot as plt %matplotlib inline import check_test from plot_utils import plot_values
_____no_output_____
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
Use the code cell below to create an instance of the [CliffWalking](https://github.com/openai/gym/blob/master/gym/envs/toy_text/cliffwalking.py) environment.
env = gym.make('CliffWalking-v0')
_____no_output_____
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
The agent moves through a $4\times 12$ gridworld, with states numbered as follows:```[[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]]```At the start of any episode, sta...
print(env.action_space) print(env.observation_space)
Discrete(4) Discrete(48)
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
In this mini-project, we will build towards finding the optimal policy for the CliffWalking environment. The optimal state-value function is visualized below. Please take the time now to make sure that you understand _why_ this is the optimal state-value function._**Note**: You can safely ignore the values of the cli...
# define the optimal state-value function V_opt = np.zeros((4,12)) V_opt[0:13][0] = -np.arange(3, 15)[::-1] V_opt[0:13][1] = -np.arange(3, 15)[::-1] + 1 V_opt[0:13][2] = -np.arange(3, 15)[::-1] + 2 V_opt[3][0] = -13 plot_values(V_opt)
/Users/amrmkayid/anaconda3/envs/kayddrl/lib/python3.7/site-packages/matplotlib/cbook/__init__.py:424: MatplotlibDeprecationWarning: Passing one of 'on', 'true', 'off', 'false' as a boolean is deprecated; use an actual boolean (True/False) instead. warn_deprecated("2.2", "Passing one of 'on', 'true', 'off', 'false' a...
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
Part 1: TD Control: SarsaIn this section, you will write your own implementation of the Sarsa control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction.- `alpha`...
def update_Q_sarsa(alpha, gamma, Q, state, action, reward, next_state=None, next_action=None): current = Q[state][action] Qsa_next = Q[next_state][next_action] if next_state is not None else 0 target = reward + (gamma * Qsa_next) new_value = current + (alpha * (target - current)) return ne...
_____no_output_____
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd ...
# obtain the estimated optimal policy and corresponding action-value function Q_sarsa = sarsa(env, 5000, .01) # print the estimated optimal policy policy_sarsa = np.array([np.argmax(Q_sarsa[key]) if key in Q_sarsa else -1 for key in np.arange(48)]).reshape(4,12) check_test.run_check('td_control_check', policy_sarsa) p...
Episode 5000/5000
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
Part 2: TD Control: Q-learningIn this section, you will write your own implementation of the Q-learning control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment interaction...
def update_Q_learning(alpha, gamma, Q, state, action, reward, next_state=None): current = Q[state][action] Qsa_next = np.max(Q[next_state]) if next_state is not None else 0 target = reward + (gamma * Qsa_next) new_value = current + (alpha * (target - current)) return new_value def q_learning...
_____no_output_____
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd l...
# obtain the estimated optimal policy and corresponding action-value function Q_sarsamax = q_learning(env, 5000, .01) # print the estimated optimal policy policy_sarsamax = np.array([np.argmax(Q_sarsamax[key]) if key in Q_sarsamax else -1 for key in np.arange(48)]).reshape((4,12)) check_test.run_check('td_control_chec...
Episode 5000/5000
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
Part 3: TD Control: Expected SarsaIn this section, you will write your own implementation of the Expected Sarsa control algorithm.Your algorithm has four arguments:- `env`: This is an instance of an OpenAI Gym environment.- `num_episodes`: This is the number of episodes that are generated through agent-environment int...
def update_Q_expected_sarsa(alpha, gamma, nA, eps, Q, state, action, reward, next_state=None): current = Q[state][action] policy_s = np.ones(nA) * eps / nA policy_s[np.argmax(Q[next_state])] = 1 - eps + (eps / nA) Qsa_next = np.dot(Q[next_state], policy_s) target = reward + (gamma *...
_____no_output_____
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
Use the next code cell to visualize the **_estimated_** optimal policy and the corresponding state-value function. If the code cell returns **PASSED**, then you have implemented the function correctly! Feel free to change the `num_episodes` and `alpha` parameters that are supplied to the function. However, if you'd ...
# obtain the estimated optimal policy and corresponding action-value function Q_expsarsa = expected_sarsa(env, 10000, 1) # print the estimated optimal policy policy_expsarsa = np.array([np.argmax(Q_expsarsa[key]) if key in Q_expsarsa else -1 for key in np.arange(48)]).reshape(4,12) check_test.run_check('td_control_che...
Episode 10000/10000
MIT
rl-basics/temporal-difference/Temporal_Difference.ipynb
AmrMKayid/udacity-drl
Hw 18_11_2021
# Проверка целостности матрицы, т.е. количество элементов в строках # должны совпадать, тип матрицы должен быть список def CheckMatrixCompletness(matrix): # проверяем тип всей матрицы if type(matrix) is not list: return False if type(matrix[0]) is not list: return False # определим колич...
[[0.6000000000000001, -0.4, 0.8], [0.7000000000000001, 0.2, 0.1], [-0.1, 0.4, -0.30000000000000004]]
MIT
hw 18_11_2021.ipynb
yuraMovsesyan/msu_hw
Transfer LearningMost of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this notebo...
from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_s...
VGG16 Parameters: 553MB [00:31, 17.6MB/s]
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
Flower powerHere we'll be using VGGNet to classify images of flowers. To get the flower dataset, run the cell below. This dataset comes from the [TensorFlow inception tutorial](https://www.tensorflow.org/tutorials/image_retraining).
import tarfile dataset_folder_path = 'flower_photos' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile('flower_ph...
Flowers Dataset: 229MB [00:02, 83.5MB/s]
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
ConvNet CodesBelow, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.Here we're usi...
import os import numpy as np import tensorflow as tf from tensorflow_vgg import vgg16 from tensorflow_vgg import utils data_dir = 'flower_photos/' contents = os.listdir(data_dir) classes = [each for each in contents if os.path.isdir(data_dir + each)]
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
Below I'm running images through the VGG network in batches.> **Exercise:** Below, build the VGG network. Also get the codes from the first fully connected layer (make sure you get the ReLUd values).
# Set the batch size higher if you can fit in in your GPU memory batch_size = 10 codes_list = [] labels = [] batch = [] codes = None with tf.Session() as sess: # TODO: Build the vgg network here vgg = vgg16.Vgg16() input_ = tf.placeholder(tf.float32, [None, 224, 224, 3]) with tf.name_scope("conte...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
Building the ClassifierNow that we have codes for all the images, we can build a simple classifier on top of them. The codes behave just like normal input into a simple neural network. Below I'm going to have you do most of the work.
# read codes and labels from file import csv with open('labels') as f: reader = csv.reader(f, delimiter='\n') labels = np.array([each for each in reader if len(each) > 0]).squeeze() with open('codes') as f: codes = np.fromfile(f, dtype=np.float32) codes = codes.reshape((len(labels), -1))
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
Data prepAs usual, now we need to one-hot encode our labels and create validation/test sets. First up, creating our labels!> **Exercise:** From scikit-learn, use [LabelBinarizer](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html) to create one-hot encoded vectors from the label...
from sklearn import preprocessing lb = preprocessing.LabelBinarizer() lb.fit(labels) labels_vecs = lb.transform(labels)
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
Now you'll want to create your training, validation, and test sets. An important thing to note here is that our labels and data aren't randomized yet. We'll want to shuffle our data so the validation and test sets contain data from all classes. Otherwise, you could end up with testing sets that are all one class. Typic...
from sklearn.model_selection import StratifiedShuffleSplit ss = StratifiedShuffleSplit(n_splits=1, test_size=0.2) train_i, test_i = next(ss.split(codes, labels_vecs)) split_val_i = len(test_i)//2 test_split, val_split = test_i[:split_val_i], test_i[split_val_i:] train_x, train_y = codes[train_i], labels_vecs[train_i...
Train shapes (x, y): (2936, 4096) (2936, 5) Validation shapes (x, y): (367, 4096) (367, 5) Test shapes (x, y): (367, 4096) (367, 5)
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
If you did it right, you should see these sizes for the training sets:```Train shapes (x, y): (2936, 4096) (2936, 5)Validation shapes (x, y): (367, 4096) (367, 5)Test shapes (x, y): (367, 4096) (367, 5)``` Classifier layersOnce you have the convolutional codes, you just need to build a classfier from some fully connec...
inputs_ = tf.placeholder(tf.float32, shape=[None, codes.shape[1]]) labels_ = tf.placeholder(tf.int64, shape=[None, labels_vecs.shape[1]]) # TODO: Classifier layers and operations fc1 = tf.contrib.layers.fully_connected(inputs_, 1024) fc2 = tf.contrib.layers.fully_connected(fc1, 1024) logits = tf.contrib.layers.fully_...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
Batches!Here is just a simple way to do batches. I've written it so that it includes all the data. Sometimes you'll throw out some data at the end to make sure you have full batches. Here I just extend the last batch to include the remaining data.
def get_batches(x, y, n_batches=10): """ Return a generator that yields batches from arrays x and y. """ batch_size = len(x)//n_batches for ii in range(0, n_batches*batch_size, batch_size): # If we're not on the last batch, grab data with size batch_size if ii != (n_batches-1)*batch_siz...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
TrainingHere, we'll train the network.> **Exercise:** So far we've been providing the training code for you. Here, I'm going to give you a bit more of a challenge and have you write the code to train the network. Of course, you'll be able to see my solution if you need help. Use the `get_batches` function I wrote befo...
saver = tf.train.Saver() epochs = 10 iteration = 0 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for e in range(epochs): for x, y in get_batches(train_x, train_y): feed = {inputs_: x, labels_: y} loss, _ = sess.run([cost, optimizer], feed) ...
Epoch: 1/10 Iterations: 0 Loss: 4.672918796539307 Epoch: 1/10 Iterations: 1 Loss: 29.755029678344727 Epoch: 1/10 Iterations: 2 Loss: 45.8921012878418 Epoch: 1/10 Iterations: 3 Loss: 25.696012496948242 Epoch: 1/10 Iterations: 4 Loss: 28.859224319458008 Epoch: 1/10 Iterations: 5 Val loss: 10.552411079406738 Epoch: 1/10 I...
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
TestingBelow you see the test accuracy. You can also see the predictions returned for images.
with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('checkpoints')) feed = {inputs_: test_x, labels_: test_y} test_acc = sess.run(accuracy, feed_dict=feed) print("Test accuracy: {:.4f}".format(test_acc)) %matplotlib inline import matplotlib.pyplot as plt from scip...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101
Below, feel free to choose images and see how the trained classifier predicts the flowers in them.
test_img_path = 'flower_photos/roses/10894627425_ec76bbc757_n.jpg' test_img = imread(test_img_path) plt.imshow(test_img) # Run this cell if you don't have a vgg graph built if 'vgg' in globals(): print('"vgg" object already exists. Will not create again.') else: #create vgg with tf.Session() as sess: ...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
sergio-lira/deep-learning101