markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
11. What about the youngest billionaires. Are any of them female? | recent.sort_values(by='age').head(5) | 07/RichPeople_Pandas_Homework_7_Skinner.ipynb | barjacks/foundations-homework | mit |
12. We compared women's and men's average fortunes before for Switzerland. Lets do the same for the whole world. | female_billionaires = recent[recent['gender'] == 'female']
male_billionaires = recent[recent['gender'] == 'male']
print("Female billionaire average wealth:", female_billionaires['networthusbillion'].mean())
print("Male billionaire average wealth:", male_billionaires['networthusbillion'].mean())
females = female_billio... | 07/RichPeople_Pandas_Homework_7_Skinner.ipynb | barjacks/foundations-homework | mit |
13. Who has the most billions? | recent.sort_values(by='networthusbillion', ascending = False).head(5) | 07/RichPeople_Pandas_Homework_7_Skinner.ipynb | barjacks/foundations-homework | mit |
14. Which nation has the wealthiest billionaires in average? | recent.groupby(['countrycode'])['networthusbillion'].mean().sort_values(ascending = False).head(15) | 07/RichPeople_Pandas_Homework_7_Skinner.ipynb | barjacks/foundations-homework | mit |
15. How is the wealth distributed by age? Lets plot that out. | %matplotlib inline
import matplotlib.pyplot as plt
plt.style.available
plt.style.use('fivethirtyeight')
recent.plot(kind='scatter', x='age', y='networthusbillion')
plt.savefig("Scatterplot_billionaires_worldwide.svg") | 07/RichPeople_Pandas_Homework_7_Skinner.ipynb | barjacks/foundations-homework | mit |
Build the MLP
Now we use the provided layers from Lasagne to build our MLP | def build_mlp(n_in, n_hidden, n_out, input_var=None):
#Input layer, 1 dimension = number of samples, 2 dimension = input, our 28*28 image
l_in = lasagne.layers.InputLayer(shape=(None, n_in), input_var=input_var)
# Our first hidden layer with n_hidden units
# As nonlinearity we use tanh, you could a... | 2015-10_Lecture/Lecture2/code/3_Intro_Lasagne_Solution.ipynb | nreimers/deeplearning4nlp-tutorial | apache-2.0 |
Create the Train Function
After loading the data and defining the MLP, we can now create the train function. | # Parameters
n_in = 28*28
n_hidden = 50
n_out = 10
# Create the network
x = T.dmatrix('x') # the data, one image per row
y = T.lvector('y') # the labels are presented as 1D vector of [int] labels
network = build_mlp(n_in, n_hidden, n_out, x)
# Create a loss expression for training, i.e., a scalar objective we want... | 2015-10_Lecture/Lecture2/code/3_Intro_Lasagne_Solution.ipynb | nreimers/deeplearning4nlp-tutorial | apache-2.0 |
Train the model
We run the training for some epochs and output the accurarcy of our network | #Function that helps to iterate over our data in minibatches
def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
assert len(inputs) == len(targets)
if shuffle:
indices = np.arange(len(inputs))
np.random.shuffle(indices)
for start_idx in range(0, len(inputs) - batchsize + 1, b... | 2015-10_Lecture/Lecture2/code/3_Intro_Lasagne_Solution.ipynb | nreimers/deeplearning4nlp-tutorial | apache-2.0 |
<h3>How many complaints do not appear in the state's public database?</h3> | df[df['public']=='offline'].count()[0] | notebooks/analysis/.ipynb_checkpoints/complaints_analysis-checkpoint.ipynb | TheOregonian/long-term-care-db | mit |
<h3>How many complaints do appear in the state's public database?</h3> | df[df['public']=='online'].count()[0] | notebooks/analysis/.ipynb_checkpoints/complaints_analysis-checkpoint.ipynb | TheOregonian/long-term-care-db | mit |
<h3>What percent of complaints are missing?</h3> | df[df['public']=='offline'].count()[0]/df.count()[0]*100 | notebooks/analysis/.ipynb_checkpoints/complaints_analysis-checkpoint.ipynb | TheOregonian/long-term-care-db | mit |
<h3>How many complaints were labelled 'Exposed to potential harm' or 'No negative outcome?'</h3> | df[(df['outcome']=='Exposed to Potential Harm') | (df['outcome']=='No Negative Outcome')].count()[0] | notebooks/analysis/.ipynb_checkpoints/complaints_analysis-checkpoint.ipynb | TheOregonian/long-term-care-db | mit |
<h3>Of all missing complaints, what percent are in the above two categories?</h3> | df[(df['outcome']=='Exposed to Potential Harm') |
(df['outcome']=='No Negative Outcome')].count()[0]/df[df['public']=='offline'].count()[0]*100 | notebooks/analysis/.ipynb_checkpoints/complaints_analysis-checkpoint.ipynb | TheOregonian/long-term-care-db | mit |
<h3>How many complaints are labelled 'A,' which stands for abuse, but are offline?</h3> | df[(df['abuse_type']=='A') & (df['public']=='offline')].count()[0]
#df.groupby('outcome').count().reset_index()[['outcome','abuse_number']].sort_values('abuse_number', ascending = False) | notebooks/analysis/.ipynb_checkpoints/complaints_analysis-checkpoint.ipynb | TheOregonian/long-term-care-db | mit |
<h3>What's the online/offline breakdown by outcome?</h3> | totals = df.groupby(['omg_outcome','public']).count()['abuse_number'].unstack().reset_index()
totals.fillna(0, inplace = True)
totals['total'] = totals['online']+totals['offline']
totals['pct_offline'] = round(totals['offline']/totals['total']*100)
totals.sort_values('pct_offline',ascending=False) | notebooks/analysis/.ipynb_checkpoints/complaints_analysis-checkpoint.ipynb | TheOregonian/long-term-care-db | mit |
Next, we import the required algorithms on which we wish to run the experiments | from nilmtk.disaggregate import CO | docs/manual/user_guide/nilmtk_api_tutorial.ipynb | nilmtk/nilmtk | apache-2.0 |
Next, we enter the values for the different parameters in the dictionary. Since we need multiple appliances, we enter the names of all the required appliances in the 'appliances' parameter. | experiment1 = {
'power': {'mains': ['apparent','active'],'appliance': ['apparent','active']},
'sample_rate': 60,
'appliances': ['fridge','air conditioner', 'microwave'],
'methods': {"CO":CO({})},
'train': {
'datasets': {
'Dataport': {
'path': 'data/dataport.hdf5',
'buil... | docs/manual/user_guide/nilmtk_api_tutorial.ipynb | nilmtk/nilmtk | apache-2.0 |
In this example experimental setup, we have set the sample rate at 60Hz and use Combinatorial Optimisation to
disaggregate the required appliances from building 10 in the dataport dataset with the RMSE metric to measure the accuracy. We also specify the dates for training and testing
Next we provide this experiment di... | api_results_experiment_1 = API(experiment1) | docs/manual/user_guide/nilmtk_api_tutorial.ipynb | nilmtk/nilmtk | apache-2.0 |
We can observe the prediction vs. truth graphs in the above cell. The accuracy metrics can be accessed using the following commands: | errors_keys = api_results_experiment_1.errors_keys
errors = api_results_experiment_1.errors
for i in range(len(errors)):
print (errors_keys[i])
print (errors[i])
print ("\n\n") | docs/manual/user_guide/nilmtk_api_tutorial.ipynb | nilmtk/nilmtk | apache-2.0 |
This was a trivial experiment that only scratches the surface of the true potential of this API.
In the next experiment we will run an incrementally more complex version of the above experiment. Here we will use multiple models to disaggregate the appliance readings with the models having their own sets of parameters w... | from nilmtk.disaggregate import FHMM_EXACT, Mean
experiment2 = {
'power': {'mains': ['apparent','active'],'appliance': ['apparent','active']},
'sample_rate': 60,
'appliances': ['fridge','air conditioner', 'microwave'],
'methods': {"Mean":Mean({}),"FHMM_EXACT":FHMM_EXACT({'num_of_states':2}), "CombinatorialOpti... | docs/manual/user_guide/nilmtk_api_tutorial.ipynb | nilmtk/nilmtk | apache-2.0 |
The API makes running experiments extremely quick and efficient, with the emphasis on creating finely tuned reproducible experiments where model and parameter performances can be easily evaluated at a glance.
In the next iteration of this experiment, we introduce more parameters chunksize, DROP_ALL_NANS and artifici... | from nilmtk.disaggregate import Hart85
experiment3 = {
'power': {'mains': ['apparent','active'],'appliance': ['apparent','active']},
'sample_rate': 60,
'appliances': ['fridge','air conditioner','electric furnace','washing machine'],
'artificial_aggregate': True,
'chunksize': 20000,
'DROP_ALL_NANS': False,
... | docs/manual/user_guide/nilmtk_api_tutorial.ipynb | nilmtk/nilmtk | apache-2.0 |
The results of the above experiment are presented for every chunk per building in the test set.
In the following experiment, we demonstrate how to run experiments across datasets, which was previously not possible. The important thing to pay attention to is that such datasets can only be trained and tested together as ... | experiment4 = {
'power': {'mains': ['apparent','active'],'appliance': ['apparent','active']},
'sample_rate': 60,
'appliances': ['washing machine','fridge'],
'artificial_aggregate': True,
'chunksize': 20000,
'DROP_ALL_NANS': False,
'methods': {"Mean":Mean({}),"Hart85":Hart85({}), "FHMM_EXACT":FHMM_EXACT({'... | docs/manual/user_guide/nilmtk_api_tutorial.ipynb | nilmtk/nilmtk | apache-2.0 |
Every 100 samples in the dataset, we save 1. If things run too slow, try increasing this number. If things run too fast, try decreasing it... =) | reduce_factor = 100 | Module4/Module4 - Lab1.ipynb | authman/DAT210x | mit |
Load up the scanned armadillo: | plyfile = PlyData.read('Datasets/stanford_armadillo.ply')
armadillo = pd.DataFrame({
'x':plyfile['vertex']['z'][::reduce_factor],
'y':plyfile['vertex']['x'][::reduce_factor],
'z':plyfile['vertex']['y'][::reduce_factor]
}) | Module4/Module4 - Lab1.ipynb | authman/DAT210x | mit |
PCA
In the method below, write code to import the libraries required for PCA.
Then, train a PCA model on the passed in armadillo dataframe parameter. Lastly, project the armadillo down to the two principal components, by dropping one dimension.
NOTE-1: Be sure to RETURN your projected armadillo rather than None! This p... | def do_PCA(armadillo, svd_solver):
# .. your code here ..
return None | Module4/Module4 - Lab1.ipynb | authman/DAT210x | mit |
Preview the Data | # Render the Original Armadillo
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.set_title('Armadillo 3D')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.scatter(armadillo.x, armadillo.y, armadillo.z, c='green', marker='.', alpha=0.75) | Module4/Module4 - Lab1.ipynb | authman/DAT210x | mit |
Time Execution Speeds
Let's see how long it takes PCA to execute: | %timeit pca = do_PCA(armadillo, 'full') | Module4/Module4 - Lab1.ipynb | authman/DAT210x | mit |
Render the newly transformed PCA armadillo! | fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Full PCA')
ax.scatter(pca[:,0], pca[:,1], c='blue', marker='.', alpha=0.75)
plt.show() | Module4/Module4 - Lab1.ipynb | authman/DAT210x | mit |
Let's also take a look at the speed of the randomized solver on the same dataset. It might be faster, it might be slower, or it might take exactly the same amount of time to execute: | %timeit rpca = do_PCA(armadillo, 'randomized') | Module4/Module4 - Lab1.ipynb | authman/DAT210x | mit |
Let's see what the results look like: | fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('Randomized PCA')
ax.scatter(rpca[:,0], rpca[:,1], c='red', marker='.', alpha=0.75)
plt.show() | Module4/Module4 - Lab1.ipynb | authman/DAT210x | mit |
Create Data | %%sql
-- Create a table of criminals
CREATE TABLE criminals (pid, name, age, sex, city, minor);
INSERT INTO criminals VALUES (412, 'James Smith', 15, 'M', 'Santa Rosa', 1);
INSERT INTO criminals VALUES (901, 'Gordon Ado', 32, 'F', 'San Francisco', 0);
INSERT INTO criminals VALUES (512, 'Bill Byson', 21, 'M', 'Petaluma... | sql/multiple_conditional_statements.ipynb | tpin3694/tpin3694.github.io | mit |
View All Rows | %%sql
-- Select all
SELECT *
-- From the criminals table
FROM criminals | sql/multiple_conditional_statements.ipynb | tpin3694/tpin3694.github.io | mit |
View Rows Where Age Is Greater Than 20 And City Is San Francisco | %%sql
-- Select all unique
SELECT distinct *
-- From the criminals table
FROM criminals
-- Where age is greater than 20 and city is San Francisco
WHERE age > 20 AND city == 'San Francisco' | sql/multiple_conditional_statements.ipynb | tpin3694/tpin3694.github.io | mit |
View Rows Where Age Is Greater Than 20 or City Is San Francisco | %%sql
-- Select all unique
SELECT distinct *
-- From the criminals table
FROM criminals
-- Where age is greater than 20 and city is San Francisco
WHERE age > 20 OR city == 'San Francisco' | sql/multiple_conditional_statements.ipynb | tpin3694/tpin3694.github.io | mit |
3.1. Molecules
MoleculeContainer has standardize, kekule, thiele, neutralize, implicify_hydrogens and canonicalize methods.
Method thiele transforms Kekule representation of rings into aromatized.
Method standardize applies functional group standardization rules to molecules (more than 50 rules).
Method canonicalize ap... | m3 # molecule with kekulized ring
m3.standardize() # apply standardization. Returns True if any group found
m3 # group-standardized structure.
m3.thiele() # aromatizes and returns True then any ring found
m3 | doc/tutorial/3_standardization.ipynb | stsouko/CGRtools | lgpl-3.0 |
Molecules has explicify_hydrogens and implicify_hydrogens methods to handle hydrogens.
This methods is used to add or remove hydrogens in molecule.
Note implicify_hydrogens working for aromatic rings only in kekule form. explicify_hydrogens for aromatized forms required kekule and optionally thiele procedures applyed b... | m3.explicify_hydrogens() # return number of added hydrogens
m3.clean2d(randomize=True) # for added hydrogen atoms coordinates are not calculated. Thus, it looks like hydrogen has the same position on image
m3
m3.kekule()
m3.implicify_hydrogens()
m3 | doc/tutorial/3_standardization.ipynb | stsouko/CGRtools | lgpl-3.0 |
3.2. Reactions standardization
ReactionContainer has same methods as molecules. In this case they are applied to all molecules in reaction. | r2
r2.standardize()
r2.explicify_hydrogens()
r2.clean2d(randomize=True)
r2 | doc/tutorial/3_standardization.ipynb | stsouko/CGRtools | lgpl-3.0 |
Connecting to KFP and listing experiments | %%bash
PREFIX=<YOUR-PREFIX>
ZONE=<YOUR-ZONE>
NAMESPACE=<YOUR-NAMESPACE>
gcloud container clusters get-credentials $PREFIX-cluster --zone $ZONE
echo "https://"$(kubectl describe configmap inverse-proxy-config -n $NAMESPACE | \
grep "googleusercontent.com") | examples/mlops-env-on-gcp/provisioning-kfp/verify-infra.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Use the URL produced by the previous cell as the HOST_URL | import kfp
HOST_URL = ''
NAMESPACE = 'kfp' # Change to your namespace
client = kfp.Client(host=HOST_URL, namespace=NAMESPACE)
[pipeline.name for pipeline in client.list_pipelines().pipelines] | examples/mlops-env-on-gcp/provisioning-kfp/verify-infra.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Connectiong to Cloud SQL ML Metadata and list tables
This page describes how to connect a mysql client to your Cloud SQL instance using the Cloud SQL Proxy. | !pip install -U -q mysql-connector
import mysql.connector
metadb = mysql.connector.connect(
host='127.0.0.1',
port=3306,
database='metadb',
user="root",
passwd="" # set root password
)
cursor = metadb.cursor(buffered=True)
cursor.execute("SHOW TABLES FROM metadb;")
cursor.fetchall() | examples/mlops-env-on-gcp/provisioning-kfp/verify-infra.ipynb | GoogleCloudPlatform/mlops-on-gcp | apache-2.0 |
Tout va bien pour l'instant. Remarquez que la dernière opération comporte des espaces entre les nombres et l'opérateur /. Dans ce cas (ce n'est pas toujours le cas), les espaces ne signifient rien - il est même suggéré de les placer pour éclaircir le code, ce qui est utile lorsque les équations sont complexes. Puis, ap... | a = 3 | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Techniquement, a pointe vers le nombre entier 3. Conséquemment, on peut effectuer des opérations sur a. | a * 6
A + 2 | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Le message d'erreur nous dit que A n'est pas défini. Sa version minuscule, a, l'est pourtant. La raison est que Python considère la case dans la définition des objets. Utiliser la mauvaise case mène donc à des erreurs.
Le nom d'une variable doit toujours commencer par une lettre, et ne doit pas contenir de caractères r... | rendement_arbre = 50 # pomme/arbre
nombre_arbre = 300 # arbre
nombre_pomme = rendement_arbre * nombre_arbre
nombre_pomme | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Types de données
Jusqu'à maintenant, nous n'avons utilisé que des nombres entiers (integer ou int) et des nombres réels (float ou float64). Python inclue d'autres types. La chaîne de caractère (string) est un ou plusieurs symboles. Elle est définie entre des double-guillemets " " ou des apostrophes ' '. Il n'existe pas... | a = "L'ours"
b = "polaire"
a + " " + b + " ressemble à un faux zèbre." | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Notez que l'objet a a été défini précédemment. Il est possible en Python de réassigner une variable, mais cela peut porter à confusion, jusqu'à générer des erreurs de calcul si une variable n'est pas assigné à l'objet auquel on voulait référer.
L'opérateur + sur des caractères retourne une concaténation.
Combien de car... | c = a + " " + b
len(c) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Quatorze, c'est bien cela (comptez "L'ours polaire", en incluant l'espace). len, pour lenght (longueur), est une fonction (aussi appelée méthode) incluse par défaut dans l'environnement de travail de Python. La fonction est appelée en écrivant len(). Mais une fonction de quoi? Des arguments qui se trouvent entre les pa... | a = 17
print(a < 10)
print(a > 10)
print(a == 10)
print(a != 10)
print(a == 17)
print(~a == 17) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Je viens d'introduire un nouveau type de donnée: les données booléennes (boolean, ou bool), qui ne peuvent prendre que deux états - True ou False. En même temps, j'ai utilisé la fonction print parce que dans mon carnet, seule la dernière opération permet d'afficher le résultat. Si l'on veut forcer une sortie, on utilis... | print('o' in 'Ours')
print('O' in 'Ours')
print('O' not in 'Ours') | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Les collections de données
Les exercices précédents ont permis de présenter les types de données offerts par défault sur Python qui sont les plus importants pour le calcul scientifique: int (integer, ou nombre entier), float64 (nombre réel), str (string, ou chaîne de caractère) et bool (booléen). D'autres s'ajouterons ... | espece = ['Petromyzon marinus', 'Lepisosteus osseus', 'Amia calva', 'Hiodon tergisus']
espece | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Pour accéder aux éléments d'une liste, appelle la liste suivie de la position de l'objet désiré entre crochets. Fait important qui reviendra tout au long du cours: en Python, l'indice du premier élément est zéro. | print(espece[0])
print(espece[2])
print(espece[:2])
print(espece[2:]) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Pour les deux dernières commandes, la position :2 signifie jusqu'à 2 non inclusivement et 2: signifie de 2 à la fin.
Pour ajouter un élément à notre liste, on peut utiliser la fonction append. | espece.append("Cyprinus carpio")
espece | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Notez que la fonction append est appelée après la variable et précédée un point. Cette manière de procéder est courrante en programmation orientée objet. La fonction append est un attribut d'un objet list et prend un seul argument: l'objet qui est ajouté à la liste. C'est une manière de dire grenouille.saute(longueur=1... | print(espece)
espece[2] = "Lepomis gibbosus"
print(espece) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Si les données contenues dans une liste sont de même type, cette liste peut être considérée comme un vecteur. En créant une liste de vecteurs de dimensions cohérentes, on crée une matrice. Nous verrons plus tard que pour les vecteurs et les matrices, on utilisera un format offert par un module complémentaire. Pour l'in... | mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]]
mat | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Les tuples, définis tuple par Python, différent des listes du fait que ses éléments ne peuvent pas être modifiés. Un tuple est délimité par des parenthèses ( ), et comme chez la liste, ses éléments sont séparés par des virgules. Les tuples sont moins polyvalents que les listes. Vous les utiliserez probablement raremen... | espece = ('Petromyzon marinus', 'Lepisosteus osseus', 'Amia calva', 'Hiodon tergisus')
espece[2] = "Lepomis gibbosus"
espece | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Les dictionnaires, ou dict, sont des listes dont chaque élément est identifié par une clé. Un dictionnaire est délimité par des accolades sous forme mon_dict = {'clé1': x, 'clé2': y, 'clé3': z }. On appelle un élément par sa clé entre des crochets, par exemple mon_dict['clé1'].
Le dict se rapproche d'un tableau: nous v... | tableau = {'espece': ['Petromyzon marinus', 'Lepisosteus osseus', 'Amia calva', 'Hiodon tergisus'], 'poids': [10, 13, 21, 4], 'longueur': [35, 44, 50, 8]}
print('Mon tableau: ', tableau)
print('Mes espèces:', tableau['espece'])
print('Noms des clés (ou colonnes):', tableau.keys()) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Les fonctions (ou méthodes)
Plus haut, j'ai présenté les fonctions len et append. Une myriade de fonctions sont livrées par défaut avec Python. Mais il en manque aussi cruellement. | sqrt(2) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Message d'erreur: la commande sqrt n'est pas définie.
Quoi, Python n'est pas foutu de calculer une racine carrée?
Par défaut, non.
Mais!
De nombreuses extensions (les modules) permettent de combler ces manques. Nous aborderons ça un peu plus loin dans ce chapitre. Pour l'instant, exerçons-nous à créer notre propre ... | def racine(x, n=2):
r = x**(1/n)
return r | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
En Python, def est le mot-clé pour définir une fonction. Suit ensuite, après un espace, le nom que vous désirez donner à la fonction: racine. Les arguments de la fonction suivent entre les parenthèses. Dans ce cas, x est la valeur de laquelle on veut extraire la racine et n est l'ordre de la racine. L'agument x n'a pas... | print(racine(9))
print(racine(x=9))
print(racine(8, 3))
print(racine(x=8, n=3)) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
S'ils ne sont pas spécifiés, Python comprend que les arguments sont entrés dans l'ordre défini dans la fonction. En entrant racine(9), Python comprend que le 9 est attribué à x et donne à n sa valeur par défaut, 2. Ce qui est équivalent à entrer racine(x=9). Les autres entrées sont aussi équivalentes, et extraient la r... | data = [3.5, 8.1, 10.2, 0.5, 5.6]
racine(x=data, n=2) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Oups. Python vous dit qu'il y a une erreur, et vous indique avec une flèche ----> à quelle ligne de notre fonction elle est encourrue. Les exposants ** (on peut aussi utiliser la fonction pow) ne sont pas applicables aux listes. Une solution est d'appliquer la fonction à chaque élément de la liste avec une ittératio... | racine_data = []
for i in [0, 1, 2, 3, 4]:
r = racine(x=data[i], n=2)
racine_data.append(r)
racine_data | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Nous avons d'abord créé une liste vide, racine_data. Ensuite, pour (for) chaque indice de la liste (i in [0, 1, 2, 3, 4]), nous demandons à Python d'effectuer la suite d'opération qui suit le ; et qui est indentée de quatre espaces. Dans la suite d'opération, calculer la racine carrée de data à l'indice i, puis l'ajout... | racine_data = []
for i in range(len(data)):
r = racine(x=data[i], n=2)
print('Racine carrée de ', data[i], ' = ', r)
racine_data.append(r) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
La fonction range retourne une séquence calculée au besoin. Elle est calculée si elle est évoquée dans une boucle ou en lançant list. | print(range(len(data)))
print(list(range(len(data))))
print(range(2, len(data)))
print(list(range(2, len(data)))) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Première observation, si un seul argument est inclus, range retourne une séquence partant de zéro. Seconde observation, la séquence se termine en excluant l'argument. Ainsi, range(2,5) retourne la séquence [2, 3, 4]. En spécifiant la longueur de data comme argument, la séquence range(5) retourne la liste [0, 1, 2, 3, 4... | x = 100
while (x > 1.1):
x=racine(x)
print(x) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Nous avons inité x à une valeur de 100. Puis, tant que (while) le test x > 1.1 est vrai, attribuer à x la nouvelle valeur calculée en extrayant la racine de la valeur précédente de x. Enfin, indiquer la valeur avec print.
Explorons maintenant comment Python réagit si on lui demande de calculer $\sqrt{-1}$. | racine(x=-1, n=2) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
D'abord, Python ne retourne pas de message d'erreur, mais un nouveau type de donnée: le nombre imaginaire. Puis, 6.123233995736766e-17 n'est pas zéro, mais très proche. La résolution des calculs étant numérique, on obeserve parfois de légères déviations par rapport aux solutions mathématiques.
Si pour un cas particulie... | def racine_positive_nn(x, n=2):
if x<0:
raise ValueError("x est négatif")
elif x==0:
raise ValueError("x est nul")
else:
r = x**(1/n)
return r | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
La racine positive et non-nulle (racine_positive_nn) comprend les mot-clés if (si), elif (une contration de else if) et else (sinon). ValueError est une fonction pour retourner un message d'erreur lorsqu'elle est précédée de raise. Comme c'est le cas pour def et for, les instructions des conditions sont indentées. Note... | racine_positive_nn(x=-1, n=2)
racine_positive_nn(x=0, n=2)
racine_positive_nn(x=4, n=2) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Charger un module
Le module numpy, installé par défaut avec Anaconda, est une boîte d'outil de calcul numérique populée par de nombreuses foncions mathématiques. Dont la racine carrée. | import numpy as np
np.sqrt(9)
from numpy import sqrt
sqrt(9) | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
La plupart des fonctions que vous aurez à construire seront vouées à des instructions spécialisées à votre cas d'étude. Pour la plupart des opérations d'ordre générale (comme les racines carrées, les tests statistiques, la gestion de matrices et de tableau, les graphiques, les modèles d'apprentissage, etc.), des équipe... | a = 5/2
a | 02_Python/2.ipynb | essicolo/ecologie-mathematique | mit |
Alternative model | import numpy as np
from dictlearn.generate_synthetic_data_alt import FakeTextGenerator
embedding_size = 20
markov_order = 3
temperature=1.0
sentence_size = 20
model = FakeTextGenerator(100, 400, embedding_size, markov_order, temperature)
n_sentences=1000
sentences = model.create_corpus(n_sentences, 5, 10, 0.7, 0.1)
... | visualize_toy_dataset.ipynb | tombosc/dict_based_learning | mit |
Study corpus | summarize(sentences, model.V, "corpus")
| visualize_toy_dataset.ipynb | tombosc/dict_based_learning | mit |
Not really zipfian so far. Maybe read that if we really care about that.
Study definitions | definitions = []
for defs in model.dictionary.values():
definitions += defs
summarize(definitions, V, "definitions")
| visualize_toy_dataset.ipynb | tombosc/dict_based_learning | mit |
I've created a function that we'll use later to create visualizations. It is a bit messy and not essential to the material so don't worry about understanding it. I'll be happy to explain it to anyone interested during a break or after the session. | from matplotlib.colors import ListedColormap
# Another messy looking function to make pretty plots of basketball courts
def visualize_court(log_reg_model, coord_type='cart', court_image = '../data/nba/nba_court.jpg'):
two_class_cmap = ListedColormap(['#FFAAAA', '#AAFFAA']) # light red for miss, light green for mak... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
We also need functions for shuffling the data and calculating classification errrors. | ### function for shuffling the data and labels
def shuffle_in_unison(features, labels):
rng_state = np.random.get_state()
np.random.shuffle(features)
np.random.set_state(rng_state)
np.random.shuffle(labels)
### calculate classification errors
# return a percentage: (number misclassified)/(total num... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
1. Warm-up
Let's start with a warm-up exercise. In the data directory you'll find a dataset of recent movies and their ratings according to several popular websites. Let's load it with Pandas... | # load a dataset of recent movies and their ratings across several websites
movie_data = pd.read_csv('../data/movie_ratings.csv')
# reduce it to just the ratings categories
movie_data = movie_data[['FILM','RottenTomatoes','RottenTomatoes_User','Metacritic','Metacritic_User','Fandango_Ratingvalue', 'IMDB']]
movie_data.h... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
Logistic Regression Review
Data
We observe pairs $(\mathbf{x}{i},y{i})$ where
\begin{eqnarray}
y_{i} \in { 0, 1} &:& \mbox{class label} \
\mathbf{x}{i} = (x{i,1}, \dots, x_{i,D}) &:& \mbox{set of $D$ explanatory variables (aka features)}
\end{eqnarray}
Parameters
\begin{eqnarray}
\mathbf{\beta}^{T} = (\beta_{0}, \dot... | from sklearn.linear_model import LogisticRegression
# set the random number generator for reproducability
np.random.seed(123)
# let's try to predict the IMDB rating from the others
features = movie_data[['RottenTomatoes','RottenTomatoes_User','Metacritic','Metacritic_User','Fandango_Ratingvalue']].as_matrix()
# creat... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
2. Feature Transformations
Good features are crucial for training well-performing classifiers: 'garbage in, garbage out.' In this section we introduce several transformations that are commonly applied to data as a preprocessing step before training a classifier.
2.1 Normal Standardization
Recall the formula of the st... | # perform z-score scaling
features_mu = np.mean(features, axis=0)
features_sigma = np.std(features, axis=0)
std_features = (features - features_mu)/features_sigma
# re-train model
lm = LogisticRegression()
lm.fit(std_features, labels)
### compute error on training data
predictions = lm.predict(std_features)
print "Cl... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
Standard Normal scaling is a common and usually default first step, especially when you know the data in measured in different units.
2.2 Domain-Specific Transformations
Sometimes the data calls for a specific transformation. We'll demonstrate this on the NBA dataset used in our first workshop. Let's load it... | nba_shot_data = pd.read_csv('../data/nba/NBA_xy_features.csv')
nba_shot_data.head() | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
And let's run logistic regression on the data just as we did before... | # split data into train and test
train_set_size = int(.80*len(nba_shot_data))
train_features = nba_shot_data.ix[:train_set_size,['x_Coordinate','y_Coordinate']].as_matrix()
test_features = nba_shot_data.ix[train_set_size:,['x_Coordinate','y_Coordinate']].as_matrix()
train_class_labels = nba_shot_data.ix[:train_set_size... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
Now let's transform the Cartesian coordinates into polar coordinates: (x,y) --> (radius, angle)... | ### Transform coordinate system
# radius coordinate: calculate distance from point to hoop
hoop_location = np.array([25.5, 0.])
train_features -= hoop_location
test_features -= hoop_location
train_dists = np.sqrt(np.sum(train_features**2, axis=1))
test_dists = np.sqrt(np.sum(test_features**2, axis=1))
# angle coordin... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
<span style="color:red">STUDENT ACTIVITY (10 mins)</span>
2.3 Mystery Data
The data folder contains some mysterious data that can't be modeled well with a linear function. Running the code below, we see the squared error is over 70. However, the error can be driven to zero using one of two transformations. See if y... | from sklearn.linear_model import LinearRegression
# load (x,y) where y is the mystery data
x = np.arange(0, 30, .2)[np.newaxis].T
y = np.load(open('../data/mystery_data.npy','rb'))
### transformation goes here ###
x = np.cos(x)
################################
# initialize regression model
lm = LinearRegression()
... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
3. Dimensionality Reduction
Sometimes the data calls for more aggressive transformations. High-dimensional data is usually hard to model because classifiers are likely to overfit. Regularization is one way to combat high dimensionality, but often it can not be enough. This section will cover dimensionality reductio... | # un-zip the paintings file
import zipfile
zipper = zipfile.ZipFile('../data/bob_ross/bob_ross_paintings.npy.zip')
zipper.extractall('../data/bob_ross/')
# load the 403 x 360,000 matrix
br_paintings = np.load(open('../data/bob_ross/bob_ross_paintings.npy','rb'))
print "Dataset size: %d x %d"%(br_paintings.shape) | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
and then visualize two of the images... | # subplot containing first image
ax1 = plt.subplot(1,2,1)
br_painting = br_paintings[70,:]
ax1.imshow(np.reshape(br_painting, (300, 400, 3)))
# subplot containing second image
ax2 = plt.subplot(1,2,2)
br_painting = br_paintings[33,:]
ax2.imshow(np.reshape(br_painting, (300, 400, 3)))
plt.show() | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
3.2 Principal Component Analysis
As we've seen, the dataset has many, many, many more features (columns) than examples (rows). Simple Lasso or Ridge regularization probably won't be enough to prevent overfitting so we have to do something more drastic. In this section, we'll cover Principal Component Analysis, a popu... | from sklearn.decomposition import PCA
pca = PCA(n_components=400)
start_time = time.time()
reduced_paintings = pca.fit_transform(br_paintings)
end_time = time.time()
print "Training took a total of %.2f seconds." %(end_time-start_time)
print "Preserved percentage of original variance: %.2f%%" %(pca.explained_variance... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
Let's visualize two of the paintings... | img_idx = 70
reconstructed_img = pca.inverse_transform(reduced_paintings[img_idx,:])
original_img = br_paintings[70,:]
# subplot for original image
ax1 = plt.subplot(1,2,1)
ax1.imshow(np.reshape(original_img, (300, 400, 3)))
ax1.set_title("Original Painting")
# subplot for reconstruction
ax2 = plt.subplot(1,2,2)
ax2.... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
We can also visualize the transformation matrix $\mathbf{W}^{T}$. It's rows act as 'filters' or 'feature detectors'... | # get the transformation matrix
transformation_mat = pca.components_ # This is the W^T matrix
# two components to show
comp1 = 13
comp2 = 350
# subplot
ax1 = plt.subplot(1,2,1)
filter1 = transformation_mat[comp1-1,:]
ax1.imshow(np.reshape(filter1, (300, 400, 3)))
ax1.set_title("%dth Principal Component"%(comp1))
# s... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
3.3 PCA for Visualization
PCA can also be done for visualization purposes. Let's perform PCA on the movie ratings dataset and see if any semblence of the class structure can be seen. | # get the movie features
movie_features = movie_data[['RottenTomatoes','RottenTomatoes_User','Metacritic','Metacritic_User','Fandango_Ratingvalue']].as_matrix()
# perform standard scaling again but via SciKit-Learn
from sklearn.preprocessing import StandardScaler
z_scaler = StandardScaler()
movie_features = z_scaler.f... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
<span style="color:red">STUDENT ACTIVITY (until end of session)</span>
Your task is to reproduce the above PCA examples on a new dataset of images. Let's load it... | from sklearn.datasets import fetch_olivetti_faces
faces_dataset = fetch_olivetti_faces(shuffle=True)
faces = faces_dataset.data # 400 flattened 64x64 images
person_ids = faces_dataset.target # denotes the identity of person (40 total)
print "Dataset size: %d x %d" %(faces.shape)
print "And the images look like this..... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
This dataset contains 400 64x64 pixel images of 40 people each exhibiting 10 facial expressions. The images are in gray-scale, not color, and therefore flattened vectors contain 4096 dimensions.
<span style="color:red">Subtask 1: Run PCA</span> | ?PCA
### Your code goes here ###
# train PCA model on 'faces'
from sklearn.decomposition import PCA
pca = PCA(n_components=100)
start_time = time.time()
faces_reduced = pca.fit_transform(faces)
end_time = time.time()
###########################
print "Training took a total of %.2f seconds." %(end_time-start_time... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
<span style="color:red">Subtask 2: Reconstruct an image</span> | ### Your code goes here ###
# Use learned transformation matrix to project back to the original 4096-dimensional space
# Remember you need to use np.reshape()
###########################
img_idx = 70
reconstructed_img = pca.inverse_transform(faces_reduced[img_idx,:])
original_img = faces[70,:]
# subplot for origin... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
Your output should look something like what's below (although could be a different face):
<span style="color:red">Subtask 3: Visualize one or more components of the transformation matrix (W)</span> | ### Your code goes here ###
# Now visualize one of the principal components
# Again, remember you need to use np.reshape()
###########################
transformation_mat = pca.components_
# two components to show
comp1 = 5
comp2 = 90
# subplot
ax1 = plt.subplot(1,2,1)
filter1 = transformation_mat[comp1,:]
ax1.ims... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
Your output should look something like what's below (although could have differently ranked components):
<span style="color:red">Subtask 4: Generate a 2D scatter plot</span> | ### Your code goes here ###
# Train another PCA model to project the data into two dimensions
# Bonus: color the scatter plot according to the person_ids to see if any structure can be seen
# Run PCA for 2 components
# Generate plot
###########################
pca = PCA(n_components=2)
start_time = time.time()
fa... | Session 4 - Features_I_Transformations_DimensionalityReduction.ipynb | dinrker/PredictiveModeling | mit |
Compute all-to-all connectivity in sensor space
Computes the Phase Lag Index (PLI) between all gradiometers and shows the
connectivity in 3D using the helmet geometry. The left visual stimulation data
are used which produces strong connectvitiy in the right occipital sensors. | # Author: Martin Luessi <mluessi@nmr.mgh.harvard.edu>
#
# License: BSD (3-clause)
import mne
from mne import io
from mne.connectivity import spectral_connectivity
from mne.datasets import sample
from mne.viz import plot_sensors_connectivity
print(__doc__) | 0.21/_downloads/974f822d2280f83b67727ee3355c7c2f/plot_sensor_connectivity.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Set parameters | data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
# Setup for reading the raw data
raw = io.read_raw_fif(raw_fname)
events = mne.read_events(event_fname)
# Add a bad channel
raw.info['bads'] ... | 0.21/_downloads/974f822d2280f83b67727ee3355c7c2f/plot_sensor_connectivity.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Given a list of values, there are several ways to count the frequency of each value. | t = [1, 2, 2, 3, 5] | code/chap02ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
You can use a Python dictionary: | hist = {}
for x in t:
hist[x] = hist.get(x, 0) + 1
hist | code/chap02ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
You can use a Counter (which is a dictionary with additional methods): | from collections import Counter
counter = Counter(t)
counter | code/chap02ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Or you can use the Hist object provided by thinkstats2: | import thinkstats2
hist = thinkstats2.Hist([1, 2, 2, 3, 5])
hist | code/chap02ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Hist provides Freq, which looks up the frequency of a value. | hist.Freq(2) | code/chap02ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
You can also use the bracket operator, which does the same thing. | hist[2] | code/chap02ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
If the value does not appear, it has frequency 0. | hist[4] | code/chap02ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
The Values method returns the values: | hist.Values() | code/chap02ex.ipynb | AllenDowney/ThinkStats2 | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.