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.the_geom_webmercator,pp.the_geom_webmercator) as the_geom_webmercator
from populated_places pp join capitals c on pp.adm0_a3 = c.adm0_a3
where c.adm0_a3 = 'ESP'
''',
color = {'column':'pop_max','scheme':styling.sunset(bins=3)},
size ={'column': 'pop_max','bin_method':'quantiles','bins' : 4, 'min': 3, 'max':10}
)
cc.map(layers=lines, interactive=True,zoom=4, lat=36.19, lng=-6.79)
points = QueryLayer(
'''
select *
from populated_places
where adm0_a3 = 'ESP'
''',
color = {'column':'pop_max','scheme':styling.sunset(bins=3)},
size = {'column':'pop_max','bin_method':'quantiles','bins' : 4, 'min': 3, 'max':7}
)
cc.map(layers=[lines,points], interactive=True,zoom=4, lat=36.19, lng=-6.79) | _____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_populated_places_simple_7
where cartodb_id = 7263
), -- cities closer to 14000 Km
dests as (
select d.*,
ST_Distance(
o.the_geom::geography,
d.the_geom::geography
)::int distance
from data d, origin o
where
ST_DWithin( o.the_geom::geography, d.the_geom::geography, 14000000 )
),
geoms as (
select
dests.cartodb_id, dests.name, dests.adm0name, dests.distance,
st_transform(
st_segmentize(
st_makeline(
origin.the_geom,
dests.the_geom
)::geography,
10000
)::geometry,
3857) the_geom_webmercator
from origin,dests
)
select *, st_transform(the_geom_webmercator,4326) as the_geom from geoms
'''
cc.map(QueryLayer(query), interactive=False, zoom=2, lat=19.9, lng=29.5) | _____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 cartodb_id = {}'''.format(vlc_id)) | _____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_data/Salary_Data.csv')
X = data['YearsExperience']
y = data['Salary']
X = X[:,np.newaxis]
model = SVR()
parameters = {
'kernel' : ['rbf'],
'C' : [1000,10000,100000],
'gamma' : [0.5,0.05,0.005]
}
grid_search = GridSearchCV(model,parameters)
grid_search.fit(X,y)
print(grid_search.best_params_)
model_baru = SVR(C=100000, gamma=0.005, kernel='rbf')
model_baru.fit(X,y)
plt.scatter(X,y)
plt.plot(X, model_baru.predict(X)) | _____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.org) — a package for scientific computing.- [Pandas](https://pandas.pydata.org) — a library providing high-performance, easy-to-use data structures and data analysis tools for the Python- [scikit-learn](http://scikit-learn.org/stable/index.html) — a tool for data mining and data analysis.- [NLTK](http://www.nltk.org) — a platform to work with natural language. DataThe following cell will download all data required for this assignment into the folder `week1/data`. | ! 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 time you want. | 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 contain answers. Upload the corpora using *pandas* and look at the data: | 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', sep='\t')
train.head() | _____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 prepare the data somehow. In this task you'll write a function, which will be also used in the other assignments. **Task 1 (TextPrepare).** Implement the function *text_prepare* following the instructions. After that, run the function *test_test_prepare* to test it on tiny cases and submit it to Coursera. | 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.sub(REPLACE_BY_SPACE_RE, " ", text)# replace REPLACE_BY_SPACE_RE symbols by space in text
text = re.sub(BAD_SYMBOLS_RE, "", text)# delete symbols which are in BAD_SYMBOLS_RE from text
# print(text)
text = ' '.join([word for word in text.split() if word not in STOPWORDS]) # Remove stopwords
# print(text)
text = text.strip()
#text = re.sub(' +', ' ', text)
# print(text)
return text
def test_text_prepare():
examples = ["SQL Server - any equivalent of Excel's CHOOSE function?",
"How to free c++ memory vector<int> * arr?"]
answers = ["sql server equivalent excels choose function",
"free c++ memory vectorint arr"]
for ex, ans in zip(examples, answers):
if text_prepare(ex) != ans:
return "Wrong answer for the case: '%s'" % ex
return 'Basic tests are passed.'
print(test_text_prepare()) | 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 #############
######################################
# print(X_train[:3], y_train[:3])
for sentence in X_train:
for word in sentence.split():
# print(word)
words_counts[word] += 1
for l in y_train:
for tag in l:
tags_counts[tag] += 1 | _____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 format (two comma-separated strings with line break): tag1,tag2,tag3 word1,word2,word3Pay attention that in this assignment you should not submit frequencies or some additional information. | 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),
','.join(word for word, _ in most_common_words))) | 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. To create this transformation, follow the steps:1. Find *N* most popular words in train corpus and numerate them. Now we have a dictionary of the most popular words.2. For each title in the corpora create a zero vector with the dimension equals to *N*.3. For each text in the corpora iterate over words which are in the dictionary and increase by 1 the corresponding coordinate.Let's try to do it for a toy example. Imagine that we have *N* = 4 and the list of the most popular words is ['hi', 'you', 'me', 'are']Then we need to numerate them, for example, like this: {'hi': 0, 'you': 1, 'me': 2, 'are': 3}And we have the text, which we want to transform to the vector: 'hi how are you'For this text we create a corresponding zero vector [0, 0, 0, 0] And iterate over all words, and if the word is in the dictionary, we increase the value of the corresponding position in the vector: 'hi': [1, 0, 0, 0] 'how': [1, 0, 0, 0] word 'how' is not in our dictionary 'are': [1, 0, 0, 1] 'you': [1, 1, 0, 1]The resulting vector will be [1, 1, 0, 1] Implement the described encoding in the function *my_bag_of_words* with the size of the dictionary equals to 5000. To find the most common words use train data. You can test your code using the function *test_my_bag_of_words*. | 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 in WORDS_TO_INDEX}
ALL_WORDS = WORDS_TO_INDEX.keys()
def my_bag_of_words(text, words_to_index, dict_size):
"""
text: a string
dict_size: size of the dictionary
return a vector which is a bag-of-words representation of 'text'
"""
result_vector = np.zeros(dict_size)
######################################
######### YOUR CODE HERE #############
######################################
for word in text.split():
if word in words_to_index :
result_vector[words_to_index[word]] +=1
return result_vector
def test_my_bag_of_words():
words_to_index = {'hi': 0, 'you': 1, 'me': 2, 'are': 3}
examples = ['hi how are you']
answers = [[1, 1, 0, 1]]
for ex, ans in zip(examples, answers):
if (my_bag_of_words(ex, words_to_index, 4) != ans).any():
return "Wrong answer for the case: '%s'" % ex
return 'Basic tests are passed.'
print(test_my_bag_of_words()) | 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([sp_sparse.csr_matrix(my_bag_of_words(text, WORDS_TO_INDEX, DICT_SIZE)) for text in X_test])
print('X_train shape ', X_train_mybag.shape)
print('X_val shape ', X_val_mybag.shape)
print('X_test shape ', X_test_mybag.shape) | 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/generated/scipy.sparse.csr_matrix.htmlscipy.sparse.csr_matrix) matrix, so we will use this one. **Task 3 (BagOfWords).** For the 11th row in *X_train_mybag* find how many non-zero elements it has. In this task the answer (variable *non_zero_elements_count*) should be a number, e.g. 20. | 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/sklearn.feature_extraction.text.TfidfVectorizer.html) from *scikit-learn*. Use *train* corpus to train a vectorizer. Don't forget to take a look into the arguments that you can pass to it. We suggest that you filter out too rare words (occur less than in 5 titles) and too frequent words (occur more than in 90% of the titles). Also, use bigrams along with unigrams in your vocabulary. | 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 the vectorizer on the train set
# Transform the train, test, and val sets and return the result
tfidf_vectorizer = TfidfVectorizer(token_pattern='(\S+)', min_df=5, max_df=0.9, ngram_range=(1,2))
######################################
######### YOUR CODE HERE #############
######################################
tfidf_vectorizer.fit(X_train)
X_train = tfidf_vectorizer.transform(X_train)
X_val = tfidf_vectorizer.transform(X_val)
X_test = tfidf_vectorizer.transform(X_test)
return X_train, X_val, X_test, tfidf_vectorizer.vocabulary_ | _____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 transormation for the data and check again. | ######### 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/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html) from *sklearn*. | 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) are trained. As a basic classifier, use [LogisticRegression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html). It is one of the simplest methods, but often it performs good enough in text classification tasks. It might take some time, because a number of classifiers to train is large. | 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 LogisticRegression wraped into OneVsRestClassifier.
######################################
######### YOUR CODE HERE #############
######################################
lr = LogisticRegression(C=C, penalty=penalty)
oneVsRest = OneVsRestClassifier(lr)
oneVsRest.fit(X_train, y_train)
return oneVsRest
| _____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 classification metrics: - [Accuracy](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html) - [F1-score](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html) - [Area under ROC-curve](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html) - [Area under precision-recall curve](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.average_precision_score.htmlsklearn.metrics.average_precision_score) Make sure you are familiar with all of them. How would you expect the things work for the multi-label scenario? Read about micro/macro/weighted averaging following the sklearn links provided above. | 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(y_val,predicted, average = 'macro')
#print('f1_score_micro')
print(f1_score(y_val,predicted, average = 'micro')
#print('f1_score_weighted')
print(f1_score(y_val,predicted, average = 'weighted')
"""
print('Bag-of-words')
print_evaluation_scores(y_val, y_val_predicted_labels_mybag)
print('Tfidf')
print_evaluation_scores(y_val, y_val_predicted_labels_tfidf) | 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 - decision functions scores - number of classes | 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 chosen one, try *L1* and *L2*-regularization techniques in Logistic Regression with different coefficients (e.g. C equal to 0.1, 1, 10, 100).You also could try other improvements of the preprocessing / model, if you want. | 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.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)
print('Bag-of-words')
print_evaluation_scores(y_val, y_val_predicted_labels_mybag)
print('Tfidf')
print_evaluation_scores(y_val, y_val_predicted_labels_tfidf)
EvaluateDifferentModel(0.1,'l1')
EvaluateDifferentModel(0.1,'l2')
EvaluateDifferentModel(1,'l1')
EvaluateDifferentModel(1,'l2')
EvaluateDifferentModel(10,'l1')
EvaluateDifferentModel(10,'l2')
EvaluateDifferentModel(100,'l1')
EvaluateDifferentModel(100,'l2')
######################################
######### YOUR CODE HERE #############
######################################
classifier_tfidf = train_classifier(X_train_tfidf, y_train, C=1.0, penalty='l1')
y_test_predicted_labels_tfidf = classifier_tfidf.predict(X_test_tfidf) | _____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_predictions_for_submission) | 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://scikit-learn.org/stable/modules/generated/sklearn.multiclass.OneVsRestClassifier.html) and [LogisticRegression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html) if needed. | 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 dictionary
return nothing, just print top 5 positive and top 5 negative words for current tag
"""
print('Tag:\t{}'.format(tag))
# Extract an estimator from the classifier for the given tag.
# Extract feature coefficients from the estimator.
######################################
######### YOUR CODE HERE #############
######################################
idx = tags_classes.index(tag)
coef=classifier_tfidf.coef_[idx]
cd = {i:coef[i] for i in range(len(coef))}
scd=sorted(cd.items(), key=lambda x: x[1], reverse=True)
top_positive_words = [index_to_words[k[0]] for k in scd[:5]] # top-5 words sorted by the coefficiens.
top_negative_words = [index_to_words[k[0]] for k in scd[-5:]] # bottom-5 words sorted by the coefficients.
print('Top positive words:\t{}'.format(', '.join(top_positive_words)))
print('Top negative words:\t{}\n'.format(', '.join(top_negative_words)))
print_words_for_tag(classifier_tfidf, 'c', mlb.classes, tfidf_reversed_vocab, ALL_WORDS)
print_words_for_tag(classifier_tfidf, 'c++', mlb.classes, tfidf_reversed_vocab, ALL_WORDS)
print_words_for_tag(classifier_tfidf, 'linux', mlb.classes, tfidf_reversed_vocab, ALL_WORDS) | 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, array, jquery, c#, javascript
| 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 = "[email protected]"# 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 android,java
5 php,xml
6 json
7 java,swing
8 pytho...
| 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 the DenseNet from MONAI for classification Train the model with a PyTorch program Evaluate on test dataset Get the datasetThe MedNIST dataset was gathered from several sets from [TCIA](https://wiki.cancerimagingarchive.net/display/Public/Data+Usage+Policies+and+Restrictions), [the RSNA Bone Age Challenge](http://rsnachallenges.cloudapp.net/competitions/4), and [the NIH Chest X-ray dataset](https://cloud.google.com/healthcare/docs/resources/public-datasets/nih-chest).The dataset is kindly made available by [Dr. Bradley J. Erickson M.D., Ph.D.](https://www.mayo.edu/research/labs/radiology-informatics/overview) (Department of Radiology, Mayo Clinic)under the Creative Commons [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/).If you use the MedNIST dataset, please acknowledge the source, e.g.https://github.com/Project-MONAI/MONAI/blob/master/examples/notebooks/mednist_tutorial.ipynb.The following commands download and unzip the dataset (~60MB). | !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 torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from monai.transforms import \
Compose, LoadPNG, AddChannel, ScaleIntensity, ToTensor, RandRotate, RandFlip, RandZoom
from monai.networks.nets import densenet121
from monai.metrics import compute_roc_auc
np.random.seed(0) | _____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(num_class)]
num_each = [len(image_files[i]) for i in range(num_class)]
image_files_list = []
image_class = []
for i in range(num_class):
image_files_list.extend(image_files[i])
image_class.extend([i] * num_each[i])
num_total = len(image_class)
image_width, image_height = Image.open(image_files_list[0]).size
print(f"Total image count: {num_total}")
print(f"Image dimensions: {image_width} x {image_height}")
print(f"Label names: {class_names}")
print(f"Label counts: {num_each}") | 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_frac:
test_x.append(image_files_list[i])
test_y.append(image_class[i])
else:
train_x.append(image_files_list[i])
train_y.append(image_class[i])
print(f"Training count: {len(train_x)}, Validation count: {len(val_x)}, Test count: {len(test_x)}") | 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),
AddChannel(),
ScaleIntensity(),
ToTensor()
])
class MedNISTDataset(Dataset):
def __init__(self, image_files, labels, transforms):
self.image_files = image_files
self.labels = labels
self.transforms = transforms
def __len__(self):
return len(self.image_files)
def __getitem__(self, index):
return self.transforms(self.image_files[index]), self.labels[index]
train_ds = MedNISTDataset(train_x, train_y, train_transforms)
train_loader = DataLoader(train_ds, batch_size=300, shuffle=True, num_workers=10)
val_ds = MedNISTDataset(val_x, val_y, val_transforms)
val_loader = DataLoader(val_ds, batch_size=300, num_workers=10)
test_ds = MedNISTDataset(test_x, test_y, val_transforms)
test_loader = DataLoader(test_ds, batch_size=300, num_workers=10) | _____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 can achieve 100% accuracy on test dataset.3. Use DenseNet from MONAI and move to GPU devide, this DenseNet can support both 2D and 3D classification tasks.4. Use Adam optimizer. | 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_data[0].to(device), batch_data[1].to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = loss_function(outputs, labels)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
print(f"{step}/{len(train_ds) // train_loader.batch_size}, train_loss: {loss.item():.4f}")
epoch_len = len(train_ds) // train_loader.batch_size
epoch_loss /= step
epoch_loss_values.append(epoch_loss)
print(f"epoch {epoch + 1} average loss: {epoch_loss:.4f}")
if (epoch + 1) % val_interval == 0:
model.eval()
with torch.no_grad():
y_pred = torch.tensor([], dtype=torch.float32, device=device)
y = torch.tensor([], dtype=torch.long, device=device)
for val_data in val_loader:
val_images, val_labels = val_data[0].to(device), val_data[1].to(device)
y_pred = torch.cat([y_pred, model(val_images)], dim=0)
y = torch.cat([y, val_labels], dim=0)
auc_metric = compute_roc_auc(y_pred, y, to_onehot_y=True, softmax=True)
metric_values.append(auc_metric)
acc_value = torch.eq(y_pred.argmax(dim=1), y)
acc_metric = acc_value.sum().item() / len(acc_value)
if auc_metric > best_metric:
best_metric = auc_metric
best_metric_epoch = epoch + 1
torch.save(model.state_dict(), 'best_metric_model.pth')
print('saved new best metric model')
print(f"current epoch: {epoch + 1} current AUC: {auc_metric:.4f}"
f" current accuracy: {acc_metric:.4f} best AUC: {best_metric:.4f}"
f" at epoch: {best_metric_epoch}")
print(f"train completed, best_metric: {best_metric:.4f} at epoch: {best_metric_epoch}") | _____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.xlabel('epoch')
plt.plot(x, y)
plt.show() | _____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(pred)):
y_true.append(test_labels[i].item())
y_pred.append(pred[i].item())
! pip install -U sklearn
from sklearn.metrics import classification_report
print(classification_report(y_true, y_pred, target_names=class_names, digits=4)) | 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 944
HeadCT 0.9929 0.9919 0.9924 985
accuracy 0.9941 5885
macro avg 0.9942 0.9941 0.9941 5885
weighted avg 0.9941 0.9941 0.9941 5885
| 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. After training the network, you will compare your prediction model against test data. Your goal, by the end of this lab, is to make predictions against that test set with at least an 80% accuracy. Let's jump in! To start this lab, you first need to import all the necessary modules. Run the code below. If it runs successfully, it will print "`All modules imported`". | 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 modules imported.') | 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.
download('https://s3.amazonaws.com/udacity-sdc/notMNIST_train.zip', 'notMNIST_train.zip')
download('https://s3.amazonaws.com/udacity-sdc/notMNIST_test.zip', 'notMNIST_test.zip')
# Make sure the files aren't corrupted
assert hashlib.md5(open('notMNIST_train.zip', 'rb').read()).hexdigest() == 'c8673b3f28f489e9cdf3a3d74e2ac8fa',\
'notMNIST_train.zip file is corrupted. Remove the file and try again.'
assert hashlib.md5(open('notMNIST_test.zip', 'rb').read()).hexdigest() == '5d3c7e653e63471c88df796156a9dfa9',\
'notMNIST_test.zip file is corrupted. Remove the file and try again.'
# Wait until you see that all files have been downloaded.
print('All files downloaded.')
def uncompress_features_labels(file):
"""
Uncompress features and labels from a zip file
:param file: The zip file to extract the data from
"""
features = []
labels = []
with ZipFile(file) as zipf:
# Progress Bar
filenames_pbar = tqdm(zipf.namelist(), unit='files')
# Get features and labels from all files
for filename in filenames_pbar:
# Check if the file is a directory
if not filename.endswith('/'):
with zipf.open(filename) as image_file:
image = Image.open(image_file)
image.load()
# Load image data as 1 dimensional array
# We're using float32 to save on memory space
feature = np.array(image, dtype=np.float32).flatten()
# Get the the letter from the filename. This is the letter of the image.
label = os.path.split(filename)[1][0]
features.append(feature)
labels.append(label)
return np.array(features), np.array(labels)
# Get the features and labels from the zip files
train_features, train_labels = uncompress_features_labels('notMNIST_train.zip')
test_features, test_labels = uncompress_features_labels('notMNIST_test.zip')
# Limit the amount of data to work with a docker container
docker_size_limit = 150000
train_features, train_labels = resample(train_features, train_labels, n_samples=docker_size_limit)
# Set flags for feature engineering. This will prevent you from skipping an important step.
is_features_normal = False
is_labels_encod = False
# Wait until you see that all features and labels have been uncompressed.
print('All features and labels uncompressed.') | 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 [grayscale](https://en.wikipedia.org/wiki/Grayscale), the current values range from a min of 0 to a max of 255.Min-Max Scaling:$X'=a+{\frac {\left(X-X_{\min }\right)\left(b-a\right)}{X_{\max }-X_{\min }}}$*If you're having trouble solving problem 1, you can view the solution [here](https://github.com/udacity/CarND-TensorFlow-Lab/blob/master/solutions.ipynb).* | 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 data
"""
# TODO: Implement Min-Max scaling for grayscale image data
a = 0.1
b = 0.9
grayscale_min = 0
grayscale_max = 255
return a + ( ( (image_data - grayscale_min)*(b - a) )/( grayscale_max - grayscale_min ) )
### DON'T MODIFY ANYTHING BELOW ###
# Test Cases
np.testing.assert_array_almost_equal(
normalize_grayscale(np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 255])),
[0.1, 0.103137254902, 0.106274509804, 0.109411764706, 0.112549019608, 0.11568627451, 0.118823529412, 0.121960784314,
0.125098039216, 0.128235294118, 0.13137254902, 0.9],
decimal=3)
np.testing.assert_array_almost_equal(
normalize_grayscale(np.array([0, 1, 10, 20, 30, 40, 233, 244, 254,255])),
[0.1, 0.103137254902, 0.13137254902, 0.162745098039, 0.194117647059, 0.225490196078, 0.830980392157, 0.865490196078,
0.896862745098, 0.9])
if not is_features_normal:
train_features = normalize_grayscale(train_features)
test_features = normalize_grayscale(test_features)
is_features_normal = True
print('Tests Passed!')
if not is_labels_encod:
# Turn labels into numbers and apply One-Hot Encoding
encoder = LabelBinarizer()
encoder.fit(train_labels)
train_labels = encoder.transform(train_labels)
test_labels = encoder.transform(test_labels)
# Change to float32, so it can be multiplied against the features in TensorFlow, which are float32
train_labels = train_labels.astype(np.float32)
test_labels = test_labels.astype(np.float32)
is_labels_encod = True
print('Labels One-Hot Encoded')
assert is_features_normal, 'You skipped the step to normalize the features'
assert is_labels_encod, 'You skipped the step to One-Hot Encode the labels'
# Get randomized datasets for training and validation
train_features, valid_features, train_labels, valid_labels = train_test_split(
train_features,
train_labels,
test_size=0.05,
random_state=832289)
print('Training features and labels randomized and split.')
# Save the data for easy access
pickle_file = 'notMNIST.pickle'
if not os.path.isfile(pickle_file):
print('Saving data to pickle file...')
try:
with open('notMNIST.pickle', 'wb') as pfile:
pickle.dump(
{
'train_dataset': train_features,
'train_labels': train_labels,
'valid_dataset': valid_features,
'valid_labels': valid_labels,
'test_dataset': test_features,
'test_labels': test_labels,
},
pfile, pickle.HIGHEST_PROTOCOL)
except Exception as e:
print('Unable to save data to', pickle_file, ':', e)
raise
print('Data cached in pickle file.') | 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_dataset']
train_labels = pickle_data['train_labels']
valid_features = pickle_data['valid_dataset']
valid_labels = pickle_data['valid_labels']
test_features = pickle_data['test_dataset']
test_labels = pickle_data['test_labels']
del pickle_data # Free up memory
print('Data and modules loaded.') | _____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 Tensor with random numbers from a truncated normal distribution. - See `tf.truncated_normal()` documentation for help. - `biases` - Variable Tensor with all zeros. - See `tf.zeros()` documentation for help.*If you're having trouble solving problem 2, review "TensorFlow Linear Function" section of the class. If that doesn't help, the solution for this problem is available [here](https://github.com/udacity/CarND-TensorFlow-Lab/blob/master/solutions.ipynb).* | 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))
### DON'T MODIFY ANYTHING BELOW ###
#Test Cases
from tensorflow.python.ops.variables import Variable
assert features._op.name.startswith('Placeholder'), 'features must be a placeholder'
assert labels._op.name.startswith('Placeholder'), 'labels must be a placeholder'
assert isinstance(weights, Variable), 'weights must be a TensorFlow variable'
assert isinstance(biases, Variable), 'biases must be a TensorFlow variable'
assert features._shape == None or (\
features._shape.dims[0].value is None and\
features._shape.dims[1].value in [None, 784]), 'The shape of features is incorrect'
assert labels._shape == None or (\
labels._shape.dims[0].value is None and\
labels._shape.dims[1].value in [None, 10]), 'The shape of labels is incorrect'
assert weights._variable._shape == (784, 10), 'The shape of weights is incorrect'
assert biases._variable._shape == (10), 'The shape of biases is incorrect'
assert features._dtype == tf.float32, 'features must be type float32'
assert labels._dtype == tf.float32, 'labels must be type float32'
# Feed dicts for training, validation, and test session
train_feed_dict = {features: train_features, labels: train_labels}
valid_feed_dict = {features: valid_features, labels: valid_labels}
test_feed_dict = {features: test_features, labels: test_labels}
# Linear Function WX + b
logits = tf.matmul(features, weights) + biases
prediction = tf.nn.softmax(logits)
# Cross entropy
cross_entropy = -tf.reduce_sum(labels * tf.log(prediction), axis=1)
# some students have encountered challenges using this function, and have resolved issues
# using https://www.tensorflow.org/api_docs/python/tf/nn/softmax_cross_entropy_with_logits
# please see this thread for more detail https://discussions.udacity.com/t/accuracy-0-10-in-the-intro-to-tensorflow-lab/272469/9
# Training loss
loss = tf.reduce_mean(cross_entropy)
# Create an operation that initializes all variables
init = tf.global_variables_initializer()
# Test Cases
with tf.Session() as session:
session.run(init)
session.run(loss, feed_dict=train_feed_dict)
session.run(loss, feed_dict=valid_feed_dict)
session.run(loss, feed_dict=test_feed_dict)
biases_data = session.run(biases)
assert not np.count_nonzero(biases_data), 'biases must be zeros'
print('Tests Passed!')
# Determine if the predictions are correct
is_correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(labels, 1))
# Calculate the accuracy of the predictions
accuracy = tf.reduce_mean(tf.cast(is_correct_prediction, tf.float32))
print('Accuracy function created.') | 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 * 300 * 50* **Learning Rate:** 0.01Configuration 2* **Epochs:** 1* **Batch Size:** 100* **Learning Rate:** * 0.8 * 0.5 * 0.1 * 0.05 * 0.01Configuration 3* **Epochs:** * 1 * 2 * 3 * 4 * 5* **Batch Size:** 100* **Learning Rate:** 0.2The code will print out a Loss and Accuracy graph, so you can see how well the neural network performed.*If you're having trouble solving problem 3, you can view the solution [here](https://github.com/udacity/CarND-TensorFlow-Lab/blob/master/solutions.ipynb).* | # 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.0
# Measurements use for graphing loss and accuracy
log_batch_step = 50
batches = []
loss_batch = []
train_acc_batch = []
valid_acc_batch = []
with tf.Session() as session:
session.run(init)
batch_count = int(math.ceil(len(train_features)/batch_size))
for epoch_i in range(epochs):
# Progress bar
batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch_i+1, epochs), unit='batches')
# The training cycle
for batch_i in batches_pbar:
# Get a batch of training features and labels
batch_start = batch_i*batch_size
batch_features = train_features[batch_start:batch_start + batch_size]
batch_labels = train_labels[batch_start:batch_start + batch_size]
# Run optimizer and get loss
_, l = session.run(
[optimizer, loss],
feed_dict={features: batch_features, labels: batch_labels})
# Log every 50 batches
if not batch_i % log_batch_step:
# Calculate Training and Validation accuracy
training_accuracy = session.run(accuracy, feed_dict=train_feed_dict)
validation_accuracy = session.run(accuracy, feed_dict=valid_feed_dict)
# Log batches
previous_batch = batches[-1] if batches else 0
batches.append(log_batch_step + previous_batch)
loss_batch.append(l)
train_acc_batch.append(training_accuracy)
valid_acc_batch.append(validation_accuracy)
# Check accuracy against Validation data
validation_accuracy = session.run(accuracy, feed_dict=valid_feed_dict)
loss_plot = plt.subplot(211)
loss_plot.set_title('Loss')
loss_plot.plot(batches, loss_batch, 'g')
loss_plot.set_xlim([batches[0], batches[-1]])
acc_plot = plt.subplot(212)
acc_plot.set_title('Accuracy')
acc_plot.plot(batches, train_acc_batch, 'r', label='Training Accuracy')
acc_plot.plot(batches, valid_acc_batch, 'x', label='Validation Accuracy')
acc_plot.set_ylim([0, 1.0])
acc_plot.set_xlim([batches[0], batches[-1]])
acc_plot.legend(loc=4)
plt.tight_layout()
plt.show()
print('Validation accuracy at {}'.format(validation_accuracy)) | 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/1425 [00:05<00:00, 239.41batches/s]
Epoch 6/30: 100%|██████████| 1425/1425 [00:06<00:00, 233.95batches/s]
Epoch 7/30: 100%|██████████| 1425/1425 [00:05<00:00, 248.55batches/s]
Epoch 8/30: 100%|██████████| 1425/1425 [00:05<00:00, 249.13batches/s]
Epoch 9/30: 100%|██████████| 1425/1425 [00:05<00:00, 246.91batches/s]
Epoch 10/30: 100%|██████████| 1425/1425 [00:05<00:00, 246.33batches/s]
Epoch 11/30: 100%|██████████| 1425/1425 [00:06<00:00, 222.22batches/s]
Epoch 12/30: 100%|██████████| 1425/1425 [00:05<00:00, 238.46batches/s]
Epoch 13/30: 100%|██████████| 1425/1425 [00:05<00:00, 247.66batches/s]
Epoch 14/30: 100%|██████████| 1425/1425 [00:05<00:00, 247.59batches/s]
Epoch 15/30: 100%|██████████| 1425/1425 [00:05<00:00, 265.48batches/s]
Epoch 16/30: 100%|██████████| 1425/1425 [00:05<00:00, 243.82batches/s]
Epoch 17/30: 100%|██████████| 1425/1425 [00:06<00:00, 236.59batches/s]
Epoch 18/30: 100%|██████████| 1425/1425 [00:05<00:00, 240.60batches/s]
Epoch 19/30: 100%|██████████| 1425/1425 [00:05<00:00, 248.57batches/s]
Epoch 20/30: 100%|██████████| 1425/1425 [00:05<00:00, 244.13batches/s]
Epoch 21/30: 100%|██████████| 1425/1425 [00:05<00:00, 244.86batches/s]
Epoch 22/30: 100%|██████████| 1425/1425 [00:05<00:00, 217.50batches/s]
Epoch 23/30: 100%|██████████| 1425/1425 [00:05<00:00, 245.30batches/s]
Epoch 24/30: 100%|██████████| 1425/1425 [00:05<00:00, 241.40batches/s]
Epoch 25/30: 100%|██████████| 1425/1425 [00:05<00:00, 251.86batches/s]
Epoch 26/30: 100%|██████████| 1425/1425 [00:05<00:00, 256.47batches/s]
Epoch 27/30: 100%|██████████| 1425/1425 [00:06<00:00, 224.38batches/s]
Epoch 28/30: 100%|██████████| 1425/1425 [00:05<00:00, 249.99batches/s]
Epoch 29/30: 100%|██████████| 1425/1425 [00:05<00:00, 246.27batches/s]
Epoch 30/30: 100%|██████████| 1425/1425 [00:05<00:00, 252.18batches/s]
| 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 least 80%. | # 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_count = int(math.ceil(len(train_features)/batch_size))
for epoch_i in range(epochs):
# Progress bar
batches_pbar = tqdm(range(batch_count), desc='Epoch {:>2}/{}'.format(epoch_i+1, epochs), unit='batches')
# The training cycle
for batch_i in batches_pbar:
# Get a batch of training features and labels
batch_start = batch_i*batch_size
batch_features = train_features[batch_start:batch_start + batch_size]
batch_labels = train_labels[batch_start:batch_start + batch_size]
# Run optimizer
_ = session.run(optimizer, feed_dict={features: batch_features, labels: batch_labels})
# Check accuracy against Test data
test_accuracy = session.run(accuracy, feed_dict=test_feed_dict)
assert test_accuracy >= 0.80, 'Test accuracy at {}, should be equal to or greater than 0.80'.format(test_accuracy)
print('Nice Job! Test Accuracy is {}'.format(test_accuracy)) | 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/1425 [00:02<00:00, 539.59batches/s]
Epoch 6/25: 100%|██████████| 1425/1425 [00:02<00:00, 540.76batches/s]
Epoch 7/25: 100%|██████████| 1425/1425 [00:02<00:00, 541.74batches/s]
Epoch 8/25: 100%|██████████| 1425/1425 [00:02<00:00, 545.16batches/s]
Epoch 9/25: 100%|██████████| 1425/1425 [00:02<00:00, 505.92batches/s]
Epoch 10/25: 32%|███▏ | 452/1425 [00:00<00:01, 491.61batches/s] | 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 that is used in `Pipeline` along with other tensor operators such as `MinMax` and `Resize`.There are only two differences between `TensorFilter` and `TensorOp`: 1. `TensorFilter` does not have outputs.2. The forward function of `TensorFilter` produces a boolean value which indicates whether to keep the data or not. Step 0 - Data preparation *(same as tutorial 1)* | # 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 = {"x": np.expand_dims(x_eval, -1), "y": y_eval}
data = {"train": train_data, "eval": 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(batch_size=32, data=data, ops=[MyFilter(inputs="y"), Minmax(inputs="x", outputs="x")])
# Let's check our pipeline ops results with show_results
results = pipeline.show_results()
print("filtering out all data with label less than 5, the labels of current batch are:")
print(results[0]["y"]) | 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.5, 0.5, 0.5]),
Minmax(inputs="x", outputs="x")])
# Let's check our pipeline ops results with show_results
results = pipeline.show_results(num_steps=10)
for idx in range(10):
batch_label = results[idx]["y"].numpy()
even_count = 0
odd_count = 0
for elem in batch_label:
if elem % 2 == 0:
even_count += 1
else:
odd_count += 1
print("in batch number {}, there are {} odd labels and {} even labels".format(idx, odd_count, even_count)) | 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 number 5, there are 22 odd labels and 10 even labels
in batch number 6, there are 21 odd labels and 11 even labels
in batch number 7, there are 20 odd labels and 12 even labels
in batch number 8, there are 22 odd labels and 10 even labels
in batch number 9, there are 25 odd labels and 7 even labels
| 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
SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_LDA_y_predito = SK_LDA.predict(X=X_teste)
SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))
# LDA - Próprio
ME_LDA = AnaliseDiscriminante(tipo='LDA')
ME_LDA.treinar(X=X_treino, y=y_treino)
ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)
ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))
# QDA - Scikit-Learn
SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_QDA_y_predito = SK_QDA.predict(X=X_teste)
SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))
# QDA - Próprio
ME_QDA = AnaliseDiscriminante(tipo='QDA')
ME_QDA.treinar(X=X_treino, y=y_treino)
ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)
ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))
SK_LDA_desempenho = np.array(SK_LDA_desempenho)
SK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)
SK_LDA_desempenho_std = np.std(SK_LDA_desempenho)
ME_LDA_desempenho = np.array(ME_LDA_desempenho)
ME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)
ME_LDA_desempenho_std = np.std(ME_LDA_desempenho)
SK_QDA_desempenho = np.array(SK_QDA_desempenho)
SK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)
SK_QDA_desempenho_std = np.std(SK_QDA_desempenho)
ME_QDA_desempenho = np.array(ME_QDA_desempenho)
ME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)
ME_QDA_desempenho_std = np.std(ME_QDA_desempenho)
print('DATASET 1')
print('------ Acurácias -----')
print('LDA - Scikit: \t{0:3.4f}'.format(SK_LDA_desempenho_media))
print('LDA - Próprio: \t{0:3.4f}'.format(ME_LDA_desempenho_media))
print('----------------------')
print('QDA - Scikit: \t{0:3.4f}'.format(SK_QDA_desempenho_media))
print('QDA - Próprio: \t{0:3.4f}'.format(ME_QDA_desempenho_media)) | 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
SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_LDA_y_predito = SK_LDA.predict(X=X_teste)
SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))
# LDA - Próprio
ME_LDA = AnaliseDiscriminante(tipo='LDA')
ME_LDA.treinar(X=X_treino, y=y_treino)
ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)
ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))
# QDA - Scikit-Learn
SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_QDA_y_predito = SK_QDA.predict(X=X_teste)
SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))
# QDA - Próprio
ME_QDA = AnaliseDiscriminante(tipo='QDA')
ME_QDA.treinar(X=X_treino, y=y_treino)
ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)
ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))
SK_LDA_desempenho = np.array(SK_LDA_desempenho)
SK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)
SK_LDA_desempenho_std = np.std(SK_LDA_desempenho)
ME_LDA_desempenho = np.array(ME_LDA_desempenho)
ME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)
ME_LDA_desempenho_std = np.std(ME_LDA_desempenho)
SK_QDA_desempenho = np.array(SK_QDA_desempenho)
SK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)
SK_QDA_desempenho_std = np.std(SK_QDA_desempenho)
ME_QDA_desempenho = np.array(ME_QDA_desempenho)
ME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)
ME_QDA_desempenho_std = np.std(ME_QDA_desempenho)
print('DATASET 2')
print('------ Acurácias -----')
print('LDA - Scikit: \t{0:3.4f}'.format(SK_LDA_desempenho_media))
print('LDA - Próprio: \t{0:3.4f}'.format(ME_LDA_desempenho_media))
print('----------------------')
print('QDA - Scikit: \t{0:3.4f}'.format(SK_QDA_desempenho_media))
print('QDA - Próprio: \t{0:3.4f}'.format(ME_QDA_desempenho_media)) | 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
SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_LDA_y_predito = SK_LDA.predict(X=X_teste)
SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))
# LDA - Próprio
ME_LDA = AnaliseDiscriminante(tipo='LDA')
ME_LDA.treinar(X=X_treino, y=y_treino)
ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)
ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))
# QDA - Scikit-Learn
SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_QDA_y_predito = SK_QDA.predict(X=X_teste)
SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))
# QDA - Próprio
ME_QDA = AnaliseDiscriminante(tipo='QDA')
ME_QDA.treinar(X=X_treino, y=y_treino)
ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)
ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))
SK_LDA_desempenho = np.array(SK_LDA_desempenho)
SK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)
SK_LDA_desempenho_std = np.std(SK_LDA_desempenho)
ME_LDA_desempenho = np.array(ME_LDA_desempenho)
ME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)
ME_LDA_desempenho_std = np.std(ME_LDA_desempenho)
SK_QDA_desempenho = np.array(SK_QDA_desempenho)
SK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)
SK_QDA_desempenho_std = np.std(SK_QDA_desempenho)
ME_QDA_desempenho = np.array(ME_QDA_desempenho)
ME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)
ME_QDA_desempenho_std = np.std(ME_QDA_desempenho)
print('DATASET 3')
print('------ Acurácias -----')
print('LDA - Scikit: \t{0:3.4f}'.format(SK_LDA_desempenho_media))
print('LDA - Próprio: \t{0:3.4f}'.format(ME_LDA_desempenho_media))
print('----------------------')
print('QDA - Scikit: \t{0:3.4f}'.format(SK_QDA_desempenho_media))
print('QDA - Próprio: \t{0:3.4f}'.format(ME_QDA_desempenho_media)) | 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
SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_LDA_y_predito = SK_LDA.predict(X=X_teste)
SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))
# LDA - Próprio
ME_LDA = AnaliseDiscriminante(tipo='LDA')
ME_LDA.treinar(X=X_treino, y=y_treino)
ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)
ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))
# QDA - Scikit-Learn
SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_QDA_y_predito = SK_QDA.predict(X=X_teste)
SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))
# QDA - Próprio
ME_QDA = AnaliseDiscriminante(tipo='QDA')
ME_QDA.treinar(X=X_treino, y=y_treino)
ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)
ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))
SK_LDA_desempenho = np.array(SK_LDA_desempenho)
SK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)
SK_LDA_desempenho_std = np.std(SK_LDA_desempenho)
ME_LDA_desempenho = np.array(ME_LDA_desempenho)
ME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)
ME_LDA_desempenho_std = np.std(ME_LDA_desempenho)
SK_QDA_desempenho = np.array(SK_QDA_desempenho)
SK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)
SK_QDA_desempenho_std = np.std(SK_QDA_desempenho)
ME_QDA_desempenho = np.array(ME_QDA_desempenho)
ME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)
ME_QDA_desempenho_std = np.std(ME_QDA_desempenho)
print('DATASET 4')
print('------ Acurácias -----')
print('LDA - Scikit: \t{0:3.4f}'.format(SK_LDA_desempenho_media))
print('LDA - Próprio: \t{0:3.4f}'.format(ME_LDA_desempenho_media))
print('----------------------')
print('QDA - Scikit: \t{0:3.4f}'.format(SK_QDA_desempenho_media))
print('QDA - Próprio: \t{0:3.4f}'.format(ME_QDA_desempenho_media)) | 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
SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_LDA_y_predito = SK_LDA.predict(X=X_teste)
SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))
# LDA - Próprio
ME_LDA = AnaliseDiscriminante(tipo='LDA')
ME_LDA.treinar(X=X_treino, y=y_treino)
ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)
ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))
# QDA - Scikit-Learn
SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_QDA_y_predito = SK_QDA.predict(X=X_teste)
SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))
# QDA - Próprio
ME_QDA = AnaliseDiscriminante(tipo='QDA')
ME_QDA.treinar(X=X_treino, y=y_treino)
ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)
ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))
SK_LDA_desempenho = np.array(SK_LDA_desempenho)
SK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)
SK_LDA_desempenho_std = np.std(SK_LDA_desempenho)
ME_LDA_desempenho = np.array(ME_LDA_desempenho)
ME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)
ME_LDA_desempenho_std = np.std(ME_LDA_desempenho)
SK_QDA_desempenho = np.array(SK_QDA_desempenho)
SK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)
SK_QDA_desempenho_std = np.std(SK_QDA_desempenho)
ME_QDA_desempenho = np.array(ME_QDA_desempenho)
ME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)
ME_QDA_desempenho_std = np.std(ME_QDA_desempenho)
print('DATASET 5')
print('------ Acurácias -----')
print('LDA - Scikit: \t{0:3.4f}'.format(SK_LDA_desempenho_media))
print('LDA - Próprio: \t{0:3.4f}'.format(ME_LDA_desempenho_media))
print('----------------------')
print('QDA - Scikit: \t{0:3.4f}'.format(SK_QDA_desempenho_media))
print('QDA - Próprio: \t{0:3.4f}'.format(ME_QDA_desempenho_media)) | 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
SK_LDA = LinearDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_LDA_y_predito = SK_LDA.predict(X=X_teste)
SK_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_LDA_y_predito))
# LDA - Próprio
ME_LDA = AnaliseDiscriminante(tipo='LDA')
ME_LDA.treinar(X=X_treino, y=y_treino)
ME_LDA_y_predito = ME_LDA.classificar(X=X_teste)
ME_LDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_LDA_y_predito))
# QDA - Scikit-Learn
SK_QDA = QuadraticDiscriminantAnalysis().fit(X=X_treino, y=y_treino)
SK_QDA_y_predito = SK_QDA.predict(X=X_teste)
SK_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=SK_QDA_y_predito))
# QDA - Próprio
ME_QDA = AnaliseDiscriminante(tipo='QDA')
ME_QDA.treinar(X=X_treino, y=y_treino)
ME_QDA_y_predito = ME_QDA.classificar(X=X_teste)
ME_QDA_desempenho.append(avaliar_desempenho(y_verdadeiro=y_teste, y_obtido=ME_QDA_y_predito))
SK_LDA_desempenho = np.array(SK_LDA_desempenho)
SK_LDA_desempenho_media = np.mean(SK_LDA_desempenho)
SK_LDA_desempenho_std = np.std(SK_LDA_desempenho)
ME_LDA_desempenho = np.array(ME_LDA_desempenho)
ME_LDA_desempenho_media = np.mean(ME_LDA_desempenho)
ME_LDA_desempenho_std = np.std(ME_LDA_desempenho)
SK_QDA_desempenho = np.array(SK_QDA_desempenho)
SK_QDA_desempenho_media = np.mean(SK_QDA_desempenho)
SK_QDA_desempenho_std = np.std(SK_QDA_desempenho)
ME_QDA_desempenho = np.array(ME_QDA_desempenho)
ME_QDA_desempenho_media = np.mean(ME_QDA_desempenho)
ME_QDA_desempenho_std = np.std(ME_QDA_desempenho)
print('DATASET 6')
print('------ Acurácias -----')
print('LDA - Scikit: \t{0:3.4f}'.format(SK_LDA_desempenho_media))
print('LDA - Próprio: \t{0:3.4f}'.format(ME_LDA_desempenho_media))
print('----------------------')
print('QDA - Scikit: \t{0:3.4f}'.format(SK_QDA_desempenho_media))
print('QDA - Próprio: \t{0:3.4f}'.format(ME_QDA_desempenho_media)) | 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 de datos lineal ordenado.Consiste en dividir el conjunto en mitades y buscar en esa mitad. Si el elemento buscado no está en la mitad, preguntas si el elemento está a la derecha o a la izquierda. Haces la lista igual a la mitad correspondiente y repites el proceso.Pseudocódigo:L = [ 4,18,47,2,34,14,78,12,48,21,31,19,1,3,5]DER = longitud(L) - 1IZQ = 0MID: apuntará a la mitad del segmento de búsqueda buscado: es el valos a buscar1. Hacer DER = longitud(L) - 12. Hacer IZQ = 03. Si IZQ > DER, significa que hay un error en los datos 4. Calcular MID = int((IZQ + DER) / 2)5. Mientras L[MID] != buscado, hacer6. - preguntar si L[MID] > buscado - hacer DER = MID - de lo contrario - hacer IZQ = MID - preguntar si (DER - IZQ) % 2 == 0 - MID = (IZQ + ((DER - IZQ) / 2)) + 1 - de lo contrario - MID = IZQ + ((DER - IZQ) / 2)7. return MID | '''
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
break
print(f"número de comparaciones realizadas = {contador}")
return indice
'''
Búsqueda binaria
'''
def busqueda_binaria(L, buscado):
IZQ = 0
DER = len(L) - 1
MID = int((IZQ + DER) / 2)
if len(L) % 2 == 0:
MID = (DER // 2) + 1
else:
MID = DER // 2
while (L[MID] != buscado):
if L[MID] > buscado:
DER = MID
else:
IZQ = MID
if (DER - IZQ) % 2 == 0:
MID = (IZQ + ((DER - IZQ) // 2)) + 1
else:
MID = IZQ + ((DER - IZQ) // 2)
return MID
def main():
datos = [ 4,18,47,2,34,14,78,12,48,21,31,19,1,3,5]
dato = int(input("Que valor quieres buscar: "))
resultado = busq_lineal(datos, dato)
print("Resultado: ", resultado)
print("Búsqueda lineal en una lista ordenada")
datos.sort() # Con esto se ordenan los datos
print(datos)
resultado = busq_lineal(datos, dato)
print("Resultado: ", resultado)
print("Búsqueda binaria")
posicion = busqueda_binaria(datos, dato)
print(f"El elemento dato está en la posición {posicion} de la lista")
main() | 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 and frequency range.
Parameters:
x (numpy array): Signal to be transformed into Fourier domain.
Returns:
mag (numpy array): Magnitude of the signal's Fourier transform.
freq (numpy array): Frequency domain of the signal's Fourier transform.
"""
signal = x.reshape(-1,1)
fourier = fourier_transform.FourierTransform(signal)
mag = fourier.dft_magnitude()
freq = fourier.frequency_domain()
return mag, freq | _____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=True)
plt.title('Low Pass Filter')
plt.grid('on')
plt.subplot(2,2,2)
plt.stem(high_pass, markerfmt='.', use_line_collection=True)
plt.title('High Pass Filter')
plt.grid('on')
plt.subplot(2,2,3)
cplots.plot_frequency_response(dft_low_pass_magnitude,
dft_low_pass_freq,
title='Low Pass Filter Response')
plt.subplot(2,2,4)
cplots.plot_frequency_response(dft_high_pass_magnitude,
dft_high_pass_freq,
title='High Pass Filter Response'); | _____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 Pass ECG')
plt.grid('on')
plt.xlabel('Samples')
plt.ylabel('Amplitude')
plt.subplot(2,1,2)
plt.plot(ecg)
plt.title('ECG Signal')
plt.grid('on')
plt.xlabel('Samples')
plt.ylabel('Amplitude'); | _____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 : [email protected] Step 1 : Definitions / Initialisations / Automatic thresholding Subroutines : * `analyse_bubble` : checks one bubble (any bubble) for shape and threshold detection * `padding` : pads an image with values from the edge (useful to avoid issues with bubbles close to the border) * `proj_fourier` : fits the bubble shape with Fourier series (produces coefficients) * `build_fourier` : rebuilds the Fourier fit based on projection coefficients* `write_csvheader` : helps me build a nice header for the data file based on * `write_logheader`: helps doing the same with the log file (saving lots of acquisition-related parameters)* `format_logstr` : bunches together some numbers to track your experiment (in log file & in stdout)* `init_figure` : initialises the (somewhat live) figure of the bubble and its interface* `init_camera` : (re)starts the camera with the proper acquisition parameters Note : If the camera is not accessible, try before re-running the cells : * camera.Close() * closing vscode and restarting it* Closing Pylon :-) | 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
import skimage.transform as sktr
import skimage.measure as skms
import skimage.filters as skfi
import skimage.morphology as skmph
##### YOUR PARAMETERS HERE #############
zoom = 3 # Check on the lens
## ZOOM VALUES z = {'zoom': [0.7, 1, 1.5, 2, 3, 4, 4.5], 'one_mm_in_px': [62, 91, 137, 184, 281, 361, 405]}
## Leads to 90.4 mm/px for a zoom of 1
exposure = 100 # in ms
imagesize = [512,512] # width x height
filter_size = 1 # To smooth images
folder_location = 'C:\\Users\\saint-michel\\Documents\\Acquisitions\\Bubbles_20211216'
pixel_format = "Mono12" # Image values are then from 0 to 4095 (and not 255). NOTE : SOME THINGS WILL BREAK IF YOU CHANGE THIS (including image saving)
threshold = None # From 0 to 4096, leave to 'None' if you want auto threshold ...
chunk_size = 100 # We save snapshots every chunk_size frames
### FUNCTIONS THAT YOU MAY CALL TO DO THINGS ##################################################################
def analyse_frame(img, myinfo, time=0):
# Finds a nice threshold, etc.
# Myinfo : dict with at least 'pixel_format' and 'threshold' (which can be None)
# Time : timestamp given by camera.grabFrame
# Subroutines ...
def img_padding(img, pad=16):
img_pad = np.zeros((np.shape(img)[0] + 2*pad, np.shape(img)[1] + 2*pad))
img_pad[pad:-pad, pad:-pad] = img
img_pad[:pad, pad:-pad] = img[0,:]
img_pad[-pad:, pad:-pad] = img[-1,:]
img_pad[:, :pad] = img_pad[:,pad, np.newaxis]
img_pad[:, -pad:] = img_pad[:, -pad-1, np.newaxis]
return img_pad, pad
def proj_fourier(signal, thetas):
nmodes = 10
proj_cos, proj_sin = np.zeros(nmodes), np.zeros(nmodes)
for mno in range(nmodes):
proj_cos[mno] = np.trapz(signal*np.cos(mno*thetas), x=thetas)*1/np.pi
proj_sin[mno] = np.trapz(signal*np.sin(mno*thetas), x=thetas)*1/np.pi
proj_amp = np.sqrt(proj_cos**2 + proj_sin**2)
proj_phs = np.arctan2(-proj_sin, proj_cos) # It works with a (-) ... so be it.
return proj_amp, proj_phs
def build_fourier(proj_amp, proj_phs, thetas):
nmodes = 10
rebuild = np.zeros(np.shape(thetas))
for mno in range(nmodes):
rebuild = rebuild + proj_amp[mno]*np.cos(mno*thetas + proj_phs[mno])
return rebuild
def local_minimum(signal, size=150):
x = np.linspace(-3,3,size+1)
kernel = np.diff(np.exp(-x**2))/np.sum(np.exp(-x**2))
signal_dfilt = np.convolve(signal, kernel, mode='same')
slope_left, slope_right = signal_dfilt[:-1], signal_dfilt[1:]
the_maxima = np.where(np.logical_and(slope_left > 0, slope_right < 0))[0]
if the_maxima.size == 2:
the_minimum = np.round(0.5*np.sum(the_maxima)).astype(int)
print('> local_minimum : Found two maxima at : ' + str(the_maxima) + ' / minimum around : ' + str(the_minimum))
return the_minimum
else:
print("> Cannot locate a minimum between : " + str(np.size(the_maxima)) + ' maxima :(' )
return 0
# fill holes & filter image
img_seed = np.copy(img)
img_seed[1:-1,1:-1] = img.min()
img_filled = skmph.reconstruction(img_seed, img, method='dilation')
img_pad, padsize = img_padding(img_filled, pad=16)
img_filt = skfi.gaussian(img_pad, sigma=myinfo['smoothing'], preserve_range=True)
myinfo['padsize'] = padsize
# Find threshold from histogram, then threshold image and analyse it
[hist, bins] = np.histogram(img_filt.ravel(), bins=np.linspace(-0.5,myinfo['max_lum']+0.5, 361)) # NOTE: bin number must mach length of theta (for bokeh CDS to be happy)
if myinfo['threshold'] is None:
myinfo['threshold'] = bins[local_minimum(hist)]
img_th = img_pad < myinfo['threshold']
labelled_img = skms.label(img_th)
props = skms.regionprops_table(labelled_img, properties=('label', 'centroid', 'area', 'eccentricity', 'coords'))
big = props['area'] > 100
# Fill in small objects, clean up a bit
x_toclean, y_toclean = np.array([], dtype=int), np.array([], dtype=int)
for elno, xy in enumerate(props['coords']):
if not big[elno]:
x_toclean, y_toclean = np.append(x_toclean, xy[:,1]), np.append(y_toclean, xy[:,0])
img_th[y_toclean, x_toclean] = 0
props = pd.DataFrame.from_dict(props).drop(columns='coords')
props = props[big].sort_values(by='area', ascending=False, ignore_index=True)
props['label'] = np.arange(1,props.shape[0]+1)
# If no objects, we can't analyse interface (== project on polar coordinates + do fourier modes)
th_rebuild = np.linspace(-np.pi, np.pi, 360)
nbubbles = np.size(props['area'])
adapter = np.atleast_1d(np.ones(np.shape(props['area']))) # matching shape of rad, ecc, ... with scalar frameno & time
local_time = (time - myinfo['reftime'])*1e-9
if nbubbles > 0:
# These will be saved later
xctr, yctr = np.atleast_1d(props['centroid-1']), np.atleast_1d(props['centroid-0'])
rad, ecc, label = np.atleast_1d(np.sqrt(props['area']/np.pi)), np.atleast_1d(props['eccentricity']), np.atleast_1d(props['label'])
frameno, time = adapter*idx, adapter*local_time
# This is not saved later, just used to check interface of the largest bubble (and verify threshold)
bub0 = np.argmax(rad)
img_pad_warp = sktr.warp_polar(img_pad, (yctr[bub0], xctr[bub0]), radius=1.4*rad[bub0]).T
img_th_warp = sktr.warp_polar(img_th, (yctr[bub0], xctr[bub0]), radius=1.4*rad[bub0]).T
coords = skms.find_contours(img_th)
longest_contour = np.argmax([elem.shape[0] for elem in coords])
coords = np.array(coords[longest_contour]) # I expect the longest contour to match the largest object ...
coords = (coords - [yctr[bub0], xctr[bub0]])/rad[bub0] # Normally : only one contour
th, r = np.arctan2(coords[:,0], coords[:,1]), np.sqrt(coords[:,0]**2 + coords[:,1]**2) - 1
reorder = np.argsort(th)
th, r = th[reorder], r[reorder]
r_amps, r_phs = proj_fourier(r, th)
img_pad_diff = skfi.gaussian(np.diff(img_pad_warp, axis=0), sigma=1)
r_fit = 1 + build_fourier(r_amps, r_phs, th_rebuild)
r_maxgrad = (np.argmax(img_pad_diff, axis=0) + 0.5)*1.4/np.shape(img_pad_warp)[0]
else:
img_pad_warp, img_th_warp = np.zeros((200, 360)), np.zeros((200, 360))
r_fit, r_maxgrad = np.zeros(360), np.zeros(360)
xctr, yctr, rad, ecc, = np.array([np.nan]), np.array([np.nan]), np.array([np.nan]), np.array([np.nan])
label, time, frameno = np.array([0]), np.array([local_time]), np.array([idx])
# Putting everything in two dicts because there is a bug in Bokeh if singleton and 1d objects are mixed
img_data = {'img': [img_pad], 'img_th': [img_th], 'img_polar': [img_pad_warp], 'img_th_polar': [img_th_warp],
'frame': frameno, 'time': time, 'label': label, 'x_px':xctr, 'y_px':yctr, 'rad':rad, 'ecc':ecc, 'padsize':[padsize]}
line_data = {'theta': th_rebuild, 'r_fourier': r_fit, 'r_gradient': r_maxgrad, 'lum_hist': hist, 'lum_bins': bins[1:]}
return img_data, line_data
### WRITE HEADER OF FILES OR DATA #################################################
def write_csvheader(myfile, mylist):
mystr = ''
for elem in mylist:
mystr += elem + ','
myfile.write(mystr[:-1] + '\n')
return 0
def write_logheader(myfile, mydict):
for k, v in zip(mydict.keys(), mydict.values()):
info_str = str(k) + ':' + str(v) + '\n'
myfile.write(info_str)
print(info_str,end='')
return 0
def format_data(data_dict, myinfo): # Data_dict is essentially img_data (or CDS_img.data)
nrows, ncols = np.shape(data_dict['x_px'])[0], 8
is_spurious = np.any(np.sum(data_dict['img'], axis=1) == 0) # Spurious == strange horizontal black lines
data = np.zeros((nrows, ncols))
if nrows > 0:
data[:,0] = data_dict['frame']
data[:,1] = data_dict['time']
data[:,2] = data_dict['label']
data[:,3] = data_dict['x_px']*myinfo['pixsize']
data[:,4] = data_dict['y_px']*myinfo['pixsize']
data[:,5] = data_dict['rad']*myinfo['pixsize']
data[:,6] = data_dict['ecc']
data[:,7] = is_spurious
return data
def format_logstr(data_dict):
is_spurious = np.any(np.sum(data_dict['img'], axis=1) == 0) # Spurious == strange horizontal black lines
nstr = 'Frame=' + '{:06.0f}'.format(data_dict['frame'][0]) + ','
tstr = 't=' + '{:.2f}'.format(data_dict['time'][0]) + ','
labstr = 'n=' + '{:.0f}'.format(data_dict['label'][-1]) + ','
xstr = 'x0=' + '{:.2f}'.format(data_dict['x_px'][0]) + ','
ystr = 'y0=' + '{:.2f}'.format(data_dict['y_px'][0]) + ','
rstr = 'r=' + '{:.2f}'.format(data_dict['rad'][0]) + ','
spstr = 'spu=' + '{:d}'.format(is_spurious)
return nstr + tstr + labstr + xstr + ystr + rstr + spstr
def save_snapshot(folder_location, img, pix_fmt="Mono12", idx=0):
rescaling = 1 + (pix_fmt=="Mono12")*(4095/255-1)
img = (img[0].astype(np.int32)/rescaling).astype(np.uint8) # The [0] is some compatibility thing with Bokeh
pilimg = Image.fromarray(img)
pilimg.save(folder_location + '\\frame_' + '{:06d}'.format(idx) + '.png')
def init_figure():
# Essentially needs the CDS_img and CDS_line objects (from analyse_frame)
# And myinfo object. Returns Bokeh figure objects
mapper_bw = LinearColorMapper(palette="Greys256")
mapper_th = LinearColorMapper(palette=['rgba(0,0,0,0)', 'lime'], high=1, low=0)
plotint = figure(title="Threshold : orange and pink closer is better", height=300, width=800, tools="")
plotint.image("img_polar", x=-np.pi, y=0, dw=2*np.pi, dh=1.4, color_mapper=mapper_bw, global_alpha=1, source=CDS_img)
plotint.image("img_th_polar", x=-np.pi, y=0, dw=2*np.pi, dh=1.4, color_mapper=mapper_th, global_alpha=0.15, source=CDS_img)
plotint.line(x='theta', y='r_fourier', line_color='hotpink', line_width=2, line_dash='dashed', source=CDS_line)
plotint.line(x='theta', y='r_gradient', line_color='orange', line_width=2, line_dash='dotted', source=CDS_line)
plotint.y_range.start, plotint.y_range.end = 0.85, 1.15
plotint.x_range.start, plotint.x_range.end = -np.pi, np.pi
plotint.xaxis.axis_label, plotint.yaxis.axis_label = 'θ', 'r/R'
f_height, f_width = np.shape(CDS_img.data['img'][0]) # Affected by img_padding (used in analyse_frame)
hist_max = np.max(CDS_line.data['lum_hist'])
plotimg = figure(height=400, width=400, title='Raw Reference Frame', tools="", match_aspect=True)
plotpdf = figure(height=400, width=400, title='Histogram', tools="")
plotimg.image("img", dw=f_width, dh=f_height, x=0, y=0, color_mapper=mapper_bw, source=CDS_img)
# plotimg.image("img_th", dw=f_width, dh=f_height, x=0, y=0, color_mapper=mapper_th, global_alpha=0.25, source=CDS_img)
plotimg.cross(x="x_px", y="y_px", size=10, line_color='lime', source=CDS_img)
plotpdf.line([myinfo['threshold'],myinfo['threshold']], [0, hist_max], line_dash='dashed')
plotpdf.line(x="lum_bins", y='lum_hist', source=CDS_line)
return plotint, plotimg, plotpdf
##### SAY HI TO THE CAMERA and set some parameters
def init_camera(myinfo):
camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
camera.Close()
camera.Open()
myinfo['cameraname'] = camera.GetDeviceInfo().GetModelName()
camera.AcquisitionFrameRateEnable.SetValue(True), camera.AcquisitionFrameRateAbs.SetValue(5) # Setting fps to 5
camera.BinningModeVertical.SetValue('Averaging'), camera.BinningModeHorizontal.SetValue('Averaging') # Activating binning in x & y
camera.BinningHorizontal.SetValue(2), camera.BinningVertical.SetValue(2) # Using 2^1 (3 would be 2^2 I guess) binning
camera.Width.SetValue(imagesize[0]), camera.Height.SetValue(imagesize[1])
camera.CenterX.SetValue(True), camera.CenterY.SetValue(True)
camera.ExposureTimeAbs.SetValue(myinfo['exposure'])
camera.PixelFormat.SetValue(myinfo['pixel_format'])
camera.GevTimestampControlReset()
return camera
# # Emulate with a PNG file
# img = Image.open('C:\\Users\\saint-michel\\Documents\\Python\\Bubbles_20211109\\frame_00000.png')
# img = np.array(img)
# time_ref = 0
# pixel_format='Mono8'
# cameraname = 'None'
# Preparing acquisition information for later
global_time_ref = time.gmtime()
gt_str = time.strftime('%Y/%m/%d %H:%M:%S', global_time_ref)
pixsize = 1000/zoom/90.4 # in UM per PX
myinfo = {'time_ref': gt_str, 'zoom': zoom, 'pixsize': pixsize, 'pixel_format': pixel_format,
'threshold': threshold, 'width':imagesize[1], 'height':imagesize[0], 'smoothing':filter_size, 'exposure':exposure,
'pixel_fmt': pixel_format}
if myinfo["pixel_format"] == 'Mono12':
myinfo['max_lum'] = 4095
else:
myinfo['max_lum'] = 255
mycolumns = ['frame', 'time', 'label', 'x', 'y', 'radius', 'eccentricity', 'spurious']
myunits = ['1', 's', '1', 'um', 'um', 'um', '1', '1']
myfmt = '%05d,%07.1f,%1d,%03.2f,%03.2f,%03.2f,%1.2f,%1d'
idx = 0
# Analysing image
camera = init_camera(myinfo)
rawframe = camera.GrabOne(5000)
camera.Close()
myinfo['reftime'] = rawframe.TimeStamp
ref_imgdata, ref_linedata = analyse_frame(rawframe.Array, myinfo, time=rawframe.TimeStamp)
data_array = format_data(ref_imgdata, myinfo)
log_str = format_logstr(ref_imgdata)
CDS_img, CDS_line = ColumnDataSource(data=ref_imgdata), ColumnDataSource(data=ref_linedata)
#### DISPLAYING / LOGGING INFO
os.makedirs(folder_location, exist_ok=True)
log_file = codecs.open(folder_location + "\\log.txt", mode='w', encoding="utf-8")
data_file = codecs.open(folder_location + "\\data.csv", mode='w', encoding="utf-8")
write_logheader(log_file, myinfo)
write_csvheader(data_file, myunits)
write_csvheader(data_file, mycolumns)
np.savetxt(data_file, data_array, fmt=myfmt, delimiter=',')
log_file.write(log_str + '\n')
save_snapshot(folder_location, ref_imgdata['img'])
log_file.close()
data_file.close()
#### PLOTTING RESULTS #########
output_notebook()
plotint, plotimg, plotpdf = init_figure()
BokehModel(column(row(plotimg, plotpdf), plotint)) | > 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 interrupted the program | 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['frame'][0] > chunk_size
xy_change, r_change = False, False
if not nbubble_change:
r_change = np.abs(now_data['rad'] - ref_data['rad'])
x_change = np.abs(now_data['x_px'] - ref_data['x_px'])
y_change = np.abs(now_data['y_px'] - ref_data['y_px'])
r_change = any(r_change > 1)
xy_change = any(x_change > 3) or any(y_change > 3)
if r_change:
event_str = ' | Event ! One (or more) bubbles have changed radius ... Refreshing & Saving'
if xy_change:
event_str = ' | Event ! One (or more) bubbles have changed location ... Refreshing & Saving'
if chunk_timeout:
event_str = ' | Event ! There has been : ' + str(chunk_size) + ' frames with no event ... Refreshing & Saving'
if nbubble_change:
event_str = ' | Event ! One (or several) bubbles have appeared or disappeared ... Refreshing & Saving'
any_change = xy_change or r_change or nbubble_change or chunk_timeout
return any_change, event_str
########################## MAIN SEQUENCE #####################################
camera.Open()
if not camera.IsGrabbing():
camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
try:
while True:
data_file = open(folder_location + '\\data.csv', 'a', encoding='utf-8')
log_file = open(folder_location + '\\log.txt', 'a', encoding='utf-8')
grab = camera.RetrieveResult(5000, pylon.TimeoutHandling_ThrowException) # I don't really mind if image comes late, I just want to know when it arrives
if grab.GrabSucceeded(): # We could fail for any other reason
idx += 1
now_imgdata, now_linedata = analyse_frame(grab.Array, myinfo, grab.TimeStamp)
data_array = np.append(data_array, format_data(now_imgdata, myinfo), axis=0)
grab.Release()
is_event, event_str = bubble_event(now_imgdata, ref_imgdata)
log_str = format_logstr(now_imgdata)
print(log_str + event_str)
if is_event:
np.savetxt(data_file, data_array, fmt=myfmt, delimiter=',')
data_file.flush()
save_snapshot(folder_location, now_imgdata['img'], pix_fmt="Mono12", idx=idx)
data_array = np.zeros((0,8))
ref_imgdata = now_imgdata
CDS_img.data = now_imgdata
CDS_line.data = now_linedata
log_file.write(log_str + event_str + '\n')
# Clear display from time to time
if np.mod(idx,10) == 0:
clear_output()
time.sleep(1)
################################################################################################
## HANDLING ERRORS SECTION HERE ... #############################################################
#################################################################################################
except pylon.TimeoutException:
timeout_str = ' /!\\ Timeout ... ! '
log_file.write(log_str + timeout_str + '\n')
print(timeout_str)
pass
except SystemError as e:
## I KNOW IT IS SUPER UGLY, HATE ME ALL YOU WANT
if "KeyboardInterrupt" in traceback.format_exc():
interrupt_str = ' /!\\ Keyboard Interrupted ... ! '
log_file.write(log_str + interrupt_str + '\n')
print(interrupt_str)
grab.Release()
camera.StopGrabbing()
camera.Close()
data_file.close()
log_file.close()
else:
err_str = 'N°' + str(idx) + e
log_file.write(err_str)
print(err_str)
pass
except KeyboardInterrupt:
interrupt_str = ' /!\\ Keyboard Interrupted ... ! '
log_file.write(log_str + interrupt_str + '\n')
print(interrupt_str)
grab.Release()
camera.StopGrabbing()
camera.Close()
data_file.close()
log_file.close()
import skimage.filters as skfi
from skimage.data import astronaut
from bokeh.plotting import figure, show, row
from bokeh.models import LinearColorMapper
from bokeh.palettes import Greys256
import numpy as np
ast = astronaut()[:,:,0]/255
height, width = np.shape(ast)
astf = skfi.gaussian(ast, sigma=1)
cmapper = LinearColorMapper(palette=Greys256, low=0, high=1)
f1 = figure(width=300, height=300, match_aspect=True)
f2 = figure(width=300, height=300, match_aspect=True)
f1.image([ast], x=0, y=0, dw=height, dh=width, color_mapper=cmapper)
f2.image([astf], x=0, y=0, dw=height, dh=width, color_mapper=cmapper)
show(row(f1,f2))
ast | _____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, state `36` is the initial state. State `47` is the only terminal state, and the cliff corresponds to states `37` through `46`.The agent has 4 potential actions:```UP = 0RIGHT = 1DOWN = 2LEFT = 3```Thus, $\mathcal{S}^+=\{0, 1, \ldots, 47\}$, and $\mathcal{A} =\{0, 1, 2, 3\}$. Verify this by running the code cell below. | 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 cliff "states" as these are not true states from which the agent can make decisions. For the cliff "states", the state-value function is not well-defined._ | # 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' as a "
/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' as a "
/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' as a "
/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' as 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`: This is the step-size parameter for the update step.- `gamma`: This is the discount rate. It must be a value between 0 and 1, inclusive (default value: `1`).The algorithm returns as output:- `Q`: This is a dictionary (of one-dimensional arrays) where `Q[s][a]` is the estimated action value corresponding to state `s` and action `a`.Please complete the function in the code cell below.(_Feel free to define additional functions to help you to organize your code._) | 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 new_value
def epsilon_greedy(Q, state, nA, eps):
if random.random() > eps:
return np.argmax(Q[state])
else:
return random.choice(np.arange(env.action_space.n))
def sarsa(env, num_episodes, alpha, gamma=1.0, plot_every=100):
nA = env.action_space.n
Q = defaultdict(lambda: np.zeros(env.nA))
# initialize performance monitor
tmp_scores = deque(maxlen=plot_every) # deque for keeping track of scores
avg_scores = deque(maxlen=num_episodes) # average scores over every plot_every episodes
# loop over episodes
for i_episode in range(1, num_episodes+1):
# monitor progress
if i_episode % 100 == 0:
print("\rEpisode {}/{}".format(i_episode, num_episodes), end="")
sys.stdout.flush()
## TODO: complete the function
score = 0
state = env.reset()
eps = 1.0 / i_episode
action = epsilon_greedy(Q, state, nA, eps)
while True:
next_state, reward, done, info = env.step(action)
score += reward
if not done:
next_action = epsilon_greedy(Q, next_state, nA, eps)
Q[state][action] = update_Q_sarsa(alpha, gamma, Q, \
state, action, reward, next_state, next_action)
state = next_state
action = next_action
if done:
Q[state][action] = update_Q_sarsa(alpha, gamma, Q, \
state, action, reward)
tmp_scores.append(score)
break
if (i_episode % plot_every == 0):
avg_scores.append(np.mean(tmp_scores))
plt.plot(np.linspace(0,num_episodes,len(avg_scores),endpoint=False), np.asarray(avg_scores))
plt.xlabel('Episode Number')
plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)
plt.show()
# print best 100-episode performance
print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores))
return Q | _____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 like to ensure the accuracy of the unit test, please do not change the value of `gamma` from the default. | # 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)
print("\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):")
print(policy_sarsa)
# plot the estimated optimal state-value function
V_sarsa = ([np.max(Q_sarsa[key]) if key in Q_sarsa else 0 for key in np.arange(48)])
plot_values(V_sarsa) | 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.- `alpha`: This is the step-size parameter for the update step.- `gamma`: This is the discount rate. It must be a value between 0 and 1, inclusive (default value: `1`).The algorithm returns as output:- `Q`: This is a dictionary (of one-dimensional arrays) where `Q[s][a]` is the estimated action value corresponding to state `s` and action `a`.Please complete the function in the code cell below.(_Feel free to define additional functions to help you to organize your code._) | 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(env, num_episodes, alpha, gamma=1.0, plot_every=100):
nA = env.action_space.n
Q = defaultdict(lambda: np.zeros(env.nA))
# initialize performance monitor
tmp_scores = deque(maxlen=plot_every)
avg_scores = deque(maxlen=num_episodes)
# loop over episodes
for i_episode in range(1, num_episodes+1):
# monitor progress
if i_episode % 100 == 0:
print("\rEpisode {}/{}".format(i_episode, num_episodes), end="")
sys.stdout.flush()
## TODO: complete the function
score = 0
state = env.reset()
eps = 1.0 / i_episode
action = epsilon_greedy(Q, state, nA, eps)
while True:
next_state, reward, done, info = env.step(action)
score += reward
if not done:
next_action = epsilon_greedy(Q, next_state, nA, eps)
Q[state][action] = update_Q_learning(alpha, gamma, Q, \
state, action, reward, next_state)
state = next_state
if done:
tmp_scores.append(score)
break
if (i_episode % plot_every == 0):
avg_scores.append(np.mean(tmp_scores))
plt.plot(np.linspace(0,num_episodes,len(avg_scores),endpoint=False), np.asarray(avg_scores))
plt.xlabel('Episode Number')
plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)
plt.show()
# print best 100-episode performance
print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores))
return Q | _____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 like to ensure the accuracy of the unit test, please do not change the value of `gamma` from the default. | # 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_check', policy_sarsamax)
print("\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):")
print(policy_sarsamax)
# plot the estimated optimal state-value function
plot_values([np.max(Q_sarsamax[key]) if key in Q_sarsamax else 0 for key in np.arange(48)]) | 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 interaction.- `alpha`: This is the step-size parameter for the update step.- `gamma`: This is the discount rate. It must be a value between 0 and 1, inclusive (default value: `1`).The algorithm returns as output:- `Q`: This is a dictionary (of one-dimensional arrays) where `Q[s][a]` is the estimated action value corresponding to state `s` and action `a`.Please complete the function in the code cell below.(_Feel free to define additional functions to help you to organize your code._) | 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 * Qsa_next)
new_value = current + (alpha * (target - current))
return new_value
def expected_sarsa(env, num_episodes, alpha, gamma=1.0, plot_every=100):
nA = env.action_space.n
Q = defaultdict(lambda: np.zeros(env.nA))
# initialize performance monitor
tmp_scores = deque(maxlen=plot_every)
avg_scores = deque(maxlen=num_episodes)
# loop over episodes
for i_episode in range(1, num_episodes+1):
# monitor progress
if i_episode % 100 == 0:
print("\rEpisode {}/{}".format(i_episode, num_episodes), end="")
sys.stdout.flush()
## TODO: complete the function
score = 0
state = env.reset()
eps = 0.005
while True:
action = epsilon_greedy(Q, state, nA, eps)
next_state, reward, done, info = env.step(action)
score += reward
Q[state][action] = update_Q_expected_sarsa(alpha, gamma, nA, eps, Q, \
state, action, reward, next_state)
state = next_state
if done:
tmp_scores.append(score)
break
if (i_episode % plot_every == 0):
avg_scores.append(np.mean(tmp_scores))
plt.plot(np.linspace(0,num_episodes,len(avg_scores),endpoint=False), np.asarray(avg_scores))
plt.xlabel('Episode Number')
plt.ylabel('Average Reward (Over Next %d Episodes)' % plot_every)
plt.show()
# print best 100-episode performance
print(('Best Average Reward over %d Episodes: ' % plot_every), np.max(avg_scores))
return Q | _____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 like to ensure the accuracy of the unit test, please do not change the value of `gamma` from the default. | # 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_check', policy_expsarsa)
print("\nEstimated Optimal Policy (UP = 0, RIGHT = 1, DOWN = 2, LEFT = 3, N/A = -1):")
print(policy_expsarsa)
# plot the estimated optimal state-value function
plot_values([np.max(Q_expsarsa[key]) if key in Q_expsarsa else 0 for key in np.arange(48)]) | 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
# определим количество столбцов
column_num = len(matrix[0])
# проверяем целостность всех строк
for row in matrix:
if type(row) is not list:
return False
if len(row) != column_num:
return False
# Проверка, что все элементы матрицы - числа
for element in row:
if type(element) is not int and type(element) is not float:
return False
return True
def AddVectors(vector_a, vector_b):
if len(vector_a) != len(vector_b):
return "Vector lengths aren't equal!"
sum_vector = []
for i in range(len(vector_a)):
sum_vector.append(vector_a[i] + vector_b[i])
return sum_vector
def MultiplyToScalar(vector, scalar):
res_vector = []
for elem in vector:
res_vector.append(scalar * elem)
return res_vector
def GetColumn(matrix, column):
result = []
for i in range(0, len(matrix)):
result += [matrix[i][column]]
return result
def TranspouseMatrix(matrix):
if not CheckMatrixCompletness(matrix):
return "Matrix is incorrect"
result = []
for i in range(len(matrix[0])):
result += [[]]
for j in range(len(matrix)):
result[i] += [matrix[j][i]]
return result
'''
[1 2] [1 2 3] = [9 12 15]
[3 4] [4 5 6] = [19 26 33]
1 * [1 3]' + 4 * [2 4]' = [1 3]' + [8 16]' = [9 19]'
2 * [1 3]' + 5 * [2 4]' = [2 6]' + [10 20]' = [12 26]'
3 * [1 3]' + 6 * [2 4]' = [3 9]' + [12 24]' = [15 33]'
'''
def MatrixMultiplation(matrix_a, matrix_b):
# Проверка соответствия на размеров матриц на произведение
matrix_a_shape = CalculateMatrixShape(matrix_a)
matrix_b_shape = CalculateMatrixShape(matrix_b)
if type(matrix_a_shape) is str:
return "Matrix_a is incorrect"
if type(matrix_b_shape) is str:
return "Matrix_b is incorrect"
if matrix_a_shape[1] != matrix_b_shape[0]:
return "Matrices shapes are not insufficient."
# --------------------------------------------------------
#return "Ok"
result = []
for matrix_b_column_id in range(0, len(matrix_b[0])):
#print(GetColumn(matrix_b, matrix_b_column_id))
matrix_b_column = GetColumn(matrix_b, matrix_b_column_id)
vec_res = [0] * len(matrix_a)
for matrix_a_column_id in range(0, len(matrix_a[0])):
vec = MultiplyToScalar(GetColumn(matrix_a, matrix_a_column_id), matrix_b_column[matrix_a_column_id])
vec_res = AddVectors(vec_res, vec)
#print("--", GetColumn(matrix_a, matrix_a_column_id), "--", matrix_b_column[matrix_a_column_id], "--", vec)
#print ("!!!", vec_res)
result += [vec_res]
return TranspouseMatrix(result)
# Вычисление размеров матрицы
def CalculateMatrixShape(matrix):
if not CheckMatrixCompletness(matrix):
return "Matrix is incorrect"
# Количетсво строк
row_num = len(matrix)
# Количетсво столбцов
col_num = len(matrix[0])
return (row_num, col_num)
def MatrixMultiplyToScalar(matrix_a, scalar):
# Проверка
matrix_a_shape = CalculateMatrixShape(matrix_a)
if type(matrix_a_shape) is str:
return "Matrix_a is incorrect"
# --------------------------------------------------------
matrix_a = [] + matrix_a
for i in range(matrix_a_shape[0]):
for j in range(matrix_a_shape[1]):
matrix_a[i][j] *= scalar
return matrix_a
from copy import deepcopy
def det(arr):
size_arr = len(arr)
if size_arr == 1: return arr[0][0]
result = 0
for index_x in range(size_arr):
arr_deepcopy = deepcopy(arr)
del (arr_deepcopy[0])
for i in range(len(arr_deepcopy)):
del (arr_deepcopy[i][index_x])
result += arr[0][index_x] * (-1 if index_x & 1 else 1 ) * det(arr_deepcopy)
return result
from copy import deepcopy
#Дополнительный Минор
def AdditionalMinor(matrix, row, col):
if not CheckMatrixCompletness(matrix):
return "Matrix is incorrect"
row_num, _ = CalculateMatrixShape(matrix)
matrix = deepcopy(matrix)
del (matrix[row])
for i in range(row_num - 1):
del (matrix[i][col])
return det(matrix)
#Алгебраическое дополнение
def AlgebraiComplement(matrix, row, col):
if not CheckMatrixCompletness(matrix):
return "Matrix is incorrect"
return (-1)**(row + col) * AdditionalMinor(matrix, row, col)
def MatrixInverse(matrix):
if not CheckMatrixCompletness(matrix):
return "Matrix is incorrect"
matrixDet = det(matrix)
if matrixDet == 0:
return "Det = 0"
row_num, col_num = CalculateMatrixShape(matrix)
result = []
for i in range(row_num):
result += [[]]
for j in range(col_num):
result[i] += [AlgebraiComplement(matrix, j, i)]
return MatrixMultiplyToScalar(result, 1 / matrixDet)
a = [[-1, 2, -2],
[2, -1, 5],
[3, -2, 4]]
print (MatrixInverse(a)) | [[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 notebook, you'll be using [VGGNet](https://arxiv.org/pdf/1409.1556.pdf) trained on the [ImageNet dataset](http://www.image-net.org/) as a feature extractor. Below is a diagram of the VGGNet architecture.VGGNet is great because it's simple and has great performance, coming in second in the ImageNet competition. The idea here is that we keep all the convolutional layers, but replace the final fully connected layers with our own classifier. This way we can use VGGNet as a feature extractor for our images then easily train a simple classifier on top of that. What we'll do is take the first fully connected layer with 4096 units, including thresholding with ReLUs. We can use those values as a code for each image, then build a classifier on top of those codes.You can read more about transfer learning from [the CS231n course notes](http://cs231n.github.io/transfer-learning/tf). Pretrained VGGNetWe'll be using a pretrained network from https://github.com/machrisaa/tensorflow-vgg. This code is already included in 'tensorflow_vgg' directory, sdo you don't have to clone it.This is a really nice implementation of VGGNet, quite easy to work with. The network has already been trained and the parameters are available from this link. **You'll need to clone the repo into the folder containing this notebook.** Then download the parameter file using the next cell. | 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_size=None):
self.total = total_size
self.update((block_num - self.last_block) * block_size)
self.last_block = block_num
if not isfile(vgg_dir + "vgg16.npy"):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc='VGG16 Parameters') as pbar:
urlretrieve(
'https://s3.amazonaws.com/content.udacity-data.com/nd101/vgg16.npy',
vgg_dir + 'vgg16.npy',
pbar.hook)
else:
print("Parameter file already exists!") | 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_photos.tar.gz'):
with DLProgress(unit='B', unit_scale=True, miniters=1, desc='Flowers Dataset') as pbar:
urlretrieve(
'http://download.tensorflow.org/example_images/flower_photos.tgz',
'flower_photos.tar.gz',
pbar.hook)
if not isdir(dataset_folder_path):
with tarfile.open('flower_photos.tar.gz') as tar:
tar.extractall()
tar.close() | 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 using the `vgg16` module from `tensorflow_vgg`. The network takes images of size $224 \times 224 \times 3$ as input. Then it has 5 sets of convolutional layers. The network implemented here has this structure (copied from [the source code](https://github.com/machrisaa/tensorflow-vgg/blob/master/vgg16.py)):```self.conv1_1 = self.conv_layer(bgr, "conv1_1")self.conv1_2 = self.conv_layer(self.conv1_1, "conv1_2")self.pool1 = self.max_pool(self.conv1_2, 'pool1')self.conv2_1 = self.conv_layer(self.pool1, "conv2_1")self.conv2_2 = self.conv_layer(self.conv2_1, "conv2_2")self.pool2 = self.max_pool(self.conv2_2, 'pool2')self.conv3_1 = self.conv_layer(self.pool2, "conv3_1")self.conv3_2 = self.conv_layer(self.conv3_1, "conv3_2")self.conv3_3 = self.conv_layer(self.conv3_2, "conv3_3")self.pool3 = self.max_pool(self.conv3_3, 'pool3')self.conv4_1 = self.conv_layer(self.pool3, "conv4_1")self.conv4_2 = self.conv_layer(self.conv4_1, "conv4_2")self.conv4_3 = self.conv_layer(self.conv4_2, "conv4_3")self.pool4 = self.max_pool(self.conv4_3, 'pool4')self.conv5_1 = self.conv_layer(self.pool4, "conv5_1")self.conv5_2 = self.conv_layer(self.conv5_1, "conv5_2")self.conv5_3 = self.conv_layer(self.conv5_2, "conv5_3")self.pool5 = self.max_pool(self.conv5_3, 'pool5')self.fc6 = self.fc_layer(self.pool5, "fc6")self.relu6 = tf.nn.relu(self.fc6)```So what we want are the values of the first fully connected layer, after being ReLUd (`self.relu6`). To build the network, we use```with tf.Session() as sess: vgg = vgg16.Vgg16() input_ = tf.placeholder(tf.float32, [None, 224, 224, 3]) with tf.name_scope("content_vgg"): vgg.build(input_)```This creates the `vgg` object, then builds the graph with `vgg.build(input_)`. Then to get the values from the layer,```feed_dict = {input_: images}codes = sess.run(vgg.relu6, feed_dict=feed_dict)``` | 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("content_vgg"):
vgg.build(input_)
for each in classes:
print("Starting {} images".format(each))
class_path = data_dir + each
files = os.listdir(class_path)
for ii, file in enumerate(files, 1):
# Add images to the current batch
# utils.load_image crops the input images for us, from the center
img = utils.load_image(os.path.join(class_path, file))
batch.append(img.reshape((1, 224, 224, 3)))
labels.append(each)
# Running the batch through the network to get the codes
if ii % batch_size == 0 or ii == len(files):
# Image batch to pass to VGG network
images = np.concatenate(batch)
# TODO: Get the values from the relu6 layer of the VGG network
codes_batch = sess.run(vgg.relu6, feed_dict={input_: images})
# Here I'm building an array of the codes
if codes is None:
codes = codes_batch
else:
codes = np.concatenate((codes, codes_batch))
# Reset to start building the next batch
batch = []
print('{} images processed'.format(ii))
# write codes to file
with open('codes', 'w') as f:
codes.tofile(f)
# write labels to file
import csv
with open('labels', 'w') as f:
writer = csv.writer(f, delimiter='\n')
writer.writerow(labels) | _____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 labels. | 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. Typically, you'll also want to make sure that each smaller set has the same the distribution of classes as it is for the whole data set. The easiest way to accomplish both these goals is to use [`StratifiedShuffleSplit`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html) from scikit-learn.You can create the splitter like so:```ss = StratifiedShuffleSplit(n_splits=1, test_size=0.2)```Then split the data with ```splitter = ss.split(x, y)````ss.split` returns a generator of indices. You can pass the indices into the arrays to get the split sets. The fact that it's a generator means you either need to iterate over it, or use `next(splitter)` to get the indices. Be sure to read the [documentation](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.StratifiedShuffleSplit.html) and the [user guide](http://scikit-learn.org/stable/modules/cross_validation.htmlrandom-permutations-cross-validation-a-k-a-shuffle-split).> **Exercise:** Use StratifiedShuffleSplit to split the codes and labels into training, validation, and test sets. | 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]
val_x, val_y = codes[val_split], labels_vecs[val_split]
test_x, test_y = codes[test_split], labels_vecs[test_split]
print("Train shapes (x, y):", train_x.shape, train_y.shape)
print("Validation shapes (x, y):", val_x.shape, val_y.shape)
print("Test shapes (x, y):", test_x.shape, test_y.shape) | 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 connected layers. You use the codes as the inputs and the image labels as targets. Otherwise the classifier is a typical neural network.> **Exercise:** With the codes and labels loaded, build the classifier. Consider the codes as your inputs, each of them are 4096D vectors. You'll want to use a hidden layer and an output layer as your classifier. Remember that the output layer needs to have one unit for each class and a softmax activation function. Use the cross entropy to calculate the cost. | 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_connected(fc2, labels_vecs.shape[1], activation_fn=None)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=labels_, logits=logits)
cost = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer().minimize(cost)
# Operations for validation/test accuracy
predicted = tf.nn.softmax(logits)
correct_pred = tf.equal(tf.argmax(predicted, 1), tf.argmax(labels_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) | _____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_size:
X, Y = x[ii: ii+batch_size], y[ii: ii+batch_size]
# On the last batch, grab the rest of the data
else:
X, Y = x[ii:], y[ii:]
# I love generators
yield X, Y | _____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 before to get your batches like `for x, y in get_batches(train_x, train_y)`. Or write your own! | 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)
print('Epoch: {}/{}'.format(e+1, epochs),
'Iterations: {}'.format(iteration),
"Loss: {}".format(loss))
iteration+=1
if iteration%5 == 0:
feed = {inputs_: val_x, labels_: val_y}
loss, _ = sess.run([cost, optimizer], feed)
print('Epoch: {}/{}'.format(e+1, epochs),
'Iterations: {}'.format(iteration),
"Val loss: {}".format(loss))
saver.save(sess, "checkpoints/flowers.ckpt") | 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 Iterations: 5 Loss: 3.189404249191284
Epoch: 1/10 Iterations: 6 Loss: 2.639348268508911
Epoch: 1/10 Iterations: 7 Loss: 2.9115426540374756
Epoch: 1/10 Iterations: 8 Loss: 2.798640251159668
Epoch: 1/10 Iterations: 9 Loss: 2.4628725051879883
Epoch: 1/10 Iterations: 10 Val loss: 1.82681405544281
Epoch: 2/10 Iterations: 10 Loss: 1.1171455383300781
Epoch: 2/10 Iterations: 11 Loss: 1.0355298519134521
Epoch: 2/10 Iterations: 12 Loss: 0.47368577122688293
Epoch: 2/10 Iterations: 13 Loss: 0.5847135782241821
Epoch: 2/10 Iterations: 14 Loss: 0.8828096389770508
Epoch: 2/10 Iterations: 15 Val loss: 0.8436155319213867
Epoch: 2/10 Iterations: 15 Loss: 0.6585701704025269
Epoch: 2/10 Iterations: 16 Loss: 0.556399941444397
Epoch: 2/10 Iterations: 17 Loss: 0.487338125705719
Epoch: 2/10 Iterations: 18 Loss: 0.4912504553794861
Epoch: 2/10 Iterations: 19 Loss: 0.4451310634613037
Epoch: 2/10 Iterations: 20 Val loss: 0.4065427780151367
Epoch: 3/10 Iterations: 20 Loss: 0.34170132875442505
Epoch: 3/10 Iterations: 21 Loss: 0.4052823781967163
Epoch: 3/10 Iterations: 22 Loss: 0.2879161238670349
Epoch: 3/10 Iterations: 23 Loss: 0.3895888924598694
Epoch: 3/10 Iterations: 24 Loss: 0.3391869366168976
Epoch: 3/10 Iterations: 25 Val loss: 0.2961403727531433
Epoch: 3/10 Iterations: 25 Loss: 0.30506736040115356
Epoch: 3/10 Iterations: 26 Loss: 0.25008511543273926
Epoch: 3/10 Iterations: 27 Loss: 0.22011327743530273
Epoch: 3/10 Iterations: 28 Loss: 0.24098922312259674
Epoch: 3/10 Iterations: 29 Loss: 0.26284387707710266
Epoch: 3/10 Iterations: 30 Val loss: 0.22571401298046112
Epoch: 4/10 Iterations: 30 Loss: 0.21583987772464752
Epoch: 4/10 Iterations: 31 Loss: 0.22172130644321442
Epoch: 4/10 Iterations: 32 Loss: 0.161707803606987
Epoch: 4/10 Iterations: 33 Loss: 0.1930975317955017
Epoch: 4/10 Iterations: 34 Loss: 0.17036172747612
Epoch: 4/10 Iterations: 35 Val loss: 0.16700726747512817
Epoch: 4/10 Iterations: 35 Loss: 0.17953141033649445
Epoch: 4/10 Iterations: 36 Loss: 0.1555631011724472
Epoch: 4/10 Iterations: 37 Loss: 0.12652190029621124
Epoch: 4/10 Iterations: 38 Loss: 0.12226159125566483
Epoch: 4/10 Iterations: 39 Loss: 0.16163228452205658
Epoch: 4/10 Iterations: 40 Val loss: 0.11334959417581558
Epoch: 5/10 Iterations: 40 Loss: 0.11021738499403
Epoch: 5/10 Iterations: 41 Loss: 0.12303079664707184
Epoch: 5/10 Iterations: 42 Loss: 0.08418866246938705
Epoch: 5/10 Iterations: 43 Loss: 0.11311700195074081
Epoch: 5/10 Iterations: 44 Loss: 0.08980914205312729
Epoch: 5/10 Iterations: 45 Val loss: 0.07618114352226257
Epoch: 5/10 Iterations: 45 Loss: 0.09904886037111282
Epoch: 5/10 Iterations: 46 Loss: 0.0816163569688797
Epoch: 5/10 Iterations: 47 Loss: 0.06527123600244522
Epoch: 5/10 Iterations: 48 Loss: 0.07217283546924591
Epoch: 5/10 Iterations: 49 Loss: 0.0818411335349083
Epoch: 5/10 Iterations: 50 Val loss: 0.050673067569732666
Epoch: 6/10 Iterations: 50 Loss: 0.055724550038576126
Epoch: 6/10 Iterations: 51 Loss: 0.056342266499996185
Epoch: 6/10 Iterations: 52 Loss: 0.04057794064283371
Epoch: 6/10 Iterations: 53 Loss: 0.07455720007419586
Epoch: 6/10 Iterations: 54 Loss: 0.05536913871765137
Epoch: 6/10 Iterations: 55 Val loss: 0.032396264374256134
Epoch: 6/10 Iterations: 55 Loss: 0.05769611522555351
Epoch: 6/10 Iterations: 56 Loss: 0.04174236208200455
Epoch: 6/10 Iterations: 57 Loss: 0.03454503044486046
Epoch: 6/10 Iterations: 58 Loss: 0.03190534561872482
Epoch: 6/10 Iterations: 59 Loss: 0.039301518350839615
Epoch: 6/10 Iterations: 60 Val loss: 0.027403196319937706
Epoch: 7/10 Iterations: 60 Loss: 0.03119419328868389
Epoch: 7/10 Iterations: 61 Loss: 0.03252197429537773
Epoch: 7/10 Iterations: 62 Loss: 0.02040104568004608
Epoch: 7/10 Iterations: 63 Loss: 0.02649182826280594
Epoch: 7/10 Iterations: 64 Loss: 0.02423202432692051
Epoch: 7/10 Iterations: 65 Val loss: 0.01874398998916149
Epoch: 7/10 Iterations: 65 Loss: 0.04282507300376892
Epoch: 7/10 Iterations: 66 Loss: 0.035250939428806305
Epoch: 7/10 Iterations: 67 Loss: 0.020883135497570038
Epoch: 7/10 Iterations: 68 Loss: 0.01988316886126995
Epoch: 7/10 Iterations: 69 Loss: 0.01939186453819275
Epoch: 7/10 Iterations: 70 Val loss: 0.013688798993825912
Epoch: 8/10 Iterations: 70 Loss: 0.02058236673474312
Epoch: 8/10 Iterations: 71 Loss: 0.025333741679787636
Epoch: 8/10 Iterations: 72 Loss: 0.02040153741836548
Epoch: 8/10 Iterations: 73 Loss: 0.03184022754430771
Epoch: 8/10 Iterations: 74 Loss: 0.012570078484714031
Epoch: 8/10 Iterations: 75 Val loss: 0.006841983646154404
Epoch: 8/10 Iterations: 75 Loss: 0.015580104663968086
Epoch: 8/10 Iterations: 76 Loss: 0.014343924820423126
Epoch: 8/10 Iterations: 77 Loss: 0.018154548481106758
Epoch: 8/10 Iterations: 78 Loss: 0.025013182312250137
Epoch: 8/10 Iterations: 79 Loss: 0.028149407356977463
Epoch: 8/10 Iterations: 80 Val loss: 0.006597414147108793
Epoch: 9/10 Iterations: 80 Loss: 0.00860650185495615
Epoch: 9/10 Iterations: 81 Loss: 0.00733830314129591
Epoch: 9/10 Iterations: 82 Loss: 0.00633214833214879
Epoch: 9/10 Iterations: 83 Loss: 0.014129566960036755
Epoch: 9/10 Iterations: 84 Loss: 0.008173373527824879
Epoch: 9/10 Iterations: 85 Val loss: 0.007537458091974258
Epoch: 9/10 Iterations: 85 Loss: 0.01679036393761635
Epoch: 9/10 Iterations: 86 Loss: 0.00960800051689148
Epoch: 9/10 Iterations: 87 Loss: 0.005559608340263367
Epoch: 9/10 Iterations: 88 Loss: 0.005612092092633247
Epoch: 9/10 Iterations: 89 Loss: 0.010039210319519043
Epoch: 9/10 Iterations: 90 Val loss: 0.002736186608672142
Epoch: 10/10 Iterations: 90 Loss: 0.005322793032974005
Epoch: 10/10 Iterations: 91 Loss: 0.0052515072748064995
Epoch: 10/10 Iterations: 92 Loss: 0.013230983167886734
Epoch: 10/10 Iterations: 93 Loss: 0.01197117194533348
Epoch: 10/10 Iterations: 94 Loss: 0.0041971355676651
Epoch: 10/10 Iterations: 95 Val loss: 0.0022358843125402927
Epoch: 10/10 Iterations: 95 Loss: 0.004806811455637217
Epoch: 10/10 Iterations: 96 Loss: 0.0033794238697737455
Epoch: 10/10 Iterations: 97 Loss: 0.0032531919423490763
Epoch: 10/10 Iterations: 98 Loss: 0.0034035572316497564
Epoch: 10/10 Iterations: 99 Loss: 0.009972398169338703
Epoch: 10/10 Iterations: 100 Val loss: 0.0017780129564926028
| 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 scipy.ndimage import imread | _____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:
input_ = tf.placeholder(tf.float32, [None, 224, 224, 3])
vgg = vgg16.Vgg16()
vgg.build(input_)
with tf.Session() as sess:
img = utils.load_image(test_img_path)
img = img.reshape((1, 224, 224, 3))
feed_dict = {input_: img}
code = sess.run(vgg.relu6, feed_dict=feed_dict)
saver = tf.train.Saver()
with tf.Session() as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
feed = {inputs_: code}
prediction = sess.run(predicted, feed_dict=feed).squeeze()
plt.imshow(test_img)
plt.barh(np.arange(5), prediction)
_ = plt.yticks(np.arange(5), lb.classes_) | _____no_output_____ | MIT | transfer-learning/Transfer_Learning.ipynb | sergio-lira/deep-learning101 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.