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 |
|---|---|---|---|---|---|
Linguistic Features Part-of-speech tagging After tokenization, spaCy can parse and tag a given Doc. This is where the statistical model comes in, which enables spaCy to make a prediction of which tag or label most likely applies in this context. A model consists of binary data and is produced by showing a system enou... | nlp = spacy.load('en_core_web_sm')
doc = nlp(u'Apple is looking at buying U.K. startup for $1 billion')
for token in doc:
print(token.text, token.lemma_, token.pos_, token.tag_, token.dep_,
token.shape_, token.is_alpha, token.is_stop) | Apple apple PROPN NNP nsubj Xxxxx True False
is be VERB VBZ aux xx True True
looking look VERB VBG ROOT xxxx True False
at at ADP IN prep xx True True
buying buy VERB VBG pcomp xxxx True False
U.K. u.k. PROPN NNP compound X.X. False False
startup startup NOUN NN dobj xxxx True False
for for ADP IN prep xxx True True
$ ... | MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Dependency parsing Noun chunksNoun chunks are "base noun phrases" – flat phrases that have a noun as their head. You can think of noun chunks as a noun plus the words describing the noun – for example, "the lavish green grass" or "the world’s largest tech fund". To get the noun chunks in a document, simply iterate ov... | nlp = spacy.load('en_core_web_sm')
doc = nlp(u"Autonomous cars shift insurance liability toward manufacturers")
for chunk in doc.noun_chunks:
print(chunk.text, chunk.root.text, chunk.root.dep_,
chunk.root.head.text) | Autonomous cars cars nsubj shift
insurance liability liability dobj shift
manufacturers manufacturers pobj toward
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Navigating the parse treespaCy uses the terms head and child to describe the words connected by a single arc in the dependency tree. The term dep is used for the arc label, which describes the type of syntactic relation that connects the child to the head. As with other attributes, the value of .dep is a hash value. Y... | nlp = spacy.load('en_core_web_sm')
doc = nlp(u"Autonomous cars shift insurance liability toward manufacturers")
for token in doc:
print(token.text, token.dep_, token.head.text, token.head.pos_,
[child for child in token.children]) | Autonomous amod cars NOUN []
cars nsubj shift VERB [Autonomous]
shift ROOT shift VERB [cars, liability, toward]
insurance compound liability NOUN []
liability dobj shift VERB [insurance]
toward prep shift VERB [manufacturers]
manufacturers pobj toward ADP []
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Because the syntactic relations form a tree, every word has exactly one head. You can therefore iterate over the arcs in the tree by iterating over the words in the sentence. This is usually the best way to match an arc of interest — from below: | from spacy.symbols import nsubj, VERB
nlp = spacy.load('en_core_web_sm')
doc = nlp(u"Autonomous cars shift insurance liability toward manufacturers")
# Finding a verb with a subject from below — good
verbs = set()
for possible_subject in doc:
if possible_subject.dep == nsubj and possible_subject.head.pos == VERB... | {shift}
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
If you try to match from above, you'll have to iterate twice: once for the head, and then again through the children: | # Finding a verb with a subject from above — less good
verbs = []
for possible_verb in doc:
if possible_verb.pos == VERB:
for possible_subject in possible_verb.children:
if possible_subject.dep == nsubj:
verbs.append(possible_verb)
break
verbs | _____no_output_____ | MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Iterating around the local treeA few more convenience attributes are provided for iterating around the local tree from the token. The Token.lefts and Token.rights attributes provide sequences of syntactic children that occur before and after the token. Both sequences are in sentence order. There are also two integer-t... | nlp = spacy.load('en_core_web_sm')
doc = nlp(u"bright red apples on the tree")
print([token.text for token in doc[2].lefts]) # ['bright', 'red']
print([token.text for token in doc[2].rights]) # ['on']
print(doc[2].n_lefts) # 2
print(doc[2].n_rights) # 1
nlp = spacy.load('en_core_web_sm')
doc = nlp(u"Credit and mor... | Credit nmod 0 2 ['holders', 'submit']
and cc 0 0 ['Credit', 'holders', 'submit']
mortgage compound 0 0 ['account', 'Credit', 'holders', 'submit']
account conj 1 0 ['Credit', 'holders', 'submit']
holders nsubj 1 0 ['submit']
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
You can get a whole phrase by its syntactic head using the Token.subtree attribute. This returns an ordered sequence of tokens. You can walk up the tree with the Token.ancestors attribute, and check dominance with Token.is_ancestor() . | nlp = spacy.load('en_core_web_sm')
doc = nlp(u"Credit and mortgage account holders must submit their requests")
root = [token for token in doc if token.head == token][0]
subject = list(root.lefts)[0]
for descendant in subject.subtree:
assert subject is descendant or subject.is_ancestor(descendant)
print(descen... | Credit nmod 0 2 ['holders', 'submit']
and cc 0 0 ['Credit', 'holders', 'submit']
mortgage compound 0 0 ['account', 'Credit', 'holders', 'submit']
account conj 1 0 ['Credit', 'holders', 'submit']
holders nsubj 1 0 ['submit']
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Finally, the .left_edge and .right_edge attributes can be especially useful, because they give you the first and last token of the subtree. This is the easiest way to create a Span object for a syntactic phrase. Note that .right_edge gives a token within the subtree — so if you use it as the end-point of a range, don't... | nlp = spacy.load('en_core_web_sm')
doc = nlp(u"Credit and mortgage account holders must submit their requests")
span = doc[doc[4].left_edge.i : doc[4].right_edge.i+1]
span.merge()
for token in doc:
print(token.text, token.pos_, token.dep_, token.head.text) | Credit and mortgage account holders NOUN nsubj submit
must VERB aux submit
submit VERB ROOT submit
their ADJ poss requests
requests NOUN dobj submit
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Visualizing dependenciesThe best way to understand spaCy's dependency parser is interactively. To make this easier, spaCy v2.0+ comes with a visualization module. You can pass a Doc or a list of Doc objects to displaCy and run displacy.serve to run the web server, or displacy.render to generate the raw markup. If you ... | from spacy import displacy
nlp = spacy.load('en_core_web_sm')
doc = nlp(u"Autonomous cars shift insurance liability toward manufacturers")
displacy.render(doc, style='dep', jupyter=True) | _____no_output_____ | MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Disabling the parserIn the default models, the parser is loaded and enabled as part of the standard processing pipeline. If you don't need any of the syntactic information, you should disable the parser. Disabling the parser will make spaCy load and run much faster. If you want to load the parser, but need to disable ... | from spacy.lang.en import English
nlp = spacy.load('en', disable=['parser'])
#nlp = English().from_disk('/model', disable=['parser'])
doc = nlp(u"I don't want parsed", disable=['parser']) | _____no_output_____ | MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Named EntitiesspaCy features an extremely fast statistical entity recognition system, that assigns labels to contiguous spans of tokens. The default model identifies a variety of named and numeric entities, including companies, locations, organizations and products. You can add arbitrary classes to the entity recognit... | nlp = spacy.load('en_core_web_sm')
doc = nlp(u'Apple is looking at buying U.K. startup for $1 billion')
for ent in doc.ents:
print(ent.text, ent.start_char, ent.end_char, ent.label_) | Apple 0 5 ORG
U.K. 27 31 GPE
$1 billion 44 54 MONEY
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Accessing entity annotationsThe standard way to access entity annotations is the doc.ents property, which produces a sequence of Span objects. The entity type is accessible either as a hash value or as a string, using the attributes ent.label and ent.label_. The Span object acts as a sequence of tokens, so you can ite... | nlp = spacy.load('en_core_web_sm')
doc = nlp(u'San Francisco considers banning sidewalk delivery robots')
# document level
ents = [(e.text, e.start_char, e.end_char, e.label_) for e in doc.ents]
print(ents)
# token level
ent_san = [doc[0].text, doc[0].ent_iob_, doc[0].ent_type_]
ent_francisco = [doc[1].text, doc[1].e... | [('San Francisco', 0, 13, 'GPE')]
['San', 'B', 'GPE']
['Francisco', 'I', 'GPE']
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Setting entity annotationsTo ensure that the sequence of token annotations remains consistent, you have to set entity annotations at the document level. However, you can't write directly to the token.ent_iob or token.ent_type attributes, so the easiest way to set entities is to assign to the doc.ents attribute and cre... | from spacy.tokens import Span
nlp = spacy.load('en_core_web_sm')
doc = nlp(u"FB is hiring a new Vice President of global policy")
ents = [(e.text, e.start_char, e.end_char, e.label_) for e in doc.ents]
print('Before', ents)
# the model didn't recognise "FB" as an entity :(
ORG = doc.vocab.strings[u'ORG'] # get hash ... | Before []
After [('FB', 0, 2, 'ORG')]
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Setting entity annotations from arrayYou can also assign entity annotations using the doc.from_array() method. To do this, you should include both the `ENT_TYPE` and the ENT_IOB attributes in the array you're importing from. | import numpy
from spacy.attrs import ENT_IOB, ENT_TYPE
nlp = spacy.load('en_core_web_sm')
doc = nlp.make_doc(u'London is a big city in the United Kingdom.')
print('Before', list(doc.ents)) # []
header = [ENT_IOB, ENT_TYPE]
attr_array = numpy.zeros((len(doc), len(header)))
attr_array[0, 0] = 3 # B
attr_array[0, 1] ... | Before []
After [London]
| MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
Setting entity annotations in CythonFinally, you can always write to the underlying struct, if you compile a Cython function. This is easy to do, and allows you to write efficient native code.This code needs cython to work.```cython cython: infer_types=Truefrom spacy.tokens.doc cimport Doccpdef set_entity(Doc doc, int... | from spacy import displacy
text = """But Google is starting from behind. The company made a late push
into hardware, and Apple’s Siri, available on iPhones, and Amazon’s Alexa
software, which runs on its Echo and Dot devices, have clear leads in
consumer adoption."""
nlp = spacy.load('xx_ent_wiki_sm')
doc = nlp(text)... | _____no_output_____ | MIT | 3_DL_Libraries_Review/3_1_SpaCy/Exploring Spacy.ipynb | TheManohar/DLearn_Pro |
a = [1,2,3,4,5] #lista
b = (1,2,3,4,5) #tuplas
print(a)
print(b)
a[0] = 99
print(a)
b[0] = 99
print(b)
import numpy as np
import skimage #scikit-image
import matplotlib.pyplot as plt
im = skimage.data.astronaut()
im.shape
plt.imshow(im)
plt.title("Red")
plt.imshow(im[:,:,0], cmap='gray')
plt.colorbar()
plt.title("Green... | _____no_output_____ | MIT | Clase01.ipynb | dvsivle/sitio-web | |
Algorithmic Fairness, Accountability, and Ethics, Spring 2022 Exercise 5 Task 0 (Setup)We use the same dataset as in week 3 and 4. If you missed to install the module, please carry out the installation tasks at .After successful installation, you should be able to run the following code to generate a prediction task.... | from folktables.acs import adult_filter
from folktables import ACSDataSource
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
data_source = ACSDataSource(survey_year='2018', horizon='1-Year', survey='person')
acs_data = data_source.get_data(states=["CA"], download=True)
fea... | _____no_output_____ | MIT | Week 5/afae22-exercise-05.ipynb | carlomarxdk/algorithmic-fairness |
1 Short Answer (25pts)1. (5pts) True or False. (And explain your reason.)Mean-variance optimization goes long the highest Sharpe-Ratio assets and shorts the lowestSharpe-ratio assets.A. False: Not necessarily. MV optimization optimizes for the total portfolio return vs the portfolio variance. The optimiza... | import pandas as pd
import numpy as np
import statsmodels.api as sm
from statsmodels.regression.rolling import RollingOLS
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import seaborn as sns
# reading data
factor_data = pd.read_excel('/Users/rkb/Desktop/PortfolioT/data/proshares_anal... | _____no_output_____ | MIT | solutions/mid1/submissions/khandurbhanuprakashrahul_142394_6241866_PortfolioTheory_Mid Term.ipynb | tulyu96/finm-portfolio-2021 |
5. (5pts) Suppose that instead of optimizing these 5 risky assets, we optimized 5 commodity futures:oil, coffee, cocoa, lumber, cattle, and gold.Do you think the out-of-sample fragility problem would be better or worse than what we haveseen optimizing equities?No calculation is needed for this question–we just want a ... | hedge_data = pd.read_excel('/Users/rkb/Desktop/PortfolioT/data/proshares_analysis_data.xlsx', sheet_name = 'merrill_factors')
hedge_data.set_index('date',inplace=True)
hedge_data.head()
X = risky_data['SPY US Equity']
#X = hedge_data['EEM US Equity']
y = risky_data['EEM US Equity']
static_model_noint = sm.OLS(y,X).fit(... | _____no_output_____ | MIT | solutions/mid1/submissions/khandurbhanuprakashrahul_142394_6241866_PortfolioTheory_Mid Term.ipynb | tulyu96/finm-portfolio-2021 |
LSTM on PynqThis notebook covers how to use the FPGA-accelerated BiLSTM implementation on PYNQ to perform optical character recognition (OCR) on Fraktur text. 1. Instantiate the OCR modelInstantiating the OCR model will automatically download the appropria... | import lstm
hw_ocr = lstm.PynqFrakturOCR(lstm.RUNTIME_HW) | _____no_output_____ | BSD-3-Clause | notebooks/Fraktur_OCR.ipynb | tukl-msd/LSTM-PYNQ |
2. Load a line of textLoad a line of Fraktur text that has been extracted from the Fraktur text "Wanderungen durch die Mark Brandenburg" by Theodor Fontane. | from PIL import Image
im = Image.open('/home/xilinx/jupyter_notebooks/lstm/Fraktur_images/010006.raw.lnrm.png').convert('L')
im | _____no_output_____ | BSD-3-Clause | notebooks/Fraktur_OCR.ipynb | tukl-msd/LSTM-PYNQ |
3. Perform OCR in hardwarePerform the OCR task on the input image using the hardware-accelerated OCR engine. | import numpy as np
hw_result = hw_ocr.inference(np.array(im))
hw_mops_per_s, hw_ms_inference_time, hw_recognized_text = hw_result
print("HW OCRed text: {}".format(hw_recognized_text))
print("HW MOps/s: {}".format(hw_mops_per_s))
print("HW inference time [ms]: {}".format(hw_ms_inference_time)) | HW OCRed text: Für Andre hier gethan, sei stumme Gabe, -
HW MOps/s: 54833.779575112705
HW inference time [ms]: 1.7328369617462158
| BSD-3-Clause | notebooks/Fraktur_OCR.ipynb | tukl-msd/LSTM-PYNQ |
4. Perform OCR in softwareFor the sake of evaluating the performances of the hardware-accelerated OCR engine, perform the same OCR task using the Arm CPU. | sw_ocr = lstm.PynqFrakturOCR(lstm.RUNTIME_SW)
sw_result = sw_ocr.inference(np.array(im))
sw_mops_per_s, sw_ms_inference_time, sw_recognized_text = sw_result
print("SW OCRed text: {}".format(sw_recognized_text))
print("SW MOps/s: {}".format(sw_mops_per_s))
print("SW inference time [ms]: {}".format(sw_ms_inference_time... | SW OCRed text: Für Andre hier gethan, sei stumme Gabe, -
SW MOps/s: 1.2310819261405748
SW inference time [ms]: 77182.515625
| BSD-3-Clause | notebooks/Fraktur_OCR.ipynb | tukl-msd/LSTM-PYNQ |
5. Reset the hardware accelerator | hw_ocr.cleanup() | _____no_output_____ | BSD-3-Clause | notebooks/Fraktur_OCR.ipynb | tukl-msd/LSTM-PYNQ |
Strategy 1: Once threshold is reach, remove the point | def lineseg_dist(p, a, b):
# normalized tangent vector
d = np.divide(b - a, np.linalg.norm(b - a))
# signed parallel distance components
s = np.dot(a - p, d)
t = np.dot(p - b, d)
# clamped parallel distance
h = np.maximum.reduce([s, t, 0])
# perpendicular distance component
c = n... | _____no_output_____ | MIT | ECS129 Knot or Not_v1.ipynb | mmaliu97/ECS-129 |
Run Code | for k in range(0, 50):
nproblem = 0
for i in range(0, len(dataVals) - 2):
xCoord = (dataVals[i][0] + dataVals[i + 1][0] + dataVals[i + 2][0]) / 3
yCoord = (dataVals[i][1] + dataVals[i + 1][1] + dataVals[i + 2][1]) / 3
zCoord = (dataVals[i][2] + dataVals[i + 1][2] + dataVals[i + 2][2]) / ... | _____no_output_____ | MIT | ECS129 Knot or Not_v1.ipynb | mmaliu97/ECS-129 |
HistGradientBoostingClassifier with MaxAbsScaler This code template is for classification analysis using a HistGradientBoostingClassifier and the feature rescaling technique called MaxAbsScaler Required Packages | import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as se
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.experimental import enable_hist_gradient_boosting
from sklearn.ensemble import HistGr... | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
InitializationFilepath of CSV file | #filepath
file_path="" | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
List of features which are required for model training . | #x_values
features = [] | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Target feature for prediction. | #y_value
target='' | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. | df=pd.read_csv(file_path)
df.head() | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to... | X = df[features]
Y = df[target] | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_dummies(df)... | Encoded Target: ['Iris-setosa' 'Iris-versicolor' 'Iris-virginica'] to [0, 1, 2]
| Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | f,ax = plt.subplots(figsize=(18, 18))
matrix = np.triu(X.corr())
se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)
plt.show() | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Distribution Of Target Variable | plt.figure(figsize = (10,6))
se.countplot(Y) | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123) | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Data Rescaling sklearn.preprocessing.MaxAbsScaler is usedScale each feature by its maximum absolute value.Read more at [scikit-learn.org](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MaxAbsScaler.html) | Scaler=MaxAbsScaler()
x_train=Scaler.fit_transform(x_train)
x_test=Scaler.transform(x_test) | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
ModelHistogram-based Gradient Boosting Classification Tree.This estimator is much faster than GradientBoostingClassifier for big datasets (n_samples >= 10 000).This estimator has native support for missing values (NaNs). [Reference](https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.HistGradientBoostin... | model = HistGradientBoostingClassifier(random_state = 123)
model.fit(x_train, y_train) | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Model Accuracyscore() method return the mean accuracy on the given test data and labels.In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. | print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100)) | Accuracy score 90.00 %
| Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Confusion MatrixA confusion matrix is utilized to understand the performance of the classification model or algorithm in machine learning for a given test set where results are known. | plot_confusion_matrix(model,x_test,y_test,cmap=plt.cm.Blues) | _____no_output_____ | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Classification ReportA Classification report is used to measure the quality of predictions from a classification algorithm. How many predictions are True, how many are False.* **where**: - Precision:- Accuracy of positive predictions. - Recall:- Fraction of positives that were correctly identified. - f1-score... | print(classification_report(y_test,model.predict(x_test))) | precision recall f1-score support
0 1.00 1.00 1.00 13
1 0.71 0.83 0.77 6
2 0.90 0.82 0.86 11
accuracy 0.90 30
macro avg 0.87 0.88 0.88 ... | Apache-2.0 | Classification/Histogram-Based Gradient Boosting Trees/HistGradientBoostingClassifier_MaxAbsScaler.ipynb | shreepad-nade/ds-seed |
Prática Guiada: Demonstração de `GridSearchCV` Vamos usar o conjunto de dados iris... que já conhecemos bem.Veremos como usar `GridSearchCV` para otimizar o hiperparâmetro `k` do algoritmo de vizinhos mais próximos.[aqui](http://rcs.chemometrics.ru/Tutorials/classification/Fisher.pdf) há um link para o paper de Ronald... | import pandas as pd
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score, train_test_split
import matplotlib.pyplot as plt
%matplotlib inline
df = load_iris()
X = df.data
y = df.target
X_train, X_test, y_train, y_test = train_test_... | _____no_output_____ | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
1. Escrevendo os parâmetros à mãoÉ claro que, dependendo do modelo, os hiperparâmetros podem ter um efeito considerável na qualidade da previsão. Vamos ver como a precisão varia na hora de prever a espécie das flores para diferentes valores de K. | k_range = list(range(1, 100))
k_scores = []
for k in k_range:
knn = KNeighborsClassifier(n_neighbors=k)
scores = cross_val_score(knn, X_train, y_train, cv=10, scoring='accuracy')
k_scores.append(scores.mean())
k_scores
plt.plot(k_range, k_scores)
plt.xlabel('Value of K for KNN')
plt.ylabel('Cross-Valid... | _____no_output_____ | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
Como sempre, observamos que o desempenho muda para diferentes valores do hiperparâmetro. Como podemos sistematizar essa pesquisa e adicionar mais hiperparâmetros à exploração? 2. Usando `GridSearch` | from sklearn.model_selection import GridSearchCV | _____no_output_____ | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
É definida uma lista de parâmetros a serem testados. | k_range = list(range(1, 31))
knn = KNeighborsClassifier()
range(1, 31)
param_grid = dict(n_neighbors=range(1, 31))
print(param_grid) | {'n_neighbors': range(1, 31)}
| MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
Instanciar o método `GridSearchCV` | grid = GridSearchCV(knn, param_grid, cv=10, scoring='accuracy', n_jobs=-1) | _____no_output_____ | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
Fazer o ajuste | grid.fit(X_train, y_train) | /home/marcossilva/anaconda3/lib/python3.7/site-packages/sklearn/model_selection/_search.py:841: DeprecationWarning: The default of the `iid` parameter will change from True to False in version 0.22 and will be removed in 0.24. This will change numeric results when test-set sizes are unequal.
DeprecationWarning)
| MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
`GridSeachCV` retorna um dict com muitas informações. Do momento da configuração de cada parâmetro até os scores médios (via validação cruzada). Ele também fornece os scores em cada conjunto de treino e teste da Validação Cruzada K-Fold. | grid.cv_results_.keys()
pd.DataFrame(grid.cv_results_).columns
pd.DataFrame(grid.cv_results_) | _____no_output_____ | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
Vamos ver o melhor modelo: | grid.best_params_
grid.best_estimator_, grid.best_score_, grid.best_params_ | _____no_output_____ | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
2.1 Adicionando outros parâmetros para ajustar Vamos adicionar o parâmetro binário de peso do algoritmo knn que determina se alguns vizinhos terão mais peso do que outros no momento da classificação. O valor de distância indica que o peso é inversamente proporcional à distânciaGridSearchCV exige que a grade de parâmet... | k_range = list(range(1, 31))
weight_options = ['uniform', 'distance'] | _____no_output_____ | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
Agora a otimização será feita iterando e alternando `weights` e `k` (número de vizinhos próximos). | param_grid = dict(n_neighbors=k_range, weights=weight_options)
print(param_grid) | {'n_neighbors': [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], 'weights': ['uniform', 'distance']}
| MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
**Verificar:** 1. Como o processo de busca será realizado? 2. Quantas vezes o algoritmo terá que ser iterado? Ajustar os modelos | grid = GridSearchCV(knn, param_grid, cv=10, scoring='accuracy')
grid.fit(X_train, y_train)
pd.DataFrame(grid.cv_results_) | /home/marcossilva/anaconda3/lib/python3.7/site-packages/sklearn/utils/deprecation.py:125: FutureWarning: You are accessing a training score ('split0_train_score'), which will not be available by default any more in 0.21. If you need training scores, please set return_train_score=True
warnings.warn(*warn_args, **warn_... | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
Escolher o melhor modelo | print (grid.best_estimator_)
print(grid.best_score_)
print(grid.best_params_) | KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
metric_params=None, n_jobs=None, n_neighbors=8, p=2,
weights='uniform')
0.9833333333333333
{'n_neighbors': 8, 'weights': 'uniform'}
| MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
3. Usar os melhores modelos para executar as previsões | knn = KNeighborsClassifier(n_neighbors=8, weights='uniform')
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix
import seaborn as sns
print (classification_report(y_test, y_pred))
sns.heatmap(confusion_matrix(y_test, y_pred),annot=True) | precision recall f1-score support
0 1.00 1.00 1.00 8
1 1.00 0.81 0.90 16
2 0.67 1.00 0.80 6
micro avg 0.90 0.90 0.90 30
macro avg 0.89 0.94 0.90 ... | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
Podemos usar o atalho que `GridSeachCV` possui: usando o método` predict` sobre o objeto `grid`. | grid.predict(X_test) | _____no_output_____ | MIT | 03-machine-learning-tabular-crossection/10 - Parametrização/GridSearch.ipynb | sn3fru/datascience_course |
**Deep-STORM (2D)**---Deep-STORM is a neural network capable of image reconstruction from high-density single-molecule localization microscopy (SMLM), first published in 2018 by [Nehme *et al.* in Optica](https://www.osapublishing.org/optica/abstract.cfm?uri=optica-5-4-458). The architecture used here is a U-Net based... | Notebook_version = '1.13'
Network = 'Deep-STORM'
from builtins import any as b_any
def get_requirements_path():
# Store requirements file in 'contents' directory
current_dir = os.getcwd()
dir_count = current_dir.count('/') - 1
path = '../' * (dir_count) + 'requirements.txt'
return path
def fil... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**2. Complete the Colab session**--- **2.1. Check for GPU access**---By default, the session should be using Python 3 and GPU acceleration, but it is possible to ensure that these are set properly by doing the following:Go to **Runtime -> Change the Runtime type****Runtime type: Python 3** *(Python 3 is programming l... | #@markdown ##Run this cell to check if you have GPU access
# %tensorflow_version 1.x
import tensorflow as tf
# if tf.__version__ != '2.2.0':
# !pip install tensorflow==2.2.0
if tf.test.gpu_device_name()=='':
print('You do not have GPU access.')
print('Did you change your runtime ?')
print('If the runtime se... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**2.2. Mount your Google Drive**--- To use this notebook on the data present in your Google Drive, you need to mount your Google Drive to this notebook. Play the cell below to mount your Google Drive and follow the link. In the new browser window, select your drive and select 'Allow', copy the code, paste into the cel... | #@markdown ##Run this cell to connect your Google Drive to Colab
#@markdown * Click on the URL.
#@markdown * Sign in your Google Account.
#@markdown * Copy the authorization code.
#@markdown * Enter the authorization code.
#@markdown * Click on "Files" site on the right. Refresh the site. Your Google Drive fol... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**3. Generate patches for training**---For Deep-STORM the training data can be obtained in two ways:* Simulated using ThunderSTORM or other simulation tool and loaded here (**using Section 3.1.a**)* Directly simulated in this notebook (**using Section 3.1.b**) **3.1.a Load training data**---Here you can load your sim... | #@markdown ##Load raw data
load_raw_data = True
# Get user input
ImageData_path = "" #@param {type:"string"}
LocalizationData_path = "" #@param {type: "string"}
#@markdown Get pixel size from file?
get_pixel_size_from_file = True #@param {type:"boolean"}
#@markdown Otherwise, use this value:
pixel_size = 100 #@param ... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**3.1.b Simulate training data**---This simulation tool allows you to generate SMLM data of randomly distrubuted emitters in a field-of-view. The assumptions are as follows:* Gaussian Point Spread Function (PSF) with standard deviation defined by `Sigma`. The nominal value of `sigma` can be evaluated using `sigma = ... | load_raw_data = False
# ---------------------------- User input ----------------------------
#@markdown Run the simulation
#@markdown ---
#@markdown Camera settings:
FOV_size = 6400#@param {type:"number"}
pixel_size = 100#@param {type:"number"}
ADC_per_photon_conversion = 1 #@param {type:"number"}
ReadOutNoise_ADC... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**3.2. Generate training patches**---Training patches need to be created from the training data generated above. * The `patch_size` needs to give sufficient contextual information and for most cases a `patch_size` of 26 (corresponding to patches of 26x26 pixels) works fine. **DEFAULT: 26*** The `upsampling_factor`... | #@markdown ## **Provide patch parameters**
# -------------------- User input --------------------
patch_size = 26 #@param {type:"integer"}
upsampling_factor = 8 #@param ["4", "8", "16"] {type:"raw"}
num_patches_per_frame = 500#@param {type:"integer"}
min_number_of_emitters_per_patch = 7#@param {type:"integer"}
max_n... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**4. Train the network**--- **4.1. Select your paths and parameters**---**`model_path`**: Enter the path where your model will be saved once trained (for instance your result folder).**`model_name`:** Use only my_model -style, not my-model (Use "_" not "-"). Do not use spaces in the name. Avoid using the name of an e... | #@markdown ###Path to training images and parameters
model_path = "" #@param {type: "string"}
model_name = "" #@param {type: "string"}
number_of_epochs = 80#@param {type:"integer"}
batch_size = 16#@param {type:"integer"}
number_of_steps = 0#@param {type:"integer"}
percentage_validation = 30 #@param {type:"number... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**4.2. Using weights from a pre-trained model as initial weights**--- Here, you can set the the path to a pre-trained model from which the weights can be extracted and used as a starting point for this training session. **This pre-trained model needs to be a Deep-STORM 2D model**. This option allows you to perform t... | # @markdown ##Loading weights from a pre-trained network
Use_pretrained_model = False #@param {type:"boolean"}
pretrained_model_choice = "Model_from_file" #@param ["Model_from_file"]
Weights_choice = "best" #@param ["last", "best"]
#@markdown ###If you chose "Model_from_file", please provide the path to the model fol... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**4.4. Start Training**---When playing the cell below you should see updates after each epoch (round). Network training can take some time.* **CRITICAL NOTE:** Google Colab has a time limit for processing (to prevent using GPU power for datamining). Training time must be less than 12 hours! If training takes longer th... | #@markdown ##Start training
# Start the clock to measure how long it takes
start = time.time()
# --------------------- Using pretrained model ------------------------
#Here we ensure that the learning rate set correctly when using pre-trained models
if Use_pretrained_model:
if Weights_choice == "last":
initial_... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**5. Evaluate your model**---This section allows the user to perform important quality checks on the validity and generalisability of the trained model. **We highly recommend to perform quality control on all newly trained models.** | # model name and path
#@markdown ###Do you want to assess the model you just trained ?
Use_the_current_trained_model = True #@param {type:"boolean"}
#@markdown ###If not, please provide the path to the model folder:
#@markdown #####During training, the model files are automatically saved inside a folder named after th... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**5.1. Inspection of the loss function**---First, it is good practice to evaluate the training progress by comparing the training loss with the validation loss. The latter is a metric which shows how well the network performs on a subset of unseen data which is set aside from the training dataset. For more information... | #@markdown ##Play the cell to show a plot of training errors vs. epoch number
lossDataFromCSV = []
vallossDataFromCSV = []
with open(os.path.join(QC_model_path,'Quality Control/training_evaluation.csv'),'r') as csvfile:
csvRead = csv.reader(csvfile, delimiter=',')
next(csvRead)
for row in csvRead:
... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**5.2. Error mapping and quality metrics estimation**---This section will display SSIM maps and RSE maps as well as calculating total SSIM, NRMSE and PSNR metrics for all the images provided in the "QC_image_folder" using teh corresponding localization data contained in "QC_loc_folder" !**1. The SSIM (structural simil... |
# ------------------------ User input ------------------------
#@markdown ##Choose the folders that contain your Quality Control dataset
QC_image_folder = "" #@param{type:"string"}
QC_loc_folder = "" #@param{type:"string"}
#@markdown Get pixel size from file?
get_pixel_size_from_file = True #@param {type:"boolean"}
#@... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**6. Using the trained model**---In this section the unseen data is processed using the trained model (in section 4). First, your unseen images are uploaded and prepared for prediction. After that your trained model from section 4 is activated and finally saved into your Google Drive. **6.1 Generate image prediction ... |
# ------------------------------- User input -------------------------------
#@markdown ### Data parameters
Data_folder = "" #@param {type:"string"}
Result_folder = "" #@param {type:"string"}
#@markdown Get pixel size from file?
get_pixel_size_from_file = True #@param {type:"boolean"}
#@markdown Otherwise, use this va... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**6.2 Drift correction**---The visualization above is the raw output of the network and displayed at the `upsampling_factor` chosen during model training. The display is a preview without any drift correction applied. This section performs drift correction using cross-correlation between time bins to estimate the drif... | # @markdown ##Data parameters
Loc_file_path = "" #@param {type:"string"}
# @markdown Provide information about original data. Get the info automatically from the raw data?
Get_info_from_file = True #@param {type:"boolean"}
# Loc_file_path = "/content/gdrive/My Drive/Colab notebooks testing/DeepSTORM/Glia data from CL/R... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
**6.3 Visualization of the localizations**---The visualization in section 6.1 is the raw output of the network and displayed at the `upsampling_factor` chosen during model training. This section performs visualization of the result by plotting the localizations as a simple histogram.**`Loc_file_path`:** is the path to... | # @markdown ##Data parameters
Use_current_drift_corrected_localizations = True #@param {type:"boolean"}
# @markdown Otherwise provide a localization file path
Loc_file_path = "" #@param {type:"string"}
# @markdown Provide information about original data. Get the info automatically from the raw data?
Get_info_from_file ... | _____no_output_____ | MIT | Colab_notebooks/Deep-STORM_2D_ZeroCostDL4Mic.ipynb | junelsolis/ZeroCostDL4Mic |
Microstructure classification using Neural Networks In this example, we will generate microstructures of 4 different types with different grain sizes. Then we will split the dataset into training and testing set.Finally we will trian the neural network using CrysX-NN to make predictions. Run the following cell for Go... | ! pip install --upgrade --no-cache-dir https://github.com/manassharma07/crysx_nn/tarball/main
! pip install pymks
! pip install IPython==7.7.0
! pip install fsspec>=0.3.3 | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Import necessary librariesWe will use PyMKS for generation artificial microstructures. | from pymks import (
generate_multiphase,
plot_microstructures,
# PrimitiveTransformer,
# TwoPointCorrelation,
# FlattenTransformer,
# GenericTransformer
)
import numpy as np
import matplotlib.pyplot as plt
# For GPU
import cupy as cp | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Define some parameterslike number of samples per type, the width and height of a microstructure image in pixels.[For Google Colab, generating 10,000 samples of each type results in out of memory error. 8000 seems to work fine.] | nSamples_per_type = 10000
width = 100
height = 100 | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Generate microstructuresThe following code will generate microstructures of 4 different types.The first type has 6 times more grain boundaries along the x-axis than the y-axis.The second type has 4 times more grain boundaries along the y-axis than the x-axis.The third type has same number of grain boundaries along the... | grain_sizes = [(30, 5), (10, 40), (15, 15), (5, 30)]
seeds = [10, 99, 4, 36]
data_synth = np.concatenate([
generate_multiphase(shape=(nSamples_per_type, width, height), grain_size=grain_size,
volume_fraction=(0.5, 0.5),
percent_variance=0.2,
seed=seed
)
for grain_size, seed in zip(g... | C:\Users\manas\anaconda3\envs\crysx_nn\lib\site-packages\toolz\functoolz.py:306: FutureWarning: arrays to stack must be passed as a "sequence" type such as list or tuple. Support for non-sequence iterables such as generators is deprecated as of NumPy 1.16 and will raise an error in the future.
return self._partial(*a... | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Plot a microstructure of each type | plot_microstructures(*data_synth[::nSamples_per_type+0], colorbar=True)
# plot_microstructures(*data_synth[::nSamples_per_type+1], colorbar=True)
# plot_microstructures(*data_synth[::nSamples_per_type+2], colorbar=True)
# plot_microstructures(*data_synth[::nSamples_per_type+3], colorbar=True)
#plt.savefig("Microstructu... | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Check the shape of the data generatedThe first dimension corresponds to the total number of samples, the second and third axes are for width and height. | # Print shape of the array
print(data_synth.shape)
print(type(data_synth)) | (40000, 100, 100)
<class 'numpy.ndarray'>
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Rename the generated data --> `X_data` as it is the input data | X_data = np.array(data_synth)
print(X_data.shape) | (40000, 100, 100)
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Create the target/true labels for the dataThe microstructure data we have generated is such that the samples of different types are grouped together. Furthermore, their order is the same as the one we provided when generating the data. Therefore, we can generate the true labels quite easily by making a numpy array who... | Y_data = np.concatenate([np.ones(nSamples_per_type)*0,np.ones(nSamples_per_type)*1,np.ones(nSamples_per_type)*2,np.ones(nSamples_per_type)*3])
print(Y_data)
print(Y_data.shape) | [0. 0. 0. ... 3. 3. 3.]
(40000,)
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Plot some samples taken from the data randomly as well as their labels that we created for confirmation | rng = np.random.default_rng()
### Plot examples
fig, axes = plt.subplots(nrows=2, ncols=6, figsize=(15., 6.))
for axes_row in axes:
for ax in axes_row:
test_index = rng.integers(0, len(Y_data))
image = X_data[test_index]
orig_label = Y_data[test_index]
ax.set_axis_off()
ax.i... | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Use sklearn to split the data into train and test set | from sklearn.model_selection import train_test_split
# Split into train and test
X_train_orig, X_test_orig, Y_train_orig, Y_test_orig = train_test_split(X_data, Y_data, test_size=0.20, random_state=1) | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Some statistics of the training data | print('Training data MIN',X_train_orig.min())
print('Training data MAX',X_train_orig.max())
print('Training data MEAN',X_train_orig.mean())
print('Training data STD',X_train_orig.std()) | Training data MIN 0
Training data MAX 1
Training data MEAN 0.49983095625
Training data STD 0.49999997142421193
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Check some shapes | print(X_train_orig.shape)
print(Y_train_orig.shape)
print(X_test_orig.shape)
print(Y_test_orig.shape) | (32000, 100, 100)
(32000,)
(8000, 100, 100)
(8000,)
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Flatten the input pixel data for each sample by reshaping the 2d array of size `100,100`, for each sample to a 1d array of size `100*100` | X_train = X_train_orig.reshape(X_train_orig.shape[0], width*height)
X_test = X_test_orig.reshape(X_test_orig.shape[0], width*height) | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Check the shapes | print(X_train.shape)
print(X_test.shape) | (32000, 10000)
(8000, 10000)
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Use a utility from CrysX-NN to one-hot encode the target/true labels This means that a sample with type 3 will be represented as an array [0,0,0,1] | from crysx_nn import mnist_utils as mu
Y_train = mu.one_hot_encode(Y_train_orig, 4)
Y_test = mu.one_hot_encode(Y_test_orig, 4)
print(Y_train.shape)
print(Y_test.shape) | (32000, 4)
(8000, 4)
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Standardize the training and testing input data using the mean and standard deviation of the training data | X_train = (X_train - np.mean(X_train_orig)) / np.std(X_train_orig)
X_test = (X_test - np.mean(X_train_orig)) / np.std(X_train_orig)
# Some statistics after standardization
print('Training data MIN',X_train.min())
print('Training data MAX',X_train.max())
print('Training data MEAN',X_train.mean())
print('Training data S... | Training data MIN -0.9996619696322572
Training data MAX 1.0003381446709014
Training data MEAN -1.0667022820598504e-16
Training data STD 0.9999999999999942
Testing data MIN -0.9996619696322572
Testing data MAX 1.0003381446709014
Testing data MEAN 0.0016794125959809832
Testing data STD 0.999999157574746
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Finally we will begin creating a neural networkSet some important parameters for the Neural Network.**Note**: In some cases I got NAN values while training. The issue could be circumvented by choosing a different batch size. | nInputs = width*height # No. of nodes in the input layer
neurons_per_layer = [500, 4] # Neurons per layer (excluding the input layer)
activation_func_names = ['ReLU', 'Softmax']
nLayers = len(neurons_per_layer)
nEpochs = 4
batchSize = 32 # No. of input samples to process at a time for optimization | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Create the neural network modelUse the parameters define above to create the model | from crysx_nn import network
model = network.nn_model(nInputs=nInputs, neurons_per_layer=neurons_per_layer, activation_func_names=activation_func_names, batch_size=batchSize, device='GPU', init_method='Xavier')
model.lr = 0.02 | C:\Users\manas\anaconda3\envs\crysx_nn\lib\site-packages\crysx_nn\network.py:13: TqdmExperimentalWarning: Using `tqdm.autonotebook.tqdm` in notebook mode. Use `tqdm.tqdm` instead to force console mode (e.g. in jupyter console)
from tqdm.autonotebook import tqdm
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Check the details of the Neural Network | model.details() | ----------------------------------------------------------------------------------
****Neural Network Model Details****
----------------------------------------------------------------------------------
Number of input nodes: 10000
Number of layers (hidden+output): 2
Number of nodes in each layer (hidden & output): ... | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Visualize the neural network | model.visualize() | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Begin optimization/trainingWe will use `float32` precision, so convert the input and output arrays.We will use Categorical Cross Entropy for the loss function. | inputs = cp.array(X_train.astype(np.float32))
outputs = cp.array(Y_train.astype(np.float32))
# Run optimization
# model.optimize(inputs, outputs, lr=0.02,nEpochs=nEpochs,loss_func_name='CCE', miniterEpoch=1, batchProgressBar=True, miniterBatch=100)
# To get accuracies at each epoch
model.optimize(inputs, outputs, lr=0.... | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Error at each epoch | print(model.errors) | [array(0.80813736, dtype=float32), array(0.11121845, dtype=float32), array(0.01747202, dtype=float32), array(0.00730846, dtype=float32)]
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Accuracy at each epoch | print(model.accuracy) | [array(0.66996875), array(0.9783125), array(0.99965625), array(1.)]
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Save model weights and biases | # Save weights
model.save_model_weights('NN_crysx_microstructure_96_weights_cupy')
# Save biases
model.save_model_biases('NN_crysx_microstructure_96_biases_cupy') | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Load model weights and biases from files | model.load_model_weights('NN_crysx_microstructure_96_weights_cupy')
model.load_model_biases('NN_crysx_microstructure_96_biases_cupy') | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Performance on Test data | ## Convert to float32 arrays
inputs = cp.array(X_test.astype(np.float32))
outputs = cp.array(Y_test.astype(np.float32))
# predictions, error = model.predict(inputs, outputs, loss_func_name='BCE')
# print('Error:',error)
# print(predictions)
predictions, error, accuracy = model.predict(inputs, outputs, loss_func_name='C... | Error: 0.0909118
Accuracy %: 97.7
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Confusion matrix | from crysx_nn import utils
# Convert predictions to numpy array for using the utility function
predictions = cp.asnumpy(predictions)
# Get the indices of the maximum probabilities for each sample in the predictions array
pred_type = np.argmax(predictions, axis=1)
# Get the digit index from the one-hot encoded array
t... | Confusion matrix:
[[2.022e+03 0.000e+00 4.000e+00 0.000e+00]
[0.000e+00 1.958e+03 0.000e+00 4.900e+01]
[2.000e+00 1.000e+00 1.952e+03 1.000e+00]
[0.000e+00 1.270e+02 0.000e+00 1.884e+03]]
| MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Draw some random images from the test dataset and compare the true labels to the network outputs | ### Draw some random images from the test dataset and compare the true labels to the network outputs
fig, axes = plt.subplots(nrows=2, ncols=6, figsize=(15., 6.))
### Loop over subplots
for axes_row in axes:
for ax in axes_row:
### Draw the images
test_index = rng.integers(0, len(Y_test_orig))
... | _____no_output_____ | MIT | examples/Microstructures_Classification_GPU.ipynb | manassharma07/cysx_nn |
Pandas**pandas is short for Python Data Analysis Library | import pandas as pd | _____no_output_____ | MIT | week8/in_class_notebooks/week8-192.ipynb | anamarina/Data_Analysis_in_Python |
In pandas you need to work with DataFrames and Series. According to [the documentation of pandas](https://pandas.pydata.org/pandas-docs/stable/):* **DataFrame**: Two-dimensional, size-mutable, potentially heterogeneous tabular data. Data structure also contains labeled axes (rows and columns). Arithmetic operations ali... | pd.Series([5, 6, 7, 8, 9, 10])
pd.DataFrame([1])
some_data = {'Student': ['1', '2'], 'Name': ['Alice', 'Michael'], 'Surname': ['Brown', 'Williams']}
pd.DataFrame(some_data)
some_data = [{'Student': ['1', '2'], 'Name': ['Alice', 'Michael'], 'Surname': ['Brown', 'Williams']}]
pd.DataFrame(some_data)
pd.DataFrame([{'Stu... | _____no_output_____ | MIT | week8/in_class_notebooks/week8-192.ipynb | anamarina/Data_Analysis_in_Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.