markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Lijstjes onthouden
Als je een lijst van objecten wil opslaan, kan dat met vierkante haakjes: | minions = ['Dave','Stuart','Jerry','Jorge']
print(minions[2])
#opgelet, elementnummers beginnen te tellen bij 0, daarom wordt de derde minion in de lijst geprint! | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Maar als je eigenlijk de favoriete ijsjes van de minions wil opslaan, gebruik je best een dictionary (Engels voor "woordenboek", omdat het je toelaat om dingen op te zoeken op basis van een index / sleutel): | minion_ijsjes = {
'Dave':'aardbei', # 'Dave' is hier de sleutel, 'aardbei' is de ermee gekoppelde waarde
'Stuart':'vanille',
'Jerry':['mokka', 'vanille'], # Inderdaad, we kunnen dit nog veel ingewikkelder maken :-)
'Jorge':'chocolade'
}
print(minion_ijsjes['Jerry'])
# en begrijp je deze?... | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Loopen
-ja, dat moet echt met dubbele 'oo' en je spreekt het uit als 'loepen'-
Kan ik in plaats van maar één ook de ijsjes van alle minions printen?
nota tussendoor: range() is een functie om lijstjes van nummers te maken. | print(range(4)) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Dit kunnen we gebruiken om 4 keer dezelfde print te herhalen, maar telkens met één nummer hoger | for nummer in range(4):
print(minions[nummer]) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Opgelet! de "whitespace" (witruimte) vóór het print commando is van belang! Zonder deze spaties zou Python niet weten wat er binnen en wat er buiten de loop valt: | for nummer in range(4):
print(nummer)
print(minions[nummer]) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Is niet hetzelfde als: | for nummer in range(4):
print(nummer)
print(minions[nummer]) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
We kunnen ook iets één keer herhalen voor elke minion in ons minions lijstje. | for minion in minions:
print(minion) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Of voor elke minion in ons minions lijstje de minion printen plus zijn ijsje(s) uit de minion_ijsjes dictionary | for minion in minions:
print(minion, minion_ijsjes[minion]) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
While is een gelijkaardig soort loop. "while" is Engels voor "terwijl" en het betekent dat de instructies in de loop uitgevoerd zullen worden terwijl aan een bepaalde voorwaarde voldaan is.
Bijvoorbeeld met een dobbelsteen gooien tot er 6 gegooid wordt: | import random # om de random module te kunnen gebruiken; import wordt verder nog uitgelegd
worp = 0 # een worp van 0 kan niet, maar we moeten ergens beginnen...
while worp < 6:
worp = random.randint(1,6) # een willekeurig getal van 1 tot 6
print(worp) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Als je het een paar keer probeert kan je zien dat het echt willekeurig is (met Ctrl+Enter wordt de cel uitgevoerd terwijl de cursor blijft staan)
Een speciaal geval is de "while True:" constructie; aangezien aan True (Engels voor "Waar") altijd voldaan wordt, blijft dit voor eeuwig loopen, tenzij je de executie manueel... | import time # om de time module te kunnen gebruiken; import wordt verder nog uitgelegd
while True:
print('.'), # met de komma voorkom je dat er na elk punt een nieuwe lijn gestart wordt
time.sleep(0.2) # 0.2 seconden pauzeren | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Druk op de Stop knop (<i class="fa-stop fa"></i>) om de executie te beëindigen.
Deze methode wordt soms gebruikt om een programma te starten dat moet blijven lopen.
Voor gevorderden: Je kan foutmeldingen neutralizeren en een dergelijke Kernel Interrupt dus op een elegante manier opvangen zonder dat IPython lelijke Keyb... | import time
while True:
try: # probeer de code uit te voeren...
print('.'),
time.sleep(0.2)
except KeyboardInterrupt: # ... en als een KeyboardInterrupt fout optreedt, toon ze dan niet, maar:
print('\nEinde') # print 'Einde' (op ee... | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Voorwaarden
Met een "if" uitdrukking kunnen we beïnvloeden hoe de uitvoering van de code verloopt.
"if" betekent "als" in het Engels en het laat ons toe om de computer iets wel of niet te laten doen, afhankelijk wat we erachter zetten. | punten = 85
if punten > 90:
print('Schitterend')
elif punten > 80:
print('Zeer goed')
elif punten > 60:
print('Goed')
else:
print('Hm') | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Bijvoorbeeld: die Jerry is me toch wat gulzig, dus: | for minion in minions:
if minion == 'Jerry':
print('--Gulzigaard--')
else:
print(minion, minion_ijsjes[minion]) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Echt programmeren
We kunnen in Python ook zelf functies maken en die vervolgens gebruiken; dat helpt om de code ordelijk te houden en bepaalde stukjes code maar één maal te moeten schrijven / corrigeren / onderhouden. | def begroet(naam):
print('Dag ' + naam) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Zullen we onze nieuwe functie eens uitproberen? | begroet('Mariette') | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
En nog een extraatje
we kunnen strings (tekst variabelen) gebruiken als template om teksten samen te stellen zoals de Samenvoegen functonaliteit in tekstverwerkers zoals Microsoft Word.
Dat gebeurt met de format() functie:
'Dag {}'.format(naam)
maakt dat de accolades in de tekst vervangen worden door de waarde van de v... | def begroet(naam):
print('Dag {}'.format(naam))
begroet('Willy') | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Python libraries (Bibliotheken)
Natuurlijk zijn er al heel wat mensen die Python code geschreven hebben en veel van die code is beschikbaar in de vorm van libraries die je kant en klaar kan installeren.
Als zo'n library geïnstalleerd hebt, kan je ze importeren en de functies ervan beginnen gebruiken: | import math
print("PI: {}".format(math.pi))
print("sin(PI/2): {}".format(math.cos(math.pi))) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
requests is een bibliotheek om webpagina's in te laden; hier bezoeken we een openweathermap en drukken een deel van de weersvoorspelling voor Mechelen af. | import requests
r = requests.get('http://api.openweathermap.org/data/2.5/weather?q=Mechelen').json()
print(r['weather'][0]['description']) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Of een quote uit de online database van iheartquotes.com | import requests
r = requests.get('http://www.iheartquotes.com/api/v1/random')
print(r.text) | notebooks/nl-be/101 - Intro - Python leren kennen en IPython gebruiken.ipynb | RaspberryJamBe/ipython-notebooks | cc0-1.0 |
Données | from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
data = load_boston()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split(X, y) | _doc/notebooks/td2a_ml/ml_lasso_rf_grid_search_correction.ipynb | sdpython/ensae_teaching_cs | mit |
Premiers modèles | from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score
rf = RandomForestRegressor()
rf.fit(X_train, y_train)
r2_score(y_test, rf.predict(X_test)) | _doc/notebooks/td2a_ml/ml_lasso_rf_grid_search_correction.ipynb | sdpython/ensae_teaching_cs | mit |
Pour le modèle, il suffit de copier coller le code écrit dans ce fichier lasso_random_forest_regressor.py. | from ensae_teaching_cs.ml.lasso_random_forest_regressor import LassoRandomForestRegressor
lrf = LassoRandomForestRegressor()
lrf.fit(X_train, y_train)
r2_score(y_test, lrf.predict(X_test)) | _doc/notebooks/td2a_ml/ml_lasso_rf_grid_search_correction.ipynb | sdpython/ensae_teaching_cs | mit |
Le modèle a réduit le nombre d'arbres. | len(lrf.estimators_) | _doc/notebooks/td2a_ml/ml_lasso_rf_grid_search_correction.ipynb | sdpython/ensae_teaching_cs | mit |
Grid Search
On veut trouver la meilleure paire de paramètres (n_estimators, alpha). scikit-learn implémente l'objet GridSearchCV qui effectue de nombreux apprentissage avec toutes les valeurs de paramètres qu'il reçoit. Voici tous les paramètres qu'on peut changer : | lrf.get_params()
params = {
'lasso_estimator__alpha': [0.25, 0.5, 0.75, 1., 1.25, 1.5],
'rf_estimator__n_estimators': [20, 40, 60, 80, 100, 120]
}
from sklearn.exceptions import ConvergenceWarning
from sklearn.model_selection import GridSearchCV
import warnings
warnings.filterwarnings("ignore", category=Conv... | _doc/notebooks/td2a_ml/ml_lasso_rf_grid_search_correction.ipynb | sdpython/ensae_teaching_cs | mit |
Les meilleurs paramètres sont les suivants : | grid.best_params_ | _doc/notebooks/td2a_ml/ml_lasso_rf_grid_search_correction.ipynb | sdpython/ensae_teaching_cs | mit |
Et le modèle a gardé un nombre réduit d'arbres : | len(grid.best_estimator_.estimators_)
r2_score(y_test, grid.predict(X_test)) | _doc/notebooks/td2a_ml/ml_lasso_rf_grid_search_correction.ipynb | sdpython/ensae_teaching_cs | mit |
Evolution de la performance en fonction des paramètres | grid.cv_results_
import numpy
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(14, 6))
ax = fig.add_subplot(131, projection='3d')
xs = numpy.array([el['lasso_estimator__alpha'] for el in grid.cv_results_['params']])
ys = numpy.array([el['rf_estimator__n_estimators'] fo... | _doc/notebooks/td2a_ml/ml_lasso_rf_grid_search_correction.ipynb | sdpython/ensae_teaching_cs | mit |
Create an array of 10 zeros | # CODE HERE
np.zeros(10) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Create an array of 10 ones | # CODE HERE
np.ones(10) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Create an array of 10 fives | # CODE HERE
np.ones(10) * 5 | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Create an array of the integers from 10 to 50 | # CODE HERE
np.arange(10, 51) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Create an array of all the even integers from 10 to 50 | # CODE HERE
np.arange(10, 51, 2) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Create a 3x3 matrix with values ranging from 0 to 8 | # CODE HERE
np.arange(9).reshape(3,3) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Create a 3x3 identity matrix | # CODE HERE
np.eye(3) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Use NumPy to generate a random number between 0 and 1 | # CODE HERE
np.random.randn(1) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Use NumPy to generate an array of 25 random numbers sampled from a standard normal distribution | # CODE HERE
np.random.randn(25) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Create the following matrix: | np.arange(1, 101).reshape(10, 10) / 100 | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Create an array of 20 linearly spaced points between 0 and 1: | np.linspace(0, 1, 20) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Numpy Indexing and Selection
Now you will be given a few matrices, and be asked to replicate the resulting matrix outputs: | # HERE IS THE GIVEN MATRIX CALLED MAT
# USE IT FOR THE FOLLOWING TASKS
mat = np.arange(1,26).reshape(5,5)
mat
# WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW
# BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWISE YOU WON'T
# BE ABLE TO SEE THE OUTPUT ANY MORE
mat[2:, ]
# WRITE CODE HERE THAT REPRODUCES THE... | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Now do the following
Get the sum of all the values in mat | # CODE HERE
np.sum(mat) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Get the standard deviation of the values in mat | # CODE HERE
np.std(mat) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Get the sum of all the columns in mat | # CODE HERE
np.sum(mat, axis = 0) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Bonus Question
We worked a lot with random data with numpy, but is there a way we can insure that we always get the same random numbers? Click Here for a Hint | # My favourite number is 7
np.random.seed(7) | 17-09-17-Python-for-Financial-Analysis-and-Algorithmic-Trading/.ipynb_checkpoints/2 - Numpy Exercises-checkpoint.ipynb | arcyfelix/Courses | apache-2.0 |
Compare evoked responses for different conditions
In this example, an Epochs object for visual and
auditory responses is created. Both conditions
are then accessed by their respective names to
create a sensor layout plot of the related
evoked responses. | # Authors: Denis Engemann <denis.engemann@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# License: BSD (3-clause)
import matplotlib.pyplot as plt
import mne
from mne.viz import plot_evoked_topo
from mne.datasets import sample
print(__doc__)
data_path = sample.data_path() | 0.13/_downloads/plot_topo_compare_conditions.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Set parameters | 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'
event_id = 1
tmin = -0.2
tmax = 0.5
# Setup for reading the raw data
raw = mne.io.read_raw_fif(raw_fname)
events = mne.read_events(event_fname)
# Set up pick list: MEG ... | 0.13/_downloads/plot_topo_compare_conditions.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Show topography for two different conditions | colors = 'yellow', 'green'
title = 'MNE sample data - left vs right (A/V combined)'
plot_evoked_topo(evokeds, color=colors, title=title)
conditions = [e.comment for e in evokeds]
for cond, col, pos in zip(conditions, colors, (0.025, 0.07)):
plt.figtext(0.99, pos, cond, color=col, fontsize=12,
hori... | 0.13/_downloads/plot_topo_compare_conditions.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Gegeben seien folgende Merkmalstrukturen: | f1 = FeatStruct(
'[Vorname=Max, Nachname=Mustermann,' +
'Privat=[Strasse=Hauptstrasse, Ort=[Muenchen]]]'
)
f2 = FeatStruct(
'[Arbeit=[Strasse="Oettingenstrasse", Ort=(1)["Muenchen"]],' +
'Privat=[Ort->(1)]]')
f3 = FeatStruct(
'[Strasse="Hauptstrasse"]'
)
f4 = FeatStruct(
'[Privat=[Strasse="Haup... | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Unifizieren Sie:
- f1 mit f2 | print(f1.unify(f2).__repr__()) | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
f2 mit f4 | print(f2.unify(f4).__repr__()) | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Aufgabe 2 Typhierarchie im NLTK
Gegeben sei folgende Typhierarchie:
$$\bot \sqsubseteq \text{Genitiv}$$
$$\bot \sqsubseteq \text{nicht-Genitiv}$$
$$\text{nicht-Genitiv} \sqsubseteq \text{Nominativ-Akkusativ}$$
$$\text{nicht-Genitiv} \sqsubseteq \text{Dativ}$$
$$\text{Nominativ-Akkusativ} \sqsubseteq ... | grammar = """
S -> NP[*CASE*=nom] VP
NP[*CASE*=?x] -> DET[*CASE*=?x,GEN=?y] NOM[*CASE*=?x,GEN=?y]
NOM[*CASE*=?x,GEN=?y] -> N[*CASE*=?x,GEN=?y] NP[*CASE*=gen]
NOM[*CASE*=?x,GEN=?y] -> N[*CASE*=?x,GEN=?y]
VP -> V
V -> "schläft"
DET[*CASE*=nomakk,GEN=fem] -> "die"
DET[*CASE*=nomakk,GEN=neut] -> "das"
DET[*CASE*=gen,GEN=m... | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Hier muss die Typhierarchie in Form eines Dictionary definiert werden: | type_hierarchy = {
"gen": [],
"nongen": ["nomakk", "dat"],
"nomakk": ["nom", "akk"],
"nom": [],
"dat": [],
"akk": []
}
CASE = HierarchicalFeature("CASE", type_hierarchy)
compiled_grammar = nltk.grammar.FeatureGrammar.fromstring(
grammar, features=(CASE, TYPE)
)
parser = nltk.FeatureEarleyCh... | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Folgendes sollte funktionieren: | for t in parser.parse("das Kind der Frau schläft".split()):
display(t) | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Folgendes sollte leer sein: | list(parser.parse("des Mannes schläft".split())) | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Folgendes sollte wieder funktionieren. Betrachten Sie aufmerksam die Merkmale im Syntaxbaum. | for t in parser.parse("der Mann der Frau schläft".split()):
display(t) | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Hausaufgaben
Aufgabe 3 Unifikation II
Es seien wieder die Merkmalstrukturen aus Aufgabe 1 gegeben.
Unifizieren Sie:
- f1 mit f4 | print(f1.unify(f4).__repr__()) | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
f2 mit f3 | print(f2.unify(f3).__repr__()) | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Aufgabe 4 Weniger Redundanz dank besonderer Merkmale
Beseitigen Sie die Redundanz in den lexikalischen Regeln (Zeilen 8 - 32) der folgenden Grammatik durch eine Typhierarchie (wo dies nötig ist). Achten Sie darauf, die Menge der akzeptierten Sätze weder zu verkleinern noch zu vergrößern!
Anzugeben si... | case_hierarchy = {
"nongen": ["nomakk", "dat"],
"gendat": ["gen", "dat"],
"nomakk": ["nom", "akk"],
"nom": [],
"gen": [],
"dat": [],
"akk": []
}
gen_hierarchy = {
"maskneut": ["mask", "neut"],
"mask": [],
"fem": [],
"neut": []
}
redundant_grammar = """
S -> NP[*KAS*=nom] VP
... | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
Testen Sie mit Ihren eigenen Negativbeispielen! | neg_sentences = [
"des Mannes gibt der Frau das Buch",
"Mann gibt der Frau das Buch",
"der Mann gibt der Frau Buch",
"der Frau gibt dem Buch den Mann",
"das Buch der Mann gibt der Frau das Buch"
]
import sys
def test_grammar(parser, sentences):
for i, sent in enumerate(sentences, 1):
... | 09-notebook-solution.ipynb | mnschmit/LMU-Syntax-nat-rlicher-Sprachen | apache-2.0 |
TensorFlow の NumPy API
<table class="tfo-notebook-buttons" align="left">
<td> <a target="_blank" href="https://www.tensorflow.org/guide/tf_numpy"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a> </td>
<td> <a target="_blank" href="https://colab.research.google.com/githu... | import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow.experimental.numpy as tnp
import timeit
print("Using TensorFlow version %s" % tf.__version__) | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
NumPy 動作の有効化
tnp を NumPy として使用するには、TensorFlow の NumPy の動作を有効にしてください。 | tnp.experimental_enable_numpy_behavior() | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
この呼び出しによって、TensorFlow での型昇格が可能になり、リテラルからテンソルに変換される場合に、型推論も Numpy の標準により厳格に従うように変更されます。
注意: この呼び出しは、tf.experimental.numpy モジュールだけでなく、TensorFlow 全体の動作を変更します。
TensorFlow NumPy ND 配列
ND 配列と呼ばれる tf.experimental.numpy.ndarray は、特定のデバイスに配置されたある dtype の多次元の密な配列を表します。tf.Tensor のエイリアスです。ndarray.T、ndarray.reshape、ndarray.ravel など... | # Create an ND array and check out different attributes.
ones = tnp.ones([5, 3], dtype=tnp.float32)
print("Created ND array with shape = %s, rank = %s, "
"dtype = %s on device = %s\n" % (
ones.shape, ones.ndim, ones.dtype, ones.device))
# `ndarray` is just an alias to `tf.Tensor`.
print("Is `ones` an i... | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
型昇格
TensorFlow NumPy API には、リテラルを ND 配列に変換するためと ND 配列入力で型昇格を実行するための明確に定義されたセマンティクスがあります。詳細については、np.result_type をご覧ください。
TensorFlow API は tf.Tensor 入力を変更せずそのままにし、それに対して型昇格を実行しませんが、TensorFlow NumPy API は NumPy 型昇格のルールに従って、すべての入力を昇格します。次の例では、型昇格を行います。まず、さまざまな型の ND 配列入力で加算を実行し、出力の型を確認します。これらの型昇格は、TensorFlow API では行えません。 | print("Type promotion for operations")
values = [tnp.asarray(1, dtype=d) for d in
(tnp.int32, tnp.int64, tnp.float32, tnp.float64)]
for i, v1 in enumerate(values):
for v2 in values[i + 1:]:
print("%s + %s => %s" %
(v1.dtype.name, v2.dtype.name, (v1 + v2).dtype.name)) | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
最後に、ndarray.asarray を使ってリテラルをND 配列に変換し、結果の型を確認します。 | print("Type inference during array creation")
print("tnp.asarray(1).dtype == tnp.%s" % tnp.asarray(1).dtype.name)
print("tnp.asarray(1.).dtype == tnp.%s\n" % tnp.asarray(1.).dtype.name) | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
リテラルを ND 配列に変換する際、NumPy は tnp.int64 や tnp.float64 といった幅広い型を優先します。一方、tf.convert_to_tensor は、tf.int32 と tf.float32 の型を優先して定数を tf.Tensor に変換します。TensorFlow NumPy API は、整数に関しては NumPy の動作に従っています。浮動小数点数については、experimental_enable_numpy_behavior の prefer_float32 引数によって、tf.float64 よりも tf.float32 を優先するかどうかを制御することができます(デフォルトは False... | tnp.experimental_enable_numpy_behavior(prefer_float32=True)
print("When prefer_float32 is True:")
print("tnp.asarray(1.).dtype == tnp.%s" % tnp.asarray(1.).dtype.name)
print("tnp.add(1., 2.).dtype == tnp.%s" % tnp.add(1., 2.).dtype.name)
tnp.experimental_enable_numpy_behavior(prefer_float32=False)
print("When prefer_f... | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
ブロードキャスティング
TensorFlow と同様に、NumPy は「ブロードキャスト」値の豊富なセマンティクスを定義します。詳細については、NumPy ブロードキャストガイドを確認し、これを TensorFlow ブロードキャストセマンティクスと比較してください。 | x = tnp.ones([2, 3])
y = tnp.ones([3])
z = tnp.ones([1, 2, 1])
print("Broadcasting shapes %s, %s and %s gives shape %s" % (
x.shape, y.shape, z.shape, (x + y + z).shape)) | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
インデックス
NumPy は、非常に洗練されたインデックス作成ルールを定義しています。NumPy インデックスガイドを参照してください。以下では、インデックスとして ND 配列が使用されていることに注意してください。 | x = tnp.arange(24).reshape(2, 3, 4)
print("Basic indexing")
print(x[1, tnp.newaxis, 1:3, ...], "\n")
print("Boolean indexing")
print(x[:, (True, False, True)], "\n")
print("Advanced indexing")
print(x[1, (0, 0, 1), tnp.asarray([0, 1, 1])])
# Mutation is currently not supported
try:
tnp.arange(6)[1] = -1
except Ty... | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
サンプルモデル
次に、モデルを作成して推論を実行する方法を見てみます。この簡単なモデルは、relu レイヤーとそれに続く線形射影を適用します。後のセクションでは、TensorFlow のGradientTapeを使用してこのモデルの勾配を計算する方法を示します。 | class Model(object):
"""Model with a dense and a linear layer."""
def __init__(self):
self.weights = None
def predict(self, inputs):
if self.weights is None:
size = inputs.shape[1]
# Note that type `tnp.float32` is used for performance.
stddev = tnp.sqrt(size).astype(tnp.float32)
... | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorFlow NumPy および NumPy
TensorFlow NumPy は、完全な NumPy 仕様のサブセットを実装します。シンボルは、今後追加される予定ですが、近い将来にサポートされなくなる体系的な機能があります。これらには、NumPy C API サポート、Swig 統合、Fortran ストレージ優先順位、ビュー、stride_tricks、およびいくつかのdtype(np.recarrayや<code> np.object</code>)が含まれます。詳細については、 <a>TensorFlow NumPy API ドキュメント</a>をご覧ください。
NumPy 相互運用性
TensorFlow ND 配... | # ND array passed into NumPy function.
np_sum = np.sum(tnp.ones([2, 3]))
print("sum = %s. Class: %s" % (float(np_sum), np_sum.__class__))
# `np.ndarray` passed into TensorFlow NumPy function.
tnp_sum = tnp.sum(np.ones([2, 3]))
print("sum = %s. Class: %s" % (float(tnp_sum), tnp_sum.__class__))
# It is easy to plot ND ... | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
バッファコピー
TensorFlow NumPy を NumPy コードと混在させると、データコピーがトリガーされる場合があります。これは、TensorFlow NumPy のメモリアライメントに関する要件が NumPy の要件よりも厳しいためです。
np.ndarrayが TensorFlow Numpy に渡されると、アライメント要件を確認し、必要に応じてコピーがトリガーされます。ND 配列 CPU バッファを NumPy に渡す場合、通常、バッファはアライメント要件を満たし、NumPy はコピーを作成する必要はありません。
ND 配列は、ローカル CPU メモリ以外のデバイスに配置されたバッファを参照できます。このような場合、... | x = tnp.ones([2]) + np.ones([2])
print("x = %s\nclass = %s" % (x, x.__class__)) | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
TF NumPy と TensorFlow
TensorFlow NumPy は TensorFlow の上に構築されているため、TensorFlow とシームレスに相互運用できます。
tf.Tensor と ND 配列
ND 配列は tf.Tensor のエイリアスであるため、実際のデータのコピーを呼び出さずに混在させることが可能です。 | x = tf.constant([1, 2])
print(x)
# `asarray` and `convert_to_tensor` here are no-ops.
tnp_x = tnp.asarray(x)
print(tnp_x)
print(tf.convert_to_tensor(tnp_x))
# Note that tf.Tensor.numpy() will continue to return `np.ndarray`.
print(x.numpy(), x.numpy().__class__) | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorFlow 相互運用性
ND 配列は tf.Tensor のエイリアスにすぎないため、TensorFlow API に渡すことができます。前述のように、このような相互運用では、アクセラレータやリモートデバイスに配置されたデータであっても、データのコピーは行われません。
逆に言えば、tf.Tensor オブジェクトを、データのコピーを実行せずに、tf.experimental.numpy API に渡すことができます。 | # ND array passed into TensorFlow function.
tf_sum = tf.reduce_sum(tnp.ones([2, 3], tnp.float32))
print("Output = %s" % tf_sum)
# `tf.Tensor` passed into TensorFlow NumPy function.
tnp_sum = tnp.sum(tf.ones([2, 3]))
print("Output = %s" % tnp_sum) | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
勾配とヤコビアン: tf.GradientTape
TensorFlow の GradientTape は、TensorFlow と TensorFlow NumPy コードを介してバックプロパゲーションに使用できます。
サンプルモデルセクションで作成されたモデルを使用して、勾配とヤコビアンを計算します。 | def create_batch(batch_size=32):
"""Creates a batch of input and labels."""
return (tnp.random.randn(batch_size, 32).astype(tnp.float32),
tnp.random.randn(batch_size, 2).astype(tnp.float32))
def compute_gradients(model, inputs, labels):
"""Computes gradients of squared loss between model prediction and... | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
トレースコンパイル: tf.function
Tensorflow の tf.function は、コードを「トレースコンパイル」し、これらのトレースを最適化してパフォーマンスを大幅に向上させます。グラフと関数の概要を参照してください。
また、tf.function を使用して、TensorFlow NumPy コードを最適化することもできます。以下は、スピードアップを示す簡単な例です。tf.function コードの本文には、TensorFlow NumPy API への呼び出しが含まれていることに注意してください。 | inputs, labels = create_batch(512)
print("Eager performance")
compute_gradients(model, inputs, labels)
print(timeit.timeit(lambda: compute_gradients(model, inputs, labels),
number=10) * 100, "ms")
print("\ntf.function compiled performance")
compiled_compute_gradients = tf.function(compute_gradients... | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
ベクトル化:tf.vectorized_map
TensorFlow には、並列ループのベクトル化のサポートが組み込まれているため、10 倍から 100 倍のスピードアップが可能です。これらのスピードアップは、tf.vectorized_map API を介して実行でき、TensorFlow NumPy にも適用されます。
w.r.t. (対応する入力バッチ要素)バッチで各出力の勾配を計算すると便利な場合があります。このような計算は、以下に示すように tf.vectorized_map を使用して効率的に実行できます。 | @tf.function
def vectorized_per_example_gradients(inputs, labels):
def single_example_gradient(arg):
inp, label = arg
return compute_gradients(model,
tnp.expand_dims(inp, 0),
tnp.expand_dims(label, 0))
# Note that a call to `tf.vectorized_map` semant... | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
デバイスに配置する
TensorFlow NumPy は、CPU、GPU、TPU、およびリモートデバイスに演算を配置できます。デバイスにおける配置には標準の TensorFlow メカニズムを使用します。以下の簡単な例は、すべてのデバイスを一覧表示してから、特定のデバイスに計算を配置する方法を示しています。
ここでは取り上げませんが、TensorFlow には、デバイス間で計算を複製し、集合的な削減を実行するための API もあります。
デバイスをリストする
使用するデバイスを見つけるには、tf.config.list_logical_devices およびtf.config.list_physical_devices を使用します... | print("All logical devices:", tf.config.list_logical_devices())
print("All physical devices:", tf.config.list_physical_devices())
# Try to get the GPU device. If unavailable, fallback to CPU.
try:
device = tf.config.list_logical_devices(device_type="GPU")[0]
except IndexError:
device = "/device:CPU:0" | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
演算の配置:tf.device
デバイスに演算を配置するには、tf.device スコープでデバイスを呼び出します。 | print("Using device: %s" % str(device))
# Run operations in the `tf.device` scope.
# If a GPU is available, these operations execute on the GPU and outputs are
# placed on the GPU memory.
with tf.device(device):
prediction = model.predict(create_batch(5)[0])
print("prediction is placed on %s" % prediction.device) | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
デバイス間での ND 配列のコピー: tnp.copy
特定のデバイススコープで tnp.copy を呼び出すと、データがそのデバイスに既に存在しない限り、そのデバイスにデータがコピーされます。 | with tf.device("/device:CPU:0"):
prediction_cpu = tnp.copy(prediction)
print(prediction.device)
print(prediction_cpu.device) | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
パフォーマンスの比較
TensorFlow NumPy は、CPU、GPU、TPU にディスパッチできる高度に最適化された TensorFlow カーネルを使用します。TensorFlow は、演算の融合など、多くのコンパイラ最適化も実行し、パフォーマンスとメモリを向上します。詳細については、Grappler を使用した TensorFlow グラフの最適化をご覧ください。
ただし、TensorFlow では、NumPy と比較してディスパッチ演算のオーバーヘッドが高くなります。小規模な演算(約 10 マイクロ秒未満)で構成されるワークロードの場合、これらのオーバーヘッドがランタイムを支配する可能性があり、NumPy はより優れたパ... | def benchmark(f, inputs, number=30, force_gpu_sync=False):
"""Utility to benchmark `f` on each value in `inputs`."""
times = []
for inp in inputs:
def _g():
if force_gpu_sync:
one = tnp.asarray(1)
f(inp)
if force_gpu_sync:
with tf.device("CPU:0"):
tnp.copy(one) # F... | site/ja/guide/tf_numpy.ipynb | tensorflow/docs-l10n | apache-2.0 |
Queremos comprimir esta imagen para reducir el tamaño que cuesta almacenarlo en memoria. Una de las estrategias de compresión es reducir la paleta de colore
s.
En cualquier imagen, la paleta de de colores es una combinación de 256 tonos de rojo, verde y azul; entonces el espacio de colores tiene 3 dimensiones y $256^3$... | iso = china.reshape(-1,3)
print(iso.shape)
print(iso.nbytes) | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
Como se ha dicho anteriormente, hay colores más o menos posibles. Sabiendo que tenemos tres posibles canales, representaremos todos los píxeles en función de dónde están situados en el espacio de color. Para ello los proyectaremos en las combinaciones de dos canales rojo-verde, rojo-azul y verde-azul. | fig = plt.figure(2)
rg = fig.add_subplot(2,2,1)
rb = fig.add_subplot(2,2,2)
gb = fig.add_subplot(2,2,3)
rg.plot(iso[::5,0], iso[::5,1], 'b.', markersize=1)
rg.set_title('Red-Green channel', fontsize=10)
rb.plot(iso[::5,0], iso[::5,2], 'b.', markersize=1)
rb.set_title('Red-Blue channel', fontsize=10)
gb.plot(iso[::5,1]... | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
Como se puede ver, la mayoría de píxeles siguen un patrón desde el negro al blanco, pasando por combinaciones que tienden al gris (iguales cantidades de rojo verde y azul). Los colores más poco frecuentes son los rojos puros y los verdes puros.
Una paleta eficiente se conseguirá resumiendo todos estos píxeles en unos c... | from sklearn.cluster import KMeans
model = KMeans(32, n_jobs=-1)
labels = model.fit_predict(iso)
colors = model.cluster_centers_ | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
A continuación representaremos sobre la anterior figura los centroides como puntos en rojo. Como se aprecia perfectamente, hay mayor densidad de centroides donde hay colores más probables. | fig = plt.figure(3)
rg = fig.add_subplot(2,2,1)
rb = fig.add_subplot(2,2,2)
gb = fig.add_subplot(2,2,3)
rg.plot(iso[::5,0], iso[::5,1], 'b.', markersize=1)
rg.set_title('Red-Green channel', fontsize=10)
rb.plot(iso[::5,0], iso[::5,2], 'b.', markersize=1)
rb.set_title('Red-Blue channel', fontsize=10)
gb.plot(iso[::5,1]... | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
Finalmente podemos reconstruir la imagen utilizando los valores ajustados al modelo, para ello tenemos que pasar de la representación bidimensional que hemos utilizaro para el modelo a la tridimensional que requiere la imagen.* | new_image = colors[labels].reshape(china.shape).astype(np.uint8)
fig = plt.figure(4)
ax = fig.add_subplot(1,1,1)
ax.imshow(new_image) | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
Distinguir entre el Iris Virginica y el Iris Versicolor
Volvemos al Iris, la flor preferida del Machine Learning. | import pandas as pd
iris = pd.read_csv('data/iris.csv')
iris.head() | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
Un problema clásico de predicción es poder distinguir entre la Iris Virginica y la Iris Versicolor. Los datos tomados para cada flor son la longitud y la anchura del sépalo y el pétalo respectivamente. Distinguir la setosa de la virginica y versicolor es sencillo, puesto que la setosa tiene un sépalo claramente más cor... | fig = plt.figure(5)
ax = fig.add_subplot(1,1,1)
for s, c in zip(iris.groupby('Name'), ['r', 'w', 'b']):
s[1].plot.scatter(x='SepalWidth',
y='SepalLength',
c=c,
s=50*s[1]['PetalLength'],
ax=ax,
label=s[0])
... | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
En cambio, no parece que haya una manera obvia de distinguir la versicolor de la virginica por sus propiedades. Los pétalos y los sépalos tienen un aspecto parecido: cuando son largos son anchos y al contrario. Entonces no es trivial entrenar un modelo que prediga, dadas las características de una flor, su variedad.
Lo... | from sklearn.decomposition import PCA
data = np.vstack((iris.SepalLength.as_matrix(),
iris.SepalWidth.as_matrix(),
iris.PetalLength.as_matrix(),
iris.PetalWidth.as_matrix())).T
pca = PCA(n_components=2)
X_r = pca.fit(data).transform(data)
print('Components', pca.co... | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
Lo que obtenemos es que las dos medidas que separan bien la virginica de la versicolor son
$$ m_1 = 0.36 s_l + -0.08 s_w + 0.86 p_l + 0.36 p_w $$
$$ m_2 = -0.66 s_l + -0.73 s_w + 0.18 p_l + 0.07 p_w $$
donde $s_l$ y $s_w$ son la longitud y la anchura del sépalo y $p_l$ y $p_w$ son la longitud y la anchura del pétalo re... | fig = plt.figure(6)
ax = fig.add_subplot(1,1,1)
projected = pd.DataFrame(
{'Axis1': X_r[:,0],
'Axis2': X_r[:,1],
'Name': iris.Name.as_matrix()
}
)
for (group, data), c in zip(projected.groupby('Name'), 'rwb'):
plt.scatter(data.Axis1, data.Axis2, c=c, label=group)
ax.set_xlabel(r'$m_1$', fon... | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
En estas nuevas medidas derivadas, la combinación de $m_1$ y $m_2$ de la virginica es proporcionalmente mayor que la versicolor. En este nuevo subespacio la setosa es aún más fácil de distinguir, especialmente tomando la medida $m_1$.
Podemos también volver a utilizar el algoritmo KMeans par clasificar automáticamente ... | data = np.vstack((projected.Axis1.as_matrix(),
projected.Axis2.as_matrix())).T
model = KMeans(3, n_jobs=-1)
labels = model.fit_predict(data)
label_name_map = {
1: 'Iris-setosa',
2: 'Iris-versicolor',
0: 'Iris-virginica'
}
projected['Label'] = [label_name_map[l] for l in... | curso/6-ML.ipynb | ekergy/jupyter_notebooks | gpl-3.0 |
Hint: Use dtype=tf.float64 if you want to have same precision as numpy for testing<br>
Hint: You migth wanna use tf.InterativeSession for convenience
1a: Create two random 0-d tensors x and y of any distribution. <br>
Create a TensorFlow object that returns x + y if x > y, and x - y otherwise. <br>
Hint: look up tf.con... | def task_1a_np(x, y):
return np.where(x > y, x + y, x - y)
X = tf.placeholder(tf.float64)
Y = tf.placeholder(tf.float64)
out = tf.cond(tf.greater(X, Y), lambda: tf.add(X, Y), lambda: tf.subtract(X, Y))
with tf.Session() as sess:
for xx, yy in np.random.uniform(size=(50, 2)):
actual = sess.run(out, fee... | seminar_1/homework_task1.ipynb | Rauf-Kurbanov/au_dl_course | gpl-3.0 |
1b: Create two 0-d tensors x and y randomly selected from the range [-1, 1).<br>
Return x + y if x < y, x - y if x > y, 0 otherwise.<br>
Hint: Look up tf.case().<br> | def task_1b_np(x, y):
return np.select(condlist=[x < y, x > y],
choicelist=[x + y, x - y],
default=0) | seminar_1/homework_task1.ipynb | Rauf-Kurbanov/au_dl_course | gpl-3.0 |
1c: Create the tensor x of the value [[0, -2, -1], [0, 1, 2]] <br>
and y as a tensor of zeros with the same shape as x. <br>
Return a boolean tensor that yields Trues if x equals y element-wise. <br>
Hint: Look up tf.equal(). <br> | def task_1c_np():
x = np.array([[0, -2, -1], [0, 1, 2]])
y = np.zeros_like(x)
return x == y | seminar_1/homework_task1.ipynb | Rauf-Kurbanov/au_dl_course | gpl-3.0 |
1d:<br>
Get the indices of elements in x whose values are greater than 30.<br>
Hint: Use tf.where().<br>
Then extract elements whose values are greater than 30.<br>
Hint: Use tf.gather().<br> | def task_1d_np(x):
return x[x > 30].reshape(-1, 1) | seminar_1/homework_task1.ipynb | Rauf-Kurbanov/au_dl_course | gpl-3.0 |
1e: Create a diagnoal 2-d tensor of size 6 x 6 with the diagonal values of 1,<br>
2, ..., 6<br>
Hint: Use tf.range() and tf.diag().<br> | def task_1e_np():
return np.diag(np.arange(1, 7)) | seminar_1/homework_task1.ipynb | Rauf-Kurbanov/au_dl_course | gpl-3.0 |
1f: Create a random 2-d tensor of size 10 x 10 from any distribution.<br>
Calculate its determinant.<br>
Hint: Look at tf.matrix_determinant().<br> | def task_1f_np(x):
return np.linalg.det(x) | seminar_1/homework_task1.ipynb | Rauf-Kurbanov/au_dl_course | gpl-3.0 |
1g: Create tensor x with value [5, 2, 3, 5, 10, 6, 2, 3, 4, 2, 1, 1, 0, 9].<br>
Return the unique elements in x<br>
Hint: use tf.unique(). Keep in mind that tf.unique() returns a tuple.<br> | def task_1g_np():
x = [5, 2, 3, 5, 10, 6, 2, 3, 4, 2, 1, 1, 0, 9]
_, idx = np.unique(x, return_index=True)
return np.take(x, sorted(idx)) | seminar_1/homework_task1.ipynb | Rauf-Kurbanov/au_dl_course | gpl-3.0 |
1h: Create two tensors x and y of shape 300 from any normal distribution,<br>
as long as they are from the same distribution.<br>
Use tf.cond() to return:<br>
- The mean squared error of (x - y) if the average of all elements in (x - y)<br>
is negative, or<br>
- The sum of absolute value of all elements in the tensor... | def task_1h_np(x, y):
average = np.mean(x - y)
mse = np.mean((x - y) ** 2)
asum = np.sum(np.abs(x - y))
return mse if average < 0 else asum | seminar_1/homework_task1.ipynb | Rauf-Kurbanov/au_dl_course | gpl-3.0 |
Parte 1: Word2Vec
A técnica word2vec aprende através de uma rede neural semântica uma representação vetorial de cada token em um corpus de tal forma que palavras semanticamente similares sejam similares na representação vetorial.
O PySpark contém uma implementação dessa técnica, para aplicá-la basta passar um RDD em qu... | # EXERCICIO
import re
split_regex = r'\W+'
stopfile = os.path.join("Data","stopwords.txt")
stopwords = set(sc.textFile(stopfile).collect())
def tokenize(string):
""" An implementation of input string tokenization that excludes stopwords
Args:
string (str): input string
Returns:
list: a li... | Spark/Lab04.ipynb | folivetti/BIGDATA | mit |
(1b) Aplicando transformação word2vec
Crie um modelo word2vec aplicando o método fit na RDD criada no exercício anterior.
Para aplicar esse método deve ser fazer um pipeline de métodos, primeiro executando Word2Vec(), em seguida aplicando o método setVectorSize() com o tamanho que queremos para nosso vetor (utilize tam... | # EXERCICIO
from pyspark.mllib.feature import Word2Vec
model = Word2Vec().<COMPLETAR>
print (model.transform(u'entertaining'))
print (list(model.findSynonyms(u'entertaining', 2)))
dist = np.abs(model.transform(u'entertaining')-np.array([0.0136831374839,0.00371457682922,-0.135785803199,0.047585401684,0.0414853096008]... | Spark/Lab04.ipynb | folivetti/BIGDATA | mit |
(1c) Gerando uma RDD de matrizes
Como primeiro passo, precisamos gerar um dicionário em que a chave são as palavras e o valor é o vetor representativo dessa palavra.
Para isso vamos primeiro gerar uma lista uniqueWords contendo as palavras únicas do RDD words, removendo aquelas que aparecem menos do que 5 vezes $^1$. E... | # EXERCICIO
uniqueWords = (wordsRDD
.<COMPLETAR>
.<COMPLETAR>
.<COMPLETAR>
.<COMPLETAR>
.collect()
)
print ('{} tokens únicos'.format(len(uniqueWords)))
w2v = {}
for w in uniqueWords:
w2v[w] = <COMPLETAR>
w2vb = sc.broadcast... | Spark/Lab04.ipynb | folivetti/BIGDATA | mit |
Parte 2: k-Means para quantizar os atributos
Nesse momento é fácil perceber que não podemos aplicar nossas técnicas de aprendizado supervisionado nessa base de dados:
A regressão logística requer um vetor de tamanho fixo representando cada objeto
O k-NN necessita uma forma clara de comparação entre dois objetos, qu... | # EXERCICIO
from pyspark.mllib.clustering import KMeans
vectors2RDD = sc.parallelize(np.array(list(w2v.values())),1)
print ('Sample vector: {}'.format(vectors2RDD.take(1)))
modelK = KMeans.<COMPLETAR>
clustersRDD = vectors2RDD.<COMPLETAR>
print ('10 first clusters allocation: {}'.format(clustersRDD.take(10)))
# TE... | Spark/Lab04.ipynb | folivetti/BIGDATA | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.