markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Download and load the model. SpaCy has an excellent English NLP processor. It has the following features which we shall explore: - Entity recognition - Dependency Parsing - Part of Speech tagging - Word Vectorization - Tokenization - Lemmatization - Noun Chunks Download the Model, it may take a while
import spacy import spacy.en.download # spacy.en.download.main() processor = spacy.en.English() processed_text = processor(text) processed_text
notebooks/nlp_spacy.ipynb
AlJohri/DAT-DC-12
mit
Looks like the same text? Let's dig a little deeper Tokenization Sentences
n = 0 for sentence in processed_text.sents: print(n, sentence) n+=1
notebooks/nlp_spacy.ipynb
AlJohri/DAT-DC-12
mit
Words and Punctuation - Along with POS tagging
n = 0 for sentence in processed_text.sents: for token in sentence: print(n, token, token.pos_, token.lemma_) n+=1
notebooks/nlp_spacy.ipynb
AlJohri/DAT-DC-12
mit
Entities - Explanation of Entity Types
for entity in processed_text.ents: print(entity, entity.label_)
notebooks/nlp_spacy.ipynb
AlJohri/DAT-DC-12
mit
Noun Chunks
for noun_chunk in processed_text.noun_chunks: print(noun_chunk)
notebooks/nlp_spacy.ipynb
AlJohri/DAT-DC-12
mit
The Semi Holy Grail - Syntactic Depensy Parsing See Demo for clarity
def pr_tree(word, level): if word.is_punct: return for child in word.lefts: pr_tree(child, level+1) print('\t'* level + word.text + ' - ' + word.dep_) for child in word.rights: pr_tree(child, level+1) for sentence in processed_text.sents: pr_tree(sentence.root, 0) print(...
notebooks/nlp_spacy.ipynb
AlJohri/DAT-DC-12
mit
What is 'nsubj'? 'acomp'? See The Universal Dependencies Word Vectorization - Word2Vec
proc_fruits = processor('''I think green apples are delicious. While pears have a strange texture to them. The bowls they sit in are ugly.''') apples, pears, bowls = proc_fruits.sents fruit = processed_text.vocab['fruit'] print(apples.similarity(fruit)) print(pe...
notebooks/nlp_spacy.ipynb
AlJohri/DAT-DC-12
mit
Add dropout layer by hand to an MLP
def dropout_layer(X, dropout): assert 0 <= dropout <= 1 # In this case, all elements are dropped out if dropout == 1: return torch.zeros_like(X) # In this case, all elements are kept if dropout == 0: return X mask = (torch.Tensor(X.shape).uniform_(0, 1) > dropout).float() ret...
notebooks/misc/dropout_MLP_torch.ipynb
probml/pyprobml
mit
Fit to FashionMNIST Uses the d2l.load_data_fashion_mnist function.
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=256)
notebooks/misc/dropout_MLP_torch.ipynb
probml/pyprobml
mit
Fit model using SGD. Uses the d2l.train_ch3 function.
torch.manual_seed(0) # We pick a wide model to cause overfitting without dropout num_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256 net = Net(num_inputs, num_outputs, num_hiddens1, num_hiddens2, dropout1=0.5, dropout2=0.5) loss = nn.CrossEntropyLoss() lr = 0.5 trainer = torch.optim.SGD(net.paramete...
notebooks/misc/dropout_MLP_torch.ipynb
probml/pyprobml
mit
When we turn dropout off, we notice a slightly larger gap between train and test accuracy.
torch.manual_seed(0) net = Net(num_inputs, num_outputs, num_hiddens1, num_hiddens2, dropout1=0.0, dropout2=0.0) loss = nn.CrossEntropyLoss() trainer = torch.optim.SGD(net.parameters(), lr=lr) num_epochs = 10 d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)
notebooks/misc/dropout_MLP_torch.ipynb
probml/pyprobml
mit
Dropout using PyTorch layer
dropout1 = 0.5 dropout2 = 0.5 net = nn.Sequential( nn.Flatten(), nn.Linear(num_inputs, num_hiddens1), nn.ReLU(), # Add a dropout layer after the first fully connected layer nn.Dropout(dropout1), nn.Linear(num_hiddens2, num_hiddens1), nn.ReLU(), # Add a dropout layer after the second full...
notebooks/misc/dropout_MLP_torch.ipynb
probml/pyprobml
mit
Visualize some predictions
def display_predictions(net, test_iter, n=6): # Extract first batch from iterator for X, y in test_iter: break # Get labels trues = d2l.get_fashion_mnist_labels(y) preds = d2l.get_fashion_mnist_labels(d2l.argmax(net(X), axis=1)) # Plot titles = [true + "\n" + pred for true, pred in z...
notebooks/misc/dropout_MLP_torch.ipynb
probml/pyprobml
mit
Work up a minimum example of a trend following system Let's get some data We can get data from various places; however for now we're going to use prepackaged 'legacy' data stored in csv files
data = csvFuturesSimData() data
examples/introduction/asimpletradingrule.ipynb
robcarver17/pysystemtrade
gpl-3.0
We get stuff out of data with methods
print(data.get_instrument_list()) print(data.get_raw_price("EDOLLAR").tail(5))
examples/introduction/asimpletradingrule.ipynb
robcarver17/pysystemtrade
gpl-3.0
data can also behave in a dict like manner (though it's not a dict)
data['SP500'] data.keys()
examples/introduction/asimpletradingrule.ipynb
robcarver17/pysystemtrade
gpl-3.0
... however this will only access prices (note these prices have already been backadjusted for rolls) We have extra futures data here
data.get_instrument_raw_carry_data("EDOLLAR").tail(6)
examples/introduction/asimpletradingrule.ipynb
robcarver17/pysystemtrade
gpl-3.0
Technical note: csvFuturesSimData inherits from FuturesData which itself inherits from simData The chain is 'data specific' <- 'asset class specific' <- 'generic' Let's create a simple trading rule No capping or scaling
import pandas as pd from sysquant.estimators.vol import robust_vol_calc def calc_ewmac_forecast(price, Lfast, Lslow=None): """ Calculate the ewmac trading rule forecast, given a price and EWMA speeds Lfast, Lslow and vol_lookback """ # price: This is the stitched price series # We can't use t...
examples/introduction/asimpletradingrule.ipynb
robcarver17/pysystemtrade
gpl-3.0
Try it out (this isn't properly scaled at this stage of course)
instrument_code = 'EDOLLAR' price = data.daily_prices(instrument_code) ewmac = calc_ewmac_forecast(price, 32, 128) ewmac.columns = ['forecast'] ewmac.tail(5) ewmac.plot(); plt.title('Forecast') plt.ylabel('Position') plt.xlabel('Time')
examples/introduction/asimpletradingrule.ipynb
robcarver17/pysystemtrade
gpl-3.0
Did we make money?
from systems.accounts.account_forecast import pandl_for_instrument_forecast account = pandl_for_instrument_forecast(forecast=ewmac, price = price) account.curve().plot(); plt.title('Profit and Loss') plt.ylabel('PnL') plt.xlabel('Time'); account.percent.stats()
examples/introduction/asimpletradingrule.ipynb
robcarver17/pysystemtrade
gpl-3.0
Obtenga las posiciones en el espacio articular, $q_1$ y $q_2$, necesarias para que el punto final del pendulo doble llegue a las coordenadas $p_1 = (0,1)$, $p_2 = (1,3)$ y $p_3 = (3,2)$.
# YOUR CODE HERE raise NotImplementedError() from numpy.testing import assert_allclose assert_allclose((q11, q21),(0.25268 , 2.636232), rtol=1e-05, atol=1e-05) from numpy.testing import assert_allclose assert_allclose((q12, q22),(0.589988, 1.318116), rtol=1e-05, atol=1e-05) from numpy.testing import assert_allclose ...
Practicas/practica5/Problemas.ipynb
robblack007/clase-cinematica-robot
mit
Genere las trayectorias necesarias para que el pendulo doble se mueva del punto $p_1$ al punto $p_2$ en $2s$, del punto $p_2$ al punto $p_3$ en $2s$ y del punto $p_3$ al punto $p_1$ en $2s$. Utiliza 100 puntos por segundo y asegurate de guardar las trayectorias generadas en las variables correctas para que q1s y q2s t...
from generacion_trayectorias import grafica_trayectoria # YOUR CODE HERE raise NotImplementedError() q1s = q1s1 + q1s2 + q1s3 q2s = q2s1 + q2s2 + q2s3 from numpy.testing import assert_allclose assert_allclose((q1s[0], q1s[-1]),(0.25268, 0.25268), rtol=1e-05, atol=1e-05) from numpy.testing import assert_allclose asser...
Practicas/practica5/Problemas.ipynb
robblack007/clase-cinematica-robot
mit
Cree una animación con las trayectorias generadas y las funciones proporcionadas a continuación (algunas funciones estan marcadas con comentarios en donde hace falta agregar código).
from matplotlib.pyplot import figure, style from matplotlib import animation, rc rc('animation', html='html5') from numpy import sin, cos, arange fig = figure(figsize=(8, 8)) axi = fig.add_subplot(111, autoscale_on=False, xlim=(-0.6, 3.1), ylim=(-0.6, 3.1)) linea, = axi.plot([], [], "-o", lw=2, color='gray') def cd_p...
Practicas/practica5/Problemas.ipynb
robblack007/clase-cinematica-robot
mit
Are there certain populations we're not getting reports from? We can create a basic cross tab between age and gender to see if there are any patterns that emerges.
pd.crosstab(data['GenderDescription'], data['age_range'])
reports/api data.ipynb
minh5/cpsc
mit
From the data, it seems that there's not much underrepresentation by gender. There are only around a thousand less males than females in a dataset of 28,000. Age seems to be a bigger issue. There appears to be a lack of representation of older people using the API. Given that older folks may be less likely to self repo...
#removing minor harm incidents no_injuries = ['Incident, No Injury', 'Unspecified', 'Level of care not known', 'No Incident, No Injury', 'No First Aid or Medical Attention Received'] damage = data.ix[~data['SeverityTypePublicName'].isin(no_injuries), :] damage.ProductCategoryPublicName.value_counts()[0:9...
reports/api data.ipynb
minh5/cpsc
mit
This is actually preplexing, so I decided to investigate further by analyzing the complaints filed for the "Footwear" category. To do this, I created a Word2Vec model that uses a convolution neural network for text analysis. This process maps a word and the linguistic context it is in to be able to calculate similarity...
data.SeverityTypeDescription.value_counts()
reports/api data.ipynb
minh5/cpsc
mit
Although, while it is label to have no injury, it does not necessarily mean that we can't take precaution. What I did was take the same approach as the previous model, I subsetted the data to only complaints that had "no injury" and ran a model to examine words used. From the analysis, we see that the word to, was, and...
model.most_similar('was')
reports/api data.ipynb
minh5/cpsc
mit
Who are the people who are actually reporting to us? This question is difficult to answer because of a lack of data on the reporter. From the cross tabulation in Section 3.1, we see that the majority of our the respondents are female and the largest age group are 40-60. That is probably the best guess of who are the pe...
data.GenderDescription.value_counts() data['age'] = map(lambda x: x/12, data['VictimAgeInMonths']) labels = ['under 10', '10-20', '20-30', '30-40', '40-50', '50-60', '60-70','70-80', '80-90', '90-100', 'over 100'] data['age_range'] = pd.cut(data['age'], bins=np.arange(0,120,10), labels=labels) data['age_range...
reports/api data.ipynb
minh5/cpsc
mit
However after doing this, we still have around 13,000 people with an age of zero, whether it is that they did not fill in the age or that the incident involves infant is still unknown but looking at the distribution betweeen of the product that are affecting people with an age of 0 and the overall dataset, it appears t...
#Top products affect by people with 0 age data.ix[data['age_range'].isnull(), 'ProductCategoryPublicName'].value_counts()[0:9] #top products that affect people overall data.ProductCategoryPublicName.value_counts()[0:9]
reports/api data.ipynb
minh5/cpsc
mit
Question 2.2 At first glance, we can look at the products that were reported, like below. And see that Eletric Ranges or Ovens is at top in terms of harm. However, there are levels of severity within the API that needs to be filtered before we can assess which products causes the most harm.
#overall products listed data.ProductCategoryPublicName.value_counts()[0:9] #removing minor harm incidents no_injuries = ['Incident, No Injury', 'Unspecified', 'Level of care not known', 'No Incident, No Injury', 'No First Aid or Medical Attention Received'] damage = data.ix[~data['SeverityTypePublicNam...
reports/api data.ipynb
minh5/cpsc
mit
This shows that incidents where there are actually injuries and medical attention was given was that in footwear, which was weird. To explore this, I created a Word2Vec model that maps out how certain words relate to each other. To train the model, I used the comments that were made from the API. This will train a mode...
model = gensim.models.Word2Vec.load('/home/datauser/cpsc/models/footwear') model.most_similar('walking') model.most_similar('injury') model.most_similar('instability')
reports/api data.ipynb
minh5/cpsc
mit
Question 2.3
model = gensim.models.Word2Vec.load('/home/datauser/cpsc/models/severity') items_dict = {} for word, vocab_obj in model.vocab.items(): items_dict[word] = vocab_obj.count sorted_dict = sorted(items_dict.items(), key=operator.itemgetter(1)) sorted_dict.reverse() sorted_dict[0:5]
reports/api data.ipynb
minh5/cpsc
mit
Let us define two vector variables (a regular sequence and a random one) and print them.
x, y = np.arange(10), np.random.rand(10) print(x, y, sep='\n')
exercises.ipynb
okartal/popgen-systemsX
cc0-1.0
The following command plots $y$ as a function of $x$ and labels the axes using $\LaTeX$.
plt.plot(x, y, linestyle='--', color='r', linewidth=2) plt.xlabel('time, $t$') plt.ylabel('frequency, $f$')
exercises.ipynb
okartal/popgen-systemsX
cc0-1.0
From the tutorial: "matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB." Comment: The tutorial is a good starting point to learn about the most basic functionalities of matplotlib, especially if you are familiar with MATLAB. Matplotlib is a powerful library but sometimes ...
alp_genotype = {'obs_number': {'SS': 141, 'SF': 111, 'FF': 28, 'SI': 32, 'FI': 15, 'II': 5} }
exercises.ipynb
okartal/popgen-systemsX
cc0-1.0
Generating samples from a single stoichiometry
stoich = stoichiometry.Stoichiometry({'C': 10, 'O': 2, 'N': 3, 'H': 16, 'F': 2, 'O-': 1, 'N+': 1}) assert stoichiometry.is_valid(stoich), 'Cannot form a connected graph with this stoichiometry.' print('Number of heavy atoms:', sum(stoich.counts.values()) - stoich.counts['H']) %%time sampler = molecule_sampler.Molecule...
graph_sampler/molecule_sampling_demo.ipynb
google-research/google-research
apache-2.0
Combining samples from multiple stoichiometries Here we'll generate random molecules with 5 heavy atoms selected from C, N, and O. These small numbers are chosen just to illustrate the code. In this small an example, you could just enumerate all molecules. For large numbers of heavy atoms selected from a large set, you...
#@title Enumerate valid stoichiometries subject to the given constraint heavy_elements = ['C', 'N', 'O'] num_heavy = 5 # We'll dump stoichiometries, samples, and statistics into a big dictionary. all_data = {} for stoich in stoichiometry.enumerate_stoichiometries(num_heavy, heavy_elements): key = ''.join(stoich.to_e...
graph_sampler/molecule_sampling_demo.ipynb
google-research/google-research
apache-2.0
oracledb integration with Pandas
import pandas as pd # query Oracle using ora_conn and put the result into a pandas Dataframe df_ora = pd.read_sql('select * from emp', con=ora_conn) df_ora
Oracle_Jupyter/Oracle_Jupyter_oracledb_pandas.ipynb
LucaCanali/Miscellaneous
apache-2.0
Use of bind variables
df_ora = pd.read_sql('select * from emp where empno=:myempno', params={"myempno":7839}, con=ora_conn) df_ora
Oracle_Jupyter/Oracle_Jupyter_oracledb_pandas.ipynb
LucaCanali/Miscellaneous
apache-2.0
Basic visualization
import matplotlib.pyplot as plt plt.style.use('seaborn-darkgrid') df_ora = pd.read_sql('select ename "Name", sal "Salary" from emp', con=ora_conn) ora_conn.close() df_ora.plot(x='Name', y='Salary', title='Salary details, from Oracle demo table', figsize=(10, 6), kind='bar', color='blue');
Oracle_Jupyter/Oracle_Jupyter_oracledb_pandas.ipynb
LucaCanali/Miscellaneous
apache-2.0
A few Qumulo API file and direcotory python bindings fs.create_directory arguments: - name: Name of directory to be created - dir_path*: Destination path for the parent of created directory - dir_id*: Destination inode id for the parent of the created directory *Either dir_path or dir_id is required fs.create_file arg...
base_path = '/' dir_name = 'test-qumulo-fs-data' try: the_dir_meta = rc.fs.create_directory(dir_path=base_path, name=dir_name) print("Successfully created %s%s." % (base_path, dir_name)) except RequestError as e: print("** Exception: %s - Details: %s\n" % (e.error_class,e)) if e.error_class == 'fs_entr...
notebooks/File and Data Management.ipynb
Qumulo/python-notebooks
gpl-3.0
Create a file in an existing path
file_name = 'first-file.txt' # relies on the base path and direcotry name created in the code above. try: the_file_meta = rc.fs.create_file(name=file_name, dir_path=base_path + dir_name) except RequestError as e: print("** Exception: %s - Details: %s\n" % (e.error_class,e)) if e.error_class == 'fs_entry_ex...
notebooks/File and Data Management.ipynb
Qumulo/python-notebooks
gpl-3.0
1. Implementar o algoritmo K-means Nesta etapa você irá implementar as funções que compõe o algoritmo do KMeans uma a uma. É importante entender e ler a documentação de cada função, principalmente as dimensões dos dados esperados na saída. 1.1 Inicializar os centróides A primeira etapa do algoritmo consiste em iniciali...
def calculate_initial_centers(dataset, k): """ Inicializa os centróides iniciais de maneira arbitrária Argumentos: dataset -- Conjunto de dados - [m,n] k -- Número de centróides desejados Retornos: centroids -- Lista com os centróides calculados - [k,n] """ #### CODE ...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
Teste a função criada e visualize os centróides que foram calculados.
k = 3 centroids = calculate_initial_centers(dataset, k) plt.scatter(dataset[:,0], dataset[:,1], s=10) plt.scatter(centroids[:,0], centroids[:,1], marker='^', c='red',s=100) plt.show()
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
1.2 Definir os clusters Na segunda etapa do algoritmo serão definidos o grupo de cada dado, de acordo com os centróides calculados. 1.2.1 Função de distância Codifique a função de distância euclidiana entre dois pontos (a, b). Definido pela equação: $$ dist(a, b) = \sqrt{(a_1-b_1)^{2}+(a_2-b_2)^{2}+ ... + (a_n-b_n)^{2}...
def euclidean_distance(a, b): """ Calcula a distância euclidiana entre os pontos a e b Argumentos: a -- Um ponto no espaço - [1,n] b -- Um ponto no espaço - [1,n] Retornos: distance -- Distância euclidiana entre os pontos """ #### CODE HERE #### n = len(a) ...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
Teste a função criada.
a = np.array([1, 5, 9]) b = np.array([3, 7, 8]) if (euclidean_distance(a,b) == 3): print("Distância calculada corretamente!") else: print("Função de distância incorreta")
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
1.2.2 Calcular o centroide mais próximo Utilizando a função de distância codificada anteriormente, complete a função abaixo para calcular o centroid mais próximo de um ponto qualquer. Dica: https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmin.html
def nearest_centroid(a, centroids): """ Calcula o índice do centroid mais próximo ao ponto a Argumentos: a -- Um ponto no espaço - [1,n] centroids -- Lista com os centróides - [k,n] Retornos: nearest_index -- Índice do centróide mais próximo """ #### CODE HERE #### ...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
Teste a função criada
# Seleciona um ponto aleatório no dataset index = np.random.randint(dataset.shape[0]) a = dataset[index,:] # Usa a função para descobrir o centroid mais próximo idx_nearest_centroid = nearest_centroid(a, centroids) # Plota os dados ------------------------------------------------ plt.scatter(dataset[:,0], dataset[:,...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
1.2.3 Calcular centroid mais próximo de cada dado do dataset Utilizando a função anterior que retorna o índice do centroid mais próximo, calcule o centroid mais próximo de cada dado do dataset.
def all_nearest_centroids(dataset, centroids): """ Calcula o índice do centroid mais próximo para cada ponto do dataset Argumentos: dataset -- Conjunto de dados - [m,n] centroids -- Lista com os centróides - [k,n] Retornos: nearest_indexes -- Índices do centróides mais próximo...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
Teste a função criada visualizando os cluster formados.
nearest_indexes = all_nearest_centroids(dataset, centroids) plt.scatter(dataset[:,0], dataset[:,1], c=nearest_indexes) plt.scatter(centroids[:,0], centroids[:,1], marker='^', c='red', s=100) plt.show()
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
1.3 Métrica de avaliação Após formar os clusters, como sabemos se o resultado gerado é bom? Para isso, precisamos definir uma métrica de avaliação. O algoritmo K-means tem como objetivo escolher centróides que minimizem a soma quadrática das distância entre os dados de um cluster e seu centróide. Essa métrica é conheci...
def inertia(dataset, centroids, nearest_indexes): """ Soma das distâncias quadradas das amostras para o centro do cluster mais próximo. Argumentos: dataset -- Conjunto de dados - [m,n] centroids -- Lista com os centróides - [k,n] nearest_indexes -- Índices do centróides mais próximos -...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
Teste a função codificada executando o código abaixo.
tmp_data = np.array([[1,2,3],[3,6,5],[4,5,6]]) tmp_centroide = np.array([[2,3,4]]) tmp_nearest_indexes = all_nearest_centroids(tmp_data, tmp_centroide) if inertia(tmp_data, tmp_centroide, tmp_nearest_indexes) == 26: print("Inertia calculada corretamente!") else: print("Função de inertia incorreta!") # Use a f...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
1.4 Atualizar os clusters Nessa etapa, os centróides são recomputados. O novo valor de cada centróide será a media de todos os dados atribuídos ao cluster.
def update_centroids(dataset, centroids, nearest_indexes): """ Atualiza os centroids Argumentos: dataset -- Conjunto de dados - [m,n] centroids -- Lista com os centróides - [k,n] nearest_indexes -- Índices do centróides mais próximos - [m,1] Retornos: centroids -- Lista com cen...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
Visualize os clusters formados
nearest_indexes = all_nearest_centroids(dataset, centroids) # Plota os os cluster ------------------------------------------------ plt.scatter(dataset[:,0], dataset[:,1], c=nearest_indexes) # Plota os centroids plt.scatter(centroids[:,0], centroids[:,1], marker='^', c='red', s=100) for index, centroid in enumerate(ce...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
Execute a função de atualização e visualize novamente os cluster formados
centroids = update_centroids(dataset, centroids, nearest_indexes)
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
2. K-means 2.1 Algoritmo completo Utilizando as funções codificadas anteriormente, complete a classe do algoritmo K-means!
class KMeans(): def __init__(self, n_clusters=8, max_iter=300): self.n_clusters = n_clusters self.max_iter = max_iter def fit(self,X): # Inicializa os centróides self.cluster_centers_ = calculate_initial_centers(X, self.n_clusters) # Computa o ...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
Verifique o resultado do algoritmo abaixo!
kmeans = KMeans(n_clusters=3) kmeans.fit(dataset) print("Inércia = ", kmeans.inertia_) plt.scatter(dataset[:,0], dataset[:,1], c=kmeans.labels_) plt.scatter(kmeans.cluster_centers_[:,0], kmeans.cluster_centers_[:,1], marker='^', c='red', s=100) plt.show()
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
2.2 Comparar com algoritmo do Scikit-Learn Use a implementação do algoritmo do scikit-learn do K-means para o mesmo conjunto de dados. Mostre o valor da inércia e os conjuntos gerados pelo modelo. Você pode usar a mesma estrutura da célula de código anterior. Dica: https://scikit-learn.org/stable/modules/generated/sk...
#### CODE HERE #### from sklearn.cluster import KMeans as sk_KMeans skkmeans = sk_KMeans(n_clusters=3).fit(dataset) print("Scikit-Learn KMeans' inertia: ", skkmeans.inertia_) print("My KMeans inertia: ", kmeans.inertia_)
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
3. Método do cotovelo Implemete o método do cotovelo e mostre o melhor K para o conjunto de dados.
#### CODE HERE #### # Initialize array of Ks ks = np.array(range(1, 11)) # Create array to receive the inertias for each K inertias = np.zeros(len(ks)) for i in range(len(ks)): # Compute inertia for K kmeans = KMeans(ks[i]).fit(dataset) inertias[i] = kmeans.inertia_ # Best K is the last one to im...
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
4. Dataset Real Exercícios 1 - Aplique o algoritmo do K-means desenvolvido por você no datatse iris [1]. Mostre os resultados obtidos utilizando pelo menos duas métricas de avaliação de clusteres [2]. [1] http://archive.ics.uci.edu/ml/datasets/iris [2] http://scikit-learn.org/stable/modules/clustering.html#clustering-...
#### CODE HERE ####
2019/09-clustering/cl_AlefCarneiro.ipynb
InsightLab/data-science-cookbook
mit
Import File into Python Change File Name!
df = pd.read_csv('/Users/John/Dropbox/LLU/ROP/Pulse Ox/ROP018PO.csv', parse_dates={'timestamp': ['Date','Time']}, index_col='timestamp', usecols=['Date', 'Time', 'SpO2', 'PR', 'PI', 'Exceptions'], na_values=['0'], converters={'Exceptions': readD} ...
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Set Date and Time of ROP Exam and Eye Drops
df_first = df.first_valid_index() #get the first number from index Y = pd.to_datetime(df_first) #convert index to datetime # Y = TIME DATA COLLECTION BEGAN / First data point on CSV # SYNTAX: # datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) W = datetime(2016, 1, 20, 7, 30)+TC # W = f...
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Baseline Averages
avg0PI = df_clean.PI[Y:W].mean() avg0O2 = df.SpO2[Y:W].mean() avg0PR = df.PR[Y:W].mean() print 'Baseline Averages\n', 'PI :\t',avg0PI, '\nSpO2 :\t',avg0O2,'\nPR :\t',avg0PR, #df.std() for standard deviation
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Average q 5 Min for 1 hour after 1st Eye Drops
# Every 5 min Average from start of eye drops to start of exam def perdeltadrop(start, end, delta): rdrop = [] curr = start while curr < end: rdrop.append(curr) curr += delta return rdrop dfdropPI = df_clean.PI[W:W+timedelta(hours=1)] dfdropO2 = df.SpO2[W:W+timedelta(hours=1)] dfdr...
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Average Every 10 Sec During ROP Exam for first 4 minutes
#AVERAGE DURING ROP EXAM FOR FIRST FOUR MINUTES def perdelta1(start, end, delta): r1 = [] curr = start while curr < end: r1.append(curr) curr += delta return r1 df1PI = df_clean.PI[X:X+timedelta(minutes=4)] df1O2 = df.SpO2[X:X+timedelta(minutes=4)] df1PR = df.PR[X:X+timedelta(minutes=4)...
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Average Every 5 Mins Hour 1-2 After ROP Exam
#AVERAGE EVERY 5 MINUTES ONE HOUR AFTER ROP EXAM def perdelta2(start, end, delta): r2 = [] curr = start while curr < end: r2.append(curr) curr += delta return r2 # datetime(year, month, day, hour, etc.) df2PI = df_clean.PI[Z:(Z+timedelta(hours=1))] df2O2 = df.SpO2[Z:(Z+timedelta(hours...
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Average Every 15 Mins Hour 2-3 After ROP Exam
#AVERAGE EVERY 15 MINUTES TWO HOURS AFTER ROP EXAM def perdelta3(start, end, delta): r3 = [] curr = start while curr < end: r3.append(curr) curr += delta return r3 # datetime(year, month, day, hour, etc.) df3PI = df_clean.PI[(Z+timedelta(hours=1)):(Z+timedelta(hours=2))] df3O2 = df.Sp...
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Average Every 30 Mins Hour 3-4 After ROP Exam
#AVERAGE EVERY 30 MINUTES THREE HOURS AFTER ROP EXAM def perdelta4(start, end, delta): r4 = [] curr = start while curr < end: r4.append(curr) curr += delta return r4 # datetime(year, month, day, hour, etc.) df4PI = df_clean.PI[(Z+timedelta(hours=2)):(Z+timedelta(hours=3))] df4O2 = df....
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Average Every Hour 4-24 Hours Post ROP Exam
#AVERAGE EVERY 60 MINUTES 4-24 HOURS AFTER ROP EXAM def perdelta5(start, end, delta): r5 = [] curr = start while curr < end: r5.append(curr) curr += delta return r5 # datetime(year, month, day, hour, etc.) df5PI = df_clean.PI[(Z+timedelta(hours=3)):(Z+timedelta(hours=24))] df5O2 = df....
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Mild, Moderate, and Severe Desaturation Events
df_O2_pre = df[Y:W] #Find count of these ranges below = 0 # v <=80 middle = 0 #v >= 81 and v<=84 above = 0 #v >=85 and v<=89 ls = [] b_dict = {} m_dict = {} a_dict = {} for i, v in df_O2_pre['SpO2'].iteritems(): if v <= 80: #below block if not ls: ls.append(v) else: ...
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
Export to CSV
import csv class excel_tab(csv.excel): delimiter = '\t' csv.register_dialect("excel_tab", excel_tab) with open('ROP018_PO.csv', 'w') as f: #CHANGE CSV FILE NAME, saves in same directory writer = csv.writer(f, dialect=excel_tab) #writer.writerow(['PI, O2, PR']) accidently found this out but using com...
Old Code/.ipynb_checkpoints/Masimo160127-checkpoint.ipynb
johntanz/ROP
gpl-2.0
4. Pandas简介 最重要的是DataFrame和Series
import numpy as np import pandas as pd
Python数据科学101.ipynb
liulixiang1988/documents
mit
4.1 Series 创建一个series,包含空值NaN
s = pd.Series([1, 3, 5, np.nan, 6, 8]) s[4] # 6.0
Python数据科学101.ipynb
liulixiang1988/documents
mit
4.2 Dataframes
df = pd.DataFrame({'data': ['2016-01-01', '2016-01-02', '2016-01-03'], 'qty': [20, 30, 40]}) df
Python数据科学101.ipynb
liulixiang1988/documents
mit
更大的数据应当从文件里获取
rain = pd.read_csv('data/rainfall/rainfall.csv') rain # 加载一列 rain['City'] # 加载一行(第二行) rain.loc[[1]] # 第一行和第二行 rain.loc[0:1]
Python数据科学101.ipynb
liulixiang1988/documents
mit
4.3 过滤
# 查找所有降雨量小于10的数据 rain[rain['Rainfall'] < 10]
Python数据科学101.ipynb
liulixiang1988/documents
mit
查找4月份的降雨
rain[rain['Month'] == 'Apr']
Python数据科学101.ipynb
liulixiang1988/documents
mit
查找Los Angeles的数据
rain[rain['City'] == 'Los Angeles']
Python数据科学101.ipynb
liulixiang1988/documents
mit
4.4 给行起名(Naming Rows)
rain = rain.set_index(rain['City'] + rain['Month'])
Python数据科学101.ipynb
liulixiang1988/documents
mit
注意,当我们修改dataframe时,其实是在创建一个副本,因此要把这个值再赋值给原有的dataframe
rain.loc['San FranciscoApr']
Python数据科学101.ipynb
liulixiang1988/documents
mit
5. Pandas 例子
%matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np df = pd.read_csv('data/nycflights13/flights.csv.gz') df
Python数据科学101.ipynb
liulixiang1988/documents
mit
这里我们主要关注统计数据和可视化。我们来看一下按月统计的晚点时间的均值。
mean_delay_by_month = df.groupby(['month'])['arr_delay'].mean() mean_delay_by_month mean_month_plt = mean_delay_by_month.plot(kind='bar', title='Mean Delay By Month') mean_month_plt
Python数据科学101.ipynb
liulixiang1988/documents
mit
注意,这里9、10月均值会有负值。
mean_delay_by_month_ord = df[(df.dest == 'ORD')].groupby(['month'])['arr_delay'].mean() print("Flights to Chicago (ORD)") print(mean_delay_by_month_ord) mean_month_plt_ord = mean_delay_by_month_ord.plot(kind='bar', title="Mean Delay By Month (Chicago)") mean_month_plt_ord # 再看看Los Angeles进行比较一下 mean_delay_by_month_la...
Python数据科学101.ipynb
liulixiang1988/documents
mit
从上面的图表中我们可以直观的看到一些特征。现在我们再来看看每个航空公司晚点的情况,并进行一些可视化。
# 看看是否不同的航空公司对晚点会有不同的影响 df[['carrier', 'arr_delay']].groupby('carrier').mean().plot(kind='bar', figsize=(12, 8)) plt.xticks(rotation=0) plt.xlabel('Carrier') plt.ylabel('Average Delay in Min') plt.title('Average Arrival Delay by Carrier in 2008, All airports') df[['carrier', 'dep_delay']].groupby('carrier').mean().plo...
Python数据科学101.ipynb
liulixiang1988/documents
mit
从上面的图表里我们可以看到F9(Front Airlines)几乎是最经常晚点的,而夏威夷(HA)在这方面表现最好。 5.3 Joins 我们有多个数据集,天气、机场的。现在我们来看一下如何把两个表连接在一起
weather = pd.read_csv('data/nycflights13/weather.csv.gz') weather df_withweather = pd.merge(df, weather, how='left', on=['year', 'month', 'day', 'hour']) df_withweather airports = pd.read_csv('data/nycflights13/airports.csv.gz') airports df_withairport = pd.merge(df_withweather, airports, how='left', left_on='dest',...
Python数据科学101.ipynb
liulixiang1988/documents
mit
6 Numpy和SciPy Numpy和SciPy是Python数据科学的CP。早期Python的list比较慢,并且对于处理矩阵和向量运算不太好,因此有了Numpy来解决这个问题。它引入了array-type的数据类型。 创建数组:
import numpy as np a = np.array([1, 2, 3]) a
Python数据科学101.ipynb
liulixiang1988/documents
mit
注意这里我们传的是列表,而不是np.array(1, 2, 3)。 现在我们创建一个arange
np.arange(10) # 给序列乘以一个系数 np.arange(10) * np.pi
Python数据科学101.ipynb
liulixiang1988/documents
mit
我们也可以使用shape方法从一维数组创建多维数组
a = np.array([1, 2, 3, 4, 5, 6]) a.shape = (2, 3) a
Python数据科学101.ipynb
liulixiang1988/documents
mit
6.1 矩阵Matrix
np.matrix('1 2; 3 4') #矩阵乘 a1 = np.matrix('1 2; 3 4') a2 = np.matrix('3 4; 5 7') a1 * a2 #array转换为矩阵 mat_a = np.mat(a1) mat_a
Python数据科学101.ipynb
liulixiang1988/documents
mit
6.2 稀疏矩阵(Sparse Matrices)
import numpy, scipy.sparse n = 100000 x = (numpy.random.rand(n) * 2).astype(int).astype(float) #50%稀疏矩阵 x_csr = scipy.sparse.csr_matrix(x) x_dok = scipy.sparse.dok_matrix(x.reshape(x_csr.shape)) x_dok
Python数据科学101.ipynb
liulixiang1988/documents
mit
6.3 从CSV文件中加载数据
import csv with open('data/array/array.csv', 'r') as csvfile: csvreader = csv.reader(csvfile) data = [] for row in csvreader: row = [float(x) for x in row] data.append(row) data
Python数据科学101.ipynb
liulixiang1988/documents
mit
6.4 求解矩阵方程(Solving a matrix)
import numpy as np import scipy as sp a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]]) b = np.array([2, 4, -1]) x = np.linalg.solve(a, b) x #检查结果是否正确 np.dot(a, x) == b
Python数据科学101.ipynb
liulixiang1988/documents
mit
7 Scikit-learn 简介 前面我们介绍了pandas和numpy、scipy。现在我们来介绍python机器库Scikit。首先需要先知道机器学习的两种: 监督学习(Supervised Learning): 从训练集建立模型进行预测 非监督学习(Unsupervised Learning): 从数据中推测模型,比如从文本中找出主题 Scikit-learn有一下特性: - 预处理(Preprocessing):为机器学习reshape数据 - 降维处理(Dimensionality reduction):减少变量的重复 - 分类(Classification): 预测分类 - 回归(regression):预测连续变...
%matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler, OneHotEncoder flights = pd.read_csv('data/nycflights13/flights.csv.gz') weather = pd.read_csv('data/nycflights13/weather.csv...
Python数据科学101.ipynb
liulixiang1988/documents
mit
7.1 特征向量
pred = 'dep_delay' features = ['month', 'day', 'dep_time', 'arr_time', 'carrier', 'dest', 'air_time', 'distance', 'lat', 'lon', 'alt', 'dewp', 'humid', 'wind_speed', 'wind_gust', 'precip', 'pressure', 'visib'] features_v = df[features] pred_v = df[pred] pd.options.mode.chained_assignment = None #...
Python数据科学101.ipynb
liulixiang1988/documents
mit
7.2 对特征向量进行标准化(Scaling the feature vector)
# 因为各个特征的维度各不相同,我们需要做标准化 scaler = StandardScaler() scaled_features = scaler.fit_transform(features_v) scaled_features
Python数据科学101.ipynb
liulixiang1988/documents
mit
7.3 特征降维(Reducing Dimensions) 我们使用PCA(Principle Component Analysis主成分析)把特征降维为2个
from sklearn.decomposition import PCA pca = PCA(n_components=2) X_r = pca.fit(scaled_features).transform(scaled_features) X_r
Python数据科学101.ipynb
liulixiang1988/documents
mit
7.4 画图(Plotting)
import matplotlib.pyplot as plt print('explained variance ratio (first two components): %s' % str(pca.explained_variance_ratio_)) plt.figure() lw = 2 plt.scatter(X_r[:,0], X_r[:,1], alpha=.8, lw=lw) plt.title('PCA of flights dataset')
Python数据科学101.ipynb
liulixiang1988/documents
mit
8 构建分类器(Build a classifier) 我们来预测一个航班是否会晚点
%matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np import sklearn from sklearn import linear_model, cross_validation, metrics, svm, ensemble from sklearn.metrics import classification_report, confusion_matrix, precision_recall_fscore_support, accuracy_score from sklearn.cross_val...
Python数据科学101.ipynb
liulixiang1988/documents
mit
9 聚合数据(Cluster data) 最简单的聚类方法是K-Means
%matplotlib inline import pandas as pd import matplotlib.pyplot as plt import numpy as np import sklearn from sklearn.cluster import KMeans from sklearn import linear_model, cross_validation, cluster from sklearn.metrics import classification_report, confusion_matrix, precision_recall_fscore_support, accuracy_score fr...
Python数据科学101.ipynb
liulixiang1988/documents
mit
10 PySpark简介 扩展我们的算法:有时我们需要处理大量数据,并且采样已经无效,这个时候可以通过把数据分到多个机器来处理。 Spark是一个用来并行进行大数据处理的API。它将数据切割到集群来处理。在开发阶段,我们可以只在本地运行。 我们使用PySpark Shell来连接到集群。 运行下面路径的pyspark,会启动PySpark Shell ~/spark/bin/pyspark (Max/Linux) C:\spark\bin\pyspark (Windows) 此时,可以在Shell中运行文件加载: lines = sc.textFile("README.md") lines.first() # 加载第一行 可以在ht...
lines = sc.text('README.md') lines.take(5)
Python数据科学101.ipynb
liulixiang1988/documents
mit