markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Transform submission object to a provenance graph | #d1.get_records()
submission = d1.get_record('subm:out1_sub')[0]
review = d1.get_record('subm:out1_rev')[0]
ingest = d1.get_record('subm:out1_ing')[0]
check = d1.get_record('subm:out1_che')[0]
publication = d1.get_record('subm:out1_pub')[0]
lta = d1.get_record('subm:out1_arch')[0]
res = form_handler.prefix_dict(sf.su... | test/prov/old/prov-submission.ipynb | IS-ENES-Data/submission_forms | apache-2.0 |
Simple file operations
writing to files | # files can be opened using the open function, which creates a file object
f = open( 'new_file.txt', 'w' ) # attention overwrites existing file
# important functions: read, write, readlines, writelines
# dir(f)
f.write("Hallo Welt!")
f.close()
# writelines
lines = []
for i in range(12):
lines.append("Number: " +... | 05_dataio_matplotlib/FileHandling.ipynb | brunnerp/PythonFachkurs | mit |
reading from files | # usage of with to open files is recommended in python
with open('new_file.txt', 'r') as f: # open file for reading
content = f.read() # get the whole content of a file into a string
print(content)
with open('new_file.txt', 'r') as f: # open file for reading
lines = f.readlines()
print(lines)
f.close() | 05_dataio_matplotlib/FileHandling.ipynb | brunnerp/PythonFachkurs | mit |
Parsing data | with open('data.txt', 'r') as f:
lines = f.readlines()
#print(lines)
data = {}
# iterate over all lines in the file
for line in lines:
if line.startswith('#'): # skip comments
continue
left, right = line.split(':') # split splits a string at the occurence of the keyword
data[ left.strip() ] = ... | 05_dataio_matplotlib/FileHandling.ipynb | brunnerp/PythonFachkurs | mit |
Object serialization using pickle | # the pickle class is used to serialize python variables (convert them to bytestrings)
import pickle | 05_dataio_matplotlib/FileHandling.ipynb | brunnerp/PythonFachkurs | mit |
how pickle converts objects to strings | d = { 1: 'green', 2: 'blue', 3: 'red' }
pickle.dumps(d) | 05_dataio_matplotlib/FileHandling.ipynb | brunnerp/PythonFachkurs | mit |
how to save objects to a file | with open('save.p', 'wb') as f:
pickle.dump(d, f)
with open('save.p', 'wb') as f:
pickle.dump(d, f)
with open('save.p', 'rb') as f:
loaded_data = pickle.load(f)
print(loaded_data) | 05_dataio_matplotlib/FileHandling.ipynb | brunnerp/PythonFachkurs | mit |
Organizing files in folders | # create a folder for the data files
import os
# get current working directory
work_path = os.getcwd()
print(work_path)
# define path for data files
data_path = os.path.join(work_path, 'data/')
# check if folder exists already
if not os.path.exists(data_path):
os.mkdir(data_path) | 05_dataio_matplotlib/FileHandling.ipynb | brunnerp/PythonFachkurs | mit |
Comma separated value (CSV) files
reading tabular data using pandas | with open('real_estate.csv', 'r') as f:
f.readlines()
import pandas as pd
df = pd.read_csv( 'real_estate.csv' )
print(df)
#print(df.values.tolist()) | 05_dataio_matplotlib/FileHandling.ipynb | brunnerp/PythonFachkurs | mit |
JavaScript Object Notation (JSON)
JSON (/ˈdʒeɪsən/ JAY-sən),[1] or JavaScript Object Notation, is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Alth... | cat employees.json
import json
d = json.load( open('employees.json') )
d['employees'][1] | 05_dataio_matplotlib/FileHandling.ipynb | brunnerp/PythonFachkurs | mit |
(a)
Let $f = x^6$. And $\int_{-1}^{1} f dx = \frac{2}{7}$.
Use Gauss-Lobatto-Legendre quadrature to numerically evaluate $\int_{-1}^{1} f dx$ with number of quadrature points $Q=4,\ 5,\ 6$. | def f(x):
"""the integrand: x**6"""
return x**6
print("The exact solution is: ", 2./7.)
for Qi in [4, 5, 6]:
qd = quad.GaussLobattoJacobi(Qi)
ans = qd(f, -1, 1)
print("Q = {0}, ans = {1}, absolute error is {2}".format(Qi, ans, abs(ans-2./7.))) | solutions/chapter02/exercise01.ipynb | piyueh/SEM-Toolbox | mit |
(b)
Let $f = x^6$. And $\int_{-1}^{2} f dx = \frac{129}{7}$.
Use Gauss-Lobatto-Legendre quadrature to numerically evaluate $\int_{-1}^{2} f dx$ with number of quadrature points $Q=4,\ 5,\ 6$. | print("The exact solution is: ", 129./7.)
for Qi in [4, 5, 6]:
qd = quad.GaussLobattoJacobi(Qi)
ans = qd(f, -1, 2)
print("Q = {0}, ans = {1}, absolute error is {2}".format(Qi, ans, abs(ans-129./7.))) | solutions/chapter02/exercise01.ipynb | piyueh/SEM-Toolbox | mit |
(c)
Let $f = \sin{x}$. And $\int_{0}^{\pi/2} f dx = 1$.
Use Gauss-Lobatto-Legendre quadrature to numerically evaluate $\int_{0}^{\pi/2} f dx$ with number of quadrature points $2 \le Q \le 8$ and plot the error to check the convergence order. | def f(x):
"""the integrand: x**6"""
return numpy.sin(x)
print("The exact solution is: ", 1.)
Q = range(2, 9)
err = numpy.zeros_like(Q, dtype=numpy.float64)
for i, Qi in enumerate(Q):
qd = quad.GaussLobattoJacobi(Qi)
ans = qd(f, 0., numpy.pi/2.)
err[i] = numpy.abs(ans - 1.)
print("Q = {0},... | solutions/chapter02/exercise01.ipynb | piyueh/SEM-Toolbox | mit |
Commands for plotting
These are used so the the usual "plot" will use matplotlib. | # commands for plotting, "plot" works with matplotlib
def mesh2triang(mesh):
xy = mesh.coordinates()
return tri.Triangulation(xy[:, 0], xy[:, 1], mesh.cells())
def mplot_cellfunction(cellfn):
C = cellfn.array()
tri = mesh2triang(cellfn.mesh())
return plt.tripcolor(tri, facecolors=C)
def mplot_fun... | .ipynb_checkpoints/Annulus_Simple_Matplotlib-checkpoint.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Annulus
This is the field in an annulus. We specify boundary conditions and solve the problem. | r1 = 1 # inner circle radius
r2 = 10 # outer circle radius
# shapes of inner/outer boundaries are circles
c1 = Circle(Point(0.0, 0.0), r1)
c2 = Circle(Point(0.0, 0.0), r2)
domain = c2 - c1 # solve between circles
res = 20
mesh = generate_mesh(domain, res)
class outer_boundary(SubDomain):
def inside(self, x, o... | .ipynb_checkpoints/Annulus_Simple_Matplotlib-checkpoint.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Plotting with matplotlib
Now the usual "plot" commands will work for plotting the mesh and the function. | plot(mesh) # usual Fenics command, will use matplotlib
plot(u) # usual Fenics command, will use matplotlib | .ipynb_checkpoints/Annulus_Simple_Matplotlib-checkpoint.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
If you want to do usual "matplotlib" stuff then you still need "plt." prefix on commands. | plt.figure()
plt.subplot(1,2,1)
plot(mesh)
plt.xlabel('x')
plt.ylabel('y')
plt.subplot(1,2,2)
plot(u)
plt.title('annulus solution') | .ipynb_checkpoints/Annulus_Simple_Matplotlib-checkpoint.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Plotting along a line
It turns out the the solution "u" is a function that can be evaluated at a point. So in the next cell we loop through a line and make a vector of points for plotting. You just need to give it coordinates $u(x,y)$. | y = np.linspace(r1,r2*0.99,100)
uu = []
np.array(uu)
for i in range(len(y)):
yy = y[i]
uu.append(u(0.0,yy)) #evaluate u along y axis
plt.figure()
plt.plot(y,uu)
plt.grid(True)
plt.xlabel('y')
plt.ylabel('V')
u | .ipynb_checkpoints/Annulus_Simple_Matplotlib-checkpoint.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Data vectors of users
<a id=userdatavectors /> | #getAllResponders()
setAnswerTemporalities(gform) | v1.52/Tests/4.1 User comparison tests.ipynb | CyberCRI/dataanalysis-herocoli-redmetrics | cc0-1.0 |
getAllUserVectorData | # small sample
#allData = getAllUserVectorData( getAllUsers( rmdf152 )[:10] )
# complete set
#allData = getAllUserVectorData( getAllUsers( rmdf152 ) )
# subjects who answered the gform
allData = getAllUserVectorData( getAllResponders() )
# 10 subjects who answered the gform
#allData = getAllUserVectorData( getAllRes... | v1.52/Tests/4.1 User comparison tests.ipynb | CyberCRI/dataanalysis-herocoli-redmetrics | cc0-1.0 |
Correlation Matrix | methods = ['pearson', 'kendall', 'spearman']
_allUserVectorData = allData.T
_method = methods[0]
_title='RedMetrics Correlations'
_abs=True
_clustered=False
_figsize = (20,20)
#def plotAllUserVectorDataCorrelationMatrix(
# _allUserVectorData,
# _method = methods[0],
# _title='RedMetrics Correlations',
# ... | v1.52/Tests/4.1 User comparison tests.ipynb | CyberCRI/dataanalysis-herocoli-redmetrics | cc0-1.0 |
List of users and their sessions
<a id=userlists /> | userSessionsRelevantColumns = ['customData.localplayerguid', 'sessionId']
userSessions = rmdf152[rmdf152['type']=='start'].loc[:,userSessionsRelevantColumns]
userSessions = userSessions.rename(index=str, columns={'customData.localplayerguid': 'userId'})
userSessions.head()
#groupedUserSessions = userSessions.groupby(... | v1.52/Tests/4.1 User comparison tests.ipynb | CyberCRI/dataanalysis-herocoli-redmetrics | cc0-1.0 |
List of sessions with their checkpoints achievements
<a id=sessionscheckpoints /> | checkpointsRelevantColumns = ['sessionId', 'customData.localplayerguid', 'type', 'section', 'userTime']
checkpoints = rmdf152.loc[:, checkpointsRelevantColumns]
checkpoints = checkpoints[checkpoints['type']=='reach'].loc[:,['section','sessionId','userTime']]
checkpoints = checkpoints[checkpoints['section'].str.startsw... | v1.52/Tests/4.1 User comparison tests.ipynb | CyberCRI/dataanalysis-herocoli-redmetrics | cc0-1.0 |
Assembly of both
<a id=assembly /> | #assembled = userSessions.combine_first(checkpoints)
assembled = pd.merge(userSessions, checkpoints, on='sessionId', how='outer')
assembled.head()
userSections = assembled.drop('sessionId', 1)
userSections.head()
userSections = userSections.dropna()
userSections.head()
checkpoints = userSections.groupby("userId")
ch... | v1.52/Tests/4.1 User comparison tests.ipynb | CyberCRI/dataanalysis-herocoli-redmetrics | cc0-1.0 |
Time analysis
<a id=time /> | #userTimedSections = userSections.groupby("userId").agg({ "userTime": np.min })
#userTimedSections = userSections.groupby("userId")
userTimes = userSections.groupby("userId").agg({ "userTime": [np.min, np.max] })
userTimes["duration"] = pd.to_datetime(userTimes["userTime"]["amax"]) - pd.to_datetime(userTimes["userTime"... | v1.52/Tests/4.1 User comparison tests.ipynb | CyberCRI/dataanalysis-herocoli-redmetrics | cc0-1.0 |
TODO
userTimes.loc[:,'duration']
userTimes = userTimes[4:]
userTimes["duration_seconds"] = userTimes["duration"].map(lambda x: pd.Timedelta(x).seconds)
maxDuration = np.max(userTimes["duration_seconds"])
userTimes["duration_rank"] = userTimes["duration_seconds"].rank(ascending=False)
userTimes.plot(x="duration_rank", y... | sessionCount = 1
_rmDF = rmdf152
sample = gform
before = False
after = True
gfMode = False
rmMode = True
#def getAllUserVectorDataCustom(before, after, gfMode = False, rmMode = True, sessionCount = 1, _rmDF = rmdf152)
userIds = []
if (before and after):
userIds = getSurveysOfUsersWhoAnsweredBoth(sample, gfMode = ... | v1.52/Tests/4.1 User comparison tests.ipynb | CyberCRI/dataanalysis-herocoli-redmetrics | cc0-1.0 |
user progress classification
tinkering | testUser = "3685a015-fa97-4457-ad73-da1c50210fe1"
def getScoreFromBinarized(binarizedAnswers):
gformIndices = binarizedAnswers.index.map(lambda s: int(s.split(correctionsColumnNameStem)[1]))
return pd.Series(np.dot(binarizedAnswers, np.ones(binarizedAnswers.shape[1])), index=gform.loc[gformIndices, localplayer... | v1.52/Tests/4.1 User comparison tests.ipynb | CyberCRI/dataanalysis-herocoli-redmetrics | cc0-1.0 |
First reload the data we generated in 1_notmnist.ipynb. | pickle_file = 'notMNIST.pickle'
with open(pickle_file, 'rb') as f:
save = pickle.load(f)
train_dataset = save['train_dataset']
train_labels = save['train_labels']
valid_dataset = save['valid_dataset']
valid_labels = save['valid_labels']
test_dataset = save['test_dataset']
test_labels = save['test_labels'... | tensorflow/examples/udacity/2_fullyconnected.ipynb | Bismarrck/tensorflow | apache-2.0 |
Reformat into a shape that's more adapted to the models we're going to train:
- data as a flat matrix,
- labels as float 1-hot encodings. | image_size = 28
num_labels = 10
def reformat(dataset, labels):
dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32)
# Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...]
labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32)
return dataset, labels
train_dataset, train_l... | tensorflow/examples/udacity/2_fullyconnected.ipynb | Bismarrck/tensorflow | apache-2.0 |
We're first going to train a multinomial logistic regression using simple gradient descent.
TensorFlow works like this:
* First you describe the computation that you want to see performed: what the inputs, the variables, and the operations look like. These get created as nodes over a computation graph. This description... | # With gradient descent training, even this much data is prohibitive.
# Subset the training data for faster turnaround.
train_subset = 10000
graph = tf.Graph()
with graph.as_default():
# Input data.
# Load the training, validation and test data into constants that are
# attached to the graph.
tf_train_dataset... | tensorflow/examples/udacity/2_fullyconnected.ipynb | Bismarrck/tensorflow | apache-2.0 |
Let's run this computation and iterate: | num_steps = 801
def accuracy(predictions, labels):
return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
/ predictions.shape[0])
with tf.Session(graph=graph) as session:
# This is a one-time operation which ensures the parameters get initialized as
# we described in the graph: rand... | tensorflow/examples/udacity/2_fullyconnected.ipynb | Bismarrck/tensorflow | apache-2.0 |
Let's now switch to stochastic gradient descent training instead, which is much faster.
The graph will be similar, except that instead of holding all the training data into a constant node, we create a Placeholder node which will be fed actual data at every call of session.run(). | batch_size = 128
graph = tf.Graph()
with graph.as_default():
# Input data. For the training data, we use a placeholder that will be fed
# at run time with a training minibatch.
tf_train_dataset = tf.placeholder(tf.float32,
shape=(batch_size, image_size * image_size))
tf_tra... | tensorflow/examples/udacity/2_fullyconnected.ipynb | Bismarrck/tensorflow | apache-2.0 |
Let's run it: | num_steps = 3001
with tf.Session(graph=graph) as session:
tic = time.time()
try:
tf.global_variables_initializer().run()
except AttributeError:
tf.initialize_all_variables().run()
print("Initialized")
for step in range(num_steps):
# Pick an offset within the training data, which has been randomiz... | tensorflow/examples/udacity/2_fullyconnected.ipynb | Bismarrck/tensorflow | apache-2.0 |
Problem
Turn the logistic regression example with SGD into a 1-hidden layer neural network with rectified linear units nn.relu() and 1024 hidden nodes. This model should improve your validation / test accuracy. | batch_size = 128
nodes = 1024
num_steps = 3001
nngraph = tf.Graph()
with nngraph.as_default():
# Input data. For the training data, we use a placeholder that will be fed
# at run time with a training minibatch.
tf_train_dataset = tf.placeholder(tf.float32,
shape=(batch_size,... | tensorflow/examples/udacity/2_fullyconnected.ipynb | Bismarrck/tensorflow | apache-2.0 |
Result function
The 'result' function investigates the VCLOD for each percentage. The reference solution is computed by a standard FEM on the fine mesh. We compute the 'worst solution' that represents zero percentage updating and clearly has no computational cost at all. Afterwards, we compute the error indicator for t... | def result(pglod, world, A, R, f, k, String):
print "-------------- " + String + " ---------------"
NWorldFine = world.NWorldFine
NWorldCoarse = world.NWorldCoarse
NCoarseElement = world.NCoarseElement
boundaryConditions = world.boundaryConditions
NpFine = np.prod(NWorldFine+1)
NpCoars... | notebooks/TEST_VCLOD_Coefficient_1.ipynb | TiKeil/Master-thesis-LOD | apache-2.0 |
Preparations
We use the same setting as we have already used before containing the 'buildcoef2d' class in order to construct the coefficient. We visualize the coefficient and store the information in an extern folder. | bg = 0.05 #background
val = 1 #values
#fine World
NWorldFine = np.array([256, 256])
NpFine = np.prod(NWorldFine+1)
#coarse World
NWorldCoarse = np.array([16,16])
NpCoarse = np.prod(NWorldCoarse+1)
#ratio between Fine and Coa... | notebooks/TEST_VCLOD_Coefficient_1.ipynb | TiKeil/Master-thesis-LOD | apache-2.0 |
Perturbations of the same entries
To keep comparability, we use the 'specific' perturbation function and use a random seed. | # random seed
random.seed(20)
# decision
valc = np.shape(CoefClass.ShapeRemember)[0]
numbers = []
decision = np.zeros(100)
decision[0] = 1
for i in range(0,valc):
a = random.sample(decision,1)[0]
if a == 1:
numbers.append(i)
value1 = 3
C1 = CoefClass.SpecificValueChange(ratio=value1,
... | notebooks/TEST_VCLOD_Coefficient_1.ipynb | TiKeil/Master-thesis-LOD | apache-2.0 |
Precomputations | k = 4
NWorldFine = world.NWorldFine
NWorldCoarse = world.NWorldCoarse
NCoarseElement = world.NCoarseElement
boundaryConditions = world.boundaryConditions
NpFine = np.prod(NWorldFine+1)
NpCoarse = np.prod(NWorldCoarse+1)
#interpolant
IPatchGenerator = lambda i, N: interp.L2ProjectionPatchMatrix(i, N, NWorldCoarse, NC... | notebooks/TEST_VCLOD_Coefficient_1.ipynb | TiKeil/Master-thesis-LOD | apache-2.0 |
We call the result function for each perturbation and store the result subsequently.
Change in value | vis, eps, PotentialUpdated, recomputefractionsafe, errorplotinfo, errorworst, errorbest = result(pglod ,world, A, C1, f, k, 'Specific value change' + str(value1))
safeChange(ROOT, C1, vis, eps, PotentialUpdated, recomputefractionsafe, errorplotinfo, errorworst, errorbest) | notebooks/TEST_VCLOD_Coefficient_1.ipynb | TiKeil/Master-thesis-LOD | apache-2.0 |
Disappearance | vis, eps, PotentialUpdated, recomputefractionsafe, errorplotinfo, errorworst, errorbest = result(pglod ,world, A, V, f, k, 'Vanish')
safeVanish(ROOT, V, vis, eps, PotentialUpdated, recomputefractionsafe, errorplotinfo, errorworst, errorbest) | notebooks/TEST_VCLOD_Coefficient_1.ipynb | TiKeil/Master-thesis-LOD | apache-2.0 |
Shift | vis, eps, PotentialUpdated, recomputefractionsafe, errorplotinfo, errorworst, errorbest = result(pglod ,world, A, M1, f, k, 'One Step Move')
safeShift(ROOT, M1, vis, eps, PotentialUpdated, recomputefractionsafe, errorplotinfo, errorworst, errorbest) | notebooks/TEST_VCLOD_Coefficient_1.ipynb | TiKeil/Master-thesis-LOD | apache-2.0 |
Données
Les données sont de plusieurs types et sont regroupées en trois fichiers :
Résultat des élections législatives françaises de 2012 au niveau bureau de vote
Countours des circonscriptions des législatives
Localisation des buraux de votes
Localisation des villes
Localisation des bureaux de vote avec Cartelec, cet... | from actuariat_python.data import elections_legislatives_bureau_vote
tour = elections_legislatives_bureau_vote(source='xd')
tour["T2"].sort_values(["Code département", "N° de circonscription Lg"]).head() | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
Géolocalisation des circonscription | from actuariat_python.data import elections_legislatives_circonscription_geo
geo = elections_legislatives_circonscription_geo()
geo.sort_values(["department", "code_circonscription"]).head()
c = list(geo.sort_values(["department", "code_circonscription"])["communes"])[0].split("-")
c.sort()
c[:5]
list(geo.sort_value... | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
Géolocation des bureaux de vote
Ces données sont importantes afin de pouvoir associer chaque bureau à une circonscription. C'est la donnée la plus compliquée à obtenir car elle nécessite de combiner plusieurs techniques et sources de données pour obtenir une table propre. Le fichier final peut être obtenu comme suit : | from actuariat_python.data import elections_vote_places_geo
bureau_geo = elections_vote_places_geo()
bureau_geo.head() | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
Ce qui suit explique la façon dont j'ai constuit cette table.
Les bureaux sont assez stables d'une élection à l'autre et cela ne devrait pas trop poser de problèmes si on mélange les données. En revanche, ces données sont assez difficiles à obtenir. open.data.fr propose ces données mais il faut récupérer chaque ville o... | from actuariat_python.data import elections_vote_place_address
bureau = elections_vote_place_address(hide_warning=True)
bureau.head() | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
On récupère une clé pour utiliser l'API de Bing Maps avec le module keyring. Pour stocker son mot de passe sur la machine, il suffit d'écrire :
import keyring
keyring.get_password("bing", "actuariat_python,key") | import keyring, os
bing_key = keyring.get_password("bing", "actuariat_python,key")
coders = ["Nominatim"]
if bing_key:
# si la clé a été trouvée
coders.append(("bing", bing_key))
len(coders)
import os
if not os.path.exists("bureauxvotegeo.zip"):
from actuariat_python.data import geocode
from pyquickhel... | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
On regarde les valeurs manquantes. | import missingno
missingno.matrix(bureau_geo, figsize=(12, 6)); | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
On pourra finalement récupérer la base des géocodes comme ceci : | from actuariat_python.data import elections_vote_places_geo
places = elections_vote_places_geo()
places.head() | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
Géolocalisation des villes | from actuariat_python.data import elections_vote_places_geo
bureau_geo = elections_vote_places_geo()
villes_geo = bureau_geo[["city", "zip", "n"]].groupby(["city", "zip"], as_index=False).count()
villes_geo.head()
from actuariat_python.data import villes_geo
villes_geo = villes_geo(as_df=True)
villes_geo.head()
impor... | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
On conserve les données pour éviter de les reconstuire et faire appel à l'API Bing à nouveau. | villes_geo.to_csv("villes_geo.txt", sep="\t", index=False, encoding="utf-8")
villes_geo.shape | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
Géolocation des bureaux de vote avec Cartélec
Le site cartelec recense beaucoup plus de bureaux de vote mais pour les élections 2007. Ils ne devraient pas avoir changé beaucoup. | from pyensae.datasource import download_data
shp_vote = download_data("base_cartelec_2007_2010.zip")
shp_vote
# La version 2.0.0.dev de pyshp est buggée. Il vaut mieux ne pas l'utiliser.
import shapefile
if "dev" in shapefile.__version__:
raise ImportError("Use a different version of pyshp not '{0}'".format(shapef... | _doc/notebooks/sessions/election_carte_electorale.ipynb | sdpython/actuariat_python | mit |
Enable inline plotting in the Jupyter Notebook | %matplotlib inline
import matplotlib.pyplot as plt | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Intro to H2O Data Munging
Read csv data into H2O. This loads the data into the H2O column compressed, in-memory, key-value store. | fr = h2o.import_file("Boston_housing_train.csv") | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
View the top of the H2O frame. | fr.head() | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
View the bottom of the H2O Frame | fr.tail() | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Select a column
fr["VAR_NAME"] | fr["CRIM"].head() # Tab completes | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Select a few columns | columns = ["CRIM", "RM", "RAD"]
fr[columns].head() | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Select a subset of rows
Unlike in Pandas, columns may be identified by index or column name. Therefore, when subsetting by rows, you must also pass the column selection. | fr[2:7,:] # explicitly select all columns with : | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Key attributes:
* columns, names, col_names
* len, shape, dim, nrow, ncol
* types
Note:
Since the data is not in local python memory
there is no "values" attribute. If you want to
pull all of the data into the local python memory
then do so explicitly with h2o.export_file and
reading the data into p... | # The columns attribute is exactly like Pandas
print "Columns:", fr.columns, "\n"
print "Columns:", fr.names, "\n"
print "Columns:", fr.col_names, "\n"
# There are a number of attributes to get at the shape
print "length:", str( len(fr) ), "\n"
print "shape:", fr.shape, "\n"
print "dim:", fr.dim, "\n"
print "nrow:", f... | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Select rows based on value | fr.shape | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Boolean masks can be used to subselect rows based on a criteria. | mask = fr["CRIM"]>1
fr[mask,:].shape | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Get summary statistics of the data and additional data distribution information. | fr.describe() | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Set up the predictor and response column names
Using H2O algorithms, it's easier to reference predictor and response columns
by name in a single frame (i.e., don't split up X and y) | x = fr.names
y="Median_value"
x.remove(y) | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Machine Learning With H2O
H2O is a machine learning library built in Java with interfaces in Python, R, Scala, and Javascript. It is open source and well-documented.
Unlike Scikit-learn, H2O allows for categorical and missing data.
The basic work flow is as follows:
* Fit the training data with a machine learning algor... | model = h2o.random_forest(x=fr[:400,x],y=fr[:400,y],seed=42) # Define and fit first 400 points
model.predict(fr[400:fr.nrow,:]) # Predict the rest | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
The performance of the model can be checked using the holdout dataset | perf = model.model_performance(fr[400:fr.nrow,:])
perf.r2() # get the r2 on the holdout data
perf.mse() # get the mse on the holdout data
perf # display the performance object | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Train-Test Split
Instead of taking the first 400 observations for training, we can use H2O to create a random test train split of the data. | r = fr.runif(seed=12345) # build random uniform column over [0,1]
train= fr[r<0.75,:] # perform a 75-25 split
test = fr[r>=0.75,:]
model = h2o.random_forest(x=train[x],y=train[y],seed=42)
perf = model.model_performance(test)
perf.r2() | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
There was a massive jump in the R^2 value. This is because the original data is not shuffled.
Cross validation
H2O's machine learning algorithms take an optional parameter nfolds to specify the number of cross-validation folds to build. H2O's cross-validation uses an internal weight vector to build the folds in an effi... | model = h2o.random_forest(x=fr[x],y=fr[y], nfolds=10) # build a 10-fold cross-validated model
scores = numpy.array([m.r2() for m in model.xvals]) # iterate over the xval models using the xvals attribute
print "Expected R^2: %.2f +/- %.2f \n" % (scores.mean(), scores.std()*1.96)
print "Scores:", scores.round(2) | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
However, you can still make use of the cross_val_score from Scikit-Learn
Cross validation: H2O and Scikit-Learn | from sklearn.cross_validation import cross_val_score
from h2o.cross_validation import H2OKFold
from h2o.estimators.random_forest import H2ORandomForestEstimator
from h2o.model.regression import h2o_r2_score
from sklearn.metrics.scorer import make_scorer | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
You still must use H2O to make the folds. Currently, there is no H2OStratifiedKFold. Additionally, the H2ORandomForestEstimator is analgous to the scikit-learn RandomForestRegressor object with its own fit method | model = H2ORandomForestEstimator(seed=42)
scorer = make_scorer(h2o_r2_score) # make h2o_r2_score into a scikit_learn scorer
custom_cv = H2OKFold(fr, n_folds=10, seed=42) # make a cv
scores = cross_val_score(model, fr[x], fr[y], scoring=scorer, cv=custom_cv)
print "Expected R^2: %.2f +/- %.2f \n" % (scores.mean(), ... | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
There isn't much difference in the R^2 value since the fold strategy is exactly the same. However, there was a major difference in terms of computation time and memory usage.
Since the progress bar print out gets annoying let's disable that | h2o.__PROGRESS_BAR__=False
h2o.no_progress() | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Grid Search
Grid search in H2O is still under active development and it will be available very soon. However, it is possible to make use of Scikit's grid search infrastructure (with some performance penalties)
Randomized grid search: H2O and Scikit-Learn | from sklearn import __version__
sklearn_version = __version__
print sklearn_version | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
If you have 0.16.1, then your system can't handle complex randomized grid searches (it works in every other version of sklearn, including the soon to be released 0.16.2 and the older versions).
The steps to perform a randomized grid search:
1. Import model and RandomizedSearchCV
2. Define model
3. Specify parameters to... | %%time
from h2o.estimators.random_forest import H2ORandomForestEstimator # Import model
from sklearn.grid_search import RandomizedSearchCV # Import grid search
from scipy.stats import randint, uniform
model = H2ORandomForestEstimator(seed=42) # Define model
params = {"ntrees": randint(20,50),
"max_... | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
We might be tempted to think that we just had a large improvement; however we must be cautious. The function below creates a more detailed report. | def report_grid_score_detail(random_search, charts=True):
"""Input fit grid search estimator. Returns df of scores with details"""
df_list = []
for line in random_search.grid_scores_:
results_dict = dict(line.parameters)
results_dict["score"] = line.mean_validation_score
results_dic... | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Based on the grid search report, we can narrow the parameters to search and rerun the analysis. The parameters below were chosen after a few runs: | %%time
params = {"ntrees": randint(30,40),
"max_depth": randint(4,10),
"mtries": randint(4,10),}
custom_cv = H2OKFold(fr, n_folds=5, seed=42) # In small datasets, the fold size can have a big
# impact on the std of the resulting scor... | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Transformations
Rule of machine learning: Don't use your testing data to inform your training data. Unfortunately, this happens all the time when preparing a dataset for the final model. But on smaller datasets, you must be especially careful.
At the moment, there are no classes for managing data transformations. On th... | from h2o.transforms.preprocessing import H2OScaler
from h2o.transforms.decomposition import H2OPCA | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Normalize Data: Use the means and standard deviations from the training data. | y_train = train.pop("Median_value")
y_test = test.pop("Median_value")
norm = H2OScaler()
norm.fit(train)
X_train_norm = norm.transform(train)
X_test_norm = norm.transform(test)
print X_test_norm.shape
X_test_norm | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Then, we can apply PCA and keep the top 5 components. | pca = H2OPCA(n_components=5)
pca.fit(X_train_norm)
X_train_norm_pca = pca.transform(X_train_norm)
X_test_norm_pca = pca.transform(X_test_norm)
# prop of variance explained by top 5 components?
print X_test_norm_pca.shape
X_test_norm_pca[:5]
model = H2ORandomForestEstimator(seed=42)
model.fit(X_train_norm_pca,y_trai... | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Although this is MUCH simpler than keeping track of all of these transformations manually, it gets to be somewhat of a burden when you want to chain together multiple transformers.
Pipelines
"Tranformers unite!"
If your raw data is a mess and you have to perform several transformations before using it, use a pipeline t... | from h2o.transforms.preprocessing import H2OScaler
from h2o.transforms.decomposition import H2OPCA
from h2o.estimators.random_forest import H2ORandomForestEstimator
from sklearn.pipeline import Pipeline # Import Pipeline <other imports not shown>
model = H2ORandomForestEstimator(seed=42)
pipe = Pipeline... | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
This is so much easier!!!
But, wait a second, we did worse after applying these transformations! We might wonder how different hyperparameters for the transformations impact the final score.
Combining randomized grid search and pipelines
"Yo dawg, I heard you like models, so I put models in your models to model models.... | pipe = Pipeline([("standardize", H2OScaler()),
("pca", H2OPCA()),
("rf", H2ORandomForestEstimator(seed=42))])
params = {"standardize__center": [True, False], # Parameters to test
"standardize__scale": [True, False],
"pca__n_components": randin... | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
Currently Under Development (drop-in scikit-learn pieces):
* Richer set of transforms (only PCA and Scale are implemented)
* Richer set of estimators (only RandomForest is available)
* Full H2O Grid Search
Other Tips: Model Save/Load
It is useful to save constructed models to disk and reload them between H2... | best_estimator = random_search.best_estimator_ # fetch the pipeline from the grid search
h2o_model = h2o.get_model(best_estimator._final_estimator._id) # fetch the model from the pipeline
save_path = h2o.save_model(h2o_model, path=".", force=True)
print save_path
# assumes new session
m... | h2o-py/demos/H2O_tutorial_medium.ipynb | printedheart/h2o-3 | apache-2.0 |
We want to stop RP from reporting all sorts of stuff for this example so we set a specific environment variable to tell RP to do so. If you want to see what RP reports change it to REPORT. | # verbose = os.environ.get('RADICAL_PILOT_VERBOSE', 'REPORT')
os.environ['RADICAL_PILOT_VERBOSE'] = 'ERROR' | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
We will import the appropriate parts from AdaptiveMD as we go along so it is clear what it needed at what stage. Usually you will have the block of imports at the beginning of your script or notebook as suggested in PEP8. | from adaptivemd import Project
from adaptivemd import OpenMMEngine
from adaptivemd import PyEMMAAnalysis
from adaptivemd import File, Directory, WorkerScheduler
from adaptivemd import DT | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
Let's open a project with a UNIQUE name. This will be the name used in the DB so make sure it is new and not too short. Opening a project will always create a non-existing project and reopen an exising one. You cannot chose between opening types as you would with a file. This is a precaution to not accidentally delete ... | Project.delete('test')
project = Project('test') | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
Now we have a handle for our project. First thing is to set it up to work on a resource.
1. Set the resource
What is a resource? A Resource specifies a shared filesystem with one or more clusteres attached to it. This can be your local machine or just a regular cluster or even a group of cluster that can access the sam... | from adaptivemd import LocalCluster, AllegroCluster
resource_id = 'local.jhp'
resource = LocalCluster()
resource.wrapper.append('source activate xyz')
if resource_id == 'local.jhp':
project.initialize(resource)
elif resource_id == 'local.sheep':
project.initialize(LocalCluster())
elif resource_id == 'fub.all... | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
TaskGenerators
TaskGenerators are instances whose purpose is to create tasks to be executed. This is similar to the
way Kernels work. A TaskGenerator will generate Task objects for you which will be translated into a ComputeUnitDescription and executed. In simple terms:
The task generator creates the bash scripts for y... | pdb_file = File('file://../files/alanine/alanine.pdb').named('initial_pdb').load() | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
Here we used a special prefix that can point to specific locations.
file:// points to files on your local machine.
unit:// specifies files on the current working directory of the executing node. Usually these are temprary files for a single execution.
shared:// specifies the root shared FS directory (e.g. NO_BACKUP/... | engine = OpenMMEngine(
pdb_file=pdb_file,
system_file=File('file://../files/alanine/system.xml').load(),
integrator_file=File('file://../files/alanine/integrator.xml').load(),
args='-r --report-interval 1 -p CPU --store-interval 1'
).named('openmm') | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
To explain this we have now an OpenMMEngine which uses the previously made pdb File object and uses the location defined in there. The same some Files for the OpenMM XML files and some args to store each frame (to keep it fast) and run using the CPU kernel.
Last we name the engine openmm to find it later. | engine.name | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
The modeller
The instance to compute an MSM model of existing trajectories that you pass it. It is initialized with a .pdb file that is used to create features between the $c_\alpha$ atoms. This implementaton requires a PDB but in general this is not necessay. It is specific to my PyEMMAAnalysis show case. | modeller = PyEMMAAnalysis(
pdb_file=pdb_file
).named('pyemma') | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
Again we name it pyemma for later reference.
Add generators to project
Next step is to add these to the project for later usage. We pick the .generators store and just add it. Consider a store to work like a set() in python. It contains objects only once and is not ordered. Therefore we need a name to find the objects ... | project.generators.add(engine)
project.generators.add(modeller)
sc = WorkerScheduler(project.resource)
sc.enter(project)
t = engine.task_run_trajectory(project.new_trajectory(pdb_file, 100, restart=True)). extend(50).extend(100)
sc.task_to_script(t)
sc.advance()
for f in project.trajectories:
print f.basename, ... | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
Note, that you cannot add the same engine twice. But if you create a new engine it will be considered different and hence you can store it again.
Create one intial trajectory
Finally we are ready to run a first trajectory that we will store as a point of reference in the project. Also it is nice to see how it works in... | scheduler = project.get_scheduler(cores=1) | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
Next we create the parameter for the engine to run the simulation. Since it seemed appropriate we use a Trajectory object (a special File with initial frame and length) as the input. You could of course pass these things separately, but this way, we can actualy reference the no yet existing trajectory and do stuff with... | trajectory = project.new_trajectory(engine['pdb_file'], 100)
trajectory | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
This says, initial is alanine.pdb run for 100 frames and is named xxxxxxxx.dcd.
Now, we want that this trajectory actually exists so we have to make it (on the cluster which is waiting for things to do). So we need a Task object to run a simulation. Since Task objects are very flexible there are helper functions to get... | task = engine.task_run_trajectory(trajectory) | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
That's it, just that a trajectory description and turn it into a task that contains the shell commands and needed files, etc.
Last step is to really run the task. You can just use a scheduler as a function or call the .submit() method. | scheduler(task) | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
Now we have to wait. To see, if we are done, you can check the scheduler if it is still running tasks. | scheduler.is_idle
print scheduler.generators | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
or you wait until it becomes idle using .wait() | # scheduler.wait() | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
If all went as expected we will now have our first trajectory. | print project.files
print project.trajectories | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
Excellent, so cleanup and close our queue | scheduler.exit() | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
and close the project. | project.close() | examples/tutorial/test_worker.ipynb | jrossyra/adaptivemd | lgpl-2.1 |
2d problem
We've looked at the problem of finding the static temperature distribution in a bar. Now let's move on to finding the temperature distribution of a plate of length $1$ on each side. The temperature $T(x, y) = T(x_1, x_2)$ satisfies
$$
\nabla^2 T + f({\bf x}) = \left( \partial_{xx} + \partial_{yy} \right) T... | %matplotlib inline
import numpy
from matplotlib import pyplot
from matplotlib import rcParams
rcParams['font.family'] = 'serif'
rcParams['font.size'] = 16
rcParams['figure.figsize'] = (12,6)
nodes = numpy.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
IEN = numpy.array([[0, 1, 2],
[1, 3, 2... | FEEG6016 Simulation and Modelling/08-Finite-Elements-Lab-2.ipynb | ngcm/training-public | mit |
What we're doing here is
Providing a list of nodes by their global coordinates.
Providing the element node array IEN which says how the elements are linked to the nodes.
We have that for element $e$ and local node number $a = 0, 1, 2$ the global node number is $A = IEN(e, a)$. This notation is sufficiently convention... | ID = numpy.array([0,-1,1,-1]) | FEEG6016 Simulation and Modelling/08-Finite-Elements-Lab-2.ipynb | ngcm/training-public | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.