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? print(minion_ijsjes[minions[2]])
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 onderbreekt door op de Stop knop (<i class="fa-stop fa"></i>) in de menubalk te drukken of Kernel > Interrupt te kiezen uit het dropdown menu.
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 KeyboardInterrupts op het scherm toont. Dat gebeurt met een "try except" constructie en wel op de volgende manier:
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 een nieuwe lijn) break # verlaat de while lus
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 variabele
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=ConvergenceWarning) grid = GridSearchCV(estimator=LassoRandomForestRegressor(), param_grid=params, verbose=1) grid.fit(X_train, y_train)
_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'] for el in grid.cv_results_['params']]) zs = numpy.array(grid.cv_results_['mean_test_score']) ax.scatter(xs, ys, zs) ax.set_title("3D...") ax = fig.add_subplot(132) for x in sorted(set(xs)): y2 = ys[xs == x] z2 = zs[xs == x] ax.plot(y2, z2, label="alpha=%1.2f" % x, lw=x*2) ax.legend(); ax = fig.add_subplot(133) for y in sorted(set(ys)): x2 = xs[ys == y] z2 = zs[ys == y] ax.plot(x2, z2, label="n_estimators=%d" % y, lw=y/40) ax.legend();
_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 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[3, -1] # 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[:3, 1].reshape(3, 1) # 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[-1, :] # 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:, :]
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 <[email protected]> # Alexandre Gramfort <[email protected]> # 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 + STI 014 - bad channels (modify to your needs) include = [] # or stim channels ['STI 014'] # bad channels in raw.info['bads'] will be automatically excluded # Set up amplitude-peak rejection values for MEG channels reject = dict(grad=4000e-13, mag=4e-12) # pick MEG channels picks = mne.pick_types(raw.info, meg=True, eeg=False, stim=False, eog=True, include=include, exclude='bads') # Create epochs including different events event_id = {'audio/left': 1, 'audio/right': 2, 'visual/left': 3, 'visual/right': 4} epochs = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject) # Generate list of evoked objects from conditions names evokeds = [epochs[name].average() for name in ('left', 'right')]
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, horizontalalignment='right') plt.show()
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="Hauptstrasse", Ort=["Passau"]]]' )
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 &nbsp;&nbsp;&nbsp; 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 \text{Nominativ}$$ $$\text{Nominativ-Akkusativ} \sqsubseteq \text{Akkusativ}$$ Implementieren Sie mithilfe der Klasse HierarchicalFeature, die Sie sich von der Kurs-Website herunterladen können, ein Feature CASE, das der vorgegebenen Typhierarchie entspricht. Nutzen Sie dieses Feature dann, um Übergenerierung in folgender Grammatik zu vermeiden:
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=mask] -> "des" DET[*CASE*=gen,GEN=neut] -> "des" DET[*CASE*=nom,GEN=mask] -> "der" DET[*CASE*=gen,GEN=fem] -> "der" N[*CASE*=nongen,GEN=mask] -> "Mann" N[*CASE*=nongen,GEN=fem] -> "Frau" N[*CASE*=nongen,GEN=neut] -> "Kind" N[*CASE*=gen,GEN=fem] -> "Frau" N[*CASE*=gen,GEN=mask] -> "Mannes" N[*CASE*=gen,GEN=neut] -> "Kindes" """ from IPython.display import display import nltk from typed_features import HierarchicalFeature, TYPE
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.FeatureEarleyChartParser(compiled_grammar)
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 &nbsp;&nbsp;&nbsp; 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 &nbsp;&nbsp;&nbsp; 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 sind die neuen Grammatikregeln, sowie Ihre Typhierarchie (z. B. in graphischer Form).
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 NP[*KAS*=?y] -> DET[*GEN*=?x,*KAS*=?y] NOM[*GEN*=?x,*KAS*=?y] NOM[*GEN*=?x,*KAS*=?y] -> N[*GEN*=?x,*KAS*=?y] NP[*KAS*=gen] NOM[*GEN*=?x,*KAS*=?y] -> N[*GEN*=?x,*KAS*=?y] DET[*GEN*=mask,*KAS*=nom] -> "der" DET[*GEN*=maskneut,*KAS*=gen] -> "des" DET[*GEN*=maskneut,*KAS*=dat] -> "dem" DET[*GEN*=mask,*KAS*=akk] -> "den" DET[*GEN*=fem,*KAS*=nomakk] -> "die" DET[*GEN*=fem,*KAS*=gendat] -> "der" DET[*GEN*=neut,*KAS*=nomakk] -> "das" N[*GEN*=mask,*KAS*=nongen] -> "Mann" N[*GEN*=mask,*KAS*=gen] -> "Mannes" N[*GEN*=fem] -> "Frau" N[*GEN*=neut,*KAS*=nongen] -> "Buch" N[*GEN*=neut,*KAS*=gen] -> "Buches" VP -> V NP[*KAS*=dat] NP[*KAS*=akk] V -> "gibt" | "schenkt" """ CASE = HierarchicalFeature("KAS", case_hierarchy) GEN = HierarchicalFeature("GEN", gen_hierarchy) compiled_grammar = nltk.grammar.FeatureGrammar.fromstring( redundant_grammar, features=(CASE, GEN, TYPE) ) parser = nltk.FeatureEarleyChartParser(compiled_grammar) pos_sentences = [ "der Mann gibt der Frau das Buch", "die Frau des Mannes gibt dem Mann der Frau das Buch des Buches" ]
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): print("Satz {}: {}".format(i, sent)) sys.stdout.flush() results = parser.parse(sent.split()) analyzed = False for tree in results: display(tree) analyzed = True if not analyzed: print("Keine Analyse möglich", file=sys.stderr) sys.stderr.flush() test_grammar(parser, pos_sentences) test_grammar(parser, neg_sentences)
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/github/tensorflow/docs-l10n/blob/master/site/ja/guide/tf_numpy.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Google Colab で実行</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/guide/tf_numpy.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">GitHub でソースを表示</a> </td> <td> <a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/guide/tf_numpy.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png">ノートブックをダウンロード</a> </td> </table> 概要 TensorFlow では、tf.experimental.numpyを利用してNumPy API のサブセットを実装します。これにより、TensorFlow により高速化された NumPy コードを実行し、TensorFlow のすべて API にもアクセスできます。 セットアップ
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 などの便利なメソッドについては、ND 配列クラスをご覧ください。 まず、ND 配列オブジェクトを作成してから、さまざまなメソッドを呼び出します。
# 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 instance of tf.Tensor: %s\n" % isinstance(ones, tf.Tensor)) # Try commonly used member functions. print("ndarray.T has shape %s" % str(ones.T.shape)) print("narray.reshape(-1) has shape %s" % ones.reshape(-1).shape)
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_float32 is False:") 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)
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 TypeError: print("Currently, TensorFlow NumPy does not support mutation.")
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) w1 = tnp.random.randn(size, 64).astype(tnp.float32) / stddev bias = tnp.random.randn(64).astype(tnp.float32) w2 = tnp.random.randn(64, 2).astype(tnp.float32) / 8 self.weights = (w1, bias, w2) else: w1, bias, w2 = self.weights y = tnp.matmul(inputs, w1) + bias y = tnp.maximum(y, 0) # Relu return tnp.matmul(y, w2) # Linear projection model = Model() # Create input data and compute predictions. print(model.predict(tnp.ones([2, 32], dtype=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 配列は、NumPy 関数と相互運用できます。これらのオブジェクトは、__array__インターフェースを実装します。NumPy はこのインターフェースを使用して、関数の引数を処理する前にnp.ndarray値に変換します。 同様に、TensorFlow NumPy 関数は、np.ndarray などのさまざまなタイプの入力を受け入れることができます。これらの入力は、<code>ndarray.asarray</code> を呼び出すことにより、ND 配列に変換されます。 ND 配列をnp.ndarrayとの間で変換すると、実際のデータコピーがトリガーされる場合があります。詳細については、バッファコピーのセクションを参照してください。
# 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 arrays, given the __array__ interface. labels = 15 + 2 * tnp.random.randn(1, 1000) _ = plt.hist(labels)
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 メモリ以外のデバイスに配置されたバッファを参照できます。このような場合、NumPy 関数を呼び出すと、必要に応じてネットワークまたはデバイス全体でコピーが作成されます。 このため、NumPy API 呼び出しとの混合は通常、注意して行い、ユーザーはデータのコピーのオーバーヘッドに注意する必要があります。TensorFlow NumPy 呼び出しを TensorFlow 呼び出しとインターリーブすることは一般的に安全であり、データのコピーを避けられます。 詳細については、TensorFlow の相互運用性のセクションをご覧ください。 演算子の優先順位 TensorFlow NumPy は、NumPy よりも優先順位の高い__array_priority__を定義します。つまり、ND 配列とnp.ndarrayの両方を含む演算子の場合、前者が優先されます。np.ndarray入力は ND 配列に変換され、演算子の TensorFlow NumPy 実装が呼び出されます。
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 labels.""" with tf.GradientTape() as tape: assert model.weights is not None # Note that `model.weights` need to be explicitly watched since they # are not tf.Variables. tape.watch(model.weights) # Compute prediction and loss prediction = model.predict(inputs) loss = tnp.sum(tnp.square(prediction - labels)) # This call computes the gradient through the computation above. return tape.gradient(loss, model.weights) inputs, labels = create_batch() gradients = compute_gradients(model, inputs, labels) # Inspect the shapes of returned gradients to verify they match the # parameter shapes. print("Parameter shapes:", [w.shape for w in model.weights]) print("Gradient shapes:", [g.shape for g in gradients]) # Verify that gradients are of type ND array. assert isinstance(gradients[0], tnp.ndarray) # Computes a batch of jacobians. Each row is the jacobian of an element in the # batch of outputs w.r.t. the corresponding input batch element. def prediction_batch_jacobian(inputs): with tf.GradientTape() as tape: tape.watch(inputs) prediction = model.predict(inputs) return prediction, tape.batch_jacobian(prediction, inputs) inp_batch = tnp.ones([16, 32], tnp.float32) output, batch_jacobian = prediction_batch_jacobian(inp_batch) # Note how the batch jacobian shape relates to the input and output shapes. print("Output shape: %s, input shape: %s" % (output.shape, inp_batch.shape)) print("Batch jacobian shape:", batch_jacobian.shape)
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) compiled_compute_gradients(model, inputs, labels) # warmup print(timeit.timeit(lambda: compiled_compute_gradients(model, inputs, labels), number=10) * 100, "ms")
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` semantically maps # `single_example_gradient` over each row of `inputs` and `labels`. # The interface is similar to `tf.map_fn`. # The underlying machinery vectorizes away this map loop which gives # nice speedups. return tf.vectorized_map(single_example_gradient, (inputs, labels)) batch_size = 128 inputs, labels = create_batch(batch_size) per_example_gradients = vectorized_per_example_gradients(inputs, labels) for w, p in zip(model.weights, per_example_gradients): print("Weight shape: %s, batch size: %s, per example gradient shape: %s " % ( w.shape, batch_size, p.shape)) # Benchmark the vectorized computation above and compare with # unvectorized sequential computation using `tf.map_fn`. @tf.function def unvectorized_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)) return tf.map_fn(single_example_gradient, (inputs, labels), fn_output_signature=(tf.float32, tf.float32, tf.float32)) print("Running vectorized computation") print(timeit.timeit(lambda: vectorized_per_example_gradients(inputs, labels), number=10) * 100, "ms") print("\nRunning unvectorized computation") per_example_gradients = unvectorized_per_example_gradients(inputs, labels) print(timeit.timeit(lambda: unvectorized_per_example_gradients(inputs, labels), number=10) * 100, "ms")
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 はより優れたパフォーマンスを提供する可能性があります。その他の場合、一般的に TensorFlow を使用するとパフォーマンスが向上するはずです。 以下のベンチマークを実行して、さまざまな入力サイズでの NumPy と TensorFlow 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) # Force a sync for GPU case _g() # warmup t = timeit.timeit(_g, number=number) times.append(t * 1000. / number) return times def plot(np_times, tnp_times, compiled_tnp_times, has_gpu, tnp_times_gpu): """Plot the different runtimes.""" plt.xlabel("size") plt.ylabel("time (ms)") plt.title("Sigmoid benchmark: TF NumPy vs NumPy") plt.plot(sizes, np_times, label="NumPy") plt.plot(sizes, tnp_times, label="TF NumPy (CPU)") plt.plot(sizes, compiled_tnp_times, label="Compiled TF NumPy (CPU)") if has_gpu: plt.plot(sizes, tnp_times_gpu, label="TF NumPy (GPU)") plt.legend() # Define a simple implementation of `sigmoid`, and benchmark it using # NumPy and TensorFlow NumPy for different input sizes. def np_sigmoid(y): return 1. / (1. + np.exp(-y)) def tnp_sigmoid(y): return 1. / (1. + tnp.exp(-y)) @tf.function def compiled_tnp_sigmoid(y): return tnp_sigmoid(y) sizes = (2 ** 0, 2 ** 5, 2 ** 10, 2 ** 15, 2 ** 20) np_inputs = [np.random.randn(size).astype(np.float32) for size in sizes] np_times = benchmark(np_sigmoid, np_inputs) with tf.device("/device:CPU:0"): tnp_inputs = [tnp.random.randn(size).astype(np.float32) for size in sizes] tnp_times = benchmark(tnp_sigmoid, tnp_inputs) compiled_tnp_times = benchmark(compiled_tnp_sigmoid, tnp_inputs) has_gpu = len(tf.config.list_logical_devices("GPU")) if has_gpu: with tf.device("/device:GPU:0"): tnp_inputs = [tnp.random.randn(size).astype(np.float32) for size in sizes] tnp_times_gpu = benchmark(compiled_tnp_sigmoid, tnp_inputs, 100, True) else: tnp_times_gpu = None plot(np_times, tnp_times, compiled_tnp_times, has_gpu, tnp_times_gpu)
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$ (unos 16.7 millones) colores posibles. El color (0,0,0) es el negro, mientras que el (255,255,255) es el blanco. Una estrategia para comprimir imagenes parte de la base que nuestro sentido de la vista no percibe todos los colores por igual ni la naturaleza usa todos los colores a la vez. Hay colores que nuesto cerebro no percibe bien (especialmente si somos hombres) y hay colores poco frecuentes, como tonos puros de azul o rojo. Entonces se puede reducir el número de colores posibles de $256^3$ a menos de 100 sin que nuestra percepción encuentre la imagen aberrante. En los albores de la computación se utilizaban paleatas para ahorrar memoria y poder representar gráficos de manera más eficiente. Era el caso de la SEGA Master System, una consola que apareció en el año 1986, y que disponía de esta paleta de 32 colores. El objetivo es obtener una paleta lo suficientemente buena como para que basten 32 colores. Es una práctica habitual en machine learning: obtener los casos más significativos (los colores de una paleta para una imagen) de entre todas las posibilidades (los 16 millones y pico de colores posibles) Primero vamos a explorar la imagen sólo como si fueran un montón de datos. Cualquier imagen es un array con 3 dimensiones, una para la dirección horizontal, otra para la dirección vertical y una tercera para los 3 colores. El primer paso es obviar las dimensiones espaciales y convertir la imagen en una tira de numeros
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], iso[::5,2], 'b.', markersize=1) gb.set_title('Green-Blue channel', fontsize=10) fig.tight_layout()
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 cuantos colores característicos, que se aproximan a los más frecuentes. El algoritmo que permite realizar esta tarea se llama KMeans. Se trata de un algoritmo de clustering que en Scikit-Learn se usa como sigue. Primero se importa el modelo y luego se configuran el número de centroides deseados. Cada centroide será un color característico. Es también un algoritmo bastante pesado que requiere bastante esfuerzo de cálculo, así que pasaremos un -1 al parámetro n_jobs para que use todos los colores disponibles. Al utilizar el método fit_predict el modelo calculará todos los centroides y dará para cada píxel el centroide más cercano (labels)
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], iso[::5,2], 'b.', markersize=1) gb.set_title('Green-Blue channel', fontsize=10) rg.plot(colors[:,0], colors[:,1], 'r.') rb.plot(colors[:,0], colors[:,2], 'r.') gb.plot(colors[:,1], colors[:,2], 'r.') fig.tight_layout()
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 corto y más ancho que las otras dos variedades.
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]) plt.xlabel('Sepal width') plt.ylabel('Sepal length')
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 que sucede es que estamos explorando sólo unas cuantas combinaciones dentro del espacio de posibles medidas. Si proyectamos las medidas como en el caso anterior nos limitamos a combinaciones entre dos de los cuatro parámetros. Esta limitación existe sólo en nuestros cerebros porque tenemos serias dificultades para visualizar espacios con más de tres dimensiones. En el caso de estos datos, el número de dimensiones asciende a 4. Pero hay algoritmos que permiten resolver este entuerto. La pregunta es la siguiente. ¿Hay algún subespacio de dos dimensiones (una proyección), combinación de las 4 dimensiones, que permita separar las características de la virginica de la setosa? La respuesta, si es afirmativa, se puede encontrar con la descomposición en componentes principales (Principal Component Analysis o PCA). Para Scikit-Learn, PCA es un algoritmo de descomposición. Le cargamos las medidas como una matriz de 4 filas y una columna por cada medida
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.components_) print('Explained variance', pca.explained_variance_ratio_)
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 respectivamente. Representando todas las mediciones utilizando estas dos nuevas variables obtenemos que sí es posible (aproximadamente) separar la virginica de la versicolor.
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$', fontsize=18) ax.set_ylabel(r'$m_2$', fontsize=18) plt.legend() plt.title('PCA of IRIS dataset')
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 las tres variedades.
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 labels] fig = plt.figure(7) ax = fig.add_subplot(1,1,1) right = 0 wrong = 0 for i, (ax1, ax2, name, label) in projected.iterrows(): if name != label: ax.scatter(ax1, ax2, color='r') wrong += 1 elif name == label: ax.scatter(ax1, ax2, color='b') right += 1 print('Accuracy', right/(wrong+right)) plt.title('Clustering error')
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.cond() <br> I do the first problem for you <br>
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, feed_dict={X:xx, Y:yy}) expected = task_1a_np(xx, yy) if actual != expected: print('Fail') # something something else: print('Success')
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 (x - y) otherwise.<br> Hint: see the Huber loss function in the lecture slides 3.<br>
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 que cada objeto representa um documento e cada documento é representado por uma lista de tokens na ordem em que aparecem originalmente no corpus. Após o processo de treinamento, podemos transformar um token utilizando o método transform para transformar cada token em uma representaçã vetorial. Nesse ponto, cada objeto de nossa base será representada por uma matriz de tamanho variável. (1a) Gerando RDD de tokens Utilize a função de tokenização tokenize do Lab4d para gerar uma RDD wordsRDD contendo listas de tokens da nossa base original.
# 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 list of tokens without stopwords """ return <COMPLETAR> wordsRDD = dataRDD.map(lambda x: tokenize(x[1])) print (wordsRDD.take(1)[0]) # TEST Tokenize a String (1a) assert wordsRDD.take(1)[0]==[u'quiet', u'introspective', u'entertaining', u'independent', u'worth', u'seeking'], 'lista incorreta!'
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 tamanho 5), seguido de setSeed() para a semente aleatória, em caso de experimentos controlados (utilizaremos 42) e, finalmente, fit() com nossa wordsRDD como parâmetro.
# 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])).mean() assert dist<1e-6, 'valores incorretos' assert list(model.findSynonyms(u'entertaining', 1))[0][0] == 'god', 'valores incorretos'
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$. Em seguida, criaremos um dicionário w2v que a chave é um token e o valor é um np.array do vetor transformado daquele token$^2$. Finalmente, vamos criar uma RDD chamada vectorsRDD em que cada registro é representado por uma matriz onde cada linha representa uma palavra transformada. 1 Na versão 1.3 do PySpark o modelo Word2Vec utiliza apenas os tokens que aparecem mais do que 5 vezes no corpus, na versão 1.4 isso é parametrizado. 2 Na versão 1.4 do PySpark isso pode ser feito utilizando o método `getVectors()
# 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(w2v) # acesse como w2vb.value[w] print ('Vetor entertaining: {}'.format( w2v[u'entertaining'])) vectorsRDD = (wordsRDD .<COMPLETAR> ) recs = vectorsRDD.take(2) firstRec, secondRec = recs[0], recs[1] print (firstRec.shape, secondRec.shape) # TEST Tokenizing the small datasets (1c) assert len(uniqueWords) == 3388, 'valor incorreto' assert np.mean(np.abs(w2v[u'entertaining']-[0.0136831374839,0.00371457682922,-0.135785803199,0.047585401684,0.0414853096008]))<1e-6,'valor incorreto' assert secondRec.shape == (10,5)
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, que métrica de similaridade devemos aplicar? Para resolver essa situação, vamos executar uma nova transformação em nossa RDD. Primeiro vamos aproveitar o fato de que dois tokens com significado similar são mapeados em vetores similares, para agrupá-los em um atributo único. Ao aplicarmos o k-Means nesse conjunto de vetores, podemos criar $k$ pontos representativos e, para cada documento, gerar um histograma de contagem de tokens nos clusters gerados. (2a) Agrupando os vetores e criando centros representativos Como primeiro passo vamos gerar um RDD com os valores do dicionário w2v. Em seguida, aplicaremos o algoritmo k-Means com $k = 200$ e $seed = 42$.
# 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))) # TEST Amazon record with the most tokens (1d) assert clustersRDD.take(10)==[142, 83, 42, 0, 87, 52, 190, 17, 56, 0], 'valor incorreto'
Spark/Lab04.ipynb
folivetti/BIGDATA
mit