markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
See contents of the bucket on the web interface (URL will be outputted below) | print "https://console.developers.google.com/project/" + project_id + "/storage/browser/" + BUCKET_NAME + "/?authuser=0" | credentials/Test.ipynb | louisdorard/bml-base | mit |
Google Prediction
Initialize API wrapper | import googleapiclient.gpred as gpred
oauth_file = %env GPRED_OAUTH_FILE
api = gpred.api(oauth_file) | credentials/Test.ipynb | louisdorard/bml-base | mit |
Making predictions against a hosted model
Let's use the sample.sentiment hosted model (made publicly available by Google) | # projectname has to be 414649711441
prediction_request = api.hostedmodels().predict(project='414649711441',
hostedModelName='sample.sentiment',
body={'input': {'csvInstance': ['I hate that stuff is so stupid']}})
result = prediction_request.exe... | credentials/Test.ipynb | louisdorard/bml-base | mit |
Listes
Ces exercices sont un peu foireux : les "listes" en Python ne sont pas des listes simplement chaînées !
Exercice 1 : taille | from typing import TypeVar, List
_a = TypeVar('alpha')
def taille(liste : List[_a]) -> int:
longueur = 0
for _ in liste:
longueur += 1
return longueur
taille([])
taille([1, 2, 3])
len([])
len([1, 2, 3]) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 2 : concat | from typing import TypeVar, List
_a = TypeVar('alpha')
def concatene(liste1 : List[_a], liste2 : List[_a]) -> List[_a]:
# return liste1 + liste2 # easy solution
liste = []
for i in liste1:
liste.append(i)
for i in liste2:
liste.append(i)
return liste
concatene([1, 2], [3, 4])
[1, ... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Mais attention le typage est toujours optionnel en Python : | concatene([1, 2], ["pas", "entier", "?"]) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 3 : appartient | from typing import TypeVar, List
_a = TypeVar('alpha')
def appartient(x : _a, liste : List[_a]) -> bool:
for y in liste:
if x == y:
return True # on stoppe avant la fin
return False
appartient(1, [])
appartient(1, [1])
appartient(1, [1, 2, 3])
appartient(4, [1, 2, 3])
1 in []
1 in [1]
1 ... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Notre implémentation est évidemment plus lente que le test x in liste de la librarie standard...
Mais pas tant : | %timeit appartient(1000, list(range(10000)))
%timeit 1000 in list(range(10000)) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 4 : miroir | from typing import TypeVar, List
_a = TypeVar('alpha')
def miroir(liste : List[_a]) -> List[_a]:
# return liste[::-1] # version facile
liste2 = []
for x in liste:
liste2.insert(0, x)
return liste2
miroir([2, 3, 5, 7, 11])
[2, 3, 5, 7, 11][::-1]
%timeit miroir([2, 3, 5, 7, 11])
%timeit [2, 3,... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 5 : alterne
La sémantique n'était pas très claire, mais on peut imaginer quelque chose comme ça : | from typing import TypeVar, List
_a = TypeVar('alpha')
def alterne(liste1 : List[_a], liste2 : List[_a]) -> List[_a]:
liste3 = []
i, j = 0, 0
n, m = len(liste1), len(liste2)
while i < n and j < m: # encore deux
liste3.append(liste1[i])
i += 1
liste3.append(liste2[j])
j ... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
La complexité est linéaire en $\mathcal{O}(\max(|\text{liste 1}|, |\text{liste 2}|)$.
Exercice 6 : nb_occurrences | from typing import TypeVar, List
_a = TypeVar('alpha')
def nb_occurrences(x : _a, liste : List[_a]) -> int:
nb = 0
for y in liste:
if x == y:
nb += 1
return nb
nb_occurrences(0, [1, 2, 3, 4])
nb_occurrences(2, [1, 2, 3, 4])
nb_occurrences(2, [1, 2, 2, 3, 2, 4])
nb_occurrences(5, [1, 2,... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 7 : pairs
C'est un filtrage : | filter?
from typing import List
def pairs(liste : List[int]) -> List[int]:
# return list(filter(lambda x : x % 2 == 0, liste))
return [x for x in liste if x % 2 == 0]
pairs([1, 2, 3, 4, 5, 6])
pairs([1, 2, 3, 4, 5, 6, 7, 100000])
pairs([1, 2, 3, 4, 5, 6, 7, 100000000000])
pairs([1, 2, 3, 4, 5, 6, 7, 10000000... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 8 : range | from typing import List
def myrange(n : int) -> List[int]:
liste = []
i = 1
while i <= n:
liste.append(i)
i += 1
return liste
myrange(4)
from typing import List
def intervale(a : int, b : int=None) -> List[int]:
if b == None:
a, b = 1, a
liste = []
i = a
while... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 9 : premiers
Plusieurs possibilités. Un filtre d'Erathosthène marche bien, ou une filtration.
Je ne vais pas utiliser de tableaux donc on est un peu réduit d'utiliser une filtration (filtrage ? pattern matching) | def racine(n : int) -> int:
i = 1
for i in range(n + 1):
if i*i > n:
return i - 1
return i
racine(1)
racine(5)
racine(102)
racine(120031)
from typing import List
def intervale2(a : int, b : int, pas : int=1) -> List[int]:
assert pas > 0
liste = []
i = a
while i <= b:
... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Une version purement fonctionnelle est moins facile qu'une version impérative avec une référence booléenne. | def estDivisible(n : int, k : int) -> bool:
return (n % k) == 0
estDivisible(10, 2)
estDivisible(10, 3)
estDivisible(10, 4)
estDivisible(10, 5)
def estPremier(n : int) -> bool:
return (n == 2) or (n == 3) or not any(map(lambda k: estDivisible(n, k), intervale2(2, racine(n), 1)))
for n in range(2, 20):
pr... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Listes simplement chaînée (manuellement définies)
Comme ces exercices étaient un peu foireux à écrire avec les "listes" de Python, qui ne sont pas des listes simplement chaînées, je propose une autre solution où l'on va définir une petite classe qui représentera une liste simplement chaînée, et on va écrire les fonctio... | class ListeChainee():
def __init__(self, hd=None, tl=None):
self.hd = hd
self.tl = tl
def __repr__(self) -> str:
if self.tl is None:
if self.hd is None:
return "[]"
else:
return f"{self.hd} :: []"
else:
retu... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 1 : taille
Par exemple la longueur sera bien en O(n) si n=taille(liste) avec cette approche récursive : | from typing import Optional
def taille(liste: Optional[ListeChainee]) -> int:
if liste is None:
return 0
elif liste.tl is None:
return 0 if liste.hd is None else 1
return 1 + taille(liste.tl)
print(taille(vide)) # 0
print(taille(l_1)) # 1
print(taille(l_12)) # 2
print(taille(l_123))... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 2 : concat
Je vais déjà commencer par écrire une fonction copy qui permet de copier récursivement une liste simplement chaînée, pour être sûr que l'on ne modifie pas en place une des listes données en argument. | def copy(liste: ListeChainee) -> ListeChainee:
if liste.tl is None:
return ListeChainee(hd=liste.hd, tl=None)
else:
return ListeChainee(hd=liste.hd, tl=copy(liste.tl)) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
On peut vérifier que cela marche en regardant, par exemple, l'id de deux objets si le deuxième est une copie du premier : les id seront bien différents. | print(id(vide))
print(id(copy(vide))) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Et donc pour concaténer deux chaînes, c'est facile : | def concat(liste1: ListeChainee, liste2: ListeChainee) -> ListeChainee:
if taille(liste1) == 0:
return liste2
elif taille(liste2) == 0:
return liste1
# nouvelle liste : comme ça changer queue.tl ne modifie PAS liste1
resultat = copy(liste1)
queue = resultat
while taille(queue.tl)... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 3 : appartient
C'est en complexité linéaire dans le pire des cas. | def appartient(x, liste: ListeChainee) -> bool:
if liste.hd is None:
return False
else:
if liste.hd == x:
return True
else:
return appartient(x, liste.tl)
assert appartient(0, vide) == False
assert appartient(0, l_1) == False
assert appartient(0, l_12) == Fal... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 4 : miroir
Ce sera en temps quadratique, à cause de toutes les recopies : | def miroir(liste: ListeChainee) -> ListeChainee:
if taille(liste) <= 1:
return copy(liste)
else:
hd, tl = liste.hd, copy(liste.tl) # O(n)
juste_hd = ListeChainee(hd=hd, tl=None) # O(1)
return concat(miroir(tl), juste_hd) # O(n^2) + O(n) à cause de concat
print(miroir(vide)) ... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 5 : alterne
La sémantique n'était pas très claire, mais on peut imaginer quelque chose comme ça :
si une des deux listes est vide, on prend l'autre,
si les deux ne sont pas vide, on prend le début de l1, de l2, puis alterne(queue l1, queue l2) | def alterne(liste1: ListeChainee, liste2: ListeChainee) -> ListeChainee:
if taille(liste1) == 0:
return copy(liste2) # on recopie pour ne rien modifier
if taille(liste2) == 0:
return copy(liste1) # on recopie pour ne rien modifier
h1, t1 = liste1.hd, liste1.tl
h2, t2 = liste2.hd, lis... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
La complexité est quadratique en $\mathcal{O}((\max(|\text{liste 1}|, |\text{liste 2}|)^2)$ à cause des recopies.
Exercice 6 : nb_occurrences
Ce sera en temps linéaire, dans tous les cas. | def nb_occurrences(x, liste: ListeChainee) -> int:
if liste is None or liste.hd is None:
return 0
else:
count = 1 if x == liste.hd else 0
if liste.tl is None:
return count
else:
return count + nb_occurrences(x, liste.tl)
assert nb_occurrences(1, vide) == 0
assert nb_occu... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
On peut facilement écrire une variante qui sera récursive terminale ("tail recursive") : | def nb_occurrences(x, liste: ListeChainee, count=0) -> int:
if liste is None or liste.hd is None:
return count
else:
count += 1 if x == liste.hd else 0
if liste.tl is None:
return count
else:
return nb_occurrences(x, liste.tl, count=count) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 7 : pairs
C'est un filtrage par le prédicat x % 2 == 0.
Autant écrire la fonction de filtrage générique : | def filtrer(liste: ListeChainee, predicate) -> ListeChainee:
if liste is None or liste.hd is None: # liste de taille 0
return ListeChainee(hd=None, tl=None)
elif liste.tl is None: # liste de taille 1
if predicate(liste.hd): # on renvoie [hd]
return ListeChainee(hd=liste.hd, tl=Non... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Et donc c'est rapide : | def pairs(liste: ListeChainee) -> ListeChainee:
def predicate(x):
return (x % 2) == 0
# aussi : predicate = lambda x: (x % 2) == 0
return filtrer(liste, predicate)
def impairs(liste: ListeChainee) -> ListeChainee:
def predicate(x):
return (x % 2) == 1
return filtrer(liste, predicate... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 8 : range
Ce sera de complexité temporelle linéaire : | def myrange(n: int) -> ListeChainee:
if n <= 0:
return ListeChainee(hd=None, tl=None)
elif n == 1:
return ListeChainee(hd=1, tl=None)
# return insert(1, vide)
else:
return ListeChainee(hd=n, tl=myrange(n-1))
print(myrange(1)) # [1]
print(myrange(2)) # [1, 2]
print(myrange(... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Si on veut les avoir dans l'ordre croissant, il faudrait utiliser miroir qui est quadratique.
Autant écrire directement une fonction intervale(a, b) qui renvoie la liste simplement chaînée contenant a :: (a+1) :: ... :: b : | def intervale(a: int, b: Optional[int]=None) -> ListeChainee:
if b is None:
a, b = 1, a
n = b - a
if n < 0: # [a..b] = []
return ListeChainee(hd=None, tl=None)
elif n == 0: # [a..b] = [a]
return ListeChainee(hd=a, tl=None)
else: # [a..b] = a :: [a+1..b]
r... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Une autre approche est d'écrire la fonction mymap et de dire que
python
intervale_bis(a, b) = miroir(mymap(lambda x: x + (a - 1), myrange(b - a + 1))) | from typing import Callable
def mymap(fonction: Callable, liste: ListeChainee) -> ListeChainee:
if liste is None or liste.hd is None: # liste de taille 0
return ListeChainee(hd=None, tl=None)
elif liste.tl is None: # liste de taille 1
return ListeChainee(hd=fonction(liste.hd), tl=None)
el... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 9 : premiers
Plusieurs possibilités. Un filtre d'Erathosthène marche bien, ou une filtrage.
Je ne vais pas utiliser de tableaux donc on est un peu réduit d'utiliser une filtrage.
On a besoin des fonctions suivantes :
calculer la racine entière de $n$, très facile par une boucle,
calculer les nombres impairs e... | def racine(n: int) -> int:
i = 1
for i in range(n + 1):
if i*i > n:
return i - 1
return i
print(racine(1)) # 1
print(racine(5)) # 2
print(racine(102)) # 10
print(racine(120031)) # 346
def intervale2(a: int, b: Optional[int]=None, pas: int=1) -> ListeChainee:
if b is None:
... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Une version purement fonctionnelle est moins facile qu'une version impérative avec une référence booléenne. | def estDivisible(n: int, k: int) -> bool:
return (n % k) == 0
estDivisible(10, 2)
estDivisible(10, 3)
estDivisible(10, 4)
estDivisible(10, 5) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
On est prêt à écrire estPremier : | def estPremier(n : int) -> bool:
return taille(filtrer(intervale2(2, racine(n), 1), lambda k: estDivisible(n, k))) == 0 | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
En effet il suffit de construire d'abord la liste des entiers impairs de 2 à $\lfloor \sqrt{n} \rfloor$, de les filtrer par ceux qui divisent $n$, et de vérifier si on a aucun diviseur (taille(..) == 0) auquel cas $n$ est premier, ou si $n$ a au moins un diviseur auquel cas $n$ n'est pas premier. | for n in range(2, 20):
print("Petits diviseurs de", n, " -> ", filtrer(intervale2(2, racine(n), 1), lambda k: estDivisible(n, k))) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
On voit dans l'exemple ci dessus les nombres premiers comme ceux n'ayant aucun diviseurs, et les nombres non premiers comme ceux ayant au moins un diviseur. | def premiers(n : int) -> ListeChainee:
return filtrer(intervale2(2, n, 1), estPremier)
premiers(10) # [2, 3, 5, 7]
premiers(100) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Quelques tris par comparaison
On fera les tris en ordre croissant. | test = [3, 1, 8, 4, 5, 6, 1, 2] | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 10 : Tri insertion | from typing import TypeVar, List
_a = TypeVar('alpha')
def insere(x : _a, liste : List[_a]) -> List[_a]:
if len(liste) == 0:
return [x]
else:
t, q = liste[0], liste[1:]
if x <= t:
return [x] + liste
else:
return [t] + insere(x, q)
def tri_insertion(liste... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Complexité en temps $\mathcal{O}(n^2)$.
Exercice 11 : Tri insertion générique | from typing import TypeVar, List, Callable
_a = TypeVar('alpha')
def insere2(ordre : Callable[[_a, _a], bool], x : _a, liste : List[_a]) -> List[_a]:
if len(liste) == 0:
return [x]
else:
t, q = liste[0], liste[1:]
if ordre(x, t):
return [x] + liste
else:
... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 12 : Tri selection | from typing import TypeVar, List, Tuple
_a = TypeVar('alpha')
def selectionne_min(liste : List[_a]) -> Tuple[_a, List[_a]]:
if len(liste) == 0:
raise ValueError("Selectionne_min sur liste vide")
else:
def cherche_min(mini : _a, autres : List[_a], reste : List[_a]) -> Tuple[_a, List[_a]]:
... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
(On voit que la liste autre a été inversée) | def tri_selection(liste : List[_a]) -> List[_a]:
if len(liste) == 0:
return []
else:
mini, autres = selectionne_min(liste)
return [mini] + tri_selection(autres)
tri_selection(test) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Complexité en temps : $\mathcal{O}(n^2)$.
Exercices 13, 14, 15 : Tri fusion | from typing import TypeVar, List, Tuple
_a = TypeVar('alpha')
def separe(liste : List[_a]) -> Tuple[List[_a], List[_a]]:
if len(liste) == 0:
return ([], [])
elif len(liste) == 1:
return ([liste[0]], [])
else:
x, y, q = liste[0], liste[1], liste[2:]
a, b = separe(q)
r... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Complexité en temps $\mathcal{O}(n \log n)$.
Comparaisons | %timeit tri_insertion(test)
%timeit tri_selection(test)
%timeit tri_fusion(test)
from sys import setrecursionlimit
setrecursionlimit(100000)
# nécessaire pour tester les différentes fonctions récursives sur de grosses listes
import random
def test_random(n : int) -> List[int]:
return [random.randint(-1000, 1000)... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
C'est assez pour vérifier que le tri fusion est bien plus efficace que les autres.
On voit aussi que les tris par insertion et sélection sont pire que linéaires,
Mais que le tri par fusion est presque linéaire (pour $n$ petits, $n \log n$ est presque linéaire).
Listes : l'ordre supérieur
Je ne corrige pas les questio... | from typing import TypeVar, List, Callable
_a, _b = TypeVar('_a'), TypeVar('_b')
def applique(f : Callable[[_a], _b], liste : List[_a]) -> List[_b]:
# Triche :
return list(map(f, liste))
# 1ère approche :
return [f(x) for x in liste]
# 2ème approche :
fliste = []
for x in liste:
fli... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 17 | def premiers_carres_parfaits(n : int) -> List[int]:
return applique(lambda x : x * x, list(range(1, n + 1)))
premiers_carres_parfaits(12) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 18 : itere | from typing import TypeVar, List, Callable
_a = TypeVar('_a')
def itere(f : Callable[[_a], None], liste : List[_a]) -> None:
for x in liste:
f(x) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 19 | print_int = lambda i: print("{}".format(i))
def affiche_liste_entiers(liste : List[int]) -> None:
print("Debut")
itere(print_int, liste)
print("Fin")
affiche_liste_entiers([1, 2, 4, 5, 12011993]) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 20 : qqsoit et ilexiste | from typing import TypeVar, List, Callable
_a = TypeVar('_a')
# Comme all(map(f, liste))
def qqsoit(f : Callable[[_a], bool], liste : List[_a]) -> bool:
for x in liste:
if not f(x): return False # arret preliminaire
return True
# Comme any(map(f, liste))
def ilexiste(f : Callable[[_a], bool], liste ... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 21 : appartient version 2 | def appartient_curry(x : _a) -> Callable[[List[_a]], bool]:
return lambda liste: ilexiste(lambda y: x == y, liste)
def appartient(x : _a, liste : List[_a]) -> bool:
return ilexiste(lambda y: x == y, liste)
def toutes_egales(x : _a, liste : List[_a]) -> bool:
return qqsoit(lambda y: x == y, liste)
apparti... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Est-ce que notre implémentation peut être plus rapide que le test x in liste ?
Non, mais elle est aussi rapide. C'est déjà pas mal ! | %timeit appartient(random.randint(-10, 10), [random.randint(-1000, 1000) for _ in range(1000)])
%timeit random.randint(-10, 10) in [random.randint(-1000, 1000) for _ in range(1000)] | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 22 : filtre | from typing import TypeVar, List, Callable
_a = TypeVar('_a')
# Comme list(filter(f, liste))
def filtre(f : Callable[[_a], bool], liste : List[_a]) -> List[_a]:
# return [x for x in liste if f(x)]
liste2 = []
for x in liste:
if f(x):
liste2.append(x)
return liste2
filtre(lambda x: ... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 23
Je vous laisse trouver pour premiers. | pairs = lambda liste: filtre(lambda x: (x % 2) == 0, liste)
impairs = lambda liste: filtre(lambda x: (x % 2) != 0, liste)
pairs(list(range(10)))
impairs(list(range(10))) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 24 : reduit | from typing import TypeVar, List, Callable
_a = TypeVar('_a')
# Comme list(filter(f, liste))
def reduit_rec(f : Callable[[_a, _b], _a], acc : _a, liste : List[_b]) -> _a:
if len(liste) == 0:
return acc
else:
h, q = liste[0], liste[1:]
return reduit(f, f(acc, h), q)
# Version non récurs... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Très pratique pour calculer des sommes, notamment.
Exercice 25 : somme, produit | from operator import add
somme_rec = lambda liste: reduit_rec(add, 0, liste)
somme = lambda liste: reduit(add, 0, liste)
somme_rec(list(range(10)))
somme(list(range(10)))
sum(list(range(10)))
%timeit somme_rec(list(range(10)))
%timeit somme(list(range(10)))
%timeit sum(list(range(10))) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Pour de petites listes, la version récursive est aussi efficace que la version impérative. Chouette ! | %timeit somme_rec(list(range(1000)))
%timeit somme(list(range(1000)))
%timeit sum(list(range(1000)))
from operator import mul
produit = lambda liste: reduit(mul, 1, liste)
produit(list(range(1, 6))) # 5! = 120 | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Bonus : | def factorielle(n : int) -> int:
return produit(range(1, n + 1))
for n in range(1, 15):
print("{:>7}! = {:>13}".format(n, factorielle(n))) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 26 : miroir version 2 | miroir = lambda liste: reduit(lambda l, x : [x] + l, [], liste)
miroir([2, 3, 5, 7, 11]) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Attention en Python, les listes ne sont PAS simplement chainées, donc lambda l, x : [x] + l est en temps linéaire en $|l| = n$, pas en $\mathcal{O}(1)$ comme en Caml/OCaml pour fun l x -> x :: l.
Arbres
/!\ Les deux dernières parties sont bien plus difficiles en Python qu'en Caml.
Exercice 27 | from typing import Dict, Optional, Tuple
# Impossible de définir un type récursivement, pas comme en Caml
arbre_bin = Dict[str, Optional[Tuple[Dict, Dict]]]
from pprint import pprint
arbre_test = {'Noeud': (
{'Noeud': (
{'Noeud': (
{'Feuille': None},
{'Feuille': No... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Avec une syntaxe améliorée, on se rapproche de très près de la syntaxe de Caml/OCaml : | Feuille = {'Feuille': None}
Noeud = lambda x, y : {'Noeud': (x, y)}
arbre_test = Noeud(Noeud(Noeud(Feuille, Feuille), Feuille), Feuille)
pprint(arbre_test) | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 28
Compte le nombre de feuilles et de sommets. | def taille(a : arbre_bin) -> int:
# Pattern matching ~= if, elif,.. sur les clés de la profondeur 1
# du dictionnaire (une seule clé)
if 'Feuille' in a:
return 1
elif 'Noeud' in a:
x, y = a['Noeud']
return 1 + taille(x) + taille(y)
taille(arbre_test) # 7 | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 29 | def hauteur(a : arbre_bin) -> int:
if 'Feuille' in a:
return 0
elif 'Noeud' in a:
x, y = a['Noeud']
return 1 + max(hauteur(x), hauteur(y))
hauteur(arbre_test) # 3 | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 30
Bonus. (Écrivez une fonction testant si un arbre étiqueté par des entiers est tournoi.)
Parcours d'arbres binaires
Après quelques exercices manipulant cette structure de dictionnaire, écrire la suite n'est pas trop difficile.
Exercice 31 | from typing import TypeVar, Union, List
F = TypeVar('F')
N = TypeVar('N')
element_parcours = Union[F, N]
parcours = List[element_parcours] | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 32 : Parcours naifs (complexité quadratique) | def parcours_prefixe(a : arbre_bin) -> parcours:
if 'Feuille' in a:
return [F]
elif 'Noeud' in a:
g, d = a['Noeud']
return [N] + parcours_prefixe(g) + parcours_prefixe(d)
parcours_prefixe(arbre_test)
def parcours_postfixe(a : arbre_bin) -> parcours:
if 'Feuille' in a:
retur... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Pourquoi ont-ils une complexité quadratique ? La concaténation (@ en OCaml, + en Python) ne se fait pas en temps constant mais linéaire dans la taille de la plus longue liste.
Exercice 33 : Parcours linéaires
On ajoute une fonction auxiliaire et un argument vus qui est une liste qui stocke les élements observés dans l'... | def parcours_prefixe2(a : arbre_bin) -> parcours:
def parcours(vus, b):
if 'Feuille' in b:
vus.insert(0, F)
return vus
elif 'Noeud' in b:
vus.insert(0, N)
g, d = b['Noeud']
return parcours(parcours(vus, g), d)
p = parcours([], a)
re... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 34 : parcours en largeur et en profondeur
Pour utiliser une file de priorité (priority queue), on utilise le module collections.deque. | from collections import deque
def parcours_largeur(a : arbre_bin) -> parcours:
file = deque()
# fonction avec effet de bord sur la file
def vasy() -> parcours:
if len(file) == 0:
return []
else:
b = file.pop()
if 'Feuille' in b:
# return [... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
En remplaçant la file par une pile (une simple list), on obtient le parcours en profondeur, avec la même complexité. | def parcours_profondeur(a : arbre_bin) -> parcours:
pile = []
# fonction avec effet de bord sur la file
def vasy() -> parcours:
if len(pile) == 0:
return []
else:
b = pile.pop()
if 'Feuille' in b:
# return [F] + vasy()
v = v... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Exercice 35 et fin
Reconstruction depuis le parcours prefixe | test_prefixe = parcours_prefixe2(arbre_test)
test_prefixe | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
L'idée de cette solution est la suivante :
j'aimerais une fonction récursive qui fasse le travail;
le problème c'est que si on prend un parcours prefixe, soit il commence
par F et l'arbre doit être une feuille; soit il est de la forme N::q
où q n'est plus un parcours prefixe mais la concaténation de DEUX parcours
prefi... | from typing import Tuple
def reconstruit_prefixe(par : parcours) -> arbre_bin:
def reconstruit(p : parcours) -> Tuple[arbre_bin, parcours]:
if len(p) == 0:
raise ValueError("parcours invalide pour reconstruit_prefixe")
elif p[0] == F:
return (Feuille, p[1:])
elif p[0... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Et cet exemple va échouer : | reconstruit_prefixe([N, F, F] + test_prefixe) # échoue | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Reconstruction depuis le parcours en largeur
Ce n'est pas évident quand on ne connait pas. L'idée est de se servir d'une file
pour stocker les arbres qu'on reconstruit peu à peu depuis les feuilles. La file
permet de récupérer les bons sous-arbres quand on rencontre un noeud | largeur_test = parcours_largeur(arbre_test)
largeur_test
from collections import deque
def reconstruit_largeur(par : parcours) -> arbre_bin:
file = deque()
# Fonction avec effets de bord
def lire_element(e : element_parcours) -> None:
if e == F:
file.append(Feuille)
elif e == N... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Le même algorithme (enfin presque, modulo interversion de g et d)
avec une pile donne une autre version de la reconstruction du parcours prefixe. | from collections import deque
def reconstruit_prefixe2(par : parcours) -> arbre_bin:
pile = deque()
# Fonction avec effets de bord
def lire_element(e : element_parcours) -> None:
if e == F:
pile.append(Feuille)
elif e == N:
g = pile.pop()
d = pile.pop() ... | agreg/TP_Programmation_2017-18/TP2__Python.ipynb | Naereen/notebooks | mit |
Text classification with TensorFlow Lite Model Maker
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/lite/tutorials/model_maker_text_classification"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
... | !pip install -q tflite-model-maker | tensorflow/lite/g3doc/tutorials/model_maker_text_classification.ipynb | Intel-Corporation/tensorflow | apache-2.0 |
Get the MNIST Dataset | def get_mnist(sc, mnist_path):
(train_images, train_labels) = mnist.read_data_sets(mnist_path = "/tmp/mnist", "train")
train_images = np.reshape(train_images, (60000, 1, 28, 28))
rdd_train_images = sc.parallelize(train_images)
rdd_train_sample = rdd_train_images.map(lambda img:
... | apps/variational-autoencoder/using_variational_autoencoder_to_generate_digital_numbers.ipynb | intel-analytics/BigDL | apache-2.0 |
<br>
<br>
Lets do it with Gradient Descent now | theta0 = 0
theta1 = 2
alpha = 0.1
interations = 100
cost_log = []
theta_log = [];
inc = 0.1
for j in range(interations):
cost = 0
grad = 0
for i in range(m):
hx = theta1*X[i,0] + theta0
cost += pow((hx - y[i,0]),2)
grad += ((hx - y[i,0]))*X[i,0]
cost = cost/(2*m)
... | lectures/lec04-linear-regression-example.ipynb | w4zir/ml17s | mit |
We will produce some plots based on a frequency range to illustrate the concepts: | import matplotlib.pyplot as plt
%matplotlib inline
ff = np.linspace(0.01, 6., num=600)
wn = 2.*np.pi*ff | Rayleigh_damping.ipynb | pxcandeias/py-notebooks | mit |
Back to top
Mass proportional damping
Mass proportional damping means that the damping matrix is somehow a multiple of the mass matrix:
\begin{equation}
\mathbf{C} = \alpha \cdot \mathbf{M}
\end{equation}
where $\alpha$ is the constant of mass proportionality. In these circunstances, the dynamic equilibrium equation ca... | alpha = 0.1
zn_a = alpha/(2.*wn)
plt.plot(wn, zn_a, label='mass proportional')
plt.xlabel('Vibration frequency $\omega_n$ [rad/s]')
plt.ylabel('Damping coefficient $\zeta_n$ [-]')
plt.legend(loc='best')
plt.grid(True)
plt.xlim([0, 35.])
plt.ylim([0, 0.2])
plt.show() | Rayleigh_damping.ipynb | pxcandeias/py-notebooks | mit |
Back to top
Stiffness proportional damping
Stiffness proportional damping means that damping matrix is somehow a multiple of the stiffness matrix:
\begin{equation}
\mathbf{C} = \beta \cdot \mathbf{K}
\end{equation}
where $\beta$ is the constant of stiffness proportionality. In these circunstances, the dynamic equilibri... | beta = 0.005
zn_b = (beta*wn)/2.
plt.plot(wn, zn_b, label='stiffness proportional')
plt.xlabel('Vibration frequency $\omega_n$ [rad/s]')
plt.ylabel('Damping coefficient $\zeta_n$ [-]')
plt.legend(loc='best')
plt.grid(True)
plt.xlim([0, 35.])
plt.ylim([0, 0.2])
plt.show() | Rayleigh_damping.ipynb | pxcandeias/py-notebooks | mit |
Back to top
Rayleigh damping
When Rayleigh damping is considered it means that the damping coefficient is a combination of the two previous ones, that is, it is a multiple of mass and stifnness:
\begin{equation}
\mathbf{C} = \alpha \cdot \mathbf{M} + \beta \cdot \mathbf{K}
\end{equation}
where $\alpha$ and $\beta$ have... | plt.hold(True)
plt.plot(wn, zn_a+zn_b, label='Rayleigh damping')
plt.plot(wn, zn_a, label='mass proportional')
plt.plot(wn, zn_b, label='stiffness proportional')
plt.xlabel('Vibration frequency $\omega_n$ [rad/s]')
plt.ylabel('Damping coefficient $\zeta_n$ [-]')
plt.legend(loc='best')
plt.grid(True)
plt.xlim([0, 35.])
... | Rayleigh_damping.ipynb | pxcandeias/py-notebooks | mit |
When the Rayleigh damping is used in MDOF systems, the coefficients $\alpha$ and $\beta$ can be computed in order to give an appropriate damping coefficient value for a given frequency range, related to the vibration modes of interest for the dynamic analysis. This is achieved by setting a simple two equation system wh... | f1, f2 = 1., 4.
z1, z2 = 0.02, 0.05
w1 = 2.*np.pi*f1
w2 = 2.*np.pi*f2
alpha, beta = np.linalg.solve([[1./(2.*w1), w1/2.], [1./(2.*w2), w2/2.]], [z1, z2])
print('Alpha={:.6f}\nBeta={:.6f}'.format(alpha, beta)) | Rayleigh_damping.ipynb | pxcandeias/py-notebooks | mit |
We can check that the Rayleigh damping assumes the required values at the desired frequencies, although may vary considerably for other frequencies: | zn_a = alpha/(2.*wn)
zn_b = (beta*wn)/2.
plt.hold(True)
plt.plot(wn, zn_a+zn_b, label='Rayleigh damping')
plt.plot(wn, zn_a, label='mass proportional')
plt.plot(wn, zn_b, label='stiffness proportional')
plt.plot(w1, z1, 'o')
plt.plot(w2, z2, 'o')
plt.axvline(w1, ls=':')
plt.axhline(z1, ls=':')
plt.axvline(w2, ls=':')
p... | Rayleigh_damping.ipynb | pxcandeias/py-notebooks | mit |
다음으로 이 코퍼스를 입력 인수로 하여 Word2Vec 클래스 객체를 생성한다. 이 시점에 트레이닝이 이루어진다. | from gensim.models.word2vec import Word2Vec
%%time
model = Word2Vec(sentences) | 30. 딥러닝/06. 단어 임베딩의 원리와 gensim.word2vec 사용법.ipynb | zzsza/Datascience_School | mit |
트레이닝이 완료되면 init_sims 명령으로 필요없는 메모리를 unload 시킨다. | model.init_sims(replace=True) | 30. 딥러닝/06. 단어 임베딩의 원리와 gensim.word2vec 사용법.ipynb | zzsza/Datascience_School | mit |
이제 이 모형에서 다음과 같은 메서드를 사용할 수 있다. 보다 자세한 내용은 https://radimrehurek.com/gensim/models/word2vec.html 를 참조한다.
similarity : 두 단어의 유사도 계산
most_similar : 가장 유사한 단어를 출력 | model.similarity('actor', 'actress')
model.similarity('he', 'she')
model.similarity('actor', 'she')
model.most_similar("villain") | 30. 딥러닝/06. 단어 임베딩의 원리와 gensim.word2vec 사용법.ipynb | zzsza/Datascience_School | mit |
most_similar 메서드는 positive 인수와 negative 인수를 사용하여 다음과 같은 단어간 관계도 찾을 수 있다.
actor + he - actress = she | model.most_similar(positive=['actor', 'he'], negative='actress', topn=1) | 30. 딥러닝/06. 단어 임베딩의 원리와 gensim.word2vec 사용법.ipynb | zzsza/Datascience_School | mit |
이번에는 네이버 영화 감상 코퍼스를 사용하여 한국어 단어 임베딩을 해보자. | import codecs
def read_data(filename):
with codecs.open(filename, encoding='utf-8', mode='r') as f:
data = [line.split('\t') for line in f.read().splitlines()]
data = data[1:] # header 제외
return data
train_data = read_data('/home/dockeruser/data/nsmc/ratings_train.txt')
from konlpy.tag impo... | 30. 딥러닝/06. 단어 임베딩의 원리와 gensim.word2vec 사용법.ipynb | zzsza/Datascience_School | mit |
Now that we have an idea of how to use h5py to read in an h5 file, let's try it out. Note that if the h5 file is stored in a different directory than where you are running your notebook, you need to include the path (either relative or absolute) to the directory where that data file is stored. Use os.path.join to creat... | # Note that you will need to update this filepath for your local machine
f = h5py.File('/Users/olearyd/Git/data/NEON_D02_SERC_DP3_368000_4306000_reflectance.h5','r') | tutorials/Python/Hyperspectral/intro-hyperspectral/Intro_NEON_AOP_HDF5_Reflectance_Tiles_py/Intro_NEON_AOP_HDF5_Reflectance_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
This 3-D shape (1000,1000,426) corresponds to (y,x,bands), where (x,y) are the dimensions of the reflectance array in pixels. Hyperspectral data sets are often called "cubes" to reflect this 3-dimensional shape.
<figure>
<a href="https://raw.githubusercontent.com/NEONScience/NEON-Data-Skills/main/graphics/hyperspec... | #define the wavelengths variable
wavelengths = serc_refl['Metadata']['Spectral_Data']['Wavelength']
#View wavelength information and values
print('wavelengths:',wavelengths) | tutorials/Python/Hyperspectral/intro-hyperspectral/Intro_NEON_AOP_HDF5_Reflectance_Tiles_py/Intro_NEON_AOP_HDF5_Reflectance_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Here we can see that we extracted a 2-D array (1000 x 1000) of the scaled reflectance data corresponding to the wavelength band 56. Before we can use the data, we need to clean it up a little. We'll show how to do this below.
Scale factor and No Data Value
This array represents the scaled reflectance for band 56. Reca... | #View and apply scale factor and data ignore value
scaleFactor = serc_reflArray.attrs['Scale_Factor']
noDataValue = serc_reflArray.attrs['Data_Ignore_Value']
print('Scale Factor:',scaleFactor)
print('Data Ignore Value:',noDataValue)
b56[b56==int(noDataValue)]=np.nan
b56 = b56/scaleFactor
print('Cleaned Band 56 Reflect... | tutorials/Python/Hyperspectral/intro-hyperspectral/Intro_NEON_AOP_HDF5_Reflectance_Tiles_py/Intro_NEON_AOP_HDF5_Reflectance_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
Here you can see that adjusting the colorlimit displays features (eg. roads, buildings) much better than when we set the colormap limits to the entire range of reflectance values.
Extension: Basic Image Processing -- Contrast Stretch & Histogram Equalization
We can also try out some basic image processing to better vi... | from skimage import exposure
from IPython.html.widgets import *
def linearStretch(percent):
pLow, pHigh = np.percentile(b56[~np.isnan(b56)], (percent,100-percent))
img_rescale = exposure.rescale_intensity(b56, in_range=(pLow,pHigh))
plt.imshow(img_rescale,extent=serc_ext,cmap='gist_earth')
#cbar = plt... | tutorials/Python/Hyperspectral/intro-hyperspectral/Intro_NEON_AOP_HDF5_Reflectance_Tiles_py/Intro_NEON_AOP_HDF5_Reflectance_Tiles_py.ipynb | NEONScience/NEON-Data-Skills | agpl-3.0 |
텐서플로 1 코드를 텐서플로 2로 바꾸기
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/migrate">
<img src="https://www.tensorflow.org/images/tf_logo_32px.png" />
TensorFlow.org에서 보기</a>
</td>
<td>
<a target="_blank" href="https://colab.research.goog... | import tensorflow as tf
import tensorflow_datasets as tfds | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
저수준 변수와 연산 실행
저수준 API를 사용하는 예는 다음과 같습니다:
재사용을 위해 변수 범위(variable scopes)를 사용하기
v1.get_variable로 변수를 만들기
명시적으로 컬렉션을 참조하기
다음과 같은 메서드를 사용하여 암묵적으로 컬렉션을 참조하기:
v1.global_variables
v1.losses.get_regularization_loss
그래프 입력을 위해 v1.placeholder를 사용하기
session.run으로 그래프를 실행하기
변수를 수동으로 초기화하기
변환 전
다음 코드는 텐서플로 1.x를 사용한 코드에서 볼... | W = tf.Variable(tf.ones(shape=(2,2)), name="W")
b = tf.Variable(tf.zeros(shape=(2)), name="b")
@tf.function
def forward(x):
return W * x + b
out_a = forward([1,0])
print(out_a)
out_b = forward([0,1])
regularizer = tf.keras.regularizers.l2(0.04)
reg_loss = regularizer(W) | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
tf.layers 기반의 모델
v1.layers 모듈은 변수를 정의하고 재사용하기 위해 v1.variable_scope에 의존하는 층 함수를 포함합니다.
변환 전
```python
def model(x, training, scope='model'):
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
x = tf.layers.conv2d(x, 32, 3, activation=tf.nn.relu,
kernel_regularizer=tf.contrib.layers.l2_regularizer(0.04))... | model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.04),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.1),
t... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
변수와 v1.layers의 혼용
기존 코드는 종종 저수준 TF 1.x 변수와 고수준 v1.layers 연산을 혼용합니다.
변경 전
```python
def model(x, training, scope='model'):
with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):
W = tf.get_variable(
"W", dtype=tf.float32,
initializer=tf.ones(shape=x.shape),
regularizer=tf.contrib.layers.l2_regulariz... | # 모델에 추가하기 위해 사용자 정의 층을 만듭니다.
class CustomLayer(tf.keras.layers.Layer):
def __init__(self, *args, **kwargs):
super(CustomLayer, self).__init__(*args, **kwargs)
def build(self, input_shape):
self.w = self.add_weight(
shape=input_shape[1:],
dtype=tf.float32,
initializer=tf.keras.initi... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
노트:
클래스 상속으로 만든 케라스 모델과 층은 v1 그래프(연산간의 의존성이 자동으로 제어되지 않습니다)와 즉시 실행 모드 양쪽에서 실행될 수 있어야 합니다.
오토그래프(autograph)와 의존성 자동 제어(automatic control dependency)를 위해 tf.function()으로 call() 메서드를 감쌉니다.
call 메서드에 training 매개변수를 추가하는 것을 잊지 마세요.
경우에 따라 이 값은 tf.Tensor가 됩니다.
경우에 따라 이 값은 파이썬 불리언(boolean)이 됩니다.
self.add_weight()를 사용하... | datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True)
mnist_train, mnist_test = datasets['train'], datasets['test'] | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
그 다음 훈련용 데이터를 준비합니다:
각 이미지의 스케일을 조정합니다.
샘플의 순서를 섞습니다.
이미지와 레이블(label)의 배치를 만듭니다. | BUFFER_SIZE = 10 # 실전 코드에서는 더 큰 값을 사용합니다.
BATCH_SIZE = 64
NUM_EPOCHS = 5
def scale(image, label):
image = tf.cast(image, tf.float32)
image /= 255
return image, label | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
간단한 예제를 위해 5개의 배치만 반환하도록 데이터셋을 자릅니다: | train_data = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE)
test_data = mnist_test.map(scale).batch(BATCH_SIZE)
STEPS_PER_EPOCH = 5
train_data = train_data.take(STEPS_PER_EPOCH)
test_data = test_data.take(STEPS_PER_EPOCH)
image_batch, label_batch = next(iter(train_data)) | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
케라스 훈련 루프 사용하기
훈련 과정을 세부적으로 제어할 필요가 없다면 케라스의 내장 메서드인 fit, evaluate, predict를 사용하는 것이 좋습니다. 이 메서드들은 모델 구현(Sequential, 함수형 API, 클래스 상속)에 상관없이 일관된 훈련 인터페이스를 제공합니다.
이 메서드들의 장점은 다음과 같습니다:
넘파이 배열, 파이썬 제너레이터, tf.data.Datasets을 사용할 수 있습니다.
자동으로 규제와 활성화 손실을 적용합니다.
다중 장치 훈련을 위해 tf.distribute을 지원합니다.
임의의 호출 가능한 객체를 손실과 측정 지표로 사용... | model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.02),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.1),
t... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
사용자 정의 훈련 루프 만들기
케라스 모델의 훈련 스텝(step)이 좋지만 그 외 다른 것을 더 제어하려면 자신만의 데이터 반복 루프를 만들고 tf.keras.model.train_on_batch 메서드를 사용해 보세요.
기억할 점: 많은 것을 tf.keras.Callback으로 구현할 수 있습니다.
이 메서드는 앞에서 언급한 메서드의 장점을 많이 가지고 있고 사용자가 바깥쪽 루프를 제어할 수 있습니다.
훈련하는 동안 성능을 확인하기 위해 tf.keras.model.test_on_batch나 tf.keras.Model.evaluate 메서드를 사용할 수도 있습니다.
... | # 사용자 정의 층이 없는 모델입니다.
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
for epoch in range(NUM_EPOCHS):
# 누적된 측정값을 초기화합니다.
model.reset_metrics()
for image_batch, label_batch in train_data:
result = model.tr... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
<a id="custom_loops"/>
훈련 단계 커스터마이징
자유도를 높이고 제어를 더 하려면 다음 세 단계를 사용해 자신만의 훈련 루프를 구현할 수 있습니다:
샘플 배치를 만드는 파이썬 제너레이터나 tf.data.Dataset을 반복합니다.
tf.GradientTape을 사용하여 그래디언트를 계산합니다.
tf.keras.optimizer를 사용하여 모델의 가중치 변수를 업데이트합니다.
기억할 점:
클래스 상속으로 만든 층과 모델의 call 메서드에는 항상 training 매개변수를 포함하세요.
모델을 호출할 때 training 매개변수를 올바르게 지정했는지... | model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
kernel_regularizer=tf.keras.regularizers.l2(0.02),
input_shape=(28, 28, 1)),
tf.keras.layers.MaxPooling2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.1),
t... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
새로운 스타일의 측정 지표
텐서플로 2.0에서 측정 지표와 손실은 객체입니다. 이 객체는 즉시 실행 모드와 tf.function에서 모두 사용할 수 있습니다.
손실은 호출 가능한 객체입니다. 매개변수로 (y_true, y_pred)를 기대합니다: | cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True)
cce([[1, 0]], [[-1.0,3.0]]).numpy() | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
측정 객체는 다음과 같은 메서드를 가집니다:
update_state() — 새로운 측정값을 추가합니다.
result() — 누적된 측정 결과를 얻습니다.
reset_states() — 모든 측정 내용을 지웁니다.
이 객체는 호출 가능합니다. update_state 메서드처럼 새로운 측정값과 함께 호출하면 상태를 업데이트하고 새로운 측정 결과를 반환합니다.
측정 변수를 수동으로 초기화할 필요가 없습니다. 텐서플로 2.0은 자동으로 의존성을 관리하기 때문에 어떤 경우에도 신경 쓸 필요가 없습니다.
다음은 측정 객체를 사용하여 사용자 정의 훈련 루프 안에서 평균 손실을... | # 측정 객체를 만듭니다.
loss_metric = tf.keras.metrics.Mean(name='train_loss')
accuracy_metric = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
@tf.function
def train_step(inputs, labels):
with tf.GradientTape() as tape:
predictions = model(inputs, training=True)
regularization_loss = tf.math.add_n... | site/ko/guide/migrate.ipynb | tensorflow/docs-l10n | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.