markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We can plot where in the text a word occurs, and compare it to other words, with a dispersion plot. For example, the following dispersion plots show respectively (among other things) that the words 'coconut' and 'swallow' almost always appear in the same part of the Holy Grail text, and that Willoughby and Lucy do not ... | text6.dispersion_plot(["coconut", "swallow", "KNIGHT", "witch", "ARTHUR"])
text2.dispersion_plot(["Elinor", "Marianne", "Edward", "Willoughby", "Lucy"]) | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
We can go a little crazy with text statistics. This block of code computes the average word length for each text, as well as a measure known as the "lexical diversity" that measures how much word re-use there is in a text. | def print_text_stats( thetext ):
# Average word length
awl = sum([len(w) for w in thetext]) / len( thetext )
ld = len( thetext ) / len( thetext.vocab() )
print("%.2f\t%.2f\t%s" % ( awl, ld, thetext.name ))
all_texts = [ text1, text2, text3, text4, text5, text6, text7, text8, text9 ]
print("Wlen\tL... | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
A text of your own
So far we have been using the sample texts, but we can also use any text that we have lying around on our computer. The easiest sort of text to read in is plaintext, not PDF or HTML or anything else. Once we have made the text into an NLTK text with the Text() function, we can use all the same method... | from nltk import word_tokenize
# You can read the file this way:
f = open('alice.txt', encoding='utf-8')
raw = f.read()
f.close()
# or you can read it this way.
with open('alice.txt', encoding='utf-8') as f:
raw = f.read()
# Use NLTK to break the text up into words, and put the result into a
# Text object.
alic... | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
Using text corpora
NLTK comes with several pre-existing corpora of texts, some of which are the main body of text used for certain sorts of linguistic research. Using a corpus of texts, as opposed to an individual text, brings us a few more features. | from nltk.corpus import gutenberg
print(gutenberg.fileids())
paradise_lost = Text( gutenberg.words( "milton-paradise.txt" ) )
paradise_lost | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
Paradise Lost is now a Text object, just like the ones we have worked on before. But we accessed it through the NLTK corpus reader, which means that we get some extra bits of functionality: | print("Length of text is:", len( gutenberg.raw( "milton-paradise.txt" )))
print("Number of words is:", len( gutenberg.words( "milton-paradise.txt" )))
assert( len( gutenberg.words( "milton-paradise.txt" )) == len( paradise_lost ))
print("Number of sentences is:", len( gutenberg.sents( "milton-paradise.txt" )))
print("N... | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
We can also make our own corpus if we have our own collection of files, e.g. the Federalist Papers from last week. But we have to pay attention to how those files are arranged! In this case, if you look in the text file, the paragraphs are set apart with 'hanging indentation' - all the lines | from nltk.corpus import PlaintextCorpusReader
from nltk.corpus.reader.util import read_regexp_block
# Define how paragraphs look in our text files.
def read_hanging_block( stream ):
return read_regexp_block( stream, "^[A-Za-z]" )
corpus_root = 'federalist'
file_pattern = 'federalist_.*\.txt'
federalist = Plaintex... | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
And just like before, from this corpus we can make individual Text objects, on which we can use the methods we have seen above. | fed1 = Text( federalist.words( "federalist_1.txt" ))
print("The first Federalist Paper has the following word collocations:")
fed1.collocations()
print("\n...and the following most frequent words.")
fed1.vocab().most_common(50) | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
Filtering out stopwords
In linguistics, stopwords or function words are words that are so frequent in a particular language that they say little to nothing about the meaning of a text. You can make your own list of stopwords, but NLTK also provides a list for each of several common languages. These sets of stopwords ar... | from nltk.corpus import stopwords
print("We have stopword lists for the following languages:")
print(stopwords.fileids())
print("\nThese are the NLTK-provided stopwords for the German language:")
print(", ".join( stopwords.words('german') )) | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
So reading in the stopword list, we can use it to filter out vocabulary we don't want to see. Let's look at our 50 most frequent words in Holy Grail again. | print("The most frequent words are: ")
print([word[0] for word in t6_vocab.most_common(50)])
f1_most_frequent = [ w[0] for w in t6_vocab.most_common() if w[0].lower() not in stopwords.words('english') ]
print("\nThe most frequent interesting words are: ", " ".join( f1_most_frequent[:50] )) | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
Maybe we should get rid of punctuation and all-caps words too... | import re
def is_interesting( w ):
if( w.lower() in stopwords.words('english') ):
return False
if( w.isupper() ):
return False
return w.isalpha()
f1_most_frequent = [ w[0] for w in t6_vocab.most_common() if is_interesting( w[0] ) ]
print("The most frequent interesting words are: ", " ".jo... | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
Getting word stems
Quite frequently we might want to treat different forms of a word - e.g. 'make / makes / made / making' - as the same word. A common way to do this is to find the stem of the word and use that in your analysis, in place of the word itself. There are several different approaches that can be takenNone ... | my_text = alice[305:549]
print(" ". join( my_text ))
print(len( set( my_text )), "words") | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
NLTK comes with a few different stemming algorithms; we can also use WordNet (a system for analyzing semantic relationships between words) to look for the lemma form of each word and "stem" it that way. Here are some results. | from nltk import PorterStemmer, LancasterStemmer, WordNetLemmatizer
porter = PorterStemmer()
lanc = LancasterStemmer()
wnl = WordNetLemmatizer()
porterlist = [porter.stem(w) for w in my_text]
print(" ".join( porterlist ))
print(len( set( porterlist )), "Porter stems")
lanclist = [lanc.stem(w) for w in my_text]
print(... | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
Part-of-speech tagging
This is where corpus linguistics starts to get interesting. In order to analyze a text computationally, it is useful to know its syntactic structure - what words are nouns, what are verbs, and so on? This can be done (again, imperfectly) by using part-of-speech tagging. | from nltk import pos_tag
print(pos_tag(my_text)) | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
NLTK part-of-speech tags (simplified tagset)
| Tag | Meaning | Examples |
|-----|--------------------|--------------------------------------|
| JJ | adjective | new, good, high, special, big, local |
| RB | adverb | really, already, still, early, now |
| C... | from nltk.corpus import brown
print(brown.tagged_words()[:25])
print(brown.tagged_words(tagset='universal')[:25]) | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
We can even do a frequency plot of the different parts of speech in the corpus (if we have matplotlib installed!) | tagged_word_fd = FreqDist([ w[1] for w in brown.tagged_words(tagset='universal') ])
tagged_word_fd.plot() | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
Named-entity recognition
As well as the parts of speech of individual words, it is useful to be able to analyze the structure of an entire sentence. This generally involves breaking the sentence up into its component phrases, otherwise known as chunking.
Not going to cover chunking here as there is no out-of-the-box c... | from nltk import ne_chunk
tagged_text = pos_tag(sent2)
ner_text = ne_chunk( tagged_text )
print(ner_text)
ner_text | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
Here is a function that takes the result of ne_chunk (the plain-text form, not the graph form!) and spits out only the named entities that were found. | def list_named_entities( tree ):
try:
tree.label()
except AttributeError:
return
if( tree.label() != "S" ):
print(tree)
else:
for child in tree:
list_named_entities( child )
list_named_entities( ner_text ) | lessons/09 Natural language processing with NLTK.ipynb | DHBern/Tools-and-Techniques | gpl-3.0 |
Raw data
This is an example of making a data table. | # enter column labels and raw data (with same # of values)
table1 = pd.DataFrame.from_items([
('column1', [0,1,2,3]),
('column2', [0,2,4,6])
])
# display data table
table1 | templateGraphing.ipynb | merryjman/astronomy | gpl-3.0 |
Plotting | # Uncomment the next line to make your graphs look like xkcd.com
#plt.xkcd()
# to make normal-looking plots again execute:
#mpl.rcParams.update(inline_rc)
# set variables = data['column label']
x = table1['column1']
y = table1['column2']
# this makes a scatterplot of the data
# plt.scatter(x values, y values)
plt.sc... | templateGraphing.ipynb | merryjman/astronomy | gpl-3.0 |
Do calculations with the data | # create a new empty column
table1['column3'] = ''
table1 | templateGraphing.ipynb | merryjman/astronomy | gpl-3.0 |
Here's an example of calculating the difference between the values in column 2: | # np.diff() calculates the difference between a value and the one after it
z = np.diff(x)
# fill column 3 with values from the formula (z) above:
table1['column3'] = pd.DataFrame.from_items([('', z)])
# display the data table
table1
# NaN and Inf values cause problems with math and plotting.
# Make a new table using... | templateGraphing.ipynb | merryjman/astronomy | gpl-3.0 |
Now you can copy the code above to plot your new data table. | # code for plotting table2 can go here | templateGraphing.ipynb | merryjman/astronomy | gpl-3.0 |
Exploratory Data Analysis
We'll just check out a simple pairplot for this small dataset. | # TODO 1
sns.pairplot(df, hue="Kyphosis", palette="Set1") | notebooks/launching_into_ml/solutions/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Decision Trees
We'll start just by training a single decision tree. | from sklearn.tree import DecisionTreeClassifier
dtree = DecisionTreeClassifier()
# TODO 2
dtree.fit(X_train, y_train) | notebooks/launching_into_ml/solutions/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Prediction and Evaluation
Let's evaluate our decision tree. | predictions = dtree.predict(X_test)
from sklearn.metrics import classification_report, confusion_matrix
# TODO 3a
print(classification_report(y_test, predictions))
# TODO 3b
print(confusion_matrix(y_test, predictions)) | notebooks/launching_into_ml/solutions/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Random Forests
Now let's compare the decision tree model to a random forest. | from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier(n_estimators=100)
rfc.fit(X_train, y_train)
rfc_pred = rfc.predict(X_test)
# TODO 4a
print(confusion_matrix(y_test, rfc_pred))
# TODO 4b
print(classification_report(y_test, rfc_pred)) | notebooks/launching_into_ml/solutions/supplemental/decision_trees_and_random_Forests_in_Python.ipynb | GoogleCloudPlatform/asl-ml-immersion | apache-2.0 |
Get all the method names | methodNames_list = benchmark_data['Method_Name'].unique().tolist()
#methodNames_list | Clean HPCC Data.ipynb | rhiever/sklearn-benchmarks | mit |
Store the data method wise separately | methodWiseData = {}
for name in methodNames_list:
methodWiseData[name] = benchmark_data[(benchmark_data.Method_Name == name)] | Clean HPCC Data.ipynb | rhiever/sklearn-benchmarks | mit |
Save the data method wise to a folder in tsv.gz format | #for i in names_list:
# print(d[i])
import os
if not os.path.isdir('newBenchmark_results'):
os.mkdir('newBenchmark_results')
gb = methodWiseData['GradientBoostingClassifier']
gb.to_pickle('newBenchmark_results/GradientBoostingClassifier_results.tsv.gz')
method_data = pd.read_pickle('newBenchmark_results/Gradie... | Clean HPCC Data.ipynb | rhiever/sklearn-benchmarks | mit |
Split the parameters into dfifferent columns;
make sure to set the no of coumns according to different methods | method_param = pd.DataFrame(method_data.Parameters.str.split(',').tolist(),
columns = ['Param1','Param2','Param3'])
method_param
method_data1 = method_data.drop('Parameters', 1) #delete the Paameters column from the original dataframe
idx = method_param.index.get_values() ... | Clean HPCC Data.ipynb | rhiever/sklearn-benchmarks | mit |
Save this result in the HPCC_benchmark_results folder | import os
if not os.path.isdir('HPCC_benchmark_results'):
os.mkdir('HPCC_benchmark_results')
result.to_pickle('HPCC_benchmark_results/GradientBoostingClassifier-hpcc_results.tsv.gz')
data = pd.read_pickle('HPCC_benchmark_results/GradientBoostingClassifier-hpcc_results.tsv.gz')
data | Clean HPCC Data.ipynb | rhiever/sklearn-benchmarks | mit |
Conversión de tasas de interés
Interés anticipado e interés vencido
Contenido
<img src="images/antxven.png" width=500>
Interés vencido: se paga al final del periodo.
$$F=P(1+r)$$
Interés anticipado: se paga al inicio del periodo (antes de su causación). En este caso surge una paradoja, que el interés se puede reinver... | 0.2 / (1 - 0.2) | 2016-03/IE-02-representacion-flujos-y-tasas.ipynb | jdvelasq/ingenieria-economica | mit |
Ejemplo.-- Si se desea obtener una tasa efectiva anual del 36%, ¿cuánto se deberá cobrar en forma anticipada anual para obenerla? | 0.36 / (1 + 0.36) | 2016-03/IE-02-representacion-flujos-y-tasas.ipynb | jdvelasq/ingenieria-economica | mit |
Interés nominal e interés efectivo
Contenido
Interés nominal (r): expresado sobre una base anual para un número M de periodos de pago en el año.
Interés efectivo por periodo de pago ($i$): representa el interés real para cada periodo de pago en el año.
Interés efectivo anual ($i_a$): interés real para un periodo úni... | cf.iconv(nrate = 6.72, pyr = 2) ## Banco 1
cf.iconv(nrate = 6.70, pyr = 4) ## Banco 2 -- mejor opción
cf.iconv(nrate = 6.65, pyr = 12) ## Banco 3
## Otra forma
cf.iconv(nrate = [6.72, 6.79, 6.65], pyr = [2, 4, 12]) | 2016-03/IE-02-representacion-flujos-y-tasas.ipynb | jdvelasq/ingenieria-economica | mit |
Ejemplo.-- Convierta una tasa del 12% anual compuesto semestralmente a anual compuesto mensualmente. | erate, _ = cf.iconv(nrate = 12.0, pyr = 2) ## efectiva por año
erate
nrate, _ = cf.iconv(erate = erate, pyr = 12) ## nominal compuesta mensualmente
nrate | 2016-03/IE-02-representacion-flujos-y-tasas.ipynb | jdvelasq/ingenieria-economica | mit |
Ejemplo.-- Sea un interés nominal del 12% capitalizado mensualmente. Calcule:
Tasa efectiva mensual
Tasa efectiva trimestral
Tasa efectiva anual
<img src="images/tasa-nominal-efectiva.png" width=600> | ## tasa efectiva mensual
0.12 / 12
## tasa efectiva trimestral
erate, _ = cf.iconv(nrate = 3 * 0.12 / 12, pyr = 3)
erate
## tasa efectiva anual
erate, _ = cf.iconv(nrate = 12.0, pyr = 12)
erate | 2016-03/IE-02-representacion-flujos-y-tasas.ipynb | jdvelasq/ingenieria-economica | mit |
Nomenclatura
Contenido
<img src="images/nomenclatura.png" width=600>
Ejercicios
Ejercicio.-- Cuál es la tasa efectiva anual equivalente a 15% N.A.M.V. (nominal anual mes vencido)?
Ejercicio.-- Cuál es la tasa efectiva anual equivalente a 23% N.A.T.A. (nominal anual trimestre anticipado)?
Ejercicio.-- Sea un interés no... | cf.nominal_rate(const_value=10, start=(2000, 0), nper=8, pyr=4)
cf.nominal_rate(const_value=10, start=(2000, 0), nper=8, pyr=6)
spec = ((2000, 3), 10)
cf.nominal_rate(const_value=1, start=(2000, 0), nper=8, pyr=4, spec=spec)
spec = [(3, 10), (6, 20)]
cf.nominal_rate(const_value=1, start=(2000, 0), nper=8, pyr=4, ... | 2016-03/IE-02-representacion-flujos-y-tasas.ipynb | jdvelasq/ingenieria-economica | mit |
Ejemplo.-- Se va a tomar un crédito a 48 meses. La tasa inicial es del 3% y aumenta un punto cada año. Represente la tasa de interés. | cf.nominal_rate(const_value = 3,
start = (2000, 0),
nper = 48,
pyr = 12,
spec= [(12, 4), # tasa para el año 2
(24, 5), # tasa para el año 3
(36, 6)]) # tasa para el año 4)
x = cf.nominal_rat... | 2016-03/IE-02-representacion-flujos-y-tasas.ipynb | jdvelasq/ingenieria-economica | mit |
Representación de flujos genéricos de caja
cashflow también permite la representación de flujos de efectivo en forma similar (pero no igual) a las tasas de interés, pero en este caso las tuplas (time, value) representan valores puntuales en el tiempo. | cf.cashflow(const_value=1, # valor constante
start=(2000, 0), # (periodo mayor, periodo menor)
nper=8, # número total de periodos
pyr=4) # número de periodos por año
## un valor puntual puede ser introducido mediante una tupla
spec = ((2000, 3), 10) # ((major, ... | 2016-03/IE-02-representacion-flujos-y-tasas.ipynb | jdvelasq/ingenieria-economica | mit |
En algunos casos es necesario introducir patrones de flujo más complejos. | cf.cashflow(const_value=[0, 1, 2, 2, 4, 5, 6, 7, 8])
## para 5 <= t < 10, el valor es $ 100, y 0 en el resto de los casos
cf.cashflow(const_value=0, nper=15, pyr=1, spec=[(t,100) for t in range(5,10)])
## un flujo escalonado
a = [(t, 100) for t in range( 1, 5)]
b = [(t, 150) for t in range( 6, 10)]
c = [(t, 200) f... | 2016-03/IE-02-representacion-flujos-y-tasas.ipynb | jdvelasq/ingenieria-economica | mit |
From Devito's library of examples we import the following structures: | # NBVAL_IGNORE_OUTPUT
%matplotlib inline
from examples.seismic import TimeAxis
from examples.seismic import RickerSource
from examples.seismic import Receiver
from examples.seismic import plot_velocity
from devito import SubDomain, Grid, NODE, TimeFunction, Function, Eq, solve, Operator | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
The mesh parameters that we choose define the domain $\Omega_{0}$ plus the absorption region. For this, we use the following data: | nptx = 101
nptz = 101
x0 = 0.
x1 = 1000.
compx = x1-x0
z0 = 0.
z1 = 1000.
compz = z1-z0;
hxv = (x1-x0)/(nptx-1)
hzv = (z1-z0)/(nptz-1) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
As we saw previously, HABC has three approach possibilities (A1, A2 and Higdon) and two types of weights (linear and non-linear). So, we insert two control variables. The variable called habctype chooses the type of HABC approach and is such that:
habctype=1 is equivalent to choosing A1;
habctype=2 is equivalent to ch... | habctype = 3
habcw = 2 | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
The number of points of the absorption layer in the directions $x$ and $z$ are given, respectively, by: | npmlx = 20
npmlz = 20 | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
The lengths $L_{x}$ and $L_{z}$ are given, respectively, by: | lx = npmlx*hxv
lz = npmlz*hzv | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
For the construction of the grid we have: | nptx = nptx + 2*npmlx
nptz = nptz + 1*npmlz
x0 = x0 - hxv*npmlx
x1 = x1 + hxv*npmlx
compx = x1-x0
z0 = z0
z1 = z1 + hzv*npmlz
compz = z1-z0
origin = (x0,z0)
extent = (compx,compz)
shape = (nptx,nptz)
spacing = (hxv,hzv) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
As in the case of the acoustic equation with Damping and in the acoustic equation with PML, we can define specific regions in our domain, since the solution $u_{1}(x,z,t)$ is only calculated in the blue region. We will soon follow a similar scheme for creating subdomains as was done on notebooks <a href="02_damping.ipy... | class d0domain(SubDomain):
name = 'd0'
def define(self, dimensions):
x, z = dimensions
return {x: x, z: z}
d0_domain = d0domain() | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
The blue region will be built with 3 divisions:
d1 represents the left range in the direction x, where the pairs $(x,z)$ satisfy: $x\in{0,npmlx}$ and $z\in{0,nptz}$;
d2 represents the rigth range in the direction x, where the pairs $(x,z)$ satisfy: $x\in{nptx-npmlx,nptx}$ and $z\in{0,nptz}$;
d3 represents the left ran... | class d1domain(SubDomain):
name = 'd1'
def define(self, dimensions):
x, z = dimensions
return {x: ('left',npmlx), z: z}
d1_domain = d1domain()
class d2domain(SubDomain):
name = 'd2'
def define(self, dimensions):
x, z = dimensions
return {x: ('right',npmlx), z: z}
d2_doma... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
The figure below represents the division of domains that we did previously:
<img src='domain3.png' width=500>
After we defining the spatial parameters and constructing the subdomains, we then generate the spatial grid and set the velocity field: | grid = Grid(origin=origin, extent=extent, shape=shape, subdomains=(d0_domain,d1_domain,d2_domain,d3_domain), dtype=np.float64)
v0 = np.zeros((nptx,nptz))
X0 = np.linspace(x0,x1,nptx)
Z0 = np.linspace(z0,z1,nptz)
x10 = x0+lx
x11 = x1-lx
z10 = z0
z11 = z1 - lz
xm = 0.5*(x10+x11)
zm = ... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
With the temporal parameters, we generate the time properties with TimeAxis as follows: | time_range = TimeAxis(start=t0,stop=tn,num=ntmax+1)
nt = time_range.num - 1 | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
We set the Ricker source: | f0 = 0.01
nsource = 1
xposf = 0.5*(compx-2*npmlx*hxv)
zposf = hzv
src = RickerSource(name='src',grid=grid,f0=f0,npoint=nsource,time_range=time_range,staggered=NODE,dtype=np.float64)
src.coordinates.data[:, 0] = xposf
src.coordinates.data[:, 1] = zposf | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
We set the receivers: | nrec = nptx
nxpos = np.linspace(x0,x1,nrec)
nzpos = hzv
rec = Receiver(name='rec',grid=grid,npoint=nrec,time_range=time_range,staggered=NODE,dtype=np.float64)
rec.coordinates.data[:, 0] = nxpos
rec.coordinates.data[:, 1] = nzpos | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
The displacement field u and the velocity vel are allocated: | u = TimeFunction(name="u",grid=grid,time_order=2,space_order=2,staggered=NODE,dtype=np.float64)
vel = Function(name="vel",grid=grid,space_order=2,staggered=NODE,dtype=np.float64)
vel.data[:,:] = v0[:,:] | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
We include the source term as src_term using the following command: | src_term = src.inject(field=u.forward,expr=src*dt**2*vel**2) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
The Receivers are again called rec_term: | rec_term = rec.interpolate(expr=u) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
The next step is to generate the $\omega$ weights, which are selected using the habcw variable. Our construction approach will be in two steps: in a first step we build local vectors weightsx and weightsz that represent the weights in the directions $x$ and $z$, respectively. In a second step, with the weightsx and wei... | def generateweights():
weightsx = np.zeros(npmlx)
weightsz = np.zeros(npmlz)
Mweightsx = np.zeros((nptx,nptz))
Mweightsz = np.zeros((nptx,nptz))
if(habcw==1):
for i in range(0,npmlx):
weightsx[i] = (npmlx-i)/(npmlx)
for i in range(0,npmlz):
... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
Once the generateweights function has been created, we execute it with the following command: | Mweightsx,Mweightsz = generateweights(); | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
Below we include a routine to plot the weight fields. | def graph2dweight(D):
plot.figure()
plot.figure(figsize=(16,8))
fscale = 1/10**(-3)
fscale = 10**(-3)
scale = np.amax(D)
extent = [fscale*x0,fscale*x1, fscale*z1, fscale*z0]
fig = plot.imshow(np.transpose(D), vmin=0.,vmax=scale, cmap=cm.seismic, extent=extent)
plot.gca().xaxis.set_... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
Below we include the plot of weights field in $x$ direction. | # NBVAL_IGNORE_OUTPUT
graph2dweight(Mweightsx) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
Below we include the plot of weights field in $z$ direction. | # NBVAL_IGNORE_OUTPUT
graph2dweight(Mweightsz) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
Next we create the fields for the weight arrays weightsx and weightsz: | weightsx = Function(name="weightsx",grid=grid,space_order=2,staggered=NODE,dtype=np.float64)
weightsx.data[:,:] = Mweightsx[:,:]
weightsz = Function(name="weightsz",grid=grid,space_order=2,staggered=NODE,dtype=np.float64)
weightsz.data[:,:] = Mweightsz[:,:] | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
For the discretization of the A2 and Higdon's boundary conditions (to calculate $u_{1}(x,z,t)$) we need information from three time levels, namely $u(x,z,t-1)$, $u (x,z,t)$ and $u(x,z,t+1)$. So it is convenient to create the three fields: | u1 = Function(name="u1" ,grid=grid,space_order=2,staggered=NODE,dtype=np.float64)
u2 = Function(name="u2" ,grid=grid,space_order=2,staggered=NODE,dtype=np.float64)
u3 = Function(name="u3" ,grid=grid,space_order=2,staggered=NODE,dtype=np.float64) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
We will assign to each of them the three time solutions described previously, that is,
u1(x,z) = u(x,z,t-1);
u2(x,z) = u(x,z,t);
u3(x,z) = u(x,z,t+1);
These three assignments can be represented by the stencil01 given by: | stencil01 = [Eq(u1,u.backward),Eq(u2,u),Eq(u3,u.forward)] | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
An update of the term u3(x,z) will be necessary after updating u(x,z,t+1) in the direction $x$, so that we can continue to apply the HABC method. This update is given by stencil02 defined as: | stencil02 = [Eq(u3,u.forward)] | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
For the acoustic equation with HABC without the source term we need in $\Omega$
eq1 = u.dt2 - vel0 * vel0 * u.laplace;
So the pde that represents this equation is given by: | pde0 = Eq(u.dt2 - u.laplace*vel**2) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
And the stencil for pde0 is given to: | stencil0 = Eq(u.forward, solve(pde0,u.forward)) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
For the blue region we will divide it into $npmlx$ layers in the $x$ direction and $npmlz$ layers in the $z$ direction. In this case, the representation is a little more complex than shown in the figures that exemplify the regions $A_{k}$ because there are intersections between the layers.
Observation: Note that the re... | if(habctype==1):
# Region B_{1}
aux1 = ((-vel[x,z]*dt+hx)*u2[x,z] + (vel[x,z]*dt+hx)*u2[x+1,z] + (vel[x,z]*dt-hx)*u3[x+1,z])/(vel[x,z]*dt+hx)
pde1 = (1-weightsx[x,z])*u3[x,z] + weightsx[x,z]*aux1
stencil1 = Eq(u.forward,pde1,subdomain = grid.subdomains['d1'])
# Region B_{3}
aux2 ... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
For the A2 case we have the following pdes and stencils: | if(habctype==2):
# Region B_{1}
cte11 = (1/(2*dt**2)) + (1/(2*dt*hx))*vel[x,z]
cte21 = -(1/(2*dt**2)) + (1/(2*dt*hx))*vel[x,z] - (1/(2*hz**2))*vel[x,z]*vel[x,z]
cte31 = -(1/(2*dt**2)) - (1/(2*dt*hx))*vel[x,z]
cte41 = (1/(dt**2))
cte51 = (1/(4*hz**2))*vel[x,z]**2
aux1 = (cte21*(... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
For the Higdon case we have the following pdes and stencils: | if(habctype==3):
alpha1 = 0.0
alpha2 = np.pi/4
a1 = 0.5
b1 = 0.5
a2 = 0.5
b2 = 0.5
# Region B_{1}
gama111 = np.cos(alpha1)*(1-a1)*(1/dt)
gama121 = np.cos(alpha1)*(a1)*(1/dt)
gama131 = np.cos(alpha1)*(1-b1)*(1/hx)*vel[x,z]
gama141 = np.cos(alpha1)*(b1)*(1/hx)*vel[x,z]
... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
The surface boundary conditions of the problem are the same as in the notebook <a href="01_introduction.ipynb">Introduction to Acoustic Problem</a>. They are placed in the term bc and have the following form: | bc = [Eq(u[t+1,x,0],u[t+1,x,1])] | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
We will then define the operator (op) that will join the acoustic equation, source term, boundary conditions and receivers.
The acoustic wave equation in the d0 region: [stencil01];
Source term: src_term;
Updating solutions over time: [stencil01,stencil02];
The acoustic wave equation in the d1, d2 e d3 r... | # NBVAL_IGNORE_OUTPUT
if(habctype!=2):
op = Operator([stencil0] + src_term + [stencil01,stencil3,stencil02,stencil2,stencil1] + bc + rec_term,subs=grid.spacing_map)
else:
op = Operator([stencil0] + src_term + [stencil01,stencil3,stencil02,stencil2,stencil1,stencil02,stencil4,stencil5] + bc + rec_term,subs=gr... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
Initially: | u.data[:] = 0.
u1.data[:] = 0.
u2.data[:] = 0.
u3.data[:] = 0. | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
We assign to op the number of time steps it must execute and the size of the time step in the local variables time and dt, respectively. | # NBVAL_IGNORE_OUTPUT
op(time=nt,dt=dt0) | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
We view the result of the displacement field at the end time using the graph2d routine given by: | def graph2d(U,i):
plot.figure()
plot.figure(figsize=(16,8))
fscale = 1/10**(3)
x0pml = x0 + npmlx*hxv
x1pml = x1 - npmlx*hxv
z0pml = z0
z1pml = z1 - npmlz*hzv
scale = np.amax(U[npmlx:-npmlx,0:-npmlz])/10.
extent = [fscale*x0pml,fscale*x1pml,fscale*z1pml,fscale*z... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
We plot the Receivers shot records using the graph2drec routine. | def graph2drec(rec,i):
plot.figure()
plot.figure(figsize=(16,8))
fscaled = 1/10**(3)
fscalet = 1/10**(3)
x0pml = x0 + npmlx*hxv
x1pml = x1 - npmlx*hxv
scale = np.amax(rec[:,npmlx:-npmlx])/10.
extent = [fscaled*x0pml,fscaled*x1pml, fscalet*tn, fsca... | examples/seismic/abc_methods/04_habc.ipynb | opesci/devito | mit |
Many machine learning applications involve the processing of highly multidimensional data. More data dimensions usually imply more information to make better predictions. However, a large dimension may state computational problems (the computational load of machine learning algorithms usually grows with the data dimens... | rng = np.random.RandomState(1)
X = np.dot(rng.rand(2, 2), rng.randn(2, 200)).T
plt.scatter(X[:, 0], X[:, 1])
plt.xlabel('$x_0$')
plt.ylabel('$x_1$')
plt.axis('equal')
plt.show() | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
PCA looks for the principal axes in the data, using them as new coordinates to represent the data points.
We can compute this as follows: | from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca.fit(X) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
After fitting PCA to the data, we can read the directions of the new axes (the principal directions) using: | print(pca.components_) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
These directions are unit vectors. We can plot them over the scatter plot of the input data, scaled up by the standard deviation of the data along each direction. The standard deviations can be computed as the square root of the variance along each direction, which is available through | print(pca.explained_variance_) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
The resulting axis plot is the following | def draw_vector(v0, v1, ax=None):
ax = ax or plt.gca()
arrowprops=dict(arrowstyle='->',
linewidth=2,
shrinkA=0, shrinkB=0, color='k')
ax.annotate('', v1, v0, arrowprops=arrowprops)
# plot data
plt.scatter(X[:, 0], X[:, 1], alpha=0.2)
for length, vector in zip(pca.exp... | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
The principal axes of the data can be used as a new basis for the data representation. The principal components of any point are given by the projections of the point onto each principal axes. | # plot principal components
T = pca.transform(X)
plt.scatter(T[:, 0], T[:, 1], alpha=0.2)
plt.axis('equal')
plt.xlabel('component 1')
plt.ylabel('component 2')
plt.title('principal components')
plt.show() | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
Note that PCA is essentially an affine transformation: data is centered around the mean and rotated according to the principal directions. At this point, we can select those directions that may be more relevant for prediction.
2. Mathematical Foundations
(The material in this section is based on Wikipedia: Principal Co... | pca = PCA(n_components=1)
pca.fit(X)
T = pca.transform(X)
print("original shape: ", X.shape)
print("transformed shape:", T.shape) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
and projecting the data over the first principal direction: | X_new = pca.inverse_transform(T)
plt.scatter(X[:, 0], X[:, 1], alpha=0.2)
plt.scatter(X_new[:, 0], X_new[:, 1], alpha=0.8)
plt.axis('equal'); | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
2.2. Computing further components
The error, i.e. the difference between any sample an its projection, is given by
\begin{align}
\hat{\bf x}{k0} &= {\bf x}_k - t{k0} {\bf w}0 = {\bf x}_k - {\bf w}_0 {\bf w}_0^\top \mathbf{x}_k = \
&= ({\bf I} - {\bf w}_0{\bf w}_0^\top ) {\bf x}_k
\end{align}
If we arra... | from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
This dataset contains $8\times 8$ pixel images of digit manuscritps. Thus, each image can be converted into a 64-dimensional vector, and then projected over into two dimensions: | pca = PCA(2) # project from 64 to 2 dimensions
projected = pca.fit_transform(digits.data)
print(digits.data.shape)
print(projected.shape) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
Every image has been tranformed into a 2 dimensional vector, and we can represent them into a scatter plot: | plt.scatter(projected[:, 0], projected[:, 1],
c=digits.target, edgecolor='none', alpha=0.5,
cmap=plt.cm.get_cmap('rainbow', 10))
plt.xlabel('component 1')
plt.ylabel('component 2')
plt.colorbar(); | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
Note that we have just transformed a collection of digital images into a cloud of points, using a different color to represent the points corresponding to the same digit. Note that colors from the same digit tend to be grouped in the same cluster, which suggests that these two components may contain useful information ... | def plot_pca_components(x, coefficients=None, mean=0, components=None,
imshape=(8, 8), n_components=8, fontsize=12,
show_mean=True):
if coefficients is None:
coefficients = x
if components is None:
components = np.eye(len(coefficients), le... | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
PCA provides an alternative basis for the image representation. Using PCA, we can represent each vector as linear combination of the principal direction vectors ${\bf w}0, {\bf w}_1, \cdots, {\bf w}{63}$:
$$
{\bf x} = {\bf m} + \sum_{i=0}^{63} t_i {\bf w}i
$$
and, thus, we can represent the image as the linear combinat... | idx = 25 # Select digit from the dataset
pca = PCA(n_components=10)
Xproj = pca.fit_transform(digits.data)
sns.set_style('white')
fig = plot_pca_components(digits.data[idx], Xproj[idx],
pca.mean_, pca.components_)
| U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
4. Choosing the number of components
The number of components required to approximate the data can be quantified by computing the cumulative explained variance ratio as a function of the number of components: | pca = PCA().fit(digits.data)
plt.plot(np.cumsum(pca.explained_variance_ratio_))
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance');
print(np.cumsum(pca.explained_variance_ratio_)) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
In this curve we can see that the 16 principal components explain more than 86 % of the data variance. 32 out of 64 components explain 96.6 % of the data variance. This suggest that the original data dimension can be substantally reduced.
5. PCA as Noise Filtering
The use of PCA for noise filtering can be illustrated w... | def plot_digits(data):
fig, axes = plt.subplots(4, 10, figsize=(10, 4),
subplot_kw={'xticks':[], 'yticks':[]},
gridspec_kw=dict(hspace=0.1, wspace=0.1))
for i, ax in enumerate(axes.flat):
ax.imshow(data[i].reshape(8, 8),
cmap='b... | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
As we have shown before, the majority of the data variance is concentrated in a fraction of the principal components. Now assume that the dataset is affected by AWGN noise: | np.random.seed(42)
noisy = np.random.normal(digits.data, 4)
plot_digits(noisy) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
It is not difficult to show that, in the noise samples are independent for all pixels, the noise variance over all principal directions is the same. Thus, the principal components with higher variance will be less afected by nose. By removing the compoments with lower variance, we will be removing noise, majoritarily.
... | pca = PCA(0.55).fit(noisy)
pca.n_components_ | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
15 components contain this amount of variance. The corresponding images are shown below: | components = pca.transform(noisy)
filtered = pca.inverse_transform(components)
plot_digits(filtered) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
This is another reason why PCA works well in some prediction problems: by removing the components with less variance, we can be removing mostly noise, keeping the relevant information for a prediction task in the selected components.
6. Example: Eigenfaces
We will see another application of PCA using the Labeled Faces ... | from sklearn.datasets import fetch_lfw_people
faces = fetch_lfw_people(min_faces_per_person=60)
print(faces.target_names)
print(faces.images.shape) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
We will take a look at the first 150 principal components. Because of the large dimensionality of this dataset (close to 3000), we will select the randomized solver for a fast approximation to the first $N$ principal components. | #from sklearn.decomposition import Randomized PCA
pca = PCA(150, svd_solver="randomized")
pca.fit(faces.data) | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
Now, let us visualize the images associated to the eigenvectors of the first principal components (the "eigenfaces"). These are the basis images, and all faces can be approximated as linear combinations of them. | fig, axes = plt.subplots(3, 8, figsize=(9, 4),
subplot_kw={'xticks':[], 'yticks':[]},
gridspec_kw=dict(hspace=0.1, wspace=0.1))
for i, ax in enumerate(axes.flat):
ax.imshow(pca.components_[i].reshape(62, 47), cmap='bone') | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
Note that some eigenfaces seem to be associated to the lighting conditions of the image, an other to specific features of the faces (noses, eyes, mouth, etc).
The cumulative variance shows that 150 components cope with more than 90 % of the variance: | plt.plot(np.cumsum(pca.explained_variance_ratio_))
plt.xlabel('number of components')
plt.ylabel('cumulative explained variance'); | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
We can compare the input images with the images reconstructed from these 150 components: | # Compute the components and projected faces
pca = PCA(150, svd_solver="randomized").fit(faces.data)
components = pca.transform(faces.data)
projected = pca.inverse_transform(components)
# Plot the results
fig, ax = plt.subplots(2, 10, figsize=(10, 2.5),
subplot_kw={'xticks':[], 'yticks':[]},
... | U3.PCA/PCA_professor.ipynb | ML4DS/ML4all | mit |
Explore the Data
The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following:
* airplane
* automobile
* bird
* cat
* deer
* dog
* frog
*... | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import helper
import numpy as np
# Explore the dataset
batch_id = 1
sample_id = 5
helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id) | image-classification/dlnd_image_classification.ipynb | khalido/deep-learning | mit |
Implement Preprocess Functions
Normalize
In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. | def normalize(x):
"""
Normalize a list of sample image data in the range of 0 to 1
: x: List of image data. The image shape is (32, 32, 3)
: return: Numpy array of normalize data
"""
# TODO: Implement Function
return None
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
... | image-classification/dlnd_image_classification.ipynb | khalido/deep-learning | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.