markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
The presented classes and functions are all you need to solve the following exercise. However, there are many other interesting functions that can probably make it easier for you to work with XML files. For more information, please refer to the ElementTree API.
1.1.3. Exercise: Parsing the XML project files
Implement a... | def parse_xmlproject(xml_string):
"""This function processess the specified XML field,
and outputs a dictionary with the desired project information
:xml_string: String with XML content
:Returns: Dictionary with indicated files
"""
#<SOL>
#</SOL>
parse_xmlproject(open(xmlfile,... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
1.2. Building the dataset
Now, we will use the function you just implemented, to create a database that we will use throughout this module.
For simplicity, and given that the dataset is not too large, we will keep all projects in the RAM. The dataset will consist of a list containing the dictionaries associated to each... | # Construct an iterator (or a list) for the years you want to work with
years = range(2015,2017)
datafiles_path = '../data/'
NSF_data = []
for year in years:
zpobj = zp.ZipFile(join(datafiles_path, str(year)+'.zip'))
for fileinzip in zpobj.namelist():
if fileinzip.endswith('xml'):
... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
We will extract some characteristics of the constructed dataset: | print('Number of projects in dataset:', len(NSF_data))
####
budget_data = list(map(lambda x: x['budget'], NSF_data))
print('Average budget of projects in dataset:', np.mean(budget_data))
####
insti_data = list(map(lambda x: x['institution'], NSF_data))
print('Number of unique institutions in dataset:', len(set(insti_... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
Exercise
Compute the average length of the abstracts of all projects in the dataset | #<SOL>
#</SOL> | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
2. Corpus Processing
Topic modelling algorithms process vectorized data. In order to apply them, we need to transform the raw text input data into a vector representation. To do so, we will remove irrelevant information from the text data and preserve as much relevant information as possible to capture the semantic con... | import nltk
# You should comment this code fragment if the package is already available.
# Select option "d) Download", and identifier "punkt"
# nltk.download() | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
We will create a list that contains just the abstracts in the dataset. As the order of the elements in a list is fixed, it will be later straightforward to match the processed abstracts to metadata associated to their corresponding projects. | from nltk.tokenize import word_tokenize
NSF_abstracts = list(map(lambda x: x['abstract'], NSF_data))
tokenized_abstracts = []
nprojects = len(NSF_abstracts)
for n, abstract in enumerate(NSF_abstracts):
if not n%100:
print('\rTokenizing abstract', n, 'out of', nprojects, end='', flush=True)
tokenized_... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
2.2. Homogeneization
By looking at the tokenized corpus you may verify that there are many tokens that correspond to punktuation signs and other symbols that are not relevant to analyze the semantic content. They can be removed using the stemming or lemmatization tools from nltk.
The homogeneization process will consis... | filtered_abstracts = []
for n, abstract in enumerate(tokenized_abstracts):
if not n%100:
print('\rFiltering abstract', n, 'out of', nprojects, end='', flush=True)
#<SOL>
#</SOL>
print('\n',filtered_abstracts[0]) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
2.2.1. Stemming vs Lemmatization
At this point, we can choose between applying a simple stemming or ussing lemmatization. We will try both to test their differences.
The lemmatizer from NLTK is based on WordNet. If you have not used wordnet before, you will likely need to download it from nltk (use the nltk.download() ... | stemmer = nltk.stem.SnowballStemmer('english')
from nltk.stem import WordNetLemmatizer
wnl = WordNetLemmatizer()
print('Result for the first abstract in dataset applying stemming')
print([stemmer.stem(el) for el in filtered_abstracts[0]])
print('Result for the first abstract in the dataset applying lemmatization')
pr... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
One of the advantages of the lemmatizer method is that the result of lemmmatization is still a true word, which is more advisable for the presentation of text processing results and lemmatization.
However, without using contextual information, lemmatize() does not remove grammatical differences. This is the reason why ... | lemmatized_abstracts = []
for n, abstract in enumerate(filtered_abstracts):
if not n%100:
print('\rLemmatizing abstract', n, 'out of', nprojects, end='', flush=True)
#<SOL>
#</SOL>
print('Result for the first abstract in the dataset applying lemmatization')
print('\n',lemmatized_abstracts[0]) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
2.3. Cleaning
The third step consists of removing those words that are very common in language and do not carry out usefull semantic content (articles, pronouns, etc).
Once again, we might need to load the stopword files using the download tools from nltk
Exercise
In the second line below we read a list of common engli... | from nltk.corpus import stopwords
stopwords_en = stopwords.words('english')
clean_abstracts = []
for n, abstract in enumerate(lemmatized_abstracts):
if not n%100:
print('\rCleaning abstract', n, 'out of', nprojects, end='', flush=True)
# Remove all tokens in the stopwords list and append the ... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
2.4. Vectorization
Up to this point, we have transformed the raw text collection of articles in a list of articles, where each article is a collection of the word roots that are most relevant for semantic analysis. Now, we need to convert these data (a list of token lists) into a numerical representation (a list of vec... | import gensim
# Create dictionary of tokens
D = gensim.corpora.Dictionary(clean_abstracts)
n_tokens = len(D)
print('The dictionary contains', n_tokens, 'terms')
print('First terms in the dictionary:')
for n in range(10):
print(str(n), ':', D[n]) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
We can also filter out terms that appear in too few or too many of the documents in the dataset: | no_below = 5 #Minimum number of documents to keep a term in the dictionary
no_above = .75 #Maximum proportion of documents in which a term can appear to be kept in the dictionary
D.filter_extremes(no_below=no_below,no_above=no_above, keep_n=25000)
n_tokens = len(D)
print('The dictionary contains', n_tokens, 'terms')
... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
In the second step, let us create a numerical version of our corpus using the doc2bow method. In general, D.doc2bow(token_list) transforms any list of tokens into a list of tuples (token_id, n), one per each token in token_list, where token_id is the token identifier (according to dictionary D) and n is the number of o... | corpus_bow = [D.doc2bow(doc) for doc in clean_abstracts] | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
At this point, it is good to make sure to understand what has happened. In clean_abstracts we had a list of token lists. With it, we have constructed a Dictionary, D, which assigns an integer identifier to each token in the corpus.
After that, we have transformed each article (in clean_abstracts) in a list tuples (id, ... | print('Original article (after cleaning):')
print(clean_abstracts[0])
print('Sparse vector representation (first 10 components):')
print(corpus_bow[0][:10])
print('Word counts for the first project (first 10 components):')
print(list(map(lambda x: (D[x[0]], x[1]), corpus_bow[0][:10]))) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
Note that we can interpret each element of corpus_bow as a sparse_vector. For example, a list of tuples
[(0, 1), (3, 3), (5,2)]
for a dictionary of 10 elements can be represented as a vector, where any tuple (id, n) states that position id must take value n. The rest of positions must be zero.
[1, 0, 0, 3, 0, 2, 0, 0... | all_counts = [(D[el], D.dfs[el]) for el in D.dfs]
all_counts = sorted(all_counts, key=lambda x: x[1]) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
3. Topic Modeling
3.1. Training a topic model using Gensim LDA
Since we already have computed the dictionary and documents BoW representation using Gensim, computing the topic model is straightforward using the LdaModel() function. Please, refer to Gensim API documentation for more information on the different paramete... | import gensim
num_topics = 50
ldag = gensim.models.ldamodel.LdaModel(corpus=corpus_bow, id2word=D, num_topics=num_topics) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
3.2. LDA model visualization
Gensim provides a basic visualization of the obtained topics: | ldag.print_topics(num_topics=-1, num_words=10) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
A more useful visualization is provided by the python LDA visualization library, pyLDAvis.
Before executing the next code fragment you need to install pyLDAvis:
>> pip install (--user) pyLDAvis | import pyLDAvis.gensim as gensimvis
import pyLDAvis
vis_data = gensimvis.prepare(ldag, corpus_bow, D)
pyLDAvis.display(vis_data) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
3.3. Gensim utility functions
In addition to visualization purposes, topic models are useful to obtain a semantic representation of documents that can later be used with some other purpose:
In document classification problems
In content-based recommendations systems
Essentially, the idea is that the topic model provi... | ldag.get_topic_terms(topicid=0)
ldag.get_document_topics(corpus_bow[0]) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
An alternative to the use of the get_document_topics() function is to directly transform a dataset using the ldag object as follows. You can apply this transformation to several documents at once, but then the result is an iterator from which you can build the corresponding list if necessary | print(ldag[corpus_bow[0]])
print('When applied to a dataset it will provide an iterator')
print(ldag[corpus_bow[:3]])
print('We can rebuild the list from the iterator with a one liner')
print([el for el in ldag[corpus_bow[:3]]]) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
Finally, Gensim provides some useful functions to convert between formats, and to simplify interaction with numpy and scipy. The following code fragment converts a corpus in sparse format to a full numpy matrix | reduced_corpus = [el for el in ldag[corpus_bow[:3]]]
reduced_corpus = gensim.matutils.corpus2dense(reduced_corpus, num_topics).T
print(reduced_corpus) | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
Exercise
Build a function that returns the most relevant projects for a given topic | def most_relevant_projects(ldag, topicid, corpus_bow, nprojects=10):
"""This function returns the most relevant projects in corpus_bow
: ldag: The trained topic model object provided by gensim
: topicid: The topic for which we want to find the most relevant documents
: corpus_bow: The BoW represent... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
Exercise
Build a function that computes the semantic distance between two documents. For this, you can use the functions (or code fragments) provided in the library dist_utils.py. | def pairwase_dist(doc1, doc2):
"""This function returns the Jensen-Shannon
distance between the corresponding vectors of the documents
: doc1: Semantic representation for the doc1 (a vector of length ntopics)
: doc2: Semantic representation for the doc2 (a vector of length ntopics)
: Returns: ... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
Function that creates the Node CSV file for Gephi | #print(NSF_data[0].keys())
#print(NSF_data[0]['institution'])
def strNone(str_to_convert):
if str_to_convert is None:
return ''
else:
return str_to_convert
with open('NSF_nodes.csv','w') as fout:
fout.write('Id;Title;Year;Budget;UnivName;UnivZIP;State\n')
for project in NSF_data:
... | TM4.DTUCourse/notebook/DTU02901_student.ipynb | ML4DS/ML4all | mit |
2. Uso de Pandas para descargar datos de precios de cierre
Ahora, en forma de función | def get_historical_closes(ticker, start_date, end_date):
p = web.DataReader(ticker, "yahoo", start_date, end_date).sort_index('major_axis')
d = p.to_frame()['Adj Close'].reset_index()
d.rename(columns={'minor': 'Ticker', 'Adj Close': 'Close'}, inplace=True)
pivoted = d.pivot(index='Date', columns='Ticke... | 02. Parte 2/15. Clase 15/.ipynb_checkpoints/04Class NB-checkpoint.ipynb | jdsanch1/SimRC | mit |
Una vez cargados los paquetes, es necesario definir los tickers de las acciones que se usarán, la fuente de descarga (Yahoo en este caso, pero también se puede desde Google) y las fechas de interés. Con esto, la función DataReader del paquete pandas_datareader bajará los precios solicitados.
Nota: Usualmente, las distr... | closes=get_historical_closes(['AA','AAPL','MSFT','KO'], '2010-01-01', '2016-12-31')
closes
closes.plot(figsize=(8,6)); | 02. Parte 2/15. Clase 15/.ipynb_checkpoints/04Class NB-checkpoint.ipynb | jdsanch1/SimRC | mit |
Nota: Para descargar datos de la bolsa mexicana de valores (BMV), el ticker debe tener la extensión MX.
Por ejemplo: MEXCHEM.MX, LABB.MX, GFINBURO.MX y GFNORTEO.MX.
3. Formulación del riesgo de un portafolio | def calc_daily_returns(closes):
return np.log(closes/closes.shift(1))[1:]
daily_returns=calc_daily_returns(closes)
daily_returns.plot(figsize=(8,6));
daily_returns.corr()
def calc_annual_returns(daily_returns):
grouped = np.exp(daily_returns.groupby(lambda date: date.year).sum())-1
return grouped
annual... | 02. Parte 2/15. Clase 15/.ipynb_checkpoints/04Class NB-checkpoint.ipynb | jdsanch1/SimRC | mit |
4. Optimización de portafolios | def f(x): return 2+x**2
scopt.fmin(f, 10)
def negative_sharpe_ratio_n_minus_1_stock(weights,returns,risk_free_rate):
"""
Given n-1 weights, return a negative sharpe ratio
"""
weights2 = sp.append(weights, 1-np.sum(weights))
return -sharpe_ratio(returns, weights2, risk_free_rate)
def optimize_port... | 02. Parte 2/15. Clase 15/.ipynb_checkpoints/04Class NB-checkpoint.ipynb | jdsanch1/SimRC | mit |
5. ETF | etf=get_historical_closes(['PICK','IBB','XBI','MLPX','AMLP','VGT','RYE','IEO','AAPL'], '2014-01-01', '2014-12-31')
etf.plot(figsize=(8,6));
daily_returns_etf=calc_daily_returns(etf)
daily_returns_etf
daily_returns_etf_mean=1000*daily_returns_etf.mean()
daily_returns_etf_mean
daily_returns_etf_std=daily_returns_etf.s... | 02. Parte 2/15. Clase 15/.ipynb_checkpoints/04Class NB-checkpoint.ipynb | jdsanch1/SimRC | mit |
Plot Fused-gromov-Wasserstein
This example illustrates the computation of FGW for 1D measures[18].
.. [18] Vayer Titouan, Chapel Laetitia, Flamary R{'e}mi, Tavenard Romain
and Courty Nicolas
"Optimal Transport for structured data with application on graphs"
International Conference on Machine Learning (IC... | # Author: Titouan Vayer <titouan.vayer@irisa.fr>
#
# License: MIT License
import matplotlib.pyplot as pl
import numpy as np
import ot
from ot.gromov import gromov_wasserstein, fused_gromov_wasserstein | notebooks/plot_fgw.ipynb | rflamary/POT | mit |
Generate data | #%% parameters
# We create two 1D random measures
n = 20 # number of points in the first distribution
n2 = 30 # number of points in the second distribution
sig = 1 # std of first distribution
sig2 = 0.1 # std of second distribution
np.random.seed(0)
phi = np.arange(n)[:, None]
xs = phi + sig * np.random.randn(n, ... | notebooks/plot_fgw.ipynb | rflamary/POT | mit |
Plot data | #%% plot the distributions
pl.close(10)
pl.figure(10, (7, 7))
pl.subplot(2, 1, 1)
pl.scatter(ys, xs, c=phi, s=70)
pl.ylabel('Feature value a', fontsize=20)
pl.title('$\mu=\sum_i \delta_{x_i,a_i}$', fontsize=25, usetex=True, y=1)
pl.xticks(())
pl.yticks(())
pl.subplot(2, 1, 2)
pl.scatter(yt, xt, c=phi2, s=70)
pl.xlab... | notebooks/plot_fgw.ipynb | rflamary/POT | mit |
Create structure matrices and across-feature distance matrix | #%% Structure matrices and across-features distance matrix
C1 = ot.dist(xs)
C2 = ot.dist(xt)
M = ot.dist(ys, yt)
w1 = ot.unif(C1.shape[0])
w2 = ot.unif(C2.shape[0])
Got = ot.emd([], [], M) | notebooks/plot_fgw.ipynb | rflamary/POT | mit |
Plot matrices | #%%
cmap = 'Reds'
pl.close(10)
pl.figure(10, (5, 5))
fs = 15
l_x = [0, 5, 10, 15]
l_y = [0, 5, 10, 15, 20, 25]
gs = pl.GridSpec(5, 5)
ax1 = pl.subplot(gs[3:, :2])
pl.imshow(C1, cmap=cmap, interpolation='nearest')
pl.title("$C_1$", fontsize=fs)
pl.xlabel("$k$", fontsize=fs)
pl.ylabel("$i$", fontsize=fs)
pl.xticks(l_x)... | notebooks/plot_fgw.ipynb | rflamary/POT | mit |
Compute FGW/GW | #%% Computing FGW and GW
alpha = 1e-3
ot.tic()
Gwg, logw = fused_gromov_wasserstein(M, C1, C2, p, q, loss_fun='square_loss', alpha=alpha, verbose=True, log=True)
ot.toc()
#%reload_ext WGW
Gg, log = gromov_wasserstein(C1, C2, p, q, loss_fun='square_loss', verbose=True, log=True) | notebooks/plot_fgw.ipynb | rflamary/POT | mit |
Visualize transport matrices | #%% visu OT matrix
cmap = 'Blues'
fs = 15
pl.figure(2, (13, 5))
pl.clf()
pl.subplot(1, 3, 1)
pl.imshow(Got, cmap=cmap, interpolation='nearest')
#pl.xlabel("$y$",fontsize=fs)
pl.ylabel("$i$", fontsize=fs)
pl.xticks(())
pl.title('Wasserstein ($M$ only)')
pl.subplot(1, 3, 2)
pl.imshow(Gg, cmap=cmap, interpolation='neare... | notebooks/plot_fgw.ipynb | rflamary/POT | mit |
Callback for RNN training
Callback that uses the outputs of language models to add AR and TAR regularization | #|export
@docs
class ModelResetter(Callback):
"`Callback` that resets the model at each validation/training step"
def before_train(self): self.model.reset()
def before_validate(self): self.model.reset()
def after_fit(self): self.model.reset()
_docs = dict(before_train="Reset the model befor... | nbs/34_callback.rnn.ipynb | fastai/fastai | apache-2.0 |
Export - | #|hide
from nbdev.export import notebook2script
notebook2script() | nbs/34_callback.rnn.ipynb | fastai/fastai | apache-2.0 |
Your First HARK Model: Perfect Foresight
We start with almost the simplest possible consumption model: A consumer with CRRA utility
\begin{equation}
U(C) = \frac{C^{1-\rho}}{1-\rho}
\end{equation}
has perfect foresight about everything except the (stochastic) date of death, which occurs with constant probability imply... | from HARK.ConsumptionSaving.ConsIndShockModel import PerfForesightConsumerType | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
The $\texttt{PerfForesightConsumerType}$ class contains within itself the python code that constructs the solution for the perfect foresight model we are studying here, as specifically articulated in these lecture notes.
To create an instance of $\texttt{PerfForesightConsumerType}$, we simply call the class as if it ... | # This cell defines a parameter dictionary. You can expand it if you want to see what that looks like.
PF_dictionary = {
'CRRA' : 2.5,
'DiscFac' : 0.96,
'Rfree' : 1.03,
'LivPrb' : [0.98],
'PermGroFac' : [1.01],
'T_cycle' : 1,
'cycles' : 0,
'AgentCount' : 10000
}
# To those curious enoug... | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
Let's make an object named $\texttt{PFexample}$ which is an instance of the $\texttt{PerfForesightConsumerType}$ class. The object $\texttt{PFexample}$ will bundle together the abstract mathematical description of the solution embodied in $\texttt{PerfForesightConsumerType}$, and the specific set of parameter values de... | PFexample = PerfForesightConsumerType(**PF_dictionary)
# the asterisks ** basically say "here come some arguments" to PerfForesightConsumerType | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
In $\texttt{PFexample}$, we now have defined the problem of a particular infinite horizon perfect foresight consumer who knows how to solve this problem.
Solving an Agent's Problem
To tell the agent actually to solve the problem, we call the agent's $\texttt{solve}$ method. (A method is essentially a function that an... | PFexample.solve() | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
Running the $\texttt{solve}$ method creates the attribute of $\texttt{PFexample}$ named $\texttt{solution}$. In fact, every subclass of $\texttt{AgentType}$ works the same way: The class definition contains the abstract algorithm that knows how to solve the model, but to obtain the particular solution for a specific i... | PFexample.solution[0].cFunc | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
One of the results proven in the associated the lecture notes is that, for the specific problem defined above, there is a solution in which the ratio $c = C/P$ is a linear function of the ratio of market resources to permanent income, $m = M/P$.
This is why $\texttt{cFunc}$ can be represented by a linear interpolatio... | mPlotTop=10
plot_funcs(PFexample.solution[0].cFunc,0.,mPlotTop) | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
The figure illustrates one of the surprising features of the perfect foresight model: A person with zero money should be spending at a rate more than double their income (that is, $\texttt{cFunc}(0.) \approx 2.08$ - the intersection on the vertical axis). How can this be?
The answer is that we have not incorporated an... | humanWealth = PFexample.solution[0].hNrm
mMinimum = PFexample.solution[0].mNrmMin
print("This agent's human wealth is " + str(humanWealth) + ' times his current income level.')
print("This agent's consumption function is defined (consumption is positive) down to m_t = " + str(mMinimum)) | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
Yikes! Let's take a look at the bottom of the consumption function. In the cell below, the bounds of the plot_funcs function are set to display down to the lowest defined value of the consumption function. | plot_funcs(PFexample.solution[0].cFunc,
mMinimum,
mPlotTop) | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
Changing Agent Parameters
Suppose you wanted to change one (or more) of the parameters of the agent's problem and see what that does. We want to compare consumption functions before and after we change parameters, so let's make a new instance of $\texttt{PerfForesightConsumerType}$ by copying $\texttt{PFexample}$. | NewExample = deepcopy(PFexample) | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
You can assign new parameters to an AgentType with the assign_parameter method. For example, we could make the new agent less patient: | NewExample.assign_parameters(DiscFac = 0.90)
NewExample.solve()
mPlotBottom = mMinimum
plot_funcs([PFexample.solution[0].cFunc,
NewExample.solution[0].cFunc],
mPlotBottom,
mPlotTop) | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
(Note that you can pass a list of functions to plot_funcs as the first argument rather than just a single function. Lists are written inside of [square brackets].)
Let's try to deal with the "problem" of massive human wealth by making another consumer who has essentially no future income. We can virtually eliminate hu... | # Revert NewExample's discount factor and make his future income minuscule
# print("your lines here")
# Compare the old and new consumption functions
plot_funcs([PFexample.solution[0].cFunc,NewExample.solution[0].cFunc],0.,10.) | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
Now $\texttt{NewExample}$'s consumption function has the same slope (MPC) as $\texttt{PFexample}$, but it emanates from (almost) zero-- he has basically no future income to borrow against!
If you'd like, use the cell above to alter $\texttt{NewExample}$'s other attributes (relative risk aversion, etc) and see how the c... | # This cell defines a parameter dictionary for making an instance of IndShockConsumerType.
IndShockDictionary = {
'CRRA': 2.5, # The dictionary includes our original parameters...
'Rfree': 1.03,
'DiscFac': 0.96,
'LivPrb': [0.98],
'PermGroFac': [1.01],
'PermShkStd': [0.1], # ... and th... | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
As before, we need to import the relevant subclass of $\texttt{AgentType}$ into our workspace, then create an instance by passing the dictionary to the class as if the class were a function. | from HARK.ConsumptionSaving.ConsIndShockModel import IndShockConsumerType
IndShockExample = IndShockConsumerType(**IndShockDictionary) | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
Now we can solve our new agent's problem just like before, using the $\texttt{solve}$ method. | IndShockExample.solve()
plot_funcs(IndShockExample.solution[0].cFunc,0.,10.) | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
Changing Constructed Attributes
In the parameter dictionary above, we chose values for HARK to use when constructing its numeric representation of $F_t$, the joint distribution of permanent and transitory income shocks. When $\texttt{IndShockExample}$ was created, those parameters ($\texttt{TranShkStd}$, etc) were used... | OtherExample = deepcopy(IndShockExample) # Make a copy so we can compare consumption functions
OtherExample.assign_parameters(PermShkStd = [0.2]) # Double permanent income risk (note that it's a one element list)
OtherExample.update_income_process() # Call the method to reconstruct the representation ... | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
In the cell below, use your blossoming HARK skills to plot the consumption function for $\texttt{IndShockExample}$ and $\texttt{OtherExample}$ on the same figure. | # Use the line(s) below to plot the consumptions functions against each other | examples/Gentle-Intro/Gentle-Intro-To-HARK.ipynb | econ-ark/HARK | apache-2.0 |
You will more than likely want to plot some things. In the notebook environment, this can be done in different ways. I typically choose an inline plot. However, you can also have images from matplotlib run as separate windows or as interactive objects within the notebook. | # special IPython command to prepare the notebook for matplotlib
#interactive plotting in separate window
#%matplotlib qt
#interactive charts inside notebooks, matplotlib 1.4+
#%matplotlib notebook
#normal charts inside notebooks
%matplotlib inline | sessions/01-introduction/Five Minute Notebook.ipynb | privong/pythonclub | gpl-3.0 |
So what to do first? Lets download some Gaia file. | #This cell will download some gaia data file to your pwd
import urllib2
import gzip
some_zipped_gaia_file = urllib2.urlopen('http://cdn.gea.esac.esa.int/Gaia/gaia_source/csv/GaiaSource_000-010-207.csv.gz')
some_gaia_file_saved = open('GaiaSource_000-010-207.csv.gz','wb')
some_gaia_file_saved.write(some_zipped_gaia_file... | sessions/01-introduction/Five Minute Notebook.ipynb | privong/pythonclub | gpl-3.0 |
<br>
<br>
Sections
Dealing with missing data
Eliminating samples or features with missing values
Imputing missing values
Understanding the scikit-learn estimator API
Handling categorical data
Mapping ordinal features
Encoding class labels
Performing one-hot encoding on nominal features
Partitioning a dataset in tr... | import pandas as pd
from io import StringIO
csv_data = '''A,B,C,D
1.0,2.0,3.0,4.0
5.0,6.0,,8.0
10.0,11.0,12.0,'''
# If you are using Python 2.7, you need
# to convert the string to unicode:
# csv_data = unicode(csv_data)
df = pd.read_csv(StringIO(csv_data))
df
df.isnull().sum() | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Eliminating samples or features with missing values
[back to top] | df.dropna()
df.dropna(axis=1)
# only drop rows where all columns are NaN
df.dropna(how='all')
# drop rows that have not at least 4 non-NaN values
df.dropna(thresh=4)
# only drop rows where NaN appear in specific columns (here: 'C')
df.dropna(subset=['C']) | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Imputing missing values | from sklearn.preprocessing import Imputer
imr = Imputer(missing_values='NaN', strategy='mean', axis=0)
imr = imr.fit(df)
imputed_data = imr.transform(df.values)
imputed_data
df.values | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Handling categorical data
[back to top] | import pandas as pd
df = pd.DataFrame([
['green', 'M', 10.1, 'class1'],
['red', 'L', 13.5, 'class2'],
['blue', 'XL', 15.3, 'class1']])
df.columns = ['color', 'size', 'price', 'classlabel']
df | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Mapping ordinal features
[back to top] | size_mapping = {
'XL': 3,
'L': 2,
'M': 1}
df['size'] = df['size'].map(size_mapping)
df
inv_size_mapping = {v: k for k, v in size_mapping.items()}
df['size'].map(inv_size_mapping) | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Encoding class labels
[back to top] | import numpy as np
class_mapping = {label:idx for idx,label in enumerate(np.unique(df['classlabel']))}
class_mapping
df['classlabel'] = df['classlabel'].map(class_mapping)
df
inv_class_mapping = {v: k for k, v in class_mapping.items()}
df['classlabel'] = df['classlabel'].map(inv_class_mapping)
df
from sklearn.prepr... | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Performing one-hot encoding on nominal features
[back to top] | X = df[['color', 'size', 'price']].values
color_le = LabelEncoder()
X[:, 0] = color_le.fit_transform(X[:, 0])
X
from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder(categorical_features=[0])
ohe.fit_transform(X).toarray()
pd.get_dummies(df[['price', 'color', 'size']]) | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Partitioning a dataset in training and test sets
[back to top] | df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None)
df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash',
'Alcalinity of ash', 'Magnesium', 'Total phenols',
'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins',
'Color intensity', 'Hue', 'OD28... | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Bringing features onto the same scale
[back to top] | from sklearn.preprocessing import MinMaxScaler
mms = MinMaxScaler()
X_train_norm = mms.fit_transform(X_train)
X_test_norm = mms.transform(X_test)
from sklearn.preprocessing import StandardScaler
stdsc = StandardScaler()
X_train_std = stdsc.fit_transform(X_train)
X_test_std = stdsc.transform(X_test) | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
A visual example: | ex = pd.DataFrame([0, 1, 2 ,3, 4, 5])
# standardize
ex[1] = (ex[0] - ex[0].mean()) / ex[0].std()
# normalize
ex[2] = (ex[0] - ex[0].min()) / (ex[0].max() - ex[0].min())
ex.columns = ['input', 'standardized', 'normalized']
ex | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Selecting meaningful features
[back to top]
<br>
<br>
Sparse solutions with L1-regularization
[back to top] | from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(penalty='l1', C=0.1)
lr.fit(X_train_std, y_train)
print('Training accuracy:', lr.score(X_train_std, y_train))
print('Test accuracy:', lr.score(X_test_std, y_test))
lr.intercept_
lr.coef_
import matplotlib.pyplot as plt
%matplotlib inline
f... | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Sequential feature selection algorithms
[back to top] | from sklearn.base import clone
from itertools import combinations
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
class SBS():
def __init__(self, estimator, k_features, scoring=accuracy_score,
test_size=0.25, random_state=1):
... | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
<br>
<br>
Assessing Feature Importances with Random Forests
[back to top] | from sklearn.ensemble import RandomForestClassifier
feat_labels = df_wine.columns[1:]
forest = RandomForestClassifier(n_estimators=10000,
random_state=0,
n_jobs=-1)
forest.fit(X_train, y_train)
importances = forest.feature_importances_
indices = np.arg... | TextExamples/3547_04_Code.ipynb | southpaw94/MachineLearning | gpl-2.0 |
Load USGS data into a dataframe | # Use HydroCloud.org to find a stream gauge to investigate.
# Click on the red points to find the site number.
from IPython.display import HTML
HTML('<iframe src=http://hydrocloud.org/ width=700 height=400></iframe>')
# Create a Pandas dataframe using the USGS daily discharge for Herring Run.
herring = hp.get_usgs('01... | Analyze_USGS_data.ipynb | stijnvanhoey/hydropy | bsd-2-clause |
Multiples
Print all the multiples of 3 from 0 to 25 that are not multiples of 5 or 7. | for n in range(26):
#Finish | notebooks/2_0_Loops.ipynb | rcrehuet/Python_for_Scientists_2017 | gpl-3.0 |
Now, instead of printing, generate a list of all the multiples of 3 from 0 to 25 that are not multiples of 5 or 7.
Messing with loops
What do you expect this loop to do? Check it. | for i in range(10):
print('before:', i)
if i==3 or i==7: i=i+2 #Tying to skip values 4 and 8...
print('after: ',i)
print('----------') | notebooks/2_0_Loops.ipynb | rcrehuet/Python_for_Scientists_2017 | gpl-3.0 |
From the previous example you should deduce that it is better not to modify the loop variable. So now translate the previous incorrect loop into into a while loop that really skips i==4 and i==8.
Queuing system
You have a list that should act as a kind of queueing system:
queue=['Mariona','Ramon', 'Joan', 'Quique', 'La... | queue=['Mariona','Ramon', 'Joan', 'Quique', 'Laia']
while queue:
print("popping name : ",queue.pop(0), "remaining", queue)
queue.pop(0), queue | notebooks/2_0_Loops.ipynb | rcrehuet/Python_for_Scientists_2017 | gpl-3.0 |
Factorial
Find the sum of the digits in 100! (answer is 648) | import math
math.factorial(100)
result = 1
for i in range(100):
result = result*(i+1)
result
result = 1
for i in range(1,101):
result = result*i
result = str(result)
suma = 0
for caracter in result:
suma = suma + int(caracter)
suma | notebooks/2_0_Loops.ipynb | rcrehuet/Python_for_Scientists_2017 | gpl-3.0 |
Dictionaries
Checking for keys
Soft software use keyword to define the type of calculations to be performed. As an example, here we will use the quantum chemistry software Gaussian. Imagine we have stored Gaussian keywords in a dictionary as in:
keywords={'basis':'6-31+G', 'SCF':['XQC', 'Tight'], 'Opt':['TS', 'NoEigenT... | # Check different possibilities
keywords={'basis':'6-31+G', 'SCF':['XQC', 'Tight'], 'Opt':['TS', 'NoEigenTest']}
#keywords={'basis':'6-31G', 'SCF':['XQC', 'Tight'], 'Opt':['TS', 'NoEigenTest']}
#keywords={'basis':'6-31+G', 'SCF':['XQC',], 'Opt':['TS', 'NoEigenTest']}
#keywords={'basis':'6-31+G', 'Opt':['TS', 'NoEigenTe... | notebooks/2_0_Loops.ipynb | rcrehuet/Python_for_Scientists_2017 | gpl-3.0 |
What happens if the 'SCF' keyword is not present as in here?
keywords={'basis':'6-31+G', 'Opt':['TS, 'NoEigenTest']} | #Finish | notebooks/2_0_Loops.ipynb | rcrehuet/Python_for_Scientists_2017 | gpl-3.0 |
Common keys
Given two dictionaries, find the keys that are present in both dictionaries. (Hint: you can use sets) | def common_keys(d1, d2):
"""
Return the keys shared by dictionaries d1 and d2
returns a set
"""
#Finish
#Test it
d1 = makedict(red=1, green=2, blue=3)
d2 = makedict(purple=3, green=5, blue=6, yellow=1)
print(common_keys(d1, d2)) | notebooks/2_0_Loops.ipynb | rcrehuet/Python_for_Scientists_2017 | gpl-3.0 |
Genetic code (difficult!)
Given the genetic code dictionary, calculate how many codons code each aminoacid. which aminoacid is coded by more codons? The underscore means the STOP codon. (Answer: R and L, 6 times each) | gencode = {
'ATA':'I', 'ATC':'I', 'ATT':'I', 'ATG':'M',
'ACA':'T', 'ACC':'T', 'ACG':'T', 'ACT':'T',
'AAC':'N', 'AAT':'N', 'AAA':'K', 'AAG':'K',
'AGC':'S', 'AGT':'S', 'AGA':'R', 'AGG':'R',
'CTA':'L', 'CTC':'L', 'CTG':'L', 'CTT':'L',
'CCA':'P', 'CCC':'P', 'CCG':'P', 'CCT':'P',
'CAC':'H', 'CAT'... | notebooks/2_0_Loops.ipynb | rcrehuet/Python_for_Scientists_2017 | gpl-3.0 |
Remember that you can iterate a dictionary keys with: for k in gencode: and its values with: for v in gencode.values(): Or access the values like this:
for k in d:
v =d[k]
This exercice has many possible solutions.
How many of Leu(L) codons differ in only one point mutations from a Ile(I) codon? | #Finish | notebooks/2_0_Loops.ipynb | rcrehuet/Python_for_Scientists_2017 | gpl-3.0 |
구간 설정
- 구간 개수 : 5개
- 구간 크기 : 10 | interval = 5
interval_len = ( data.max() - 50 ) / interval
interval_len | ch02-variables.ipynb | JKeun/lecture-statistics | mit |
구간별 빈도수 측정
- 50미만 : 1
- 50이상 60미만 : 10
- 60이상 70미만 : 9
- 70이상 80미만 : 10
- 80이상 90미만 : 6
- 90이상 100미만 : 4 | data1 = [[45, 1, 1],
[55, 10, 11],
[65, 9, 20],
[75, 10, 30],
[85, 6, 36],
[95, 4, 40]]
df = pd.DataFrame(data1,
index=[u'~50', u'50~60', u'60~70', u'70~80', u'80~90', u'90~100'],
columns=[u"중간값" ,u"빈도수", u"누적빈도"])
df
import matplotlib.pyplot as pl... | ch02-variables.ipynb | JKeun/lecture-statistics | mit |
Parameters | feature_names = ['GR', 'ILD_log10', 'DeltaPHI', 'PHIND', 'PE', 'NM_M', 'RELPOS']
facies_names = ['SS', 'CSiS', 'FSiS', 'SiSh', 'MS', 'WS', 'D', 'PS', 'BS']
facies_colors = ['#F4D03F', '#F5B041','#DC7633','#6E2C00', '#1B4F72','#2E86C1', '#AED6F1', '#A569BD', '#196F3D']
#Select classifier type
#clfType='GB' #Gradient... | esaTeam/esa_Submission01b.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Load data
Let's load the data | # Load data from file
data = pd.read_csv('../facies_vectors.csv')
# Load Test data from file
test_data = pd.read_csv('../validation_data_nofacies.csv')
test_data.insert(0,'Facies',np.ones(test_data.shape[0])*(-1))
#Create Dataset for PE prediction from both dasets
all_data=pd.concat([data,test_data]) | esaTeam/esa_Submission01b.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Let's store features, labels and other data into numpy arrays. | # Store features and labels
X = data[feature_names].values # features
y = data['Facies'].values # labels
# Store well labels and depths
well = data['Well Name'].values
depth = data['Depth'].values
| esaTeam/esa_Submission01b.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Data inspection
Let us inspect the features we are working with. This step is useful to understand how to normalize them and how to devise a correct cross-validation strategy. Specifically, it is possible to observe that:
- Some features seem to be affected by a few outlier measurements.
- Only a few wells contain sa... | # Define function for plotting feature statistics
def plot_feature_stats(X, y, feature_names, facies_colors, facies_names):
# Remove NaN
nan_idx = np.any(np.isnan(X), axis=1)
X = X[np.logical_not(nan_idx), :]
y = y[np.logical_not(nan_idx)]
# Merge features and labels into a single DataFram... | esaTeam/esa_Submission01b.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Feature distribution
plot_feature_stats(X, y, feature_names, facies_colors, facies_names)
mpl.rcParams.update(inline_rc) | # Facies per well
for w_idx, w in enumerate(np.unique(well)):
ax = plt.subplot(3, 4, w_idx+1)
hist = np.histogram(y[well == w], bins=np.arange(len(facies_names)+1)+.5)
plt.bar(np.arange(len(hist[0])), hist[0], color=facies_colors, align='center')
ax.set_xticks(np.arange(len(hist[0])))
ax.set_xtickla... | esaTeam/esa_Submission01b.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Feature imputation
Let us fill missing PE values. Currently no feature engineering is used, but this should be explored in the future. | reg = RandomForestRegressor(max_features='sqrt', n_estimators=50, random_state=seed)
DataImpAll = all_data[feature_names].copy()
DataImp = DataImpAll.dropna(axis = 0, inplace=False)
Ximp=DataImp.loc[:, DataImp.columns != 'PE']
Yimp=DataImp.loc[:, 'PE']
reg.fit(Ximp, Yimp)
X[np.array(data.PE.isnull()),feature_names.ind... | esaTeam/esa_Submission01b.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Augment features | # ## Feature augmentation
# Our guess is that facies do not abrutly change from a given depth layer to the next one. Therefore, we consider features at neighboring layers to be somehow correlated. To possibly exploit this fact, let us perform feature augmentation by:
# - Select features to augment.
# - Aggregating aug_... | esaTeam/esa_Submission01b.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Generate training, validation and test data splitsar4_submission_withFac.ipynb
The choice of training and validation data is paramount in order to avoid overfitting and find a solution that generalizes well on new data. For this reason, we generate a set of training-validation splits so that:
- Features from each well ... | lpgo = LeavePGroupsOut(2)
# Generate splits
split_list = []
for train, val in lpgo.split(X, y, groups=data['Well Name']):
hist_tr = np.histogram(y[train], bins=np.arange(len(facies_names)+1)+.5)
hist_val = np.histogram(y[val], bins=np.arange(len(facies_names)+1)+.5)
if np.all(hist_tr[0] != 0) & np.all(hist... | esaTeam/esa_Submission01b.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Classification parameters optimization
Let us perform the following steps for each set of parameters:
Select a data split.
Normalize features using a robust scaler.
Train the classifier on training data.
Test the trained classifier on validation data.
Repeat for all splits and average the F1 scores.
At the end of the... |
if clfType=='XB':
md_grid = [2,3]
# mcw_grid = [1]
gamma_grid = [0.2, 0.3, 0.4]
ss_grid = [0.7, 0.9, 0.5]
csb_grid = [0.6,0.8,0.9]
alpha_grid =[0.2, 0.4, 0.3]
lr_grid = [0.04, 0.06, 0.05]
ne_grid = [100,200,300]
param_grid = []
for N in md_grid:
# for M in mcw_grid:
... | esaTeam/esa_Submission01b.ipynb | esa-as/2016-ml-contest | apache-2.0 |
다음 함수는 생성된 점들을 2차원 삼각형 위에서 볼 수 있도록 그려주는 함수이다. | def plot_triangle(X, kind):
n1 = np.array([1, 0, 0])
n2 = np.array([0, 1, 0])
n3 = np.array([0, 0, 1])
n12 = (n1 + n2)/2
m1 = np.array([1, -1, 0])
m2 = n3 - n12
m1 = m1/np.linalg.norm(m1)
m2 = m2/np.linalg.norm(m2)
X1 = (X-n12).dot(m1)
X2 = (X-n12).dot(m2)
g = sns.joint... | Lecture/09. 기초 확률론 3 - 확률모형/11) 디리클레 분포.ipynb | junhwanjang/DataSchool | mit |
만약 이 문제를 단순하게 생각하여 서로 독립인 0과 1사이의 유니폼 확률 변수를 3개 생성하고 이들의 합이 1이 되도록 크기를 정규화(normalize)하면 다음 그림과 같이 삼각형의 중앙 근처에 많은 확률 분포가 집중된다. 즉, 확률 변수가 골고루 분포되지 않는다. | X1 = np.random.rand(1000, 3)
X1 = X1/X1.sum(axis=1)[:, np.newaxis]
plot_triangle(X1, kind="scatter")
plot_triangle(X1, kind="hex") | Lecture/09. 기초 확률론 3 - 확률모형/11) 디리클레 분포.ipynb | junhwanjang/DataSchool | mit |
그러나 $\alpha=(1,1,1)$인 디리클레 분포는 다음과 같이 골고루 샘플을 생성한다. | X2 = sp.stats.dirichlet((1,1,1)).rvs(1000)
plot_triangle(X2, kind="scatter")
plot_triangle(X2, kind="hex") | Lecture/09. 기초 확률론 3 - 확률모형/11) 디리클레 분포.ipynb | junhwanjang/DataSchool | mit |
$\alpha$가 $(1,1,1)$이 아닌 경우에는 다음과 같이 특정 위치에 분포가 집중되도록 할 수 있다. 이 특성을 이용하면 다항 분포의 모수를 추정하는 베이지안 추정 문제에 응용할 수 있다. | def project(x):
n1 = np.array([1, 0, 0])
n2 = np.array([0, 1, 0])
n3 = np.array([0, 0, 1])
n12 = (n1 + n2)/2
m1 = np.array([1, -1, 0])
m2 = n3 - n12
m1 = m1/np.linalg.norm(m1)
m2 = m2/np.linalg.norm(m2)
return np.dstack([(x-n12).dot(m1), (x-n12).dot(m2)])[0]
def project_reverse(x):
... | Lecture/09. 기초 확률론 3 - 확률모형/11) 디리클레 분포.ipynb | junhwanjang/DataSchool | mit |
Starting Ray
There are two main ways in which Ray can be used. First, you can start all of the relevant Ray processes and shut them all down within the scope of a single script. Second, you can connect to and use an existing Ray cluster.
Starting and stopping a cluster within a script
One use case is to start all of th... | ray.init() | Archive/The Ray API.ipynb | Bowenislandsong/Distributivecom | gpl-3.0 |
If there are GPUs available on the machine, you should specify this with the num_gpus argument. Similarly, you can also specify the number of CPUs with num_cpus. | #ray.init(num_cpus=20,num_gpus=2) | Archive/The Ray API.ipynb | Bowenislandsong/Distributivecom | gpl-3.0 |
By default, Ray will use psutil.cpu_count() to determine the number of CPUs, and by default the number of GPUs will be zero.
Instead of thinking about the number of "worker" processes on each node, we prefer to think in terms of the quantities of CPU and GPU resources on each node and to provide the illusion of an infi... | # ray.init(redis_address="12.345.67.89:6379") | Archive/The Ray API.ipynb | Bowenislandsong/Distributivecom | gpl-3.0 |
In this case, you cannot specify num_cpus or num_gpus in ray.init because that information is passed into the cluster when the cluster is started, not when your script is started.
ray.init (redis_address=None, node_ip_address=None, object_id_seed=None, num_workers=None, driver_mode=0, redirect_output=False, num_cpus=No... | @ray.remote
def f(x):
return x+1
x_id = f.remote(0)
ray.get(x_id) # 1
#y_id = f.remote(x_id)
#ray.get(y_id) # 2 | Archive/The Ray API.ipynb | Bowenislandsong/Distributivecom | gpl-3.0 |
If you want a remote function to return multiple object IDs, you can do that by passing the num_return_vals argument into the remote decorator. | @ray.remote(num_return_vals=2)
def f():
return 1,2
x_id, y_id = f.remote()
ray.get(x_id) #1
#ray.get(y_id) #2 | Archive/The Ray API.ipynb | Bowenislandsong/Distributivecom | gpl-3.0 |
ray.remote (*args , **kwargs)
This decorator is used to define remote functions and to define actors.
Parameters
* num_return_vals (int) - The number of object IDs that a call to this function should return.
num_cpus (int) - The number of CPUs needed to execute this function.
num_gpus (int) - The number of GPUs... | @ray.remote
def f():
return {'key1': ['value']}
# Get one object ID.
ray.get(f.remote()) # {'key1': ['value']}
# Get a list of object IDs.
ray.get([f.remote() for _ in range(2)]) # [{'key1': ['value']}, {'key1': ['value']}] | Archive/The Ray API.ipynb | Bowenislandsong/Distributivecom | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.