markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We want to know what you look for in the opposite sex. | # Attractiveness
plt.hist(raw_dataset['attr_o'].dropna());
# Sincere
plt.hist(raw_dataset['sinc_o'].dropna());
# Intelligent
plt.hist(raw_dataset['intel_o'].dropna()) ;
# Fun
plt.hist(raw_dataset['fun_o'].dropna());
# Ambitious
plt.hist(raw_dataset['amb_o'].dropna()); | Luigi_et_le_Machine_Learning_lui_dit_merci.ipynb | xebia-france/luigi-airflow | apache-2.0 |
What is your primary goal in participating in this event?
Seemed like a fun night out=1,
To meet new people=2,
To get a date=3,
Looking for a serious relationship=4,
To say I did it=5,
Other=6 | raw_dataset.groupby('date').iid.nunique().sort_values(ascending=False) | Luigi_et_le_Machine_Learning_lui_dit_merci.ipynb | xebia-france/luigi-airflow | apache-2.0 |
In general, how frequently do you go on dates?
Several times a week=1
Twice a week=2
Once a week=3
Twice a month=4
Once a month=5
Several times a year=6
Almost never=7 | raw_dataset.groupby('go_out').iid.nunique().sort_values(ascending=False)
raw_dataset.groupby('career').iid.nunique().sort_values(ascending=False).head(10) | Luigi_et_le_Machine_Learning_lui_dit_merci.ipynb | xebia-france/luigi-airflow | apache-2.0 |
Initialize some feature-locations | featureLocationPool = createFeatureLocationPool(size=8) | projects/l2_pooling/notebooks/similar_objects.ipynb | subutai/htmresearch | agpl-3.0 |
Issue: One column spots a difference, but its voice is drowned out
Create 8 objects, each with 7 feature-locations. Each object is 1 different from each other object. | objects = {"Object 1": set(["A", "B", "C", "D", "E", "F", "G"]),
"Object 2": set(["A", "B", "C", "D", "E", "F", "H"]),
"Object 3": set(["A", "B", "C", "D", "E", "G", "H"]),
"Object 4": set(["A", "B", "C", "D", "F", "G", "H"]),
"Object 5": set(["A", "B", "C", "E", "F", "G", "H... | projects/l2_pooling/notebooks/similar_objects.ipynb | subutai/htmresearch | agpl-3.0 |
We're testing L2 in isolation, so these "A", "B", etc. patterns are L4 representations, i.e. "feature-locations".
Train an array of 5 columns to recognize these objects, then show it Object 1. It will randomly move its sensors to different feature-locations on the object. It will never put two sensors on the same featu... | (testObject,
columnPoolers,
featureLocationLog,
activeCellsLog,
columnObjectRepresentations) = experiment(objects, numColumns=5) | projects/l2_pooling/notebooks/similar_objects.ipynb | subutai/htmresearch | agpl-3.0 |
Print what just happened | columnContentsLog = []
for timestep, allActiveCells in enumerate(activeCellsLog):
columnContents = []
for columnIndex, activeCells in enumerate(allActiveCells):
contents = {}
for objectName, objectCells in columnObjectRepresentations[columnIndex].iteritems():
containsRatio = len(acti... | projects/l2_pooling/notebooks/similar_objects.ipynb | subutai/htmresearch | agpl-3.0 |
Each column is activating a union of cells. Column 2 sees input G, so it knows this isn't "Object 2", but multiple other columns are including "Object 2" in their unions, so Column 2's voice gets drowned out.
How does this vary with number of columns? | for numColumns in xrange(2, 8):
print "With %d columns:" % numColumns
experiment(objects, numColumns)
print | projects/l2_pooling/notebooks/similar_objects.ipynb | subutai/htmresearch | agpl-3.0 |
Step 1: Making the soup
First we need to use the BeautifulSoup module to parse the HTML data into Python readable Unicode Text format.
*Let us write the code to parse a html page. We will use the trip advisor URL for an infamous restaurant - https://www.tripadvisor.com/Restaurant_Review-g187147-d1751525-Reviews-Cafe_Le... | <div class="entry">
<p class="partial_entry">
Popped in on way to Eiffel Tower for lunch, big mistake.
Pizza was disgusting and service was poor.
It’s a shame Trip Advisor don’t let you score venues zero....
<span class="taLnk ulBlueLinks" onclick="widgetEvCall('handlers.clickExpand',event,this);"... | Session 2/ipython/Lesson 5- Crawl and scrape-Worksheet.ipynb | km-Poonacha/python4phd | gpl-3.0 |
Step 3: Searching the soup for the data
Beautiful Soup defines a lot of methods for searching the parse tree (soup), the two most popular methods are: find() and find_all().
The simplest filter is a tag. Pass a tag to a search method and Beautiful Soup will perform a match against that exact string.
Let us try and fi... | #Enter your code here
| Session 2/ipython/Lesson 5- Crawl and scrape-Worksheet.ipynb | km-Poonacha/python4phd | gpl-3.0 |
Expanding this further
To add additional details we can inspect the tags further and add the reviewer rating and reviwer details.
Using the review data and the ratings available is there any way we can improve the corpus of sentiments "word_sentiment.csv" file?
Dynamic Pages
Some websites make request in the background... | header = {
'cookie': 'TAUnique=%1%enc%3AHvAwOscAcmfzIwJbsS10GnXn4FrCUpCm%2Bnw21XKuzXoV7vSwMEnyTA%3D%3D; fbm_162729813767876=base_domain=.tripadvisor.com; TACds=B.3.11419.1.2019-03-31; TASSK=enc%3AABCGM1r6xBekOjRaaQZ3QVS7dP4cwZ8sombvPTq8xK6xN55i7TN8puwZdwvXvG1i%2FJ2UQXYG1CwsU%2BXLwLs5qIxnmW5qbLt4I48DfK5FhHpwUw3Zgrbs... | Session 2/ipython/Lesson 5- Crawl and scrape-Worksheet.ipynb | km-Poonacha/python4phd | gpl-3.0 |
Now I'm going to create some fake data: | from openpathsampling.tests.test_helpers import make_1d_traj
traj = make_1d_traj([-1, 1, 4, 3, 6, 11, 22, 33, 23, 101, 205, 35, 45])
# to get a real trajectory:
# from openpathsampling.engines.openmm.tools import ops_load_trajectory
# traj = ops_load_trajectory("name_of_file.xtc", top="topology.pdb") # can also be a ... | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
Next I'll open the file. You'll only do this once, and then add all of your annotations for each trajectory into the open file. | storage = paths.Storage("output.nc", "w") | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
Annotating trajectories
Now we get to the core. For each trajectory, you can choose state names, and you create a list of annotations for those states. Each annotation includes the state name, the first frame in the state, and the final frame in the state (first and final, named begin and end, are included in the state... | annotations = [
Annotation(state="1-digit", begin=1, end=4),
Annotation(state="2-digit", begin=6, end=8),
Annotation(state="3-digit", begin=10, end=10),
Annotation(state="2-digit", begin=11, end=12)
]
a_traj = AnnotatedTrajectory(trajectory=traj, annotations=annotations) | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
Note that I worry more about incorrectly identifying something as in the state when it actually is not, than missing any frame that could be in the state. There's always some room for optimization here, but you should err on the side of ensuring that your labels actually identify that state. Allow false negatives; don'... | storage.tag['my_file_name'] = a_traj | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
Repeat the steps in the last two cells for each trajectory. When you're done, you can run: | storage.sync()
storage.close() | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
Plotting annotations | %matplotlib inline
import matplotlib.pyplot as plt
def ln_x(snapshot):
import math
return math.log10(abs(snapshot.xyz[0][0]))
cv = paths.CoordinateFunctionCV("log(x)", ln_x)
state_1 = paths.CVDefinedVolume(cv, 0.0, 1.0)
state_2 = paths.CVDefinedVolume(cv, 1.0, 2.0)
state_3 = paths.CVDefinedVolume(cv, 2.0, 3.... | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
Checking for conflicts
Now I'm going to label one of my frames in a way that conflicts with my state definition. This means I'll have a false positive: the state definition says this is in the state when the annotation says it isn't (and specifically, when the annotation says it is in a different state).
Note that this... | # only difference is that I claim frame 5 (x=11) is in the 1-digit state
bad_annotations = [
Annotation(state="1-digit", begin=1, end=5),
Annotation(state="2-digit", begin=6, end=8),
Annotation(state="3-digit", begin=10, end=10),
Annotation(state="2-digit", begin=11, end=12)
]
bad_traj = AnnotatedTrajec... | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
Note how the value at $t=0.5$ conflicts: the annotation (the line) says that this this is in the blue (1-digit) state, whereas the state definition (the points) says that this is in the can (2-digit) state. | (results, conflicts) = bad_traj.validate_states(names_to_states) | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
The results object will count something as a false postive if the state identifies it, but the annotation doesn't. Not all false positives are bad: if the state identified by the annotation is smaller than the state definition, then the state definition will catch some frames that the annotation left marked as not in a... | print(results['1-digit'])
print(results['2-digit'])
print(results['3-digit'])
print(bad_traj.trajectory.index(results['1-digit'].false_negative[0])) | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
While false positives and false negatives are not inherently bad, conflicts are. A frame is said to be in conflict if the state definition assigns a different state than the annotation. The conflicts dictionary tells which frame numbers are in conflict, organized by which state definition volume they are in. | print(conflicts) | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
You can identify which state the annotations claim using get_label_for_frame: | bad_traj.get_label_for_frame(5) | examples/annotation_example.ipynb | dwhswenson/annotated_trajectories | lgpl-2.1 |
Treatment effects of methylphenidate
В рамках исследования эффективности препарата метилфенидат 24 пациента с синдромом дефицита внимания и гиперактивности в течение недели принимали либо метилфенидат, либо плацебо. В конце недели каждый пациент проходили тест на способность к подавлению импульсивных поведенческих реак... | data = pd.read_csv('ADHD.txt', sep = ' ', header = 0)
data.columns = ['Placebo', 'Methylphenidate']
data.plot.scatter('Placebo', 'Methylphenidate', c = 'r', s = 30)
pylab.grid()
pylab.plot(range(100), c = 'black')
pylab.xlim((20, 80))
pylab.ylim((20, 80))
pylab.show()
data.plot.hist()
pylab.show() | 4 Stats for data analysis/Lectures notebooks/7 student tests/stat.student_tests.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Одновыборочный критерий Стьюдента
Исходя из того, что способность к подавлению испульсивных поведенческих реакций измеряется по шкале [0, 100], можно предположить, что при хорошей калибровке теста средняя способоность к подавлению реакций в популяции составляет 50. Тогда для того, чтобы проверить гипотезу о том, что па... | stats.ttest_1samp(data.Placebo, 50.0)
print "95%% confidence interval: [%f, %f]" % zconfint(data.Placebo) | 4 Stats for data analysis/Lectures notebooks/7 student tests/stat.student_tests.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Двухвыборочный критерий Стьюдента (независимые выборки)
Для того, чтобы использовать двухвыборочный критерий Стьюдента, убедимся, что распределения в выборках существенно не отличаются от нормальных. | pylab.figure(figsize=(12,8))
pylab.subplot(2,2,1)
stats.probplot(data.Placebo, dist="norm", plot=pylab)
pylab.subplot(2,2,2)
stats.probplot(data.Methylphenidate, dist="norm", plot=pylab)
pylab.show() | 4 Stats for data analysis/Lectures notebooks/7 student tests/stat.student_tests.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Критерий Шапиро-Уилка:
$H_0\colon$ способности к подавлению импульсивных реакций распредлены нормально
$H_1\colon$ не нормально. | print "Shapiro-Wilk normality test, W-statistic: %f, p-value: %f" % stats.shapiro(data.Placebo)
print "Shapiro-Wilk normality test, W-statistic: %f, p-value: %f" % stats.shapiro(data.Methylphenidate) | 4 Stats for data analysis/Lectures notebooks/7 student tests/stat.student_tests.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
С помощью критерия Стьюдента проверим гипотезу о развенстве средних двух выборок.
Критерий Стьюдента:
$H_0\colon$ средние значения способности к подавлению испульсивных поведенческих реакций одинаковы для пациентов, принимавших препарат, и для пациентов, принимавших плацебо.
$H_0\colon$ не одинаковы. | scipy.stats.ttest_ind(data.Placebo, data.Methylphenidate, equal_var = False)
cm = CompareMeans(DescrStatsW(data.Methylphenidate), DescrStatsW(data.Placebo))
print "95%% confidence interval: [%f, %f]" % cm.tconfint_diff(usevar='unequal') | 4 Stats for data analysis/Lectures notebooks/7 student tests/stat.student_tests.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Двухвыборочный критерий Стьюдента (зависмые выборки)
Для того, чтобы использовать критерй Стьюдента для связанных выборок, давайте проверим, что распределение попарных разностей существенно не отличается от нормального. | stats.probplot(data.Placebo - data.Methylphenidate, dist = "norm", plot = pylab)
pylab.show() | 4 Stats for data analysis/Lectures notebooks/7 student tests/stat.student_tests.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Критерий Шапиро-Уилка:
$H_0\colon$ попарные разности распределены нормально.
$H_1\colon$ не нормально. | print "Shapiro-Wilk normality test, W-statistic: %f, p-value: %f" % stats.shapiro(data.Methylphenidate - data.Placebo) | 4 Stats for data analysis/Lectures notebooks/7 student tests/stat.student_tests.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Критерий Стьюдента:
$H_0\colon$ средние значения способности к подавлению испульсивных поведенческих реакций одинаковы для пациентов, принимавших препарат, и для пациентов, принимавших плацебо.
$H_1\colon$ не одинаковы. | stats.ttest_rel(data.Methylphenidate, data.Placebo)
print "95%% confidence interval: [%f, %f]" % DescrStatsW(data.Methylphenidate - data.Placebo).tconfint_mean() | 4 Stats for data analysis/Lectures notebooks/7 student tests/stat.student_tests.ipynb | maxis42/ML-DA-Coursera-Yandex-MIPT | mit |
Algorithm to simulate GMRF with block-circulant Matrix.
Taken from: Rue, H., & Held, L. (2005). Gaussian Markov random fields: theory and applications. CRC press.
Algorithm 2.10
Now let's build the circulant matrix for the tourus
Oke, for the moment I´ll follow the example in GMRF book.
i.e. a Torus (stationary of 128x... | #c_delta = lambda d : np.hstack(((4 + d),-1,np.zeros(128 - 3),-1))
#c_delta = lambda d : np.hstack(((0),-1,np.zeros(128 - 3),-1))
#C = scipy.linalg.circulant(c_delta(0.1))
def createToroidalCircularBase(d=0.1,N=128):
"""
Creates a circular base similar to the one described in GMRF Rue and Held, 2005.
"""
... | notebooks/Sandboxes/GMRF/.ipynb_checkpoints/Stationary_with_fft-checkpoint.ipynb | molgor/spystats | bsd-2-clause |
For benchmarking we will perfom a GF simulation.
Based on non-conditional simulation. | %%time
vm = sptools.ExponentialVariogram(sill=0.3,range_a=0.4)
xx,yy,z = sptools.simulatedGaussianFieldAsPcolorMesh(vm,grid_sizex=100,grid_sizey=100,random_seed=1234)
plt.imshow(z) | notebooks/Sandboxes/GMRF/.ipynb_checkpoints/Stationary_with_fft-checkpoint.ipynb | molgor/spystats | bsd-2-clause |
comparison
| Size | Method | Seconds |
|----------|---------------|-----------|
| 100x100 | Full Gaussian | 346 |
| 100x100 | Markov FFT | 0.151 |
The stationary circulant markov FFT method is 2291x faster | 346 / 0.151
plt.figure(figsize=(10, 5))
plt.subplot(1,2,1)
plt.imshow(z)
plt.subplot(1,2,2)
plt.imshow(x,interpolation='None') | notebooks/Sandboxes/GMRF/.ipynb_checkpoints/Stationary_with_fft-checkpoint.ipynb | molgor/spystats | bsd-2-clause |
Exercice 1 : multiplication de matrices
On a besoin d'une fonction qui mesure le temps d'exécution d'une fonction. | import time
def mesure_temps_fonction(fct, N=100):
begin = time.perf_counter()
for i in range(N):
fct()
return (time.perf_counter() - begin) / N
mesure_temps_fonction(lambda: time.sleep(0.1), N=10) | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Q1 : Pourquoi (m1 @ m2) @ m3 est-il plus lent que m1 @ (m2 @ m3) ? (2 points)
Il y a deux options possible. Il suffit de compter le nombre d'opérations dans chaque option. Le coût d'une multiplication $M_{ab} \times m_{bc}$ est de l'ordre de $O(abc)$. Donc :
cout((m1 @ m2) @ m3) ~ O(997 * 93 * 1003 + 997 * 1003 * 97) ... | print(997 * 93 * 1003 + 997 * 1003 * 97, 93 * 1003 * 97 + 997 * 93 * 97)
import numpy
m1 = numpy.random.randn(997, 93)
m2 = numpy.random.randn(93, 1003)
m3 = numpy.random.randn(1003, 97)
mesure_temps_fonction(lambda: m1 @ m2 @ m3)
mesure_temps_fonction(lambda: (m1 @ m2) @ m3)
mesure_temps_fonction(lambda: m1 @ (m2... | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Q2 : Ecrire une fonction qui calcule le nombre d'operations dans une multiplication de deux matrices (2 points) | def n_ops(m1_shape, m2_shape):
return m1_shape[0] * m2_shape[1] * m1_shape[1] * 2
n_ops(m1.shape, m2.shape) | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Q3 : Ecrire une fonction qui retourne le meilleur coût d'une multiplication de deux matrices et la meilleure option (2 points) | def n_ops_3(sh1, sh2, sh3):
m1_m2m3 = n_ops(sh1, (sh2[0], sh3[1])) + n_ops(sh2, sh3)
m1m2_m3 = n_ops(sh1, sh2) + n_ops((sh1[0], sh2[1]), sh3)
if m1m2_m3 < m1_m2m3:
return m1m2_m3, 2
else:
return m1_m2m3, 1
n_ops_3(m1.shape, m2.shape, m3.shape) | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Q4 : Ecrire une fonction qui effectue le produit de trois matrices le plus rapidement possible (2 points) | from numpy.testing import assert_almost_equal
def produit3(m1, m2, m3):
cout, meilleur = n_ops_3(m1.shape, m2.shape, m3.shape)
if meilleur == 2:
return (m1 @ m2) @ m3
else:
return m1 @ (m2 @ m3)
assert_almost_equal(produit3(m1, m2, m3), m1 @ (m2 @ m3)) | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Q5 : Vérifiez que vous retrouvez les mêmes résultats avec la fonction mesure_temps (2 points) | mesure_temps_fonction(lambda: produit3(m1, m2, m3)) | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
On vérifie que c'est égal à : | mesure_temps_fonction(lambda: m1 @ (m2 @ m3)) | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Ici, vous avez le choix entre faire les questions 6 à 9 ou les questions 9 et 10.
Q6 : Ecrire une fonction qui retourne le meilleur coût d'une multiplication de 4 matrices et la meilleure option (3 points) | m4 = numpy.random.randn(97, 20)
def n_ops_4(sh1, sh2, sh3, sh4):
m1_m2m3m4 = n_ops(sh1, (sh2[0], sh4[1])) + n_ops_3(sh2, sh3, sh4)[0]
m1m2_m3m4 = n_ops(sh1, sh2) + n_ops((sh1[0], sh2[1]), (sh3[0], sh4[1])) + n_ops(sh3, sh4)
m1m2m3_m4 = n_ops_3(sh1, sh2, sh3)[0] + n_ops((sh1[0], sh3[1]), sh4)
m = min(m1... | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Q7 : Ecrire une fonction qui effectue le produit de 4 matrices le plus rapidement possible (3 points) | def produit4(m1, m2, m3, m4):
cout, meilleur = n_ops_4(m1.shape, m2.shape, m3.shape, m4.shape)
if meilleur == 1:
return m1 @ produit3(m2, m3, m4)
if meilleur == 2:
return (m1 @ m2) @ (m3 @ m4)
return produit3(m1, m2, m3) @ m4
mesure_temps_fonction(lambda: produit4(m1, m2, m3, m4)) | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Q8 : Vérifiez que vous retrouvez les mêmes résultats avec la fonction mesure_temps et la matrice m4. (2 points) | mesure_temps_fonction(lambda: ((m1 @ m2) @ m3) @ m4)
mesure_temps_fonction(lambda: (m1 @ m2) @ (m3 @ m4))
mesure_temps_fonction(lambda: m1 @ (m2 @ (m3 @ m4)))
mesure_temps_fonction(lambda: produit4(m1, m2, m3, m4)) | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Q9 : On se penche sur le cas à une multiplication de N matrices, combien y a-t-il de multiplications de 2 matrices ? (2 points)
Il y a en toujours N-1. On considère le produit $M_1 \times... \times M_n$. La multiplication commence toujours par une multiplication de deux matrices consécutives quelles qu'elles soient. On... | def n_ops_N(shapes):
if len(shapes) <= 1:
raise RuntimeError("Unexpected list of shapes: %r." % shapes)
if len(shapes) == 2:
return n_ops(*shapes), 1
if len(shapes) == 3:
return n_ops_3(*shapes)
best_cost = None
best_pos = None
for i in range(1, len(shapes)):
if i... | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Ici s'arrête ce qui est attendu comme réponse à la question 10.
Les calculs en double...
On vérifie en ajoutant une ligne pour afficher tous les appels à n_ops_N. | def n_ops_N(shapes, verbose=False):
if verbose:
print("n_ops_N(%r)" % shapes)
if len(shapes) <= 1:
raise RuntimeError("Unexpected list of shapes: %r." % shapes)
if len(shapes) == 2:
return n_ops(*shapes), 1
if len(shapes) == 3:
return n_ops_3(*shapes)
best_cost = None... | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
On voit deux appels identiques n_ops_N([(97, 20), (20, 17)]) et n_ops_N([(93, 1003), (1003, 97), (97, 20)]). Ce n'est pas trop problématique pour un petit nombre de matrices mais cela pourrait le devenir si ce même algorithme était appliquée à autre chose.
Plutôt que de réécrire l'algorithme différemment, on se propose... | def n_ops_N_opt(shapes, cache=None, verbose=False):
if cache is None:
cache = {}
key = tuple(shapes)
if key in cache:
# On s'arrête, déjà calculé.
return cache[key]
if verbose:
print("n_ops_N(%r)" % shapes)
if len(shapes) <= 1:
raise RuntimeError("Unexpected ... | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
La liste est moins longue et tous les appels sont uniques. On met à jour la fonction product_N. | def product_N_opt(inputs, cache=None):
if len(inputs) <= 1:
raise RuntimeError(
"List inputs must contain at least two elements bot has %d." % len(inputs))
cost, pos = n_ops_N_opt([i.shape for i in inputs], cache=cache)
if len(inputs) == 2:
return inputs[0] @ inputs[1]
if pos... | _doc/notebooks/exams/td_note_2022.ipynb | sdpython/ensae_teaching_cs | mit |
Now get info about all these users | print("We get %s friends" % len(friend_ids)) | Twitter bots/Botnet search #2.ipynb | UserAd/data_science | mit |
Now extract user info from these users | possible_bots = []
for group in chunks(friend_ids, 100):
for user in api.lookup_users(user_ids=list(group)):
possible_bots.append(user)
possible_bots_df = pd.DataFrame([{'name': user.name, 'id': user.id, 'location': user.location, 'screen_name': user.screen_name, 'followers': user.followers_count, ... | Twitter bots/Botnet search #2.ipynb | UserAd/data_science | mit |
Let's look at moscow users | moscow_users = possible_bots_df[(possible_bots_df["location"] == u'Москва') & (possible_bots_df["id"] > 6 * 1e17)]
moscow_users.hist()
moscow_users[:10]
print("Total found: %s" % moscow_users.count()[0])
moscow_users.to_csv("./botnet_moscow.csv", encoding="utf8") | Twitter bots/Botnet search #2.ipynb | UserAd/data_science | mit |
TensorFlow Cloud - Putting it all together
In this example, we will use all of the features outlined in the Keras cloud guide to train a state-of-the-art model to classify dog breeds using feature extraction. Let's begin by installing TensorFlow Cloud and importing a few important packages.
Setup | !pip install tensorflow-cloud
import datetime
import os
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_cloud as tfc
import tensorflow_datasets as tfds
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Model | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Cloud Configuration
In order to run TensorFlow Cloud from a Colab notebook, we'll need to upload our authentication key and specify our Cloud storage bucket for image building and publishing. | if not tfc.remote():
from google.colab import files
key_upload = files.upload()
key_path = list(key_upload.keys())[0]
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = key_path
os.system(f"gcloud auth activate-service-account --key-file {key_path}")
GCP_BUCKET = "[your-bucket-name]" #@param {type:"string"} | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Model Creation
Dataset preprocessing
We'll be loading our training data from TensorFlow Datasets: | (ds_train, ds_test), metadata = tfds.load(
"stanford_dogs",
split=["train", "test"],
shuffle_files=True,
with_info=True,
as_supervised=True,
)
NUM_CLASSES = metadata.features["label"].num_classes | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Let's visualize this dataset: | print("Number of training samples: %d" % tf.data.experimental.cardinality(ds_train))
print("Number of test samples: %d" % tf.data.experimental.cardinality(ds_test))
print("Number of classes: %d" % NUM_CLASSES)
plt.figure(figsize=(10, 10))
for i, (image, label) in enumerate(ds_train.take(9)):
ax = plt.subplot(3, 3,... | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Here we will resize and rescale our images to fit into our model's input, as well as create batches. | IMG_SIZE = 224
BATCH_SIZE = 64
BUFFER_SIZE = 2
size = (IMG_SIZE, IMG_SIZE)
ds_train = ds_train.map(lambda image, label: (tf.image.resize(image, size), label))
ds_test = ds_test.map(lambda image, label: (tf.image.resize(image, size), label))
def input_preprocess(image, label):
image = tf.keras.applications.resne... | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Model Architecture
We're using ResNet50 pretrained on ImageNet, from the Keras Applications module. | inputs = tf.keras.layers.Input(shape=(IMG_SIZE, IMG_SIZE, 3))
base_model = tf.keras.applications.ResNet50(
weights="imagenet", include_top=False, input_tensor=inputs
)
x = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)
x = tf.keras.layers.Dropout(0.5)(x)
outputs = tf.keras.layers.Dense(NUM_CLASSES)(x)
... | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Callbacks using Cloud Storage | MODEL_PATH = "resnet-dogs"
checkpoint_path = os.path.join("gs://", GCP_BUCKET, MODEL_PATH, "save_at_{epoch}")
tensorboard_path = os.path.join(
"gs://", GCP_BUCKET, "logs", datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
)
callbacks = [
# TensorBoard will store logs for each epoch and graph performance for us... | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Here, we're using the tfc.remote() flag to designate a smaller number of epochs than intended for the full training job when running locally. This enables easy debugging on Colab. | if tfc.remote():
epochs = 500
train_data = ds_train
test_data = ds_test
else:
epochs = 1
train_data = ds_train.take(5)
test_data = ds_test.take(5)
callbacks = None
model.fit(
train_data, epochs=epochs, callbacks=callbacks, validation_data=test_data, verbose=2
)
if tfc.remote():
SA... | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Our model requires two additional libraries. We'll create a requirements.txt which specifies those libraries: | requirements = ["tensorflow-datasets", "matplotlib"]
f = open("requirements.txt", 'w')
f.write('\n'.join(requirements))
f.close() | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Let's add a job label so we can document our job logs later: | job_labels = {"job":"resnet-dogs"} | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Train on Cloud
All that's left to do is run our model on Cloud. To recap, our run() call enables:
- A model that will be trained and stored on Cloud, including checkpoints
- Tensorboard callback logs that will be accessible through tensorboard.dev
- Specific python library requirements that will be fulfilled
- Customiz... | tfc.run(
requirements_txt="requirements.txt",
distribution_strategy="auto",
chief_config=tfc.MachineConfig(
cpu_cores=8,
memory=30,
accelerator_type=tfc.AcceleratorType.NVIDIA_TESLA_T4,
accelerator_count=2,
),
docker_config=tfc.DockerConfig(
image_build_bucket... | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Evaluate your model
We'll use the cloud storage directories we saved for callbacks in order to load tensorboard and retrieve the saved model. Tensorboard logs can be used to monitor training performance in real-time | !tensorboard dev upload --logdir $tensorboard_path --name "ResNet Dogs"
if tfc.remote():
model = tf.keras.models.load_model(SAVE_PATH)
model.evaluate(test_data) | src/python/tensorflow_cloud/core/tests/examples/dogs_classification.ipynb | tensorflow/cloud | apache-2.0 |
Initialize the network | network = pypsa.Network()
network.set_snapshots(index)
network.add("Bus", "place of work", carrier="AC")
network.add("Bus", "battery", carrier="Li-ion")
network.add(
"Generator",
"PV panel",
bus="place of work",
p_nom_extendable=True,
p_max_pu=pv_pu,
capital_cost=1000.0,
)
network.add("Load"... | examples/notebooks/battery-electric-vehicle-charging.ipynb | PyPSA/PyPSA | mit |
The optimal panel size in kW is | network.generators.p_nom_opt["PV panel"]
network.generators_t.p.plot.area(figsize=(9, 4))
plt.tight_layout()
df = pd.DataFrame(
{attr: network.stores_t[attr]["battery storage"] for attr in ["p", "e"]}
)
df.plot(grid=True, figsize=(10, 5))
plt.legend(labels=["Energy output", "State of charge"])
plt.tight_layout() | examples/notebooks/battery-electric-vehicle-charging.ipynb | PyPSA/PyPSA | mit |
The losses in kWh per pay are: | (
network.generators_t.p.loc[:, "PV panel"].sum()
- network.loads_t.p.loc[:, "driving"].sum()
)
network.links_t.p0.plot.area(figsize=(9, 5))
plt.tight_layout() | examples/notebooks/battery-electric-vehicle-charging.ipynb | PyPSA/PyPSA | mit |
The following function selects the columns I need. | def select_cols(df):
cols = ['cntry', 'tvtot', 'tvpol', 'rdtot', 'rdpol', 'nwsptot', 'nwsppol', 'netuse',
'rlgblg', 'rlgdgr', 'eduyrs', 'hinctnta', 'yrbrn', 'eisced', 'pspwght', 'pweight']
df = df[cols]
return df | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Read data from Cycle 1.
TODO: investigate the difference between hinctnt and hinctnta; is there a recode that reconciles them? | df1 = pd.read_stata('ESS1e06_4.dta', convert_categoricals=False)
df1['hinctnta'] = df1.hinctnt
df1 = select_cols(df1)
df1.head() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Read data from Cycle 2. | df2 = pd.read_stata('ESS2e03_4.dta', convert_categoricals=False)
df2['hinctnta'] = df2.hinctnt
df2 = select_cols(df2)
df2.head() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Read data from Cycle 3. | df3 = pd.read_stata('ESS3e03_5.dta', convert_categoricals=False)
df3['hinctnta'] = df3.hinctnt
df3 = select_cols(df3)
df3.head() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Read data from Cycle 4. | df4 = pd.read_stata('ESS4e04_3.dta', convert_categoricals=False)
df4 = select_cols(df4)
df4.head() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Read data from Cycle 5. | df5 = pd.read_stata('ESS5e03_2.dta', convert_categoricals=False)
df5 = select_cols(df5)
df5.head() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Concatenate the cycles.
TODO: Have to resample each cycle before concatenating. | df = pd.concat([df1, df2, df3, df4, df5], ignore_index=True)
df.head() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
TV watching time on average weekday | df.tvtot.replace([77, 88, 99], np.nan, inplace=True)
df.tvtot.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Radio listening, total time on average weekday. | df.rdtot.replace([77, 88, 99], np.nan, inplace=True)
df.rdtot.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Newspaper reading, total time on average weekday. | df.nwsptot.replace([77, 88, 99], np.nan, inplace=True)
df.nwsptot.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
TV watching: news, politics, current affairs | df.tvpol.replace([66, 77, 88, 99], np.nan, inplace=True)
df.tvpol.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Radio listening: news, politics, current affairs | df.rdpol.replace([66, 77, 88, 99], np.nan, inplace=True)
df.rdpol.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Newspaper reading: politics, current affairs | df.nwsppol.replace([66, 77, 88, 99], np.nan, inplace=True)
df.nwsppol.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Personal use of Internet, email, www | df.netuse.replace([77, 88, 99], np.nan, inplace=True)
df.netuse.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Belong to a particular religion or denomination | df.rlgblg.replace([7, 8, 9], np.nan, inplace=True)
df.rlgblg.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
How religious | df.rlgdgr.replace([77, 88, 99], np.nan, inplace=True)
df.rlgdgr.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Total household net income, all sources
TODO: It looks like one cycle measured HINCTNT on a 12 point scale. Might need to reconcile | df.hinctnta.replace([77, 88, 99], np.nan, inplace=True)
df.hinctnta.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Shift income to mean near 0. | df['hinctnta5'] = df.hinctnta - 5
df.hinctnta5.describe() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Year born | df.yrbrn.replace([7777, 8888, 9999], np.nan, inplace=True)
df.yrbrn.describe() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Shifted to mean near 0 | df['yrbrn60'] = df.yrbrn - 1960
df.yrbrn60.describe() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Number of years of education | df.eduyrs.replace([77, 88, 99], np.nan, inplace=True)
df.loc[df.eduyrs > 25, 'eduyrs'] = 25
df.eduyrs.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
There are a bunch of really high values for eduyrs, need to investigate. | df.eduyrs.describe() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Shift to mean near 0 | df['eduyrs12'] = df.eduyrs - 12
df.eduyrs12.describe() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Country codes | df.cntry.value_counts().sort_index() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Make a binary dependent variable | df['hasrelig'] = (df.rlgblg==1).astype(int) | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Run the model | def run_model(df, formula):
model = smf.logit(formula, data=df)
results = model.fit(disp=False)
return results | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Here's the model with all control variables and all media variables: | formula = ('hasrelig ~ yrbrn60 + eduyrs12 + hinctnta5 +'
'tvtot + tvpol + rdtot + rdpol + nwsptot + nwsppol + netuse')
res = run_model(df, formula)
res.summary() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Most of the media variables are not statistically significant. If we drop the politial media variables, we get a cleaner model: | formula = ('hasrelig ~ yrbrn60 + eduyrs12 + hinctnta5 +'
'tvtot + rdtot + nwsptot + netuse')
res = run_model(df, formula)
res.summary() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
And if we fill missing values for income, cleaner still. | def fill_var(df, var):
fill = df[var].dropna().sample(len(df), replace=True)
fill.index = df.index
df[var].fillna(fill, inplace=True)
fill_var(df, var='hinctnta5')
formula = ('hasrelig ~ yrbrn60 + eduyrs12 + hinctnta5 +'
'tvtot + rdtot + nwsptot + netuse')
res = run_model(df, formula)
res.summa... | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Now all variables have small p-values. All parameters have the expected signs:
Younger people are less affiliated.
More educated people are less affiliated.
Higher income people are less affiliated (although this could go either way)
Consumers of all media are less affiliated.
The strength of the Internet effect is ... | def extract_res(res, var='netuse'):
param = res.params[var]
pvalue = res.pvalues[var]
stars = '**' if pvalue < 0.01 else '*' if pvalue < 0.05 else ''
return res.nobs, param, stars
extract_res(res) | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Running a similar model with degree of religiosity. | formula = ('rlgdgr ~ yrbrn60 + eduyrs12 + hinctnta5 +'
'tvtot + rdtot + nwsptot + netuse')
model = smf.ols(formula, data=df)
res = model.fit(disp=False)
res.summary() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Group by country: | grouped = df.groupby('cntry')
for name, group in grouped:
print(name, len(group)) | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Run a sample country | gb = grouped.get_group('DK')
run_model(gb, formula).summary() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Run all countries | for name, group in grouped:
try:
fill_var(group, var='hinctnta5')
res = run_model(group, formula)
nobs, param, stars = extract_res(res)
arrow = '<--' if stars and param > 0 else ''
print(name, len(group), nobs, '%0.3g'%param, stars, arrow, sep='\t')
except:
print(... | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
In more than half of the countries, the association between Internet use and religious affiliation is statistically significant. In all except two, the association is negative.
In many countries we've lost a substantial number of observations due to missing data. Really need to fill that in! | group = grouped.get_group('FR')
len(group)
for col in group.columns:
print(col, sum(group[col].isnull()))
fill_var(group, 'hinctnta5')
formula
res = run_model(group, formula)
res.summary() | ess.ipynb | AllenDowney/ProbablyOverthinkingIt | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.