markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Group talks by session code
# sort by and group by session keys = ('start', 'session') sorted_talks = sorted(talks, key=itemgetter(*keys)) talk_sessions = DefaultOrderedDict(list) for talk in sorted_talks: talk_sessions[talk['session']].append(talk)
notebooks/session_instructions_toPDF.ipynb
EuroPython/ep-tools
mit
Create the HTML texts for each session
session_texts = OrderedDict() for session, talks in talk_sessions.items(): text = ['<h1>' + session + '</h1>'] for talk in talks: text += [show_talk(talk, show_duration=False, show_link_to_admin=False)] session_texts[session] = '\n'.join(text)
notebooks/session_instructions_toPDF.ipynb
EuroPython/ep-tools
mit
Export to PDF You need to have pandoc, wkhtmltopdf and xelatex installed in your computer.
import os import os.path as op import subprocess os.makedirs('session_pdfs', exist_ok=True) def pandoc_html_to_pdf(html_file, out_file, options): cmd = 'pandoc {} {} -o {}'.format(options, html_file, out_file) print(cmd) subprocess.check_call(cmd, shell=True) # pandoc options DIN-A6 # options = ' -V '...
notebooks/session_instructions_toPDF.ipynb
EuroPython/ep-tools
mit
Trace analysis For more information on this please check examples/trace_analysis/TraceAnalysis_TasksLatencies.ipynb.
# Load traces in memory (can take several minutes) platform_file = os.path.join(te.res_dir, 'platform.json') with open(platform_file, 'r') as fh: platform = json.load(fh) trace_file = os.path.join(te.res_dir, 'trace.dat') trace = Trace(trace_file, my_conf['ftrace']['events'], platform, normalize_time=False) # Fi...
ipynb/deprecated/examples/android/workloads/Android_Gmaps.ipynb
ARM-software/lisa
apache-2.0
São muitas as colunas dessa consulta (a visualização acima omite algumas). Vamos checar quais são:
list(df_contratos) df_contratos.to_excel('contratos.xls')
SOF_Contratos.ipynb
campagnucci/api_sof
gpl-3.0
Por modalidade de contratação
df_contratos.groupby(['txtDescricaoModalidade'])['valEmpenhadoLiquido', 'valPago'].sum().sort_values(['valEmpenhadoLiquido'], ascending=False)
SOF_Contratos.ipynb
campagnucci/api_sof
gpl-3.0
Agora já temos o DataFrame que junta todos Empenhos do Verde de 2017 com as informações de Contrato, deixando a base mais rica -- e corrigindo essa falha da falta de Razão Social e CNPJ na consulta de contratos!
df_empenhos_c_contratos.head()
SOF_Contratos.ipynb
campagnucci/api_sof
gpl-3.0
A tabela acima vai ter muitos valores "Nan" para codContrato -- pois há 493 empenhos e apenas 80 contratos. Como o interesse agora é só nos contratos, vamos retirar esses casos e montar um novo DataFrame que contém apenas contratos com algum empenho relacionado:
df_empenhos_c_contratos = df_empenhos_c_contratos.dropna(axis=0).reset_index(drop=True)
SOF_Contratos.ipynb
campagnucci/api_sof
gpl-3.0
Mudando o formato de número de decimal (tirar aquele .0 dali) para integer:
df_empenhos_c_contratos['codContrato'] = df_empenhos_c_contratos.loc[:,'codContrato'].astype(int)
SOF_Contratos.ipynb
campagnucci/api_sof
gpl-3.0
'Top 10' Contratos de 2017 Agora com a lista de todos os contratos do ano, vamos montar uma tabela e ordenar os dados pelo Valor Principal do Contrato. No Manual da API, aprende-se que esse campo 'valPrincipal'significa o "Valor do contrato sem ocorrência de reajustamentos, ou aditamentos".
top10 = df_contratos_empenhados[['txtDescricaoModalidade', 'txtObjetoContrato', 'txtRazaoSocial', 'numCpfCnpj', 'valPrincipal']].sort_values(['valPrincipal'], ascending=False)[:10] top10
SOF_Contratos.ipynb
campagnucci/api_sof
gpl-3.0
Passo 3 - Só quer salvar em Excel ou CSV?
df_contratos_empenhados.to_excel('exemplos/contratos_empenhados.xls') df_contratos_empenhados.to_csv('exemplos/contratos_empenhados.csv')
SOF_Contratos.ipynb
campagnucci/api_sof
gpl-3.0
Passo "Bônus" - Comparando com o Portal da Transparência Como mencionei lá em cima, o Portal da Transparência de São Paulo tem algo muito importante que é publicar os contratos na íntegra nesta página. Não vou entrar nos detalhes dos poréns que surgem aqui -- mas saiba que a ação de publicar o contrato depende de as pe...
df_contratos_portal = pd.read_excel('exemplos/contratos_portal.xls') df_contratos_portal.sort_values('Valor (R$)', ascending=False).head() df_contratos_portal.groupby('Modalidade')['Valor (R$)'].sum()
SOF_Contratos.ipynb
campagnucci/api_sof
gpl-3.0
Download the example data files if we don't already have them.
targdir = 'a1835_xmm' if not os.path.isdir(targdir): os.mkdir() filenames = ('P0098010101M2U009IMAGE_3000.FTZ', 'P0098010101M2U009EXPMAP3000.FTZ', 'P0098010101M2X000BKGMAP3000.FTZ') remotedir = 'http://heasarc.gsfc.nasa.gov/FTP/xmm/data/rev0/0098010101/PPS/' for filename in filenames: ...
examples/XrayImage/FirstLook.ipynb
hungiyang/StatisticalMethods
gpl-2.0
Use simple stock market daily data as features
#get stock basic data from quandl df = quandl.get('WIKI/AAPL',start_date="1996-9-26",end_date='2017-12-31') df = df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume']] #calculate highest and lowest price change df['HL_PCT']=(df['Adj. High']-df['Adj. Low'])/df['Adj. Close'] *100.0 #calculate return of stoc...
2018-04_Stock_prediction/linear regression stock prediction project.ipynb
NorfolkDataSci/presentations
mit
the first varible is negative because the model can be arbitrarily worse
forecast_set = clf.predict(X_test) num_samples = df.shape[0] #add Forecase column to dataframe df['Forecast'] = np.nan df['Forecast'][int(0.9*num_samples):num_samples]=forecast_set #plot graph for actual stock price and style.use('ggplot') df['Adj. Close'].plot() df['Forecast'].plot() plt.legend(loc=4) plt.xlabel('Da...
2018-04_Stock_prediction/linear regression stock prediction project.ipynb
NorfolkDataSci/presentations
mit
use price as one of the feature to predict price We can see from previous prediction, even high related correlation featrues did not predict well. However, the highest related featrue is price itself. This time I want to use price as one of the feature to predict price.
predictor2=df[['Adj. Close','HL_PCT','Adj. Volume']] predictor2=preprocessing.scale(predictor2) clf2 = linear_model.LinearRegression(n_jobs=-1) X_train2, X_test2, y_train2, y_test2 =train_test_split(predictor2 , price, test_size=0.1,shuffle= False) clf2.fit(X_train2, y_train2) forecast_set2 = clf2.predict(X_test2) prin...
2018-04_Stock_prediction/linear regression stock prediction project.ipynb
NorfolkDataSci/presentations
mit
Use 30 days stock price to predict 31 days price Because accounting price as a feature is 100% correlation to predict the price. so we can get almost 100% match prediction. I think using previous price to predict future price is best way to predict.
from sklearn.linear_model import LinearRegression price_data=pd.DataFrame(df_orig['Adj. Close']) price_data.columns = ['values'] index=price_data.index Date=index[60:5350] x_data = [] y_data = [] for d in range(30,price_data.shape[0]): x = price_data.iloc[d-30:d].values.ravel() y = price_data.iloc[d].values[0] ...
2018-04_Stock_prediction/linear regression stock prediction project.ipynb
NorfolkDataSci/presentations
mit
Use financial fundamental data to predict stock price I try to collect more financial fundamental data to predict stock price. To compare with previous 3 predictions, I collect apple quarterly revenue, yearly total assets, yearly gross profit and equity as key feature to forcast stock price.
#get apple revenue revenue=quandl.get("SF1/AAPL_REVENUE_MRQ",start_date="1996-9-26",end_date='2017-12-31', authtoken="_1LjZZVx4HVVTwzCmqxg") #get apple total assets total_assets=quandl.get("SF1/AAPL_ASSETS_MRY",start_date="1996-9-26",end_date='2017-12-31', authtoken="_1LjZZVx4HVVTwzCmqxg") #get apple gross profit gross...
2018-04_Stock_prediction/linear regression stock prediction project.ipynb
NorfolkDataSci/presentations
mit
Use PCA to reduce the number of features to two Trying to use PCA to processing the features and test accuracy.
# Use PCA to reduce the number of features to two, and test. from sklearn.decomposition import PCA #reduce 4 featrues to 2 pca = PCA(n_components=2) predictor3=pca.fit_transform(predictor3) print(predictor3.shape) clf4 = linear_model.LinearRegression(n_jobs=-1) X_train4, X_test4, y_train4, y_test4 =train_test_split(pre...
2018-04_Stock_prediction/linear regression stock prediction project.ipynb
NorfolkDataSci/presentations
mit
Visualize the Architecture of a Neural Network
import graphviz as gv
Python/7 Neural Networks/NN-Architecture.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
The function $\texttt{generateNN}(\texttt{Topology})$ takes a network topology Topology as its argument and draws a graph of the resulting fully connected feed-forward neural net. A network topology is a list of numbers specifying the number of neurons of each layer. For example, the network topology [3, 8, 6, 2] s...
def generateNN(Topology): L = len(Topology) input_layer = ['i' + str(i) for i in range(1, Topology[0]+1)] hidden_layers = [['h' + str(k+1) + ',' + str(i) for i in range(1, s+1)] for (k, s) in enumerate(Topology[1:-1])] output_layer = ['o' + str(i) ...
Python/7 Neural Networks/NN-Architecture.ipynb
karlstroetmann/Artificial-Intelligence
gpl-2.0
Cette idée vient d'une soirée Google Code initiée par Google et à laquelle des élèves de l'ENSAE ont participé. On dispose de la description des rues de Paris (qu'on considèrera comme des lignes droites). On veut déterminer le trajet de huit voitures de telle sorte qu'elles parcourent la ville le plus rapidement possib...
from jyquickhelper import add_notebook_menu add_notebook_menu()
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Une versions de ce problème est proposée sous forme de challenge : City Tour. Les données On récupère les données sur Internet.
import pyensae.datasource data = pyensae.datasource.download_data("paris_54000.zip") data
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
On extrait du fichier l'ensemble des carrefours (vertices) et des rues ou segment de rues (edges).
name = data[0] with open(name, "r") as f : lines = f.readlines() vertices = [] edges = [ ] for i,line in enumerate(lines) : spl = line.strip("\n\r").split(" ") if len(spl) == 2 : vertices.append ( (float(spl[0]), float(spl[1]) ) ) elif len(spl) == 5 and i > 0: v1,v2 = int(spl[0]),int...
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
On trace sur un graphique un échantillon des carrefours. On suppose la ville de Paris suffisamment petite et loin des pôles pour considérer les coordonnées comme cartésiennes (et non comme longitude/latitude).
import matplotlib.pyplot as plt import random sample = [ vertices[random.randint(0,len(vertices)-1)] for i in range(0,1000)] plt.plot( [_[0] for _ in sample], [_[1] for _ in sample], ".")
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Puis on dessine également un échantillon des rues.
sample = [ edges[random.randint(0,len(edges)-1)] for i in range(0,1000)] for edge in sample: plt.plot( [_[0] for _ in edge[-2:]], [_[1] for _ in edge[-2:]], "b-")
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Petite remarque : il n'y a pas de rues reliant le même carrefour :
len ( list(e for e in edges if e[0]==e[1] ))
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Une première solution au premier problème Ce problème est très similaire à celui du portier chinois. La solution qui suit n'est pas nécessaire la meilleure mais elle donne une idée de ce que peut-être une recherche un peu expérimentale sur le sujet. Chaque noeud représente un carrefour et chaque rue est un arc reliant ...
import networkx as nx g = nx.Graph() for i,j in [(1,2),(1,3),(1,4),(2,3),(3,4),(4,5),(5,2),(2,4) ]: g.add_edge( i,j ) import matplotlib.pyplot as plt f, ax = plt.subplots(figsize=(6,3)) nx.draw(g, ax = ax)
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
On ne peut pas trouver une chemin qui parcourt tous les arcs du graphe précédent une et une seule fois. Qu'en est-il du graphe de la ville de Paris ? On compte les noeuds qui ont un nombre pairs et impairs d'arcs les rejoignant (on appelle cela le degré).
nb_edge = { } for edge in edges : v1,v2 = edge[:2] nb_edge[v1] = nb_edge.get(v1,0)+1 nb_edge[v2] = nb_edge.get(v2,0)+1 parite = { } for k,v in nb_edge.items(): parite[v] = parite.get(v,0) + 1 [ sorted(parite.items()) ]
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
On remarque que la plupart des carrefours sont le départ de 3 rues. Qu'à cela ne tienne, pourquoi ne pas ajouter des arcs entre des noeuds de degré impair jusqu'à ce qu'il n'y en ait plus que 2. De cette façon, il sera facile de construire un seul chemin parcourant toutes les rues. Comment ajouter ces arcs ? Cela va se...
def distance(p1,p2): return ((p1[0]-p2[0])**2+(p1[1]-p2[1])**2)**0.5 edges = [ edge + (distance( edge[-2],edge[-1]),) for edge in edges]
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Ensuite, on implémente l'algorithme de Bellman-Ford.
import datetime init = { (e[0],e[1]) : e[-1] for e in edges } init.update ( { (e[1],e[0]) : e[-1] for e in edges } ) edges_from = { } for e in edges : if e[0] not in edges_from : edges_from[e[0]] = [] if e[1] not in edges_from : edges_from[e[1]] = [] edges_from[e[0]].append(e) edges_from[e[1]].append(...
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
On s'aperçoit vite que cela va être très très long. On décide alors de ne considérer que les paires de noeuds pour lesquelles la distance à vol d'oiseau est inférieure au plus grand segment de rue ou inférieure à cette distance multipliée par un coefficient.
max_segment = max( e[-1] for e in edges ) max_segment
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
On calcule les arcs admissibles (en espérant que les noeuds de degré impairs seront bien dedans). Cette étape prend quelques minutes :
possibles = { (e[0],e[1]) : e[-1] for e in edges } possibles.update ( { (e[1],e[0]) : e[-1] for e in edges } ) initial = possibles.copy() for i1,v1 in enumerate(vertices) : for i2 in range(i1+1,len(vertices)): v2 = vertices[i2] d = distance(v1,v2) if d < max_segment / 2 : # on ajuste...
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
On vérifie que les noeuds de degré impairs font tous partie de l'ensemble des noeuds recevant de nouveaux arcs. La matrice de Bellman envisagera au pire 2.2% de toutes les distances possibles.
allv = { p[0]:True for p in possibles if p not in initial } # possibles est symétrique for v,p in nb_edge.items() : if p % 2 == 1 and v not in allv : raise Exception("problème pour le noeud: {0}".format(v)) print("si vous voyez cette ligne, c'est que tout est bon")
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
On continue avec l'algorithme de Bellman-Ford modifié :
import datetime init = { (e[0],e[1]) : e[-1] for e in edges } init.update ( { (e[1],e[0]) : e[-1] for e in edges } ) edges_from = { } for e in edges : if e[0] not in edges_from : edges_from[e[0]] = [] if e[1] not in edges_from : edges_from[e[1]] = [] edges_from[e[0]].append(e) edges_from[e[1]].append(...
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
L'algorithme consiste à regarder les chemins $a \rightarrow b \rightarrow c$ et à comparer s'il est plus rapide que $a \rightarrow c$. 2.6% > 2.2% parce que le filtre est appliqué seulement sur $a \rightarrow b$. Finalement, on considère les arcs ajoutés puis on retire les arcs originaux.
original = { (e[0],e[1]) : e[-1] for e in edges } original.update ( { (e[1],e[0]) : e[-1] for e in edges } ) additions = { k:v for k,v in init.items() if k not in original } additions.update( { (k[1],k[0]):v for k,v in additions.items() } )
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Kruskall On trie les arcs par distance croissante, on enlève les arcs qui ne relient pas des noeuds de degré impair puis on les ajoute un par jusqu'à ce qu'il n'y ait plus d'arc de degré impair.
degre = { } for k,v in original.items() : # original est symétrique degre[k[0]] = degre.get(k[0],0) + 1 tri = [ (v,k) for k,v in additions.items() if degre[k[0]] %2 == 1 and degre[k[1]] %2 == 1 ] tri.extend( [ (v,k) for k,v in original.items() if degre[k[0]] %2 == 1 and degre[k[1]] %2 == 1 ] ) tri.sort() impai...
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Le nombre de noeuds impairs obtenus à la fin doit être inférieur à 2 pour être sûr de trouver un chemin (mais on choisira 0 pour avoir un circuit eulérien). Mon premier essai n'a pas donné satisfaction (92 noeuds impairs restant) car j'avais choisi un seuil (max_segment / 4) trop petit lors de la sélection des arcs à a...
from ensae_teaching_cs.special.rues_paris import eulerien_extension, distance_paris,get_data print("data") edges = get_data() print("start, nb edges", len(edges)) added = eulerien_extension(edges, distance=distance_paris) print("end, nb added", len(added))
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
On enregistre le résultat où on souhaite recommencer à partir de ce moment-là plus tard.
with open("added.txt","w") as f : f.write(str(added))
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Et si vous voulez le retrouver :
from ensae_teaching_cs.data import added data = added() from ensae_teaching_cs.special.rues_paris import eulerien_extension, distance_paris, get_data edges = get_data() with open(data, "r") as f: text = f.read() added_edges = eval(text)
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Chemin Eulérien A cet instant, on n'a pas vraiment besoin de connaître la longueur du chemin eulérien passant par tous les arcs. Il s'agit de la somme des arcs initiaux et ajoutés (soit environ 334 + 1511). On suppose qu'il n'y qu'une composante connexe. Construire le chemin eulérien fait apparaître quelques difficulté...
from pyquickhelper.helpgen import NbImage NbImage("euler.png")
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
Quelques algorithmes sont disponibles sur cette page Eulerian_path. L'algorithme de Hierholzer consiste à commencer un chemin eulérien qui peut revenir au premier avant d'avoir tout parcouru. Dans ce cas, on parcourt les noeuds du graphe pour trouver un noeud qui repart ailleurs et qui revient au même noeud. On insert ...
from ensae_teaching_cs.special.rues_paris import euler_path path = euler_path(edges, added_edges) path[:5]
_doc/notebooks/expose/ml_rue_paris_parcours.ipynb
sdpython/ensae_teaching_cs
mit
We want to be sure that this solution is ok. We replaced known values for $E$, $I$ and $q$ to check it. Cantilever beam with end load
sub_list = [(q(x), 0), (EI(x), E*I)] w_sol1 = w_sol.subs(sub_list).doit() L, F = symbols('L F') # Fixed end bc_eq1 = w_sol1.subs(x, 0) bc_eq2 = diff(w_sol1, x).subs(x, 0) # Free end bc_eq3 = diff(w_sol1, x, 2).subs(x, L) bc_eq4 = diff(w_sol1, x, 3).subs(x, L) + F/(E*I) [bc_eq1, bc_eq2, bc_eq3, bc_eq4] constants = so...
Euler_Bernoulli_beams.ipynb
nicoguaro/notebooks_examples
mit
Cantilever beam with uniformly distributed load
sub_list = [(q(x), 1), (EI(x), E*I)] w_sol1 = w_sol.subs(sub_list).doit() L = symbols('L') # Fixed end bc_eq1 = w_sol1.subs(x, 0) bc_eq2 = diff(w_sol1, x).subs(x, 0) # Free end bc_eq3 = diff(w_sol1, x, 2).subs(x, L) bc_eq4 = diff(w_sol1, x, 3).subs(x, L) constants = solve([bc_eq1, bc_eq2, bc_eq3, bc_eq4], [C1, C2, C3...
Euler_Bernoulli_beams.ipynb
nicoguaro/notebooks_examples
mit
Cantilever beam with exponential loading
sub_list = [(q(x), exp(x)), (EI(x), E*I)] w_sol1 = w_sol.subs(sub_list).doit() L = symbols('L') # Fixed end bc_eq1 = w_sol1.subs(x, 0) bc_eq2 = diff(w_sol1, x).subs(x, 0) # Free end bc_eq3 = diff(w_sol1, x, 2).subs(x, L) bc_eq4 = diff(w_sol1, x, 3).subs(x, L) constants = solve([bc_eq1, bc_eq2, bc_eq3, bc_eq4], [C1, C...
Euler_Bernoulli_beams.ipynb
nicoguaro/notebooks_examples
mit
Load written as a Taylor series and constant EI We can prove that the general function is written as
k = symbols('k', integer=True) C = symbols('C1:4') D = symbols('D', cls=Function) w_sol1 = 6*(C1 + C2*x) - 1/(E*I)*(3*C3*x**2 + C4*x**3 - 6*Sum(D(k)*x**(k + 4)/((k + 1)*(k + 2)*(k + 3)*(k + 4)),(k, 0, oo))) w_sol1
Euler_Bernoulli_beams.ipynb
nicoguaro/notebooks_examples
mit
Uniform load and varying cross-section
Q, alpha = symbols("Q alpha") sub_list = [(q(x), Q), (EI(x), E*x**3/12/tan(alpha))] w_sol1 = w_sol.subs(sub_list).doit() M_eq = -diff(M(x), x, 2) - Q M_eq M_sol = dsolve(M_eq, M(x)).rhs.subs([(C1, C3), (C2, C4)]) M_sol w_eq = f(x) + diff(w(x),x,2) w_eq w_sol1 = dsolve(w_eq, w(x)).subs(f(x), M_sol/(E*x**3/tan(alph...
Euler_Bernoulli_beams.ipynb
nicoguaro/notebooks_examples
mit
The shear stress would be
M = -E*x**3/tan(alpha)**3*diff(w_sol1.subs(constants).subs(C4, 0), x, 2) M diff(M, x) w_plot = w_sol1.subs(constants).subs({C4: 0, L: 1, Q: -1, E: 1, alpha: pi/9}) plot(w_plot, (x, 1e-6, 1)); from IPython.core.display import HTML def css_styling(): styles = open('./styles/custom_barba.css', 'r').read() retur...
Euler_Bernoulli_beams.ipynb
nicoguaro/notebooks_examples
mit
Quiz Question: How many predicted values in the test set are false positives?
print '1443'
course-3-classification/module-9-precision-recall-assignment-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Computing the cost of mistakes Put yourself in the shoes of a manufacturer that sells a baby product on Amazon.com and you want to monitor your product's reviews in order to respond to complaints. Even a few negative reviews may generate a lot of bad publicity about the product. So you don't want to miss any reviews w...
false_positive = confusion_matrix[(confusion_matrix['target_label'] == -1) & (confusion_matrix['predicted_label'] == 1) ]['count'][0] false_negative = confusion_matrix[(confusion_matrix['target_label'] == 1) & (confusion_matrix['predicted_label'] == -1) ]['count'][0] print 100 * false_positive + 1 * false_negative
course-3-classification/module-9-precision-recall-assignment-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Quiz Question: What fraction of the positive reviews in the test_set were correctly predicted as positive by the classifier? Quiz Question: What is the recall value for a classifier that predicts +1 for all data points in the test_data? Precision-recall tradeoff In this part, we will explore the trade-off between preci...
from graphlab import SArray def apply_threshold(probabilities, threshold): ### YOUR CODE GOES HERE # +1 if >= threshold and -1 otherwise. array = map(lambda propability: +1 if propability > threshold else -1, probabilities) return SArray(array)
course-3-classification/module-9-precision-recall-assignment-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
For each of the values of threshold, we compute the precision and recall scores.
precision_all = [] recall_all = [] best_threshold = None probabilities = model.predict(test_data, output_type='probability') for threshold in threshold_values: predictions = apply_threshold(probabilities, threshold) precision = graphlab.evaluation.precision(test_data['sentiment'], predictions) recall ...
course-3-classification/module-9-precision-recall-assignment-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Quiz Question: Among all the threshold values tried, what is the smallest threshold value that achieves a precision of 96.5% or better? Round your answer to 3 decimal places.
0.838
course-3-classification/module-9-precision-recall-assignment-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Quiz Question: Using threshold = 0.98, how many false negatives do we get on the test_data? (Hint: You may use the graphlab.evaluation.confusion_matrix function implemented in GraphLab Create.)
threshold = 0.98 probabilities = model.predict(test_data, output_type='probability') predictions = apply_threshold(probabilities, threshold) graphlab.evaluation.confusion_matrix(test_data['sentiment'], predictions)
course-3-classification/module-9-precision-recall-assignment-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Second, as we did above, let's compute precision and recall for each value in threshold_values on the baby_reviews dataset. Complete the code block below.
precision_all = [] recall_all = [] best_threshold = None for threshold in threshold_values: # Make predictions. Use the `apply_threshold` function ## YOUR CODE HERE predictions = apply_threshold(probabilities, threshold) # Calculate the precision. # YOUR CODE HERE precision = graphlab.e...
course-3-classification/module-9-precision-recall-assignment-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Quiz Question: Among all the threshold values tried, what is the smallest threshold value that achieves a precision of 96.5% or better for the reviews of data in baby_reviews? Round your answer to 3 decimal places.
best_threshold
course-3-classification/module-9-precision-recall-assignment-blank.ipynb
kgrodzicki/machine-learning-specialization
mit
Explain what the cell below will produce and why. Can you change it so the answer is correct?
# Will produce 0 in python 2. produces 0.66 in python 3 because of "true" division 2/3 # the following import will change the outcome from __future__ import division 2/3
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Answer these 3 questions without typing code. Then type code to check your answer. What is the value of the expression 4 * (6 + 5) What is the value of the expression 4 * 6 + 5 What is the value of the expression 4 + 6 * 5
# 4 * (6 + 5) = 44 4 * (6 + 5) # 4 * 6 + 5 = 29 4 * 6 + 5 # 4 + 6 * 5 = 34 4 + 6 * 5
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
What is the type of the result of the expression 3 + 1.5 + 4? Floating point number, 8.5
3 + 1.5 + 4
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
What would you use to find a number’s square root, as well as its square?
#x**y for square, x**0.5 for square root print(2**2) print(4**0.5)
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Strings Given the string 'hello' give an index command that returns 'e'. Use the code below:
s = 'hello' # Print out 'e' using indexing # Code here print(s[1])
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Reverse the string 'hello' using indexing:
s ='hello' # Reverse the string using indexing # Code here print(s[::-1])
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Given the string hello, give two methods of producing the letter 'o' using indexing.
s ='hello' # Print out the # Code here print(s[-1:]) print(s[len(s) - 1])
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Lists Build this list [0,0,0] two separate ways.
print([0,0,0]) print([0] * 3)
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Reassign 'hello' in this nested list to say 'goodbye' item in this list:
l = [1,2,[3,4,'hello']] l[2][2] = "goodbye" print(l)
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Sort the list below:
l = [3,4,5,5,6] result = l.sort() print(result)
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Dictionaries Using keys and indexing, grab the 'hello' from the following dictionaries:
d = {'simple_key':'hello'} # Grab 'hello' print(d["simple_key"]) d = {'k1':{'k2':'hello'}} # Grab 'hello' print(d["k1"]["k2"]) # Getting a little tricker d = {'k1':[ {'nest_key':['this is deep',['hello']]} ]} #Grab hello print(d["k1"][0]["nest_key"][1][0]) # This will be hard and annoying! d = {'k1':[ 1...
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Can you sort a dictionary? Why or why not? No, dictionaries aren't indexed. Tuples What is the major difference between tuples and lists? mutability: lists are, tuples aren't How do you create a tuple?
tup = (2, "yes", 3.0) print(tup)
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Sets What is unique about a set? non-repeating elements Use a set to find the unique values of the list below:
l = [1,2,2,33,4,4,11,22,3,3,2] s = set(l) print(s)
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Booleans For the following quiz questions, we will get a preview of comparison operators: <table class="table table-bordered"> <tr> <th style="width:10%">Operator</th><th style="width:45%">Description</th><th>Example</th> </tr> <tr> <td>==</td> <td>If the values of two operands are equal, then the condition becomes tru...
# Answer before running cell 2 > 3 # False # Answer before running cell 3 <= 2 # False # Answer before running cell 3 == 2.0 # False # Answer before running cell 3.0 == 3 # True # Answer before running cell 4**0.5 != 2 # False
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Final Question: What is the boolean output of the cell block below?
# two nested lists l_one = [1,2,[3,4]] l_two = [1,2,{'k1':4}] #True or False? l_one[2][0] >= l_two[2]['k1'] # False, 3 >= 4
Objects and Data Structures Assessment Test-Copy1.ipynb
spacedrabbit/PythonBootcamp
mit
Some notes should rename the tables consistently e.g. dfsummary, dfdata, dfinfo, dfsteps, dffid have to take care so that it also can read "old" cellpy-files should make (or check if it is already made) an option for giving a "custom" config-file in starting the session
my_data.make_step_table() filename2 = Path("/Users/jepe/Arbeid/Data/celldata/20171120_nb034_11_cc.nh5") my_data.save(filename2) print(f"size: {filename2.stat().st_size/1_048_576} MB") my_data2 = cellreader.CellpyData() my_data2.load(filename2) dataset2 = my_data2.dataset print(dataset2.steps.columns) del my_data2 de...
dev_utils/lookup/cellpy_check_hdf5_queries.ipynb
jepegit/cellpy
mit
Querying cellpy file (hdf5) load steptable get the stepnumbers for given cycle create query and run it scale the charge (100_000/mass)
steptable = store.select(stepname) s = my_data.get_step_numbers( steptype="charge", allctypes=True, pdtype=True, cycle_number=None, steptable=steptable, ) cycle_mask = ( s["cycle"] == 2 ) # also possible to give cycle_number in get_step_number instead s.head() a = s.loc[cycle_mask, ["point_f...
dev_utils/lookup/cellpy_check_hdf5_queries.ipynb
jepegit/cellpy
mit
Result 65% penalty for using "hdf5" query lookup 5.03 vs 3.05 ms
plt.plot(c2[c_hdr], c2[v_hdr]) store.close()
dev_utils/lookup/cellpy_check_hdf5_queries.ipynb
jepegit/cellpy
mit
You can see here the various ingredients going into each variety of concrete. We'll see in a moment how adding some additional synthetic features derived from these can help a model to learn important relationships among them. We'll first establish a baseline by training the model on the un-augmented dataset. This will...
X = df.copy() y = X.pop("CompressiveStrength") # Train and score baseline model baseline = RandomForestRegressor(criterion="mae", random_state=0) baseline_score = cross_val_score( baseline, X, y, cv=5, scoring="neg_mean_absolute_error" ) baseline_score = -1 * baseline_score.mean() print(f"MAE Baseline Score: {bas...
notebooks/feature_engineering_new/raw/tut1.ipynb
Kaggle/learntools
apache-2.0
If you ever cook at home, you might know that the ratio of ingredients in a recipe is usually a better predictor of how the recipe turns out than their absolute amounts. We might reason then that ratios of the features above would be a good predictor of CompressiveStrength. The cell below adds three new ratio features ...
X = df.copy() y = X.pop("CompressiveStrength") # Create synthetic features X["FCRatio"] = X["FineAggregate"] / X["CoarseAggregate"] X["AggCmtRatio"] = (X["CoarseAggregate"] + X["FineAggregate"]) / X["Cement"] X["WtrCmtRatio"] = X["Water"] / X["Cement"] # Train and score model on dataset with additional ratio features...
notebooks/feature_engineering_new/raw/tut1.ipynb
Kaggle/learntools
apache-2.0
Naming convention The table which defines the used references of each atom will be called construction table. The contruction table of the zmatrix of the water dimer can be seen here:
zwater.loc[:, ['b', 'a', 'd']]
Tutorial/Transformation.ipynb
mcocdawc/chemcoord
lgpl-3.0
The absolute references are indicated by magic strings: ['origin', 'e_x', 'e_y', 'e_z']. The atom which is to be set in the reference of three other atoms, is denoted $i$. The bond-defining atom is represented by $b$. The angle-defining atom is represented by $a$. The dihedral-defining atom is represented by $d$. Mat...
water = water - water.loc[5, ['x', 'y', 'z']] zmolecule = water.get_zmat() c_table = zmolecule.loc[:, ['b', 'a', 'd']] c_table.loc[6, ['a', 'd']] = [2, 1] zmolecule1 = water.get_zmat(construction_table=c_table) zmolecule2 = zmolecule1.copy() zmolecule3 = water.get_zmat(construction_table=c_table)
Tutorial/Transformation.ipynb
mcocdawc/chemcoord
lgpl-3.0
Modifications on zmolecule1
angle_before_assignment = zmolecule1.loc[4, 'angle'] zmolecule1.safe_loc[4, 'angle'] = 180 zmolecule1.safe_loc[5, 'dihedral'] = 90 zmolecule1.safe_loc[4, 'angle'] = angle_before_assignment xyz1 = zmolecule1.get_cartesian() xyz1.view()
Tutorial/Transformation.ipynb
mcocdawc/chemcoord
lgpl-3.0
Contextmanager With the following contextmanager we can switch the automatic insertion of dummy atoms of and look at the cartesian which is built after assignment of .safe_loc[4, 'angle'] = 180. It is obvious from the structure, that the coordinate system spanned by O - H - O is undefined. This was the second pathologi...
with cc.DummyManipulation(False): try: zmolecule3.safe_loc[4, 'angle'] = 180 except cc.exceptions.InvalidReference as e: e.already_built_cartesian.view()
Tutorial/Transformation.ipynb
mcocdawc/chemcoord
lgpl-3.0
Symbolic evaluation It is possible to use symbolic expressions from sympy.
import sympy sympy.init_printing() d = sympy.Symbol('d') symb_water = zwater.copy() symb_water.safe_loc[4, 'bond'] = d symb_water symb_water.subs(d, 2) cc.xyz_functions.view([symb_water.subs(d, i).get_cartesian() for i in range(2, 5)]) # If your viewer cannot open molden files you have to uncomment the following ...
Tutorial/Transformation.ipynb
mcocdawc/chemcoord
lgpl-3.0
Definition of the construction table The construction table in chemcoord is represented by a pandas DataFrame with the columns ['b', 'a', 'd'] which can be constructed manually.
pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]], columns=['b', 'a', 'd'])
Tutorial/Transformation.ipynb
mcocdawc/chemcoord
lgpl-3.0
It is possible to specify only the first $i$ rows of a Zmatrix, in order to compute the $i + 1$ to $n$ rows automatically. If the molecule consists of unconnected fragments, the construction tables are created independently for each fragment and connected afterwards. It is important to note, that an unfragmented, monol...
water.get_zmat()
Tutorial/Transformation.ipynb
mcocdawc/chemcoord
lgpl-3.0
Let's fragmentate the water
fragments = water.fragmentate() c_table = water.get_construction_table(fragment_list=[fragments[1], fragments[0]]) water.get_zmat(c_table)
Tutorial/Transformation.ipynb
mcocdawc/chemcoord
lgpl-3.0
If we want to specify the order in the second fragment, so that it connects via the oxygen 1, it is important to note, that we have to specify the full row. It is not possible to define just the order without the references.
frag_c_table = pd.DataFrame([[4, 6, 5], [1, 4, 6], [1, 2, 4]], columns=['b', 'a', 'd'], index=[1, 2, 3]) c_table2 = water.get_construction_table(fragment_list=[fragments[1], (fragments[0], frag_c_table)]) water.get_zmat(c_table2)
Tutorial/Transformation.ipynb
mcocdawc/chemcoord
lgpl-3.0
Regresion Lineal
# librerias seabron as sns import seaborn as sns # Hr sns.lmplot(x='Hr',y='HrWRF',data=data, col='Month', aspect=0.6, size=8) # Tpro sns.lmplot(x='Tpro',y='TproWRF',data=data, col='Month', aspect=0.6, size=8) # Rain sns.lmplot(x='Rain',y='RainWRF',data=data, col='Month', aspect=0.6, size=8) # Rain polynomial regres...
algoritmos/Validacion App Movil climMAPcore.ipynb
jorgemauricio/INIFAP_Course
mit
Regresion lineal con p y pearsonr
# Hr sns.jointplot("Hr", "HrWRF", data=data, kind="reg") # Tpro sns.jointplot("Tpro", "TproWRF", data=data, kind="reg") # Rain sns.jointplot("Rain", "RainWRF", data=data, kind="reg")
algoritmos/Validacion App Movil climMAPcore.ipynb
jorgemauricio/INIFAP_Course
mit
OLS Regression
# HR result = sm.ols(formula='HrWRF ~ Hr', data=data).fit() print(result.params) print(result.summary()) # Tpro result = sm.ols(formula='TproWRF ~ Tpro', data=data).fit() print(result.params) print(result.summary()) # Rain result = sm.ols(formula='RainWRF ~ Rain', data=data).fit() print(result.params) print(res...
algoritmos/Validacion App Movil climMAPcore.ipynb
jorgemauricio/INIFAP_Course
mit
Histogramas seaborn
# Hr sns.distplot(data['diffHr']) # Tpro sns.distplot(data['diffTpro']) # Rain sns.distplot(data['diffRain'])
algoritmos/Validacion App Movil climMAPcore.ipynb
jorgemauricio/INIFAP_Course
mit
Model summary Run done with model with three convolutional layers, two fully connected layers and a final softmax layer, with 64 channels per convolutional layer in first two layers and 48 in final. Fully connected layers have 512 units each. Dropout applied in first (larger) fully connected layer (dropout probability ...
print('## Model structure summary\n') print(model) params = model.get_params() n_params = {p.name : p.get_value().size for p in params} total_params = sum(n_params.values()) print('\n## Number of parameters\n') print(' ' + '\n '.join(['{0} : {1} ({2:.1f}%)'.format(k, v, 100.*v/total_params) ...
notebooks/3 convolutional layers (96-96-48 channels) 2 fully connected (512-512 units).ipynb
Neuroglycerin/neukrill-net-work
mit
Load LendingClub dataset We will be using a dataset from the LendingClub. A parsed and cleaned form of the dataset is availiable here. Make sure you download the dataset before running the following command.
loans = graphlab.SFrame('lending-club-data.gl/') loans.head()
ml-classification/week-3/module-5-decision-tree-assignment-1-blank.ipynb
zomansud/coursera
mit
Now, write some code to compute below the percentage of safe and risky loans in the dataset and validate these numbers against what was given using .show earlier in the assignment:
print "Percentage of safe loans : %.2f" % ((float(len(safe_loans_raw)) / len(loans)) * 100) print "Percentage of risky loans : %.2f" % ((float(len(risky_loans_raw)) / len(loans)) * 100)
ml-classification/week-3/module-5-decision-tree-assignment-1-blank.ipynb
zomansud/coursera
mit
Quiz Question: What percentage of the predictions on sample_validation_data did decision_tree_model get correct?
float((sample_validation_data['safe_loans'] == decision_tree_model.predict(sample_validation_data)).sum()) / len(sample_validation_data)
ml-classification/week-3/module-5-decision-tree-assignment-1-blank.ipynb
zomansud/coursera
mit
Explore probability predictions For each row in the sample_validation_data, what is the probability (according decision_tree_model) of a loan being classified as safe? Hint: Set output_type='probability' to make probability predictions using decision_tree_model on sample_validation_data:
decision_tree_model.predict(sample_validation_data, output_type='probability')
ml-classification/week-3/module-5-decision-tree-assignment-1-blank.ipynb
zomansud/coursera
mit
Checkpoint: You should see that the small_model performs worse than the decision_tree_model on the training data. Now, let us evaluate the accuracy of the small_model and decision_tree_model on the entire validation_data, not just the subsample considered above.
print small_model.evaluate(validation_data)['accuracy'] print round(decision_tree_model.evaluate(validation_data)['accuracy'],2)
ml-classification/week-3/module-5-decision-tree-assignment-1-blank.ipynb
zomansud/coursera
mit
False positives are predictions where the model predicts +1 but the true label is -1. Complete the following code block for the number of false positives:
false_positives = (predictions == +1) == (validation_data['safe_loans'] == -1) print false_positives.sum() print len(predictions) fp = 0 for i in xrange(len(predictions)): if predictions[i] == 1 and validation_data['safe_loans'][i] == -1: fp += 1 print fp
ml-classification/week-3/module-5-decision-tree-assignment-1-blank.ipynb
zomansud/coursera
mit
False negatives are predictions where the model predicts -1 but the true label is +1. Complete the following code block for the number of false negatives:
false_negatives = (predictions == -1) == (validation_data['safe_loans'] == +1) print false_negatives.sum() print len(predictions) fn = 0 for i in xrange(len(predictions)): if predictions[i] == -1 and validation_data['safe_loans'][i] == 1: fn += 1 print fn
ml-classification/week-3/module-5-decision-tree-assignment-1-blank.ipynb
zomansud/coursera
mit
Quiz Question: Let us assume that each mistake costs money: * Assume a cost of \$10,000 per false negative. * Assume a cost of \$20,000 per false positive. What is the total cost of mistakes made by decision_tree_model on validation_data?
cost = fp * 20000 + fn * 10000 cost
ml-classification/week-3/module-5-decision-tree-assignment-1-blank.ipynb
zomansud/coursera
mit
Starting with the Philips EL34 data sheet, create a PNG of the import this image into engauge Create 9 curves then use 'curve point tool' to add points to each curve Change export options, "Raw Xs and Ys" and "One curve on each line", otherwise engauge will do some interrupting of your points export a csv file
%cat data/el34-philips-1958-360V.csv
experiments/02-modeling/pentode/pentode-modeling.ipynb
holla2040/valvestudio
mit
Need to create scipy array like this x = scipy.array( [[360, -0.0, 9.66], [360, -0.0, 22.99], ... y = scipy.array( [0.17962, 0.26382, 0.3227, 0.37863, ... Vaks = scipy.array( [9.66, 22.99, 41.49, 70.55, 116.61, ... from the extracted curves
fname = "data/el34-philips-1958-360V.csv" f = open(fname,'r').readlines() deltaVgk = -4.0 n = 1.50 VgkVak = [] Iak = [] Vaks = [] f = open(fname,'r').readlines() vg2k = 360 for l in f: l = l.strip() if len(l): # skip blank lines if l[0] == 'x': vn = float(l.split("Curve")[1]) - 1....
experiments/02-modeling/pentode/pentode-modeling.ipynb
holla2040/valvestudio
mit