markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
The base row contains the results of the Schur's complement calculation using all observations. The increase in posterior forecast uncertainty for each of the 12 water level observations (e.g. or17c17 is the observation in row 18 column 18) show how much forecast uncertainty increases when that particular observation ... | # a little processing of df_worth
df_base = df_worth.loc["base",:].copy()
df_imax = df_worth.apply(lambda x:x-df_base,axis=1).idxmax()
df_max = 100.0 * (df_worth.apply(lambda x:x-df_base,axis=1).max() / df_base)
df_par = pd.DataFrame([df_imax,df_max],
index=["most important observation",
... | examples/Schurexample_freyberg.ipynb | jtwhite79/pyemu | bsd-3-clause |
We see that observation or27c07_0 is the most important for the water level forecasts (or28c05_0 and or28c05_1), while observation or10c02_0 is the most important for the surface water groundwater exchange forecasts (sw_gw_0 and sw_gw_1). Also, observation or10c02_0) results in a much greater increase in uncertainty fo... | pst.observation_data.index = pst.observation_data.obsnme
new_obs_list = [n for n in pst.observation_data.obsnme.tolist() if n not in la.forecast_names \
and n not in la.pst.nnz_obs_names]
print ("number of potential new obs locations:",len(new_obs_list)) | examples/Schurexample_freyberg.ipynb | jtwhite79/pyemu | bsd-3-clause |
This takes a while since we are evaluating forecast uncertainty for each of the potential obs locations... | from datetime import datetime
start = datetime.now()
df_worth_new_0= la.get_added_obs_importance(base_obslist=la.pst.nnz_obs_names,
obslist_dict=new_obs_list,reset_zero_weight=1.0)
print("took:",datetime.now() - start)
df_worth_new_0.head() | examples/Schurexample_freyberg.ipynb | jtwhite79/pyemu | bsd-3-clause |
Similar to the value of existing data, these results are specific to the forecast of interest. However, when adding potential new observation data, we are looking at how uncertainty will decrease if a proposed observation is added to the 12 water level observations already being used for calibration(this is opposite o... | def postproc_newworth(df_worth_new):
# a little processing of df_worth
df_new_base = df_worth_new.loc["base",:].copy()
df_new_imax = df_worth_new.apply(lambda x:df_base-x,axis=1).idxmax()
df_new_worth = 100.0 * (df_worth_new.apply(lambda x:df_base-x,axis=1) /\
df_new_base)
... | examples/Schurexample_freyberg.ipynb | jtwhite79/pyemu | bsd-3-clause |
Make a function that can display data worth for added observations | def plot_added_importance(df_worth_plot, ml, forecast_name=None,
newlox = None,figsize=(20,15)):
vmax = df_worth_plot[forecast_name].max()
#fig = plt.figure(figsize=(20,15))
fig = plt.figure(figsize=figsize)
axlist = []
# if new locations provided, plot them with the... | examples/Schurexample_freyberg.ipynb | jtwhite79/pyemu | bsd-3-clause |
We can look at the results for each forecast and for each stress period | fig0 = plot_added_importance(df_new_worth_plot_0, ml, 'or28c05_0')
fig1 = plot_added_importance(df_new_worth_plot_0, ml, 'or28c05_1')
fig2 = plot_added_importance(df_new_worth_plot_0, ml, 'sw_gw_0')
fig3 = plot_added_importance(df_new_worth_plot_0, ml, 'sw_gw_1') | examples/Schurexample_freyberg.ipynb | jtwhite79/pyemu | bsd-3-clause |
Load the data from our JSON file.
The data is stored as a dictionary of dictionaries in the json file. We store it that way beacause it's easy to add data to the existing master data file. Also, I haven't figured out how to get it in a database yet. | with open('/Users/mac28/CLCrawler/MasterApartmentData.json') as f:
my_dict = json.load(f)
dframe = DataFrame(my_dict)
dframe = dframe.T
dframe.shape | analysis/Third_Analysis.ipynb | rileyrustad/pdxapartmentfinder | mit |
Create a function that will label each point with a number coresponding to it's neighborhood | def clusterer(X, Y,neighborhoods):
neighbors = []
for i in neighborhoods:
distance = ((i[0]-X)**2 + (i[1]-Y)**2)
neighbors.append(distance)
closest = min(neighbors)
return neighbors.index(closest)
neighborhoodlist = []
for i in dframe.index:
neighborhoodlist.append(clusterer(dframe[... | analysis/Third_Analysis.ipynb | rileyrustad/pdxapartmentfinder | mit |
Here's the new Part. We're breaking out the neighborhood values into their own columns. Now the algorithms can read them as categorical data rather than continuous data. | def column_maker(neighborhoodlist,dframe):
seriesList = [[],[],[],[],[],[],[],[],[],[],[]]
for item,_ in enumerate(seriesList):
for hood in neighborhoodlist:
if hood == item:
seriesList[item].append(1)
else:
seriesList[item].append(0)
return se... | analysis/Third_Analysis.ipynb | rileyrustad/pdxapartmentfinder | mit |
Split data into Training and Testing Data
We're selecting variables now. So far I haven't been able to figure out how to feed in discrete variables. It seems to handle continuous variables just fine. The neighborhood variable is encoded, so I'm assuming that it's being interpreted like a continuous variable.
The Sci-K... | from __future__ import division
print len(dframe)
df2 = dframe[dframe.price < 10000][['bath', 'bed', 'cat', 'content', 'dog', 'feet', 'getphotos', 'hasmap', 'lat', u'long', 'price', 'neighborhood0', 'neighborhood1', 'neighborhood2', 'neighborhood3', 'neighborhood4', 'neighborhood5', 'neighborhood6', 'neighborhood7', 'n... | analysis/Third_Analysis.ipynb | rileyrustad/pdxapartmentfinder | mit |
.83 Woot!
That's about how good we were with random forests last time! Let's see if we can make even better using an ensemble method!
What about Random Forest? | from sklearn.ensemble import RandomForestRegressor
reg = RandomForestRegressor()
reg = reg.fit(features_train, price_train)
forest_pred = reg.predict(features_test)
forest_pred = np.array([[item] for item in forest_pred])
print r2_score(forest_pred, price_test)
plt.scatter(pred,price_test) | analysis/Third_Analysis.ipynb | rileyrustad/pdxapartmentfinder | mit |
Wow! up to .87! That's our best yet! What if we add more trees??? | reg = RandomForestRegressor(n_estimators = 100)
reg = reg.fit(features_train, price_train)
forest_pred = reg.predict(features_test)
forest_pred = np.array([[item] for item in forest_pred])
print r2_score(forest_pred, price_test)
print plt.scatter(pred,price_test) | analysis/Third_Analysis.ipynb | rileyrustad/pdxapartmentfinder | mit |
A python beépített filekezelő függvényei
Ebben a fejezetben a python egyéb moduloktól független, alapvető fileműveleteket biztosító függvényeivel fogunk megismerkedni. Ezen függvények egy file tartalmát többnyire karakterláncok formájában kezelik, ezért konkrét formátumú adatok beolvasása, illetve kiírása némi bonyodal... | file1 = open('data/NAPFOLT/SN_m_tot_V2.0.txt') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A fenti kódsor hatására a file1 változón keresztül férhetünk hozzá a file tartalmához. A file teljes tartalmát például a következő utasítással tölthetjük be egy karakterlánc formájában az egeszfile változóba: | egeszfile=file1.read() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Figyelem, ne keverjük össze a file1 és az egeszfile változókat! Amint azt fent is említettük, az egeszfile egy karakterlánc, a file1 pedig a file-ból való olvasást, illetve a file-ba való írást segítő segédobjektum, amelyet szokás esetenként (adat)folyam-nak vagy angolul streamnek is nevezni.
Ha már minden olvasás és í... | file1.close() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Mivel fent betöltöttük a file tartalmát az egeszfile stringbe, ezért ennek segítségével bele is pillanthatunk, vizsgáljuk meg például az első 100 karaktert a file-ból: | egeszfile[:100] | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ha megnézzük magát a file-t, akkor látható hogy tényleg ezek a dolgok vannak benne. Figyeljük meg hogy a sor vége helyett a \n karakter szerepel!
A read() függvény előre specifikált számú karakter olvasását is lehetővé teszi. Nyissuk meg ismét az előző file-t ismét: | file1 = open('data/NAPFOLT/SN_m_tot_V2.0.txt') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Olvassunk be 10 karaktert a fileból az alábbi módon: | karakterek1=file1.read(10) | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A karakterek1 változó ezután a file első 10 karakterét tartalmazza (vessük össze ezt az egeszfile[:100] parancs kimenetével): | karakterek1 | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ha ismét meghívjuk a file1 változó read() függvényét, akkor az a következő 10 karaktert olvassa be: | karakterek2=file1.read(10)
karakterek2 | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Látjuk tehát hogy a read() utasítás hatására könyörtelenül haladunk végig a file karakterein: úgy tűnhet, ha már egyszer valamit beolvastunk, akkor azt többé már nem tudjuk! Szerencsére ez nem így van, mivel a tell() és a seek() függvények segítségével kérdezhetjük le, illetve állíthatjuk be egy megnyitott filefolyam a... | file1.tell() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A seek() parancs segítségével a file egy teszőleges helyére ugorhatunk. A seek(n) függvény alkalmazásával a file n-edik karakterére ugrunk. Ha ezután alkalmazzuk a read() függvényt, akkor a file tartalmát ettől a poziciótól olvassuk. | file1.seek(5) | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Az alábbi parancs tehát a 5. karaktertől olvas be újabb 10 darab karaktert. | karakterek3=file1.read(10)
karakterek3 | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Zárjuk ismét be a file-t! | file1.close() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Nagyon sok esetben az adatfile-okban hordozott információ táblázatszerűen vannak rendezve. Az file minden sora hasonló tagolással csoportosítja a számunkra értékes adatokat.
Egy megnyitott file minden sorát - mint soronkénti karakterláncok listáját - a readlines függvény segítségével gyárthatjuk le. | file1 = open('data/NAPFOLT/SN_m_tot_V2.0.txt')
sorok = file1.readlines() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Mivel már nincs szükség a a file-ra ezért be is csukjuk azt! | file1.close() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A sorok lista minden eleme most tehát egy egy sor a file-ból, vizsgáljuk meg például az első 10 sort: | sorok[0:10] | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Amint látjuk, az első hat sor a '#' karakterrel kezdődik, és minden ilyen sor azt mondja meg hogy a tényleges adatok megfelelő oszlopa mit tartalmaz. A hetedik sortól lefelé viszont szóközökkel elválasztott számok vannak, ez maga a hőn áhitott adat, de sajnos még mindig karakterláncok formájában!
Az első értékes adats... | sorok[6] | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Egy karakterláncot a split() parancs segítségével adott karakterek mentén fel tudunk vágni egy listába. A split() parancs alapértelmezésben szóközök szerint vágja fel a megjelölt karakterláncot, így az első értékes adatsor oszlopokra szabása az alábbiak szerint történik: | sorok[6].split() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Az eredmény tehát egy lista mely tartalmazza az értékes adatokat, ugyan még mindig karakterláncok formájában!
Az egyes elemeket lebegőpontos számmá a már ismert float() függvénnyel konvertálhatjuk. Tehát az első adatsor negyedik oszlopából a következő módon készíthetünk hús-vér számot: | float(sorok[6].split()[3]) | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ha már egy elemet számmá tudunk konvertálni, akkor egy for ciklus segítségével számokat tartalmazó listákba tudjuk rendezni az adatokat a már megszokott módon: | num_napfolt=[]
meresi_ido=[]
for sor in sorok[6:]:
num_napfolt.append( float(sor.split()[3]) )
meresi_ido.append( float(sor.split()[2]) ) | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ábrázoljuk végül a napfoltok számát az évek függvényében: | plot(meresi_ido,num_napfolt)
xlabel('T[ev]')
ylabel('Napfoltszam') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Mentés
Az adatok beolvasása mellett sokszor lehet szükség a feldolgozott információ újbóli kiírására. Erre a python az adatfolyam típusú változókra alkalmazott write() függvényt kínálja. Vizsgáljuk meg, hogy hogy működik a fileírás, egy egyszerű példán! Nyissunk meg egy file-t, amelybe írni szeretnénk, ezt az open() fü... | file2=open('data/mentes1.dat',mode='w') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A file2 folyamba a write() függvény segítségével tudunk karakterláncokat írni: | file2.write('#Ez az elso kiirt fileom!\n') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A write fügvény alapértelmezett visszatérési értéke a file-ba kiírt karakterek száma. A biztonság kedvéért zárjuk be a file-t! | file2.close() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ha már meglévő file-hoz szeretnénk további karaktereket fűzni, akkor az open() függvény mode paraméterének mode='a' beállításával jelezzük ezt. Az 'a' karakter itt az append angol szó rövidítése, mely ismerős lehet már számunkra egy, a listákra vonatkozó függvény nevéből. | file2=open('data/mentes1.dat',mode='a') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Írjuk ki a mérési idő (meresi_ido) és a napfoltok számát tartalmazó (num_napfolt) adatokat a már fent létrehozott data/mentes1.dat file-ba.
Ezt egy for ciklus segítségével fogjuk megtenni: | for i in range(len(meresi_ido)):
file2.write(str(meresi_ido[i])+' '+str(num_napfolt[i])+'\n') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A write() függvény hasába írt karakterlánc a meresi_ido és num_napfolt tömbök megfelelő sorában lévő elemet tartalmazza szóközzel elválasztva, illetve a sor végét egy sortörés '\n' -el jelezve.
Zárjuk ismét be a file-t: | file2.close() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A beolvasáshoz hasonlóan a kiíratásnál is van lehetőség egész sorok kiírására. Ezt, talán nem túl meglepő módon a writelines() függvény valósítja meg. Ez a függvény karakterláncok listáját írja ki egy file-ba egy megnyitott filefolyamon keresztül. | file3=open('data/mentes2.dat',mode='w') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ha a lista minden karakterlánca '\n' karakterre végződik, akkor a kiíratás során a file-ban minden listaelem egy-egy külön sorba kerül: | sorok=['Ez az elso sor\n','Ez a masodik sor\n'];
file3.writelines(sorok) | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Mi történik, ha lemarad a '\n' ? | sorok=['Ez az harmadik','Ez hova kerult?\n'];
file3.writelines(sorok)
file3.close() | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Vizsgáljuk meg magát a file-t!
Különös karakterek karakterláncokban
A fentiekben már többször is találkoztunk a sortörést jelölő '\n' karakterrel. Ehhez hasonlóan van néhány más úgynevezett literális karakter, amelynek speciális jelentése van. Ezek közül az alábbi táblázatban összefoglalunk néhányat:
karakter | jelent... | print("EZEK ITT NAGYBETUKezek itt kisbetuk")
print("EZEK ITT NAGYBETUK\rezek itt kisbetuk")
print("EZEK ITT NAGYBETUK\tezek itt kisbetuk")
print("EZEK ITT NAGYBETUK\nezek itt kisbetuk") | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ezek a karakterek file-ba való írás közben is hasonlóan viselkednek!
Numpy filekezelő rutinok
Amint korábbiakban is láthattuk, a numpy csomag array típusú változói számos előnyös tulajdonsággal rendelkeznek a sima list típusú változókhoz képest. A numpy csomag biztosít néhány hasznos filekezelő rutint, melyek az array... | baum_data=loadtxt('data/BAUMGARTNER/h_vs_t') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A baum_data tömb első oszlopát a a t változóba, a második oszlopát pedig a h változóba tároljuk: | t=baum_data[:,0] # idő
h=baum_data[:,1] # magasság | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ábrázoljuk az adatokat! A tengelyfeliratok természetesen nem maradhatnak el! | plot(t,h)
xlabel('Ido [s]')
ylabel('Magassag [m]') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Az ugrással kapcsolatban egy igen fontos kérdés volt, hogy vajon sikerült-e szabadesésben átlépni a hangsebességet? Vizsgáljuk meg, hogy ezen adatok alapján vajon átlépte-e Felix Baumgartner a hanghatárt! Először is szükség van a sebesség időfüggésére. Ezt a magasság$--$idő függvény numerikus deriváltjával fogjuk most ... | # numerikus derivált függvény
def nderiv(y,x):
"Első szomszéd differenciál"
n = len(y) # adatpontok száma
d = zeros(n) # változó inicializálás. A zeros() függvény tetszőleges alakú és 0-kat tartalmazó arrayt gyárt
# mivel a legegyszerűbb numerikus differenciálás nem szimmetrikus a végpontokat
# kics... | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
<img src="XA99SXT37G5VNU1K1K8UJRQW04FIOI7A.png"/>
Az nderiv függvény segítségével a sebesség meghatározható. | v=nderiv(h,t) # Figyelem az első változó a h a második a t!!! | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Vizsgáljuk meg a sebesség$--$idő függvényt! | plot(t,v)
xlabel('Ido [s]')
ylabel('Sebesseg [m/s]') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Mivel általában a hang terjedési sebessége függ a magasságtól, ezért annak érdekében, hogy megtudjuk, hogy sikerült-e áttörni a hanghatárt, célszerű a sebességet a magasság függvényében ábrázolni: | plot(h,abs(v))
xlabel('Magassag [m]')
ylabel('Sebesseg [m/s]') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A wikipédián található adatok alapján a hangsebesség 25km magasságban valamivel 300 m/s alatt van. Ezen a magasságon Felix sebessége 350 m/s körül mozgott, tehát a rekord - a mérési adatok alapján - sikerült!
Vizsgáljuk meg a loadtxt() függvény néhány paraméterét is! Ezt a feladatot a 2014-es ebola járvány statisztikai... | ebola_data=loadtxt('data/EBOLA/ebola_vesszoesszazalekjel.txt') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A szemfüles halgatók talán sikeresen ki tudják bogozni a fenti hibaüzenetet:
A '%' jelet nem tudom számmá konvertálni!
Ha megvizsgáljuk magát a file-t, akkor láthatjuk, hogy a napfoltadatoktól eltérő módon itt az adatokat szolgáltató személy a legtöbbször alkalmazott '#'-jel helyett a '%'-ot alkalmazta! Jelezzük ezt a... | ebola_data=loadtxt('data/EBOLA/ebola_vesszoesszazalekjel.txt',comments='%') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ismét hiba üzenet:
a '0,' karakterláncot nem tudom számmá konvertálni !
Ha megnézzük a file-t akkor láthatjuk hogy most szóközök helyett az oszlopok bizony vesszővel, azaz a ','-karakterrel vannak elválasztva! Jelezzük ezt a függvénynek a delimiter=',' kapcsoló segítségével! | ebola_data=loadtxt('data/EBOLA/ebola_vesszoesszazalekjel.txt',comments='%',delimiter=',') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Így most már be tudtuk tölteni a file-t!
A usecols és az unpack kulcsszavak segítségével specifikálhatjuk azt, hogy melyik oszlopokra vagyunk kíváncsiak, illetve hogy kicsomagolható formában térjen vissza a függvény.
Beleolvasva szemmel a file-ba felvilágosítást kaphatunk, hogy melyik oszlopban milyen adat szerepel.
Az... | Nap,GuinLab,LibLab,NigLab,SLLab,SenLab=loadtxt('data/EBOLA/ebola_vesszoesszazalekjel.txt',
comments='%',
usecols=(0,3,6,9,12,15),
unpack=True,
... | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Ábrázoljuk a fenti adatok közzül a Guineában vizsgált fertőzések számát az idő függvényében: | plot(Nap,GuinLab)
xlabel('Nap')
ylabel('Esetek szama') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A már korábban megismert savetxt() függvény segítségével tölthetjük a feldolgozott array formátumú változókat file-ba: | savetxt('data/mentes_ebola_Guinea.dat',GuinLab) | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
A savetxt() a loadtxt() hez hasonlóan számos kulcsszavas paraméterrel bír. Ezek közül az alábbi példában bemutatjuk a header= és a comments= paraméterek használatát.
Az alábbi példa azt is illusztrálja, hogy ha ugyanolyan hosszúságú adatokat akarunk egymás melletti oszlopokba írni akkor azokat zárójelben egymás után fe... | savetxt('data/mentes_ebola_Guinea_vs_time.dat',
(Nap,GuinLab),
header=' Guineai halalozasi adatok',
comments='@') | notebooks/Package05/mintapelda05.ipynb | oroszl/szamprob | gpl-3.0 |
Preprocess
To do anything useful with it, we'll need to turn the characters into a list of integers: | def extract_character_vocab(data):
special_words = ['<pad>', '<unk>', '<s>', '<\s>']
set_words = set([character for line in data.split('\n') for character in line])
int_to_vocab = {word_i: word for word_i, word in enumerate(special_words + list(set_words))}
vocab_to_int = {word: word_i for word_i, wor... | examples/sequence_to_sequence_implementation.ipynb | zhaojijet/UdacityDeepLearningProject | apache-2.0 |
Optimization
Our loss function is tf.contrib.seq2seq.sequence_loss provided by the tensor flow seq2seq module. It calculates a weighted cross-entropy loss for the output logits. | # Loss function
cost = tf.contrib.seq2seq.sequence_loss(
train_logits,
targets,
tf.ones([batch_size, sequence_length]))
# Optimizer
optimizer = tf.train.AdamOptimizer(lr)
# optimizer = tf.train.AdamOptimizer(lr).minim
# Gradient Clipping
gradients = optimizer.compute_gradients(cost)
capped_gradients = [(t... | examples/sequence_to_sequence_implementation.ipynb | zhaojijet/UdacityDeepLearningProject | apache-2.0 |
Two Important Data Structures
Series - a one-dimensional labeled array or list. Like an independant column in a spreadsheet
Dataframe - a two-dimensional labeled table. Like the whole spreadsheet
the Index - Ok, there are THREE important data structures. The index are the labels
Built on top of Numpy
Which is a lo... | # make a list of random numbers
a_python_list = list(np.random.randn(5))
a_python_list
a_pandas_series = pd.Series(data=a_python_list)
a_pandas_series | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
You can see there is the list of random numbers
There is also a list of integers, the index
And there is a data type dype associated with the items in the list | a_simple_index = ['a', 'b', 'c', 'd', 'e']
a_pandas_series = pd.Series(data=a_python_list, index=a_simple_index)
a_pandas_series | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Notice how the index has changed from numbers to letters
we can use the index to extract specific values from the Seres | # index by label
a_pandas_series['a']
# index by location
a_pandas_series[1] | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
you can also create a Series from a python dictionary | a_python_dictionary = {'a' : 0., 'b' : 1., 'c' : 2.}
pd.Series(a_python_dictionary) | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Series are useful for doing fast, "vectorized" operations
Much faster than doing this with Python data structures | a_big_series = pd.Series(np.random.randn(1000))
a_big_series
a_big_series * 2
a_big_series.sum() / len(a_big_series)
a_big_series.mean()
a_big_series.describe() | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Dictionaries
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types.
You can think of it like a spreadsheet or R dataframe
Most popular data structure | a_dictionary = {'one' : [1., 2., 3., 4.],
'two' : [4., 3., 2., 1.]}
a_dataframe = pd.DataFrame(a_dictionary)
a_dataframe
a_dataframe = pd.DataFrame(a_dictionary,
index=['a', 'b', 'c', 'd'])
a_dataframe | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Very commonly you can create a Dataframe from a list of dictionaries | a_list_of_dictionaries = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
a_dataframe = pd.DataFrame(a_list_of_dictionaries)
a_dataframe | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
We can select columns by using python slicing | a_dataframe['a'] | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
This gives us column 'a' as a Series data structure | a_dataframe = pd.DataFrame({'a': np.random.randn(1000),
'b': np.random.randn(1000),
'c': np.random.randn(1000),
'd': np.random.randn(1000),
'e': 'hi'})
a_dataframe
a_dataframe.dtypes
a_dataframe.describe() | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Dataframes are very useful for reading and writing tabular data to disk
We can save this dataframe as a CSV or an Excel spreadsheet | a_dataframe.to_csv("random-data.csv") | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Now go back to the directory tree
You should see a new file called "random-data.csv" | a_dataframe.to_excel("random-data.xls") | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Now you can open your data in excel, how fun! | a_dataframe.to_excel("random-data.xls", index=False)
a_dataframe.to_csv("random-data.csv", index=False) | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Reading data is also super easy | a_new_dataframe = pd.read_csv("random-data.csv")
a_new_dataframe
a_new_dataframe.dtypes | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Plotting with Pandas
One of the other nice features of Pandas is how easy it is to create charts and graphs from Series and Dataframes
This is because of tight integration with Matplotlib, which is the most popular plotting library for python | a_new_dataframe.plot()
a_new_dataframe['a'].plot() | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
There are a lot of options for the plot() function
The pandas documentation for dataframe.plot() has a lot of good information | a_new_dataframe.plot(kind="box")
a_new_dataframe.plot(kind="density")
a_new_dataframe.hist() | intro-to-pandas/pandas-tour.ipynb | DSSatPitt/katz-python-workshop | cc0-1.0 |
Each row in our data represents a movie rating from a user. There are only three columns: user, movie and rating. | movie_data | notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
So What Exactly is Model Parameter Search?
To quickly create a recommender we can simply call the create method of factorization_recommender. We only need to pass it our data and tell it what columns represent: user id, item id and prediction target. That looks like: | model = gl.factorization_recommender.create(movie_data, user_id='user',
item_id='movie', target='rating') | notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
If we did it this way, the default values would be used for all of our training parameters. All of the models in Graphlab Create come with good default values. However no single value will ever be optimal for all data. With just a little work we can find better parameter values and create a more effective model.
In ord... | train_set, validation_set = movie_data.random_split(0.8) | notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
Once we have a model we want to evaluate, We can then evaluate this model with our test_set, by: | evaluation = model.evaluate(validation_set) | notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
In a nutshell, model parameter search trains several different model, each with different values for training parameters, then evaluates each of the models.
Doing a Model Parameter Search
There are a lot of different parameters we could tweak when creating a factorization_recommender. Probably the most important is the... | job = gl.model_parameter_search.create(
(train_set, validation_set),
gl.factorization_recommender.create,
model_parameters = {'user_id': 'user', 'item_id': 'movie', 'target': 'rating', 'num_factors': [4, 5, 6, 7]}
) | notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
By default, the job will run asynchronously in a background process. We can check weather the job has completed by calling job.get_status() | job.get_status() | notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
It will take a few minutes to train and evaluate four models ...... | job.get_status() | notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
Getting the Best Model
Once the job is completed, we can get the results by calling job.get_results(). The results contain two things: all of the models that were created and summary information about each model. The summary information includes the RMSE on the validation set. With a little work we can determine the be... | search_summary= job.get_results()
best_RMSE = search_summary['validation_rmse'].min()
best_model_id = search_summary[search_summary['validation_rmse'] == best_RMSE]['model_id'][0]
| notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
best_model_id will be the best of the four models we searched over.
The more parameters combinations we try the more likely we are to find an even better model. We might want to try a larger range for the number of latent factors. There are other parameter we can tweak too. For example, regularization is another import... | hadoop_cluster = gl.deploy.hadoop_cluster.create(name = '<name of hadoop cluster>',
turi_dist_path = '<distributed path>')
hadoop_conf_dir = '<path to hadoop config dir>')
| notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
To use an EC2 environment with three hosts, create an environment like this: | ec2_config = gl.deploy.Ec2Config(aws_access_key_id = '<my access key>',
aws_secret_access_key = '<my secret key>')
my_env = gl.deploy.ec2_cluster.create('<name for my environment>',
s3_path = 's3://<my bucket name>',
... | notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
Searching over several values for num_factors and regularization, and using our distributed environment, the model_parameter_search call will look like: | job = gl.model_parameter_search.create(
(train_set, validation_set),
gl.factorization_recommender.create,
environment = my_env,
model_parameters = {'user_id': 'user', 'item_id': 'movie', 'target': 'rating', 'num_factors': [4, 5, 6, 7]}
) | notebooks/model_parameter_search.ipynb | dato-code/tutorials | apache-2.0 |
Work around to visualize plot in Jupyter Notebook
This class allow use to use vcsaddons plots | import tempfile
import base64
class VCSAddonsNotebook(object):
def __init__(self, x):
self.x = x
def _repr_png_(self):
fnm = tempfile.mktemp()+".png"
x.png(fnm)
encoded = base64.b64encode(open(fnm, "rb").read())
return encoded
def __call__(self):
return self
... | graphics/ParallelCoordinates.ipynb | UV-CDAT/tutorials | bsd-2-clause |
Sample Data
These files are in the test directory of pcmdi_metrics repo at:
http://github.com/PCMDI/pcmdi_metrics.git | # Prepare list of json files
# Location on your computer
json_pth = "/git/pcmdi_metrics/test/graphics"
# Geenrate list ofjson files
json_files = glob.glob(
os.path.join(
json_pth,
"json",
"v2.0",
"*.json"))
json_files += glob.glob(
... | graphics/ParallelCoordinates.ipynb | UV-CDAT/tutorials | bsd-2-clause |
Let's take a look at the array generated
Note the axis are strings of varialbes used and models
The order of the axes is the order on the plot | rms_xyt.info()
# Ok now let's create a VCS pcoord graphic method
# initialize a canvas
x=vcs.init(geometry=(1200,600),bg=True)
import vcsaddons
gm = vcsaddons.createparallelcoordinates(x=x) | graphics/ParallelCoordinates.ipynb | UV-CDAT/tutorials | bsd-2-clause |
Preparing the plot
Data
'id' is used for variable in plot the JSON class returns var as "pmp", here "RMS" is more appropriate
'title' is used to draw the plot title (location/font controlled by template)
Template
The template section prepares where data will be rendered on plot, and the fonts used
fonts are controlled ... | # Prepare the graphics
# Set variable name
rms_xyt.id = "RMS"
# Set units of each variables on axis
# This is a trick to have units listed on plot
rms_xyt.getAxis(-2).units = ["mm/day","mm/day","hPa","W/m2","W/m2","W/m2", "K","K","K","m/s","m/s","m/s","m/s","m"]
# Sets title on the variable
rms_xyt.title = "Annual Mean... | graphics/ParallelCoordinates.ipynb | UV-CDAT/tutorials | bsd-2-clause |
Control various aspects of the graphic method
We want the first two model to be 'blue' and 'red' and a bit thicker
All other plots will be 'grey' and 'dashed' | x.clear()
gm.linecolors = ["blue","red","grey"]
gm.linestyles=["solid","solid","dot"]
gm.linewidths=[5.,5.,1.]
gm.markercolors = ["blue","red","grey"]
gm.markertypes=["triangle_up","star","dot"]
gm.markersizes=[7,5,2]
gm.plot(rms_xyt,template=t,bg=True)
show()
# change order and number of models and variables
axes = r... | graphics/ParallelCoordinates.ipynb | UV-CDAT/tutorials | bsd-2-clause |
Função iadftmatrix
Synopse
Kernel matrix for the 1-D Discrete Fourier Transform DFT.
A = iadftmatrix(N)
N:Input: Integer, number of points of the DFT.
A:Output image, square N x N, complex | def iadftmatrix(N):
x = np.arange(N).reshape(N,1)
u = x
Wn = np.exp(-1j*2*np.pi/N)
A = (1./np.sqrt(N)) * (Wn ** np.dot(u, x.T))
return A | master/dftmatrixexamples.ipynb | robertoalotufo/ia898 | mit |
Kernel images generated
Imaginary and real parts of the DFT kernel. | A = iadftmatrix(128)
plt.figure(1)
plt.imshow((A.real),cmap='gray')
plt.title('A.real')
plt.colorbar()
plt.figure(2)
plt.imshow((A.imag),cmap='gray')
plt.title('A.imag')
plt.colorbar()
| master/dftmatrixexamples.ipynb | robertoalotufo/ia898 | mit |
Four first lines
Four first lines from real and imaginary parts of the kernel matrix. Observe the increasing frequencies of the senoidals
(imaginary part) and cossenoidals (real part). | plt.figure(1, figsize=(10,10))
plt.subplot(2,2,1)
plt.title('u = 0')
plt.plot(A.real[0,:], 'r')
plt.plot(A.imag[0,:], 'g')
plt.subplot(2,2,2)
plt.title('u = 1')
plt.plot(A.real[1,:], 'r')
plt.plot(A.imag[1,:], 'g')
plt.subplot(2,2,3)
plt.title('u = 2')
plt.plot(A.real[2,:], 'r')
plt.plot(A.imag[2,:], 'g')
plt.subpl... | master/dftmatrixexamples.ipynb | robertoalotufo/ia898 | mit |
Showing complex conjugates | plt.figure(1, figsize=(10,10))
plt.subplot(2,2,1)
plt.title('u = 0')
plt.plot(A.real[ 0,:], 'r')
plt.plot(A.imag[ 0,:], 'g')
plt.subplot(2,2,2)
plt.title('u = -1')
plt.plot(A.real[-1,:], 'r')
plt.plot(A.imag[-1,:], 'g')
plt.subplot(2,2,3)
plt.title('u = -2')
plt.plot(A.real[-2,:], 'r')
plt.plot(A.imag[-2,:], 'g')
p... | master/dftmatrixexamples.ipynb | robertoalotufo/ia898 | mit |
<div class='alert'> Tarea 2. Determinar el radio de los anillos oscuros. </div>
Empleando la imagen anterior vamos a medir el diámetro de los anillos oscuros. Se pueden medir directamente en la pantalla del ordenador o imprimiendo la figura en una hoja de papel. Escribir en la siguiente tabla el diámetro de los anillos... | #INDICAR EL NÚMERO DE ANILLOS MEDIDO
anillos_medidos = 3 ## Indicar aquí el número de anillos medidos
#DESDE AQUÍ NO TOCAAR
######################
from IPython.html import widgets
from IPython.display import display
listwidgets = []
for i in range(anillos_medidos):
listwidgets.append(widgets.FloatTextWidget(de... | Trabajo Anillos de Newton/Anillos_de_Newton_Ejercicio.ipynb | ecabreragranado/OpticaFisicaII | gpl-3.0 |
MNIST数据分成3部分:55,000 个样本用作训练 (mnist.train),10,000张样本用作测试(mnist.test),以及5,000个样本用作验证 (mnist.validation)。这种分割十分重要:在机器学习中我们会挑选一部分数据不用做学习,以确保我们的学习是普适的。
就像之前所说的,每条MNIST样本有两个部分:一张手写数字的图片以及相应的标签。我们可以称之图片“x”和标“y”。训练组和测试组都包含图片及标签;举例来说,训练图片是mnist.train.images,训练标签是mnist.train.labels。
每张图片都是28像素乘28像素。我们可以转换成一大个数组:
我们可以将这个数组扁平化为一个... | import tensorflow as tf | mnist/MNIST_For_ML_Beginners.ipynb | ling7334/tensorflow-get-started | apache-2.0 |
我们操作符号变量以描述这些交互操作,让我们创建一个: | x = tf.placeholder(tf.float32, [None, 784]) | mnist/MNIST_For_ML_Beginners.ipynb | ling7334/tensorflow-get-started | apache-2.0 |
x不是一个特定的值。它是个占位符,当我们让Tensorflow运行时我们会输入数值。我们想要输入任意数量的MNIST图像,每个扁平化为784维向量。将其表示为2维浮点型数值的张量,维度维[None, 784]。(这里None意味着该维可以为任意长度。)
我们的模型还需要权重和偏置。我们可以把这些当作是额外的输入,但Tensorflow有个更好的主意:变量。一个变量是一个存在Tensorflow的交互计算图中的可变的张量。其可被使用甚至修改。对于机器学习程序,一般来说,模型参数是变量。 | W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10])) | mnist/MNIST_For_ML_Beginners.ipynb | ling7334/tensorflow-get-started | apache-2.0 |
我们通过给予tf.Variable初始值以创建这些变量:本例中,我们初始化W和b为全是0的张量。既然我们要学习W和b,它们的初始值并不重要。
注意W的维度是[784, 10],因为我们想要将784维图像向量乘以它以得到10维的证据向量。b的维度是[10],我们可以加到输出中去。
我们现在可以实现我们的模型了,这只需要一行代码! | y = tf.nn.softmax(tf.matmul(x, W) + b) | mnist/MNIST_For_ML_Beginners.ipynb | ling7334/tensorflow-get-started | apache-2.0 |
首先,我们使用tf.matmul(x, W)表达式来将x乘以W。这是从我们的方程中乘以它们的方法翻转出来的,我们有了$W_x$,这是处理具有多个输入的2维张量x的小技巧。然后加b,最后使用tf.nn.softmax。
这就是了。几行设置之后,只用了一行代码来定义我们的模型。这并不是因为Tensorflow被设计为可以特别简单的使用softmax回归:只是描述从机器学习模型到物理模拟的多种数值计算只是一种非常灵活的方式。一旦定义,我们的模型可以在不同的设备上运行:您的计算机的CPU,GPU,甚至手机!
训练
为了训练我们的模型,我们首先需要定义一个指标来评估这个模型是好的。其实,在机器学习,我们通常定义指标来表示一个模型是坏的,这个指... | y_ = tf.placeholder(tf.float32, [None, 10]) | mnist/MNIST_For_ML_Beginners.ipynb | ling7334/tensorflow-get-started | apache-2.0 |
然后我们可以用 $-\sum y'\log(y)$ 计算交叉熵: | cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) | mnist/MNIST_For_ML_Beginners.ipynb | ling7334/tensorflow-get-started | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.