markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Here's a more efficient way to compute percentiles.
def Percentile2(scores, percentile_rank): scores.sort() index = percentile_rank * (len(scores)-1) // 100 return scores[int(index)]
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Let's hope we get the same answer.
Percentile2(t, 50)
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
The Cumulative Distribution Function (CDF) is almost the same as PercentileRank. The only difference is that the result is 0-1 instead of 0-100.
def EvalCdf(sample, x): count = 0.0 for value in sample: if value <= x: count += 1 prob = count / len(sample) return prob
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
In this list
t = [1, 2, 2, 3, 5]
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
We can evaluate the CDF for various values:
EvalCdf(t, 0), EvalCdf(t, 1), EvalCdf(t, 2), EvalCdf(t, 3), EvalCdf(t, 4), EvalCdf(t, 5)
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Here's an example using real data, the distribution of pregnancy length for live births.
cdf = thinkstats2.Cdf(live.prglngth, label='prglngth') thinkplot.Cdf(cdf) thinkplot.Config(xlabel='Pregnancy length (weeks)', ylabel='CDF', loc='upper left')
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Cdf provides Prob, which evaluates the CDF; that is, it computes the fraction of values less than or equal to the given value. For example, 94% of pregnancy lengths are less than or equal to 41.
cdf.Prob(41)
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Value evaluates the inverse CDF; given a fraction, it computes the corresponding value. For example, the median is the value that corresponds to 0.5.
cdf.Value(0.5)
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
In general, CDFs are a good way to visualize distributions. They are not as noisy as PMFs, and if you plot several CDFs on the same axes, any differences between them are apparent.
first_cdf = thinkstats2.Cdf(firsts.totalwgt_lb, label='first') other_cdf = thinkstats2.Cdf(others.totalwgt_lb, label='other') thinkplot.PrePlot(2) thinkplot.Cdfs([first_cdf, other_cdf]) thinkplot.Config(xlabel='Weight (pounds)', ylabel='CDF')
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
In this example, we can see that first babies are slightly, but consistently, lighter than others. We can use the CDF of birth weight to compute percentile-based statistics.
weights = live.totalwgt_lb live_cdf = thinkstats2.Cdf(weights, label='live')
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Again, the median is the 50th percentile.
median = live_cdf.Percentile(50) median
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
The interquartile range is the interval from the 25th to 75th percentile.
iqr = (live_cdf.Percentile(25), live_cdf.Percentile(75)) iqr
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
We can use the CDF to look up the percentile rank of a particular value. For example, my second daughter was 10.2 pounds at birth, which is near the 99th percentile.
live_cdf.PercentileRank(10.2)
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
If we draw a random sample from the observed weights and map each weigh to its percentile rank.
sample = np.random.choice(weights, 100, replace=True) ranks = [live_cdf.PercentileRank(x) for x in sample]
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
The resulting list of ranks should be approximately uniform from 0-1.
rank_cdf = thinkstats2.Cdf(ranks) thinkplot.Cdf(rank_cdf) thinkplot.Config(xlabel='Percentile rank', ylabel='CDF')
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
That observation is the basis of Cdf.Sample, which generates a random sample from a Cdf. Here's an example.
resample = live_cdf.Sample(1000) thinkplot.Cdf(live_cdf) thinkplot.Cdf(thinkstats2.Cdf(resample, label='resample')) thinkplot.Config(xlabel='Birth weight (pounds)', ylabel='CDF')
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
This confirms that the random sample has the same distribution as the original data. Exercises Exercise: How much did you weigh at birth? If you don’t know, call your mother or someone else who knows. Using the NSFG data (all live births), compute the distribution of birth weights and use it to find your percentile ran...
# Solution first_cdf.PercentileRank(8.5) # Solution other_cdf.PercentileRank(8.5)
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
Exercise: The numbers generated by numpy.random.random are supposed to be uniform between 0 and 1; that is, every value in the range should have the same probability. Generate 1000 numbers from numpy.random.random and plot their PMF. What goes wrong? Now plot the CDF. Is the distribution uniform?
# Solution t = np.random.random(1000) # Solution pmf = thinkstats2.Pmf(t) thinkplot.Pmf(pmf, linewidth=0.1) thinkplot.Config(xlabel='Random variate', ylabel='PMF') # Solution cdf = thinkstats2.Cdf(t) thinkplot.Cdf(cdf) thinkplot.Config(xlabel='Random variate', ylabel='CDF')
solutions/chap04soln.ipynb
AllenDowney/ThinkStats2
gpl-3.0
# Présentation rapide de Pandas Objectifs d'apprentissage : * Introduction aux structures de données DataFrame et Series de la bibliothèque Pandas * Accéder aux données et les manipuler dans une structure DataFrame et Series * Importer des données d'un fichier CSV dans un DataFrame Pandas * Réindexer un DataFra...
from __future__ import print_function import pandas as pd pd.__version__
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
On distingue deux grandes catégories de structures de données Pandas : Le DataFrame, un tableau relationnel de données, avec des lignes et des colonnes étiquetées La Series, constituée d'une seule colonne. Un DataFrame contient une ou plusieurs Series, chacune étant étiquetée. Le DataFrame est une abstraction fréquem...
pd.Series(['San Francisco', 'San Jose', 'Sacramento'])
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
Il est possible de créer des objets DataFrame en transmettant un dictionnaire qui met en correspondance les noms de colonnes (des chaînes de caractères) avec leur Series respective. Lorsque la longueur de la Series ne correspond pas, les valeurs manquantes sont remplacées par des valeurs NA/NaN spéciales. Exemple :
city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento']) population = pd.Series([852469, 1015785, 485199]) pd.DataFrame({ 'City name': city_names, 'Population': population })
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
Le plus souvent, vous chargez un fichier entier dans un DataFrame. Dans l'exemple qui suit, le fichier chargé contient des données immobilières pour la Californie. Exécutez la cellule suivante pour charger les données et définir les caractéristiques :
california_housing_dataframe = pd.read_csv("https://download.mlcc.google.com/mledu-datasets/california_housing_train.csv", sep=",") california_housing_dataframe.describe()
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
Dans l'exemple ci-dessus, la méthode DataFrame.describe permet d'afficher des statistiques intéressantes concernant un DataFrame. La fonction DataFrame.head est également utile pour afficher les premiers enregistrements d'un DataFrame :
california_housing_dataframe.head()
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
Autre fonction puissante de Pandas : la représentation graphique. Avec DataFrame.hist, par exemple, vous pouvez vérifier rapidement la façon dont les valeurs d'une colonne sont distribuées :
california_housing_dataframe.hist('housing_median_age')
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
## Accéder aux données L'accès aux données d'un DataFrame s'effectue au moyen d'opérations de liste ou de dictionnaire Python courantes :
cities = pd.DataFrame({ 'City name': city_names, 'Population': population }) print(type(cities['City name'])) cities['City name'] print(type(cities['City name'][1])) cities['City name'][1] print(type(cities[0:2])) cities[0:2]
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
Pandas propose en outre une API extrêmement riche, avec des fonctions avancées d'indexation et de sélection, que nous ne pouvons malheureusement pas aborder ici dans le détail. ## Manipuler des données Il est possible d'effectuer des opérations arithmétiques de base de Python sur les Series. Par exemple :
population / 1000.
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
NumPy est un kit d'outils de calculs scientifiques populaire. Les Series Pandas peuvent faire office d'arguments pour la plupart des fonctions NumPy :
import numpy as np np.log(population)
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
La méthode Series.apply convient pour les transformations à une colonne plus complexes. Comme la fonction map de Python, elle accepte en argument une fonction lambda, appliquée à chaque valeur. L'exemple ci-dessous permet de créer une Series signalant si la population dépasse ou non un million d'habitants :
population.apply(lambda val: val > 1000000)
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
La modification des DataFrames est également très simple. Ainsi, le code suivant permet d'ajouter deux Series à un DataFrame existant :
cities['Area square miles'] = pd.Series([46.87, 176.53, 97.92]) cities['Population density'] = cities['Population'] / cities['Area square miles'] cities
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
## Exercice n° 1 Modifiez le tableau cities en ajoutant une colonne booléenne qui prend la valeur True si et seulement si les deux conditions suivantes sont remplies : La ville porte le nom d'un saint. La ville s'étend sur plus de 50 miles carrés. Remarque : Pour combiner des Series booléennes, utilisez des opérateur...
# Your code here
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
### Solution Cliquez ci-dessous pour afficher la solution.
cities['Is wide and has saint name'] = (cities['Area square miles'] > 50) & cities['City name'].apply(lambda name: name.startswith('San')) cities
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
## Index Les objets Series et DataFrame définissent également une propriété index, qui affecte un identifiant à chaque élément d'une Series ou chaque ligne d'un DataFrame. Par défaut, Pandas affecte les valeurs d'index en suivant l'ordre des données source. Ces valeurs ne varient pas par la suite ; elles restent incha...
city_names.index cities.index
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
Appelez DataFrame.reindex pour réorganiser manuellement les lignes. Le code suivant, par exemple, revient à trier les données par nom de ville :
cities.reindex([2, 0, 1])
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
La réindexation est un excellent moyen de mélanger (organiser aléatoirement) les données d'un DataFrame. Dans l'exemple ci-dessous, l'index de type tableau est transmis à la fonction NumPy random.permutation, qui mélange les valeurs. En appelant reindex avec ce tableau mélangé, nous mélangeons également les lignes du D...
cities.reindex(np.random.permutation(cities.index))
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
Pour en savoir plus, consultez la documentation relative aux index. ## Exercice n° 2 La méthode reindex autorise les valeurs d'index autres que celles associées au DataFrame d'origine. Voyez ce qu'il se passe lorsque vous utilisez ce type de valeurs ! Pourquoi est-ce autorisé à votre avis ?
# Your code here
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
### Solution Cliquez ci-dessous pour afficher la solution. Lorsque le tableau d'entrée reindex contient des valeurs d'index ne faisant pas partie de la liste des index du DataFrame d'origine, reindex ajoute des lignes pour ces index \'manquants\' et insère la valeur NaN dans les colonnes correspondantes :
cities.reindex([0, 4, 5, 2])
ml/cc/prework/fr/intro_to_pandas.ipynb
google/eng-edu
apache-2.0
Load the data file shared/bladder_cancer_genes_tcga.txt into a pandas.DataFrame, convert it to a numpy.ndarray matrix, and print the matrix dimensions
gene_matrix_for_network_df = gene_matrix_for_network = print(gene_matrix_for_network.shape)
class21_reveal_python3_template.ipynb
ramseylab/networkscompbio
apache-2.0
Filter the matrix to include only rows for which the column-wise median is > 14; matrix should now be 13 x 414.
genes_keep = numpy.where( ## fill in here ## > 14) matrix_filt = matrix_filt.shape N = matrix_filt.shape[0] M = matrix_filt.shape[1]
class21_reveal_python3_template.ipynb
ramseylab/networkscompbio
apache-2.0
Binarize the gene expression matrix using the mean value as a breakpoint, turning it into a NxM matrix of booleans (True/False). Call it gene_matrix_binarized.
gene_matrix_binarized = ## fill in here ##
class21_reveal_python3_template.ipynb
ramseylab/networkscompbio
apache-2.0
The core part of the REVEAL algorithm is a function that can compute the joint entropy of a collection of binary (TRUE/FALSE) vectors X1, X2, ..., Xn (where length(X1) = length(Xi) = M). Write a function entropy_multiple_vecs that takes as its input a nxM matrix (where n is the number of variables, i.e., genes, and M i...
def entropy_multiple_vecs(binary_vecs): ## use shape to get the numbers of rows and columns as [n,M] [n, M] = binary_vecs.shape # make a "M x n" dataframe from the transpose of the matrix binary_vecs binary_df = # use the groupby method to obtain a data frame of counts of unique occurrenc...
class21_reveal_python3_template.ipynb
ramseylab/networkscompbio
apache-2.0
Data Exploration Some basic exploratory analysis before creating a decision tree
# What is the shape of our data? # What variables are present in the dataset? # What is the distribution of our outcome variable `in_sf`? # How does elevation vary for houses in/not-in sf (I suggest an overlapping histogram)
decision-trees/decision-tree.ipynb
info-370/classification
mit
Build a decision tree using all variables
# Create variables to hold features and outcomes separately # Split data into testing and training sets # Create a classifier and fit your features to your outcome
decision-trees/decision-tree.ipynb
info-370/classification
mit
Assess Model Fit
# Generate a set of predictions for your test data # Calculate accuracy for our test set (percentage of the time that prediction == truth) # By comparison, how well do we predict in our training data?
decision-trees/decision-tree.ipynb
info-370/classification
mit
Show the tree A little bit of a pain, though there are some alternatives to the documentation presented here. You may have to do the following: ``` Install graphviz in your terminal conda install graphviz ``` I then suggest the following solution: tree.export_graphviz(clf, out_file="mytree.dot") with open("mytree.dot")...
# Create tree diagram
decision-trees/decision-tree.ipynb
info-370/classification
mit
Comparion to KNN Purely out of curiosity, how well does this model fit with KNN (for K=3)
# Create a knn classifier # Fit our classifier to our training data # Predict on our test data and assess accuracy
decision-trees/decision-tree.ipynb
info-370/classification
mit
<div class="alert alert-info"> <b>REMEMBER</b>: Use meaningful variable names </div> I'm measuring at sea level, what would be the air pressure of this measured value on other altitudes? I'm curious what the equivalent pressure would be on other alitudes... The barometric formula, sometimes called the exponential ...
import math # ...modules and libraries...
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-danger"> <b>DON'T</b>: <code>from os import *</code>. Just don't! </div>
standard_temperature = 288.15 gas_constant = 8.31446 gravit_acc = 9.81 molar_mass_earth = 0.02896
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-success"> <b>EXERCISE</b>: <ul> <li>Calculate the equivalent air pressure at the altitude of 2500 m above sea level for our measured value of <code>pressure_hPa</code> (1010 hPa)</li> </ul> </div>
height = 2500 pressure_hPa * math.exp(-gravit_acc * molar_mass_earth* height/(gas_constant*standard_temperature)) # ...function/definition for barometric_formula... def barometric_formula(pressure_sea_level, height=2500): """Apply barometric formula Apply the barometric formula to calculate the air pres...
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
Instead of having the functions in a notebook, importing the function from a file can be done as importing a function from an installed package. Save the function barometric_formula in a file called barometric_formula.py and add the required import statement import math on top of the file. Next, run the following cell:
from barometric_formula import barometric_formula
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-info"> <b>REMEMBER</b>: <ul> <li>Write functions to prevent copy-pasting of code and maximize reuse</li> <li>Add documentation to functions for your future self</li> <li>Named arguments provide default values</li> <li>Import functions from a file just as other m...
pressures_hPa = [1013, 1003, 1010, 1020, 1032, 993, 989, 1018, 889, 1001] # ...check methods of lists... append vs insert
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-warning"> <b>Notice</b>: <ul> <li>A list is a general container, so can exist of mixed data types as well.</li> </ul> </div>
# ...list is a container...
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
I want to apply my function to each of these measurements I want to calculate the barometric formula for each of these measured values.
# ...for loop... dummy example
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-success"> <b>EXERCISE</b>: <ul> <li>Write a <code>for</code> loop that prints the adjusted value for altitude 3000m for each of the pressures in <code>pressures_hPa</code> </li> </ul> </div>
for pressure in pressures_hPa: print(barometric_formula(pressure, 3000)) # ...list comprehensions...
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-success"> <b>EXERCISE</b>: <ul> <li>Write a <code>for</code> loop as a list comprehension to calculate the adjusted value for altitude 3000m for each of the pressures in <code>pressures_hPa</code> and store these values in a new variable <code>pressures_hPa_adjusted</code>...
pressures_hPa_adjusted = [barometric_formula(pressure, 3000) for pressure in pressures_hPa] pressures_hPa_adjusted
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
The power of numpy
import numpy as np pressures_hPa = [1013, 1003, 1010, 1020, 1032, 993, 989, 1018, 889, 1001] np_pressures_hPa = np.array([1013, 1003, 1010, 1020, 1032, 993, 989, 1018, 889, 1001]) # ...slicing/subselecting is similar... print(np_pressures_hPa[0], pressures_hPa[0])
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-info"> <b>REMEMBER</b>: <ul> <li> <code>[]</code> for accessing elements <li> <code>[start:end:step]</code> </ul> </div>
# ...original function using numpy array instead of list... do both np_pressures_hPa * math.exp(-gravit_acc * molar_mass_earth* height/(gas_constant*standard_temperature))
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-info"> <b>REMEMBER</b>: The operations do work on all elements of the array at the same time, you don't need a <strike>`for` loop<strike> </div> It is also a matter of calculation speed:
lots_of_pressures = np.random.uniform(990, 1040, 1000) %timeit [barometric_formula(pressure, 3000) for pressure in list(lots_of_pressures)] %timeit lots_of_pressures * np.exp(-gravit_acc * molar_mass_earth* height/(gas_constant*standard_temperature))
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-info"> <b>REMEMBER</b>: for calculations, numpy outperforms python </div> Boolean indexing and filtering (!)
np_pressures_hPa np_pressures_hPa > 1000
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
You can use this as a filter to select elements of an array:
boolean_mask = np_pressures_hPa > 1000 np_pressures_hPa[boolean_mask]
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
or, also to change the values in the array corresponding to these conditions:
boolean_mask = np_pressures_hPa < 900 np_pressures_hPa[boolean_mask] = 900 np_pressures_hPa
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
Intermezzo: Exercises boolean indexing:
AR = np.random.randint(0, 20, 15) AR
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-success"> <b>EXERCISE</b>: Count the number of values in AR that are larger than 10 _Tip:_ You can count with True = 1 and False = 0 and take the sum of these values </div>
sum(AR > 10)
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-success"> <b>EXERCISE</b>: Change all even numbers of `AR` into zero-values. </div>
AR[AR%2 == 0] = 0 AR
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-success"> <b>EXERCISE</b>: Change all even positions of matrix AR into the value 30 </div>
AR[1::2] = 30 AR
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-success"> <b>EXERCISE</b>: Select all values above the 75th percentile of the following array AR2 ad take the square root of these values _Tip_: numpy provides a function `percentile` to calculate a given percentile </div>
AR2 = np.random.random(10) AR2 np.sqrt(AR2[AR2 > np.percentile(AR2, 75)])
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert-success"> <b>EXERCISE</b>: Convert all values -99 of the array AR3 into Nan-values _Tip_: that Nan values can be provided in float arrays as `np.nan` and that numpy provides a specialized function to compare float values, i.e. `np.isclose()` </div>
AR3 = np.array([-99., 2., 3., 6., 8, -99., 7., 5., 6., -99.]) AR3[np.isclose(AR3, -99)] = np.nan AR3
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
I also have measurement locations
location = 'Ghent - Sterre' # ...check methods of strings... split, upper,... locations = ['Ghent - Sterre', 'Ghent - Coupure', 'Ghent - Blandijn', 'Ghent - Korenlei', 'Ghent - Kouter', 'Ghent - Coupure', 'Antwerp - Groenplaats', 'Brussels- Grand place', 'Antwerp - Justitipale...
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
<div class="alert alert alert-success"> <b>EXERCISE</b>: Use a list comprehension to convert all locations to lower case. _Tip:_ check the available methods of lists by writing: `location.` + TAB button </div>
[location.lower() for location in locations]
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
I also measure temperature
pressures_hPa = [1013, 1003, 1010, 1020, 1032, 993, 989, 1018, 889, 1001] temperature_degree = [23, 20, 17, 8, 12, 5, 16, 22, -2, 16] locations = ['Ghent - Sterre', 'Ghent - Coupure', 'Ghent - Blandijn', 'Ghent - Korenlei', 'Ghent - Kouter', 'Ghent - Coupure', 'Antwerp - Groenplaats', 'Brusse...
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
Python dictionaries are a convenient way to store multiple types of data together, to not have too much different variables:
measurement = {} measurement['pressure_hPa'] = 1010 measurement['temperature'] = 23 measurement # ...select on name, iterate over keys or items... measurements = {'pressure_hPa': pressures_hPa, 'temperature_degree': temperature_degree, 'location': locations} measurements
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
But: I want to apply my barometric function to measurements taken in Ghent when the temperature was below 10 degrees...
for idx, pressure in enumerate(measurements['pressure_hPa']): if measurements['location'][idx].startswith("Ghent") and \ measurements['temperature_degree'][idx]< 10: print(barometric_formula(pressure, 3000))
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
when a table would be more appropriate... Pandas!
import pandas as pd measurements = pd.DataFrame(measurements) measurements barometric_formula(measurements[(measurements["location"].str.contains("Ghent")) & (measurements["temperature_degree"] < 10)]["pressure_hPa"], 3000)
notebooks/python_recap/python_rehearsal.ipynb
jorisvandenbossche/DS-python-data-analysis
bsd-3-clause
Basic plot example
from matplotlib.pyplot import figure, plot, xlabel, ylabel, title, show x=linspace(0,5,10) y=x**2 figure() plot(x,y,'r') xlabel('x') ylabel('y') title('title') show()
.ipynb_checkpoints/test-jupyter-widgets-clone-checkpoint.ipynb
bjsmith/motivation-simulation
gpl-3.0
$$c = \sqrt{a^2 + b^2}$$ $$ \begin{align} c =& \sqrt{a^2 + b^2} \ =&\sqrt{4+16} \ \end{align} $$ $$ \begin{align} f(x)= & x^2 \ = & {{x[1]}} \end{align} $$ This text contains a value like $x[1]$ is {{x[1]}} Widget example
from IPython.display import display text = widgets.FloatText() floatText = widgets.FloatText(description='MyField',min=-5,max=5) floatSlider = widgets.FloatSlider(description='MyField',min=-5,max=5) #https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Basics.html float_link = widgets.jslink((floatText, 'va...
.ipynb_checkpoints/test-jupyter-widgets-clone-checkpoint.ipynb
bjsmith/motivation-simulation
gpl-3.0
Here we will set the fields to one of several values so that we can see pre-configured examples.
floatSlider.value=1 bSatiationPreset=widgets.Button( description='Salt Satiation', button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Click me' ) bDeprivationPreset=widgets.Button( description='Salt Deprivation2', button_style='', # 'success', 'info', 'warning', 'danger' or ...
.ipynb_checkpoints/test-jupyter-widgets-clone-checkpoint.ipynb
bjsmith/motivation-simulation
gpl-3.0
Introduction The quantum two-level system (TLS) is the simplest possible model to describe the quantum light-matter interaction between light and an artificial atom (quantum dot). While the version in the paper (both experiment and simulation) used a three-level system model, I decided to show only a TLS model here to ...
n_Pi = 13 # 8 pi pulse area Om_list = np.linspace(0.001, n_Pi, 80) # driving strengths wd_list_e = np.array([-1, 0, 1]) # laser offsets in meV wd_list = wd_list_e*1.5 # in angular frequency tlist = np.linspace(0, 50, 40) # tmax ...
examples/brmesolve-time-dependent-Liouvillian.ipynb
qutip/qutip-notebooks
lgpl-3.0
Setup the operators, Hamiltonian, and initial state
# initial state psi0 = fock(2, 1) # ground state # system's atomic lowering operator sm = sigmam() # Hamiltonian components H_S = -sm.dag() * sm # self-energy, varies with drive frequency H_I = sm + sm.dag() # we ignore spontaneous emission since the pulse is much faster than # the decay time c_ops = []
examples/brmesolve-time-dependent-Liouvillian.ipynb
qutip/qutip-notebooks
lgpl-3.0
Below, we define the terms specific to the Bloch-Redfield solver's system-environmental coupling. The quantum dot couples to acoustic phonons in its solid-state environment through a dispersive electron-phonon interaction of the form $$ H_\textrm{phonon}=\hbar J(\omega)\sigma^\dagger \sigma,$$ where $J(\omega)$ is the ...
# operator that couples the quantum dot to acoustic phonons a_op = sm.dag()*sm # This spectrum is a displaced gaussian multiplied by w^3, which # models coupling to LA phonons. The electron and hole # interactions contribute constructively. """ # fitting parameters ae/ah ah = 1.9e-9 # m ae = 3.5e-9 ...
examples/brmesolve-time-dependent-Liouvillian.ipynb
qutip/qutip-notebooks
lgpl-3.0
Visualize the dot-phonon interaction spectrum $J(\omega)$ has two components that give rise to its shape: a rising component due to the increasing acoustic phonon density of states and a roll-off that occurs due to the physical size of the quantum dot.
spec_list = np.linspace(-5, 10, 200) plt.figure(figsize=(8, 5)) plt.plot(spec_list, [eval(spectra_cb.replace('w', str(_))) for _ in spec_list]) plt.xlim(-5, 10) plt.xlabel('$\omega$ [THz]') plt.ylabel('$J(\omega)$ [THz]') plt.title('Quantum-dot-phonon interaction spectrum');
examples/brmesolve-time-dependent-Liouvillian.ipynb
qutip/qutip-notebooks
lgpl-3.0
Calculate the pulse-system interaction dynamics The Bloch-Redfield master equation solver takes the Hamiltonian time-dependence in list-string format. We calculate the final population at the end of the interaction of the pulse with the system, which represents the population initialized into the excited state.
# we will calculate the dot population expectation value e_ops = [sm.dag()*sm] # define callback for parallelization def brme_step(args): wd = args[0] Om = args[1] H = [wd * H_S, [Om * H_I, pulse_shape]] # calculate the population after the pulse interaction has # finished using the Bloch-Redf...
examples/brmesolve-time-dependent-Liouvillian.ipynb
qutip/qutip-notebooks
lgpl-3.0
Visualize the quantum dot's initialization fidelity Below, consider the trace of excited state occupation for increasing pulse area at a detuning of $\omega_d-\omega_L=0$. Here, the oscillations represent the standard Rabi oscillations of a driven two-level system, damped for increasing pulse area by a Markovian-like d...
plt.figure(figsize=(8, 5)) plt.plot(Om_list, inv_mat_X[0]) plt.plot(Om_list, inv_mat_X[1]) plt.plot(Om_list, inv_mat_X[2]) plt.legend(['laser detuning, -1 meV', 'laser detuning, 0 meV', 'laser detuning, +1 meV'], loc=4) plt.xlim(0, 13) plt.xlabel('Pulse area [$\pi$]') plt.ylabel('Excited st...
examples/brmesolve-time-dependent-Liouvillian.ipynb
qutip/qutip-notebooks
lgpl-3.0
Versions
from qutip.ipynbtools import version_table version_table()
examples/brmesolve-time-dependent-Liouvillian.ipynb
qutip/qutip-notebooks
lgpl-3.0
1D Wasserstein barycenter comparison between exact LP and entropic regularization This example illustrates the computation of regularized Wasserstein Barycenter as proposed in [3] and exact LP barycenters using standard LP solver. It reproduces approximately Figure 3.1 and 3.2 from the following paper: Cuturi, M., & Pe...
# Author: Remi Flamary <remi.flamary@unice.fr> # # License: MIT License import numpy as np import matplotlib.pylab as pl import ot # necessary for 3d plot even if not used from mpl_toolkits.mplot3d import Axes3D # noqa from matplotlib.collections import PolyCollection # noqa #import ot.lp.cvx as cvx
notebooks/plot_barycenter_lp_vs_entropic.ipynb
rflamary/POT
mit
Gaussian Data
#%% parameters problems = [] n = 100 # nb bins # bin positions x = np.arange(n, dtype=np.float64) # Gaussian distributions # Gaussian distributions a1 = ot.datasets.make_1D_gauss(n, m=20, s=5) # m= mean, s= std a2 = ot.datasets.make_1D_gauss(n, m=60, s=8) # creating matrix A containing all distributions A = np.v...
notebooks/plot_barycenter_lp_vs_entropic.ipynb
rflamary/POT
mit
Dirac Data
#%% parameters a1 = 1.0 * (x > 10) * (x < 50) a2 = 1.0 * (x > 60) * (x < 80) a1 /= a1.sum() a2 /= a2.sum() # creating matrix A containing all distributions A = np.vstack((a1, a2)).T n_distributions = A.shape[1] # loss matrix + normalization M = ot.utils.dist0(n) M /= M.max() #%% plot the distributions pl.figure(...
notebooks/plot_barycenter_lp_vs_entropic.ipynb
rflamary/POT
mit
Final figure
#%% plot nbm = len(problems) nbm2 = (nbm // 2) pl.figure(2, (20, 6)) pl.clf() for i in range(nbm): A = problems[i][0] bary_l2 = problems[i][1][0] bary_wass = problems[i][1][1] bary_wass2 = problems[i][1][2] pl.subplot(2, nbm, 1 + i) for j in range(n_distributions): pl.plot(x, A[:, ...
notebooks/plot_barycenter_lp_vs_entropic.ipynb
rflamary/POT
mit
Prepare Data
def parse_file(filename): xdata, ydata = [], [] fin = open(filename, "rb") i = 0 for line in fin: if i % 10000 == 0: print("{:s}: {:d} lines read".format( os.path.basename(filename), i)) cols = line.strip().split(",") ydata.append(int(cols[0])) ...
src/tensorflow/05-experiment-from-tf-estimator.ipynb
sujitpal/polydlot
apache-2.0
Define Estimator The tf.contrib.learn package provides several Estimators out of the box. * tf.contrib.learn.LinearRegressor * tf.contrib.learn.LinearClassifier * tf.contrib.learn.DNNRegressor * tf.contrib.learn.DNNClassifier
shutil.rmtree(MODEL_DIR, ignore_errors=True) feature_cols = [tf.contrib.layers.real_valued_column("", dimension=NUM_FEATURES)] estimator = tf.contrib.learn.DNNClassifier(feature_columns=feature_cols, hidden_units=[512, 256], n_classes=NUM_CLASSES, model_dir=MODEL_DIR)
src/tensorflow/05-experiment-from-tf-estimator.ipynb
sujitpal/polydlot
apache-2.0
Train Estimator
estimator.fit(input_fn=train_input_fn, steps=NUM_STEPS)
src/tensorflow/05-experiment-from-tf-estimator.ipynb
sujitpal/polydlot
apache-2.0
Evaluate Estimator
accuracy_score = estimator.evaluate(input_fn=test_input_fn, steps=1)["accuracy"] print("accuracy: {:.3f}".format(accuracy_score))
src/tensorflow/05-experiment-from-tf-estimator.ipynb
sujitpal/polydlot
apache-2.0
alternatively... Define Experiment A model is wrapped in an Estimator, which is then wrapped in an Experiment. Once you have an Experiment, you can run this in a distributed manner on CPU, GPU or TPU.
def experiment_fn(run_config, params): feature_cols = [tf.contrib.layers.real_valued_column("", dimension=NUM_FEATURES)] estimator = tf.contrib.learn.DNNClassifier( feature_columns=feature_cols, hidden_units=[512, 256], n_classes=NUM_CLASSES, config=run_config) return...
src/tensorflow/05-experiment-from-tf-estimator.ipynb
sujitpal/polydlot
apache-2.0
Run Experiment
shutil.rmtree(MODEL_DIR, ignore_errors=True) tf.contrib.learn.learn_runner.run(experiment_fn, run_config=tf.contrib.learn.RunConfig( model_dir=MODEL_DIR))
src/tensorflow/05-experiment-from-tf-estimator.ipynb
sujitpal/polydlot
apache-2.0
Alias na komendę systemową z powłoki alias
%alias whole_line echo "%l" %whole_line ala ma kota %alias params_echo echo ala ma %s a tomek ma %s a zuzia ma %s %params_echo psa kota zyrafe dane = !dir print(dane) dane = "Ala ma kota" !echo $dane !echo $$ from IPython.core.magic import register_line_magic @register_line_magic def my_custom_quadratic(line): ...
ipython_course/ipython.ipynb
andrzejkrawczyk/python-course
apache-2.0
CSV(Comma Seperated Value) => 각각의 데이터가 ","를 기준으로 나뉜 데이터 예를 들어 김기표 | 29 | 분석가 // sep="|" 이거였어 // 이렇게 하면 ,가 |이걸로 바뀌게 된다.
df.to_csv("fastcampus.csv", index=False, header=False, sep="|")
Python 복습/12일차.금_Pandas의 고급기능_DB/12일차_4T_Pandas Basic (4) - 파일 입출력 ( csv, excel, sql ).ipynb
kimkipyo/dss_git_kkp
mit
데이터 분석을 사용할 때 2가지 양식이 있다 csv(엑셀), XML, JSON == 데이터베이스 Pickle(데이터 분석에서 상당히 중요하다) => 파이썬의 객체 그대로 저장할 수 있다. 파이썬 코드를 그대로 저장 즉, 클래스나 함수를 바이너리 형태로 저장해서 언제든 쓸 수 있도록
df = pd.read_csv # 이렇게 간단하다 # 엑셀 파일을 일괄적으로 csv 형태로 바꿔주는 프로그래밍 => Pandas로 하면 금방 한다 # read_excel().to_csv 이런 식으로 하면. 해보자 pd.read_csv("fastcampus.csv") pd.read_csv("fastcampus.csv", header=None, sep="|") df = pd.read_csv("fastcampus.csv", header=None, sep="|") df.rename(columns={0: "Age", 1: "Name"}, inplace=True) df
Python 복습/12일차.금_Pandas의 고급기능_DB/12일차_4T_Pandas Basic (4) - 파일 입출력 ( csv, excel, sql ).ipynb
kimkipyo/dss_git_kkp
mit
We illustrate the concept using the subsampled data, simply replace the filename... An indepth analysis with 1.3M cells will follow in the first half of 2018.
filename = './write/subsampled.h5ad'
170522_visualizing_one_million_cells/plot.ipynb
theislab/scanpy_usage
bsd-3-clause
Opening an '.h5ad' file in "backed" mode does not load the data into memory.
adata = sc.read(filename, backed='r') # open file in backed mode for reading ('r') sc.pl.tsne(adata, color='louvain_groups') sc.logging.print_memory_usage()
170522_visualizing_one_million_cells/plot.ipynb
theislab/scanpy_usage
bsd-3-clause
Loading the data in "memory" mode needs 100 MB for the subsampled data.
adata = sc.read(filename, backed=False) # backed=False is the default of sc.read(...) sc.logging.print_memory_usage()
170522_visualizing_one_million_cells/plot.ipynb
theislab/scanpy_usage
bsd-3-clause
Wine dataset description - 84199 bytes (not large, feel free to load into memory) - header with quotations " in the text - each line has floats without quotations - each datum separated by ; Some Python basics: - file input/output - [f(a) for a in L] list comprehensions - iterables, basic types, built-in functions
datapath = "../../data/" with open(datapath + 'winequality-red.csv','r') as winefile: header = winefile.readline() wine_list = [line.strip().split(';') for line in winefile] wine_ar = np.array(wine_list,dtype=np.float64) names = [name.strip('"') for name in header.strip().split(';')] print(names) #Subselect ...
lectures/lecture1/.ipynb_checkpoints/lecture1-checkpoint.ipynb
jsharpna/DavisSML
mit
Linear model $$f_\beta(x_i) = \beta_0 + \sum_{j=1}^p \beta_j x_{i,j}$$ Inference in linear models statistically test for significance of effects requires normality assumptions, homoscedasticity, linear model is correct hard to obtain significance for individual effect under colinearity Prediction perspective think o...
## The following uses pandas! datapath = "../../data/" oecd_bli = pd.read_csv(datapath + "oecd_bli_2015.csv", thousands=',') oecd_bli = oecd_bli[oecd_bli["INEQUALITY"]=="TOT"] oecd_bli = oecd_bli.pivot(index="Country", columns="Indicator", values="Value") # Load and prepare GDP per capita data # Download data from h...
lectures/lecture1/.ipynb_checkpoints/lecture1-checkpoint.ipynb
jsharpna/DavisSML
mit