markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Save data to pickle
print("weights\n", weights) filename = "mlp_xor_weights.pkl" save_object_as_pickle(weights, filename)
_____no_output_____
MIT
lab9/lab9.ipynb
YgLK/ML
Check saved Pickles contents
# check if pickles' contents are saved correctly print("per_acc.pkl\n", pd.read_pickle("per_acc.pkl"), "\n") print("per_wght.pkl\n", pd.read_pickle("per_wght.pkl"), "\n") print("mlp_xor_weights.pkl\n", pd.read_pickle("mlp_xor_weights.pkl"), "\n")
per_acc.pkl [(1.0, 1.0), (0.6666666666666666, 0.6666666666666666), (0.825, 0.8666666666666667)] per_wght.pkl [(9.0, -2.0999999999999988, -3.0999999999999996), (-8.0, 4.600000000000016, -22.699999999999974), (-39.0, 0.7999999999999883, 27.30000000000003)] mlp_xor_weights.pkl [array([[2.8713741, 2.8880954], [2.865467 , 2.8870766]], dtype=float32), array([-2.8651741e+00, -1.7966949e-03], dtype=float32), array([[-5.7537994], [ 2.6404846]], dtype=float32), array([-3.0722845], dtype=float32)]
MIT
lab9/lab9.ipynb
YgLK/ML
testing
from load_data import * # load_data()
_____no_output_____
Apache-2.0
wandb/run-20210519_093746-2wg641lq/tmp/code/00-main.ipynb
Programmer-RD-AI/Weather-Clf-V2
Loading the data
from load_data import * X_train,X_test,y_train,y_test = load_data() len(X_train),len(y_train) len(X_test),len(y_test)
_____no_output_____
Apache-2.0
wandb/run-20210519_093746-2wg641lq/tmp/code/00-main.ipynb
Programmer-RD-AI/Weather-Clf-V2
Test Modelling
import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class Test_Model(nn.Module): def __init__(self) -> None: super().__init__() self.c1 = nn.Conv2d(1,64,5) self.c2 = nn.Conv2d(64,128,5) self.c3 = nn.Conv2d(128,256,5) self.fc4 = nn.Linear(256*10*10,256) self.fc6 = nn.Linear(256,128) self.fc5 = nn.Linear(128,4) def forward(self,X): preds = F.max_pool2d(F.relu(self.c1(X)),(2,2)) preds = F.max_pool2d(F.relu(self.c2(preds)),(2,2)) preds = F.max_pool2d(F.relu(self.c3(preds)),(2,2)) # print(preds.shape) preds = preds.view(-1,256*10*10) preds = F.relu(self.fc4(preds)) preds = F.relu(self.fc6(preds)) preds = self.fc5(preds) return preds device = torch.device('cuda') BATCH_SIZE = 32 IMG_SIZE = 112 model = Test_Model().to(device) optimizer = optim.SGD(model.parameters(),lr=0.1) criterion = nn.CrossEntropyLoss() EPOCHS = 125 from tqdm import tqdm PROJECT_NAME = 'Weather-Clf' import wandb test_index += 1 wandb.init(project=PROJECT_NAME,name=f'test') for _ in tqdm(range(EPOCHS)): for i in range(0,len(X_train),BATCH_SIZE): X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device) y_batch = y_train[i:i+BATCH_SIZE].to(device) model.to(device) preds = model(X_batch.float()) preds.to(device) loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long)) optimizer.zero_grad() loss.backward() optimizer.step() wandb.log({'loss':loss.item()}) wandb.finish() # for index in range(10): # print(torch.argmax(preds[index])) # print(y_batch[index]) # print('\n') class Test_Model(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1,16,5) self.conv2 = nn.Conv2d(16,32,5) self.conv3 = nn.Conv2d(32,64,5) self.fc1 = nn.Linear(64*10*10,16) self.fc2 = nn.Linear(16,32) self.fc3 = nn.Linear(32,64) self.fc4 = nn.Linear(64,32) self.fc5 = nn.Linear(32,6) def forward(self,X): preds = F.max_pool2d(F.relu(self.conv1(X)),(2,2)) preds = F.max_pool2d(F.relu(self.conv2(preds)),(2,2)) preds = F.max_pool2d(F.relu(self.conv3(preds)),(2,2)) # print(preds.shape) preds = preds.view(-1,64*10*10) preds = F.relu(self.fc1(preds)) preds = F.relu(self.fc2(preds)) preds = F.relu(self.fc3(preds)) preds = F.relu(self.fc4(preds)) preds = F.relu(self.fc5(preds)) return preds model = Test_Model().to(device) optimizer = optim.SGD(model.parameters(),lr=0.1) criterion = nn.CrossEntropyLoss() # test_index += 1 # wandb.init(project=PROJECT_NAME,name=f'test-{test_index}') # for _ in tqdm(range(EPOCHS)): # for i in range(0,len(X_train),BATCH_SIZE): # X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device) # y_batch = y_train[i:i+BATCH_SIZE].to(device) # model.to(device) # preds = model(X_batch.float()) # preds.to(device) # loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long)) # optimizer.zero_grad() # loss.backward() # optimizer.step() # wandb.log({'loss':loss.item()}) # wandb.finish()
_____no_output_____
Apache-2.0
wandb/run-20210519_093746-2wg641lq/tmp/code/00-main.ipynb
Programmer-RD-AI/Weather-Clf-V2
Modelling
class Test_Model(nn.Module): def __init__(self,conv1_output=16,conv2_output=32,conv3_output=64,fc1_output=16,fc2_output=32,fc3_output=64,activation=F.relu): super().__init__() self.conv3_output = conv3_output self.conv1 = nn.Conv2d(1,conv1_output,5) self.conv2 = nn.Conv2d(conv1_output,conv2_output,5) self.conv3 = nn.Conv2d(conv2_output,conv3_output,5) self.fc1 = nn.Linear(conv3_output*10*10,fc1_output) self.fc2 = nn.Linear(fc1_output,fc2_output) self.fc3 = nn.Linear(fc2_output,fc3_output) self.fc4 = nn.Linear(fc3_output,fc2_output) self.fc5 = nn.Linear(fc2_output,6) self.activation = activation def forward(self,X): preds = F.max_pool2d(self.activation(self.conv1(X)),(2,2)) preds = F.max_pool2d(self.activation(self.conv2(preds)),(2,2)) preds = F.max_pool2d(self.activation(self.conv3(preds)),(2,2)) # print(preds.shape) preds = preds.view(-1,self.conv3_output*10*10) preds = self.activation(self.fc1(preds)) preds = self.activation(self.fc2(preds)) preds = self.activation(self.fc3(preds)) preds = self.activation(self.fc4(preds)) preds = self.activation(self.fc5(preds)) return preds # conv1_output = 32 # conv2_output # conv3_output # fc1_output # fc2_output # fc3_output # activation # optimizer # loss # lr # num of epochs def get_loss(criterion,y,model,X): model.to('cpu') preds = model(X.view(-1,1,112,112).to('cpu').float()) preds.to('cpu') loss = criterion(preds,torch.tensor(y,dtype=torch.long).to('cpu')) loss.backward() return loss.item() def test(net,X,y): device = 'cpu' net.to(device) correct = 0 total = 0 net.eval() with torch.no_grad(): for i in range(len(X)): real_class = torch.argmax(y[i]).to(device) net_out = net(X[i].view(-1,1,112,112).to(device).float()) net_out = net_out[0] predictied_class = torch.argmax(net_out) if predictied_class == real_class: correct += 1 total += 1 net.train() net.to('cuda') return round(correct/total,3) EPOCHS = 3 conv3_outputs = [16,32,64,128] for conv3_output in conv3_outputs: wandb.init(project=PROJECT_NAME,name=f'conv3_output-{conv3_output}') model = Test_Model(conv1_output=32,conv2_output=8,conv3_output=conv3_output).to(device) optimizer = optim.SGD(model.parameters(),lr=0.1) criterion = nn.CrossEntropyLoss() for _ in tqdm(range(EPOCHS)): for i in range(0,len(X_train),BATCH_SIZE): X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device) y_batch = y_train[i:i+BATCH_SIZE].to(device) model.to(device) preds = model(X_batch.float()) preds.to(device) loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long)) optimizer.zero_grad() loss.backward() optimizer.step() wandb.log({'loss':get_loss(criterion,y_train,model,X_train),'accuracy':test(model,X_train,y_train),'val_accuracy':test(model,X_test,y_test),'val_loss':get_loss(criterion,y_test,model,X_test)}) for index in range(10): print(torch.argmax(preds[index])) print(y_batch[index]) print('\n') wandb.finish() # conv2_outputs = [8,16,32,64] # for conv2_output in conv2_outputs: # wandb.init(project=PROJECT_NAME,name=f'conv2_output-{conv2_output}') # model = Test_Model(conv1_output=32,conv2_output=conv2_output).to(device) # optimizer = optim.SGD(model.parameters(),lr=0.1) # criterion = nn.CrossEntropyLoss() # for _ in tqdm(range(EPOCHS)): # for i in range(0,len(X_train),BATCH_SIZE): # X_batch = X_train[i:i+BATCH_SIZE].view(-1,1,112,112).to(device) # y_batch = y_train[i:i+BATCH_SIZE].to(device) # model.to(device) # preds = model(X_batch.float()) # preds.to(device) # loss = criterion(preds,torch.tensor(y_batch,dtype=torch.long)) # optimizer.zero_grad() # loss.backward() # optimizer.step() # wandb.log({'loss':get_loss(criterion,y_train,model,X_train),'accuracy':test(model,X_train,y_train),'val_accuracy':test(model,X_test,y_test),'val_loss':get_loss(criterion,y_test,model,X_test)}) # for index in range(10): # print(torch.argmax(preds[index])) # print(y_batch[index]) # print('\n') # wandb.finish()
_____no_output_____
Apache-2.0
wandb/run-20210519_093746-2wg641lq/tmp/code/00-main.ipynb
Programmer-RD-AI/Weather-Clf-V2
$\newcommand{\xbf}{{\bf x}}\newcommand{\ybf}{{\bf y}}\newcommand{\wbf}{{\bf w}}\newcommand{\Ibf}{\mathbf{I}}\newcommand{\Xbf}{\mathbf{X}}\newcommand{\Rbb}{\mathbb{R}}\newcommand{\vec}[1]{\left[\begin{array}{c}1\end{array}\right]}$ Introduction aux réseaux de neurones : TD 1 (partie 1)Matériel de cours rédigé par Pascal Germain, 2018************
%matplotlib inline from matplotlib import pyplot as plt import numpy as np from math import sqrt import aidecours
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
La libraire pyTorchhttps://pytorch.org/
import torch
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Les tenseurs
torch.tensor?
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Un tenseur peut contenir un scalaire
a = torch.tensor(1.5) a a + 2 a.item()
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Les tenseurs contenant des vecteurs ou des matrices se comportent similairement aux *array numpy*.
v = torch.tensor([1,2,3]) v torch.sum(v) u = torch.tensor([1.,2.,3.]) u torch.log(u) u[0] u[1:] np.array(u) M = torch.tensor([[1.,2.,3.], [4, 5, 6]]) M M.shape 2 * M + 1 M @ u torch.ones((2, 3)) torch.zeros((3, 2)) torch.rand((3, 4)) torch.randn((3, 4))
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
**ATTENTION:** Les *tenseurs pyTorch* sont plus capricieux sur le type des variables que les *array numpy*.
v = np.array([.3, .6, .9]) v.dtype w = np.array([-1, 3, 8]) w.dtype v_tensor = torch.from_numpy(v) v_tensor.dtype w_tensor = torch.from_numpy(w) w_tensor.dtype print('v:', v.dtype) print('w:', w.dtype) result = v @ w print('v @ w:', result.dtype) result print('v_tensor:', w_tensor.dtype) print('w_tensor:', v_tensor.dtype) result = v_tensor @ w_tensor print('v_tensor @ w_tensor:', result.dtype) w_tensor = torch.tensor(w, dtype=torch.float64) w_tensor print('v_tensor:', v_tensor.dtype) print('w_tensor:', w_tensor.dtype) result = v_tensor @ w_tensor print('v_tensor @ x_tensor:', result.dtype)
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Dérivation automatique Lors de l'initialisation d'un tenseur, l'argument `requires_grad=True` indique que nous désirons calculer le gradient des variables contenues dans le tenseur.
x = torch.tensor(3., requires_grad=True)
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Le graphe de calcul est alors bâti au fur et à mesure des opérations impliquant les tenseurs.
F = x ** 2
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
La fonction `F.backward()` parcours le graphe de calcul en sens inverse et calcule le gradient de la fonction $F$ selon les variables voulues.
F.backward()
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Après avoir exécuté la fonction `backward()`, l'attribut `grad` des tenseurs impliqués dans le calcul contient la valeur du gradient calculé au point courant. Ici, on aura la valeur :$$\left[\frac{\partial F(x)}{\partial x}\right]_{x=3} = \big[\,2\,x\,\big]_{x=3} = 6$$
x.grad
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Illustrons le fonctionnement de la dérivation par quelques autres exemples
x = torch.linspace(-1, 1, 11, requires_grad=True) x quad = x @ x quad quad.backward() x.grad a = torch.tensor(-3., requires_grad=True) b = torch.tensor(2., requires_grad=True) m = a*b m.backward() print('a.grad =', a.grad) print('b.grad =', b.grad) a = torch.tensor(-3., requires_grad=True) b = torch.tensor(2., requires_grad=True) m = 2*a + b m.backward() print('a.grad =', a.grad) print('b.grad =', b.grad) a = torch.tensor(3., requires_grad=True) b = torch.tensor(2., requires_grad=False) m = a ** b m.backward() print('a.grad =', a.grad) print('b.grad =', b.grad) a = torch.tensor(-3., requires_grad=True) b = torch.tensor(2., requires_grad=True) c = torch.tensor(4., requires_grad=True) m1 = (a + b) m2 = m1 * c m2.backward() print('a.grad =', a.grad) print('b.grad =', b.grad) print('c.grad =', c.grad) vecteur_a = torch.tensor([-1., 2, 3], requires_grad=True) vecteur_b = torch.ones(3, requires_grad=True) produit = vecteur_a @ vecteur_b produit.backward() print('vecteur_a =', vecteur_a, '; vecteur_a.grad =', vecteur_a.grad) print('vecteur_b =', vecteur_b, '; vecteur_b.grad =', vecteur_b.grad) print('produit =', produit.item()) vecteur_a = torch.tensor([1., 4, 9], requires_grad=True) result = torch.sum(torch.sqrt(vecteur_a)) result.backward() print('vecteur_a =', vecteur_a, '; vecteur_a.grad =', vecteur_a.grad) print('result =', result.item())
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Descente de gradient Commencons par un exemple en une dimension.$$f(x) = x^2 - x + 3$$
def fonction_maison(x): return x**2 - x + 3 x = np.linspace(-2, 2) plt.plot(x, fonction_maison(x) ) plt.plot((.5,),(fonction_maison(.5)), 'r*'); eta = .4 # Pas de gradient T = 20 # Nombre d'itérations # Initialisation aléatoire x = torch.randn(1, requires_grad=True) for t in range(T): # Calcul de la fonction objectif val = fonction_maison(x) # Calcul des gradients val.backward() print('Interation', t+1, ': x =', x.item(), '; f(x) =', val.item(), '; f\'(x) =', x.grad.item()) # Mise à jour de la variable x with torch.no_grad(): x -= eta * x.grad # Remise à zéro du gradient x.grad.zero_()
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Reprenons l'exemple des moindres carrés présentés dans les transparents du cours.$$\min_\wbf \left[\frac1n \sum_{i=1}^n (\wbf\cdot\xbf_i- y_i)^2\right].$$
def moindre_carres_objectif(x, y, w): return np.mean((x @ w - y) ** 2) x = np.array([(1,1), (0,-1), (2,.5)]) y = np.array([-1, 3, 2]) fonction_objectif = lambda w: moindre_carres_objectif(x, y, w) aidecours.show_2d_function(fonction_objectif, -5, 5, .5) w_opt = np.linalg.inv(x.T @ x) @ x.T @ y aidecours.show_2d_function(fonction_objectif, -5, 5, .5, optimal=w_opt)
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Nous créons une classe `moindre_carres` avec un fonctionnement semblable aux algorithmes de *scikit-learn* qui résout le problème des moindres carrés par descente de gradient, en utilisant les fonctionnalités de *pyTorch*
class moindre_carres: def __init__(self, eta=0.4, nb_iter=50, seed=None): self.eta=eta self.nb_iter=nb_iter self.seed = seed def fit(self, x, y): if self.seed is not None: torch.manual_seed(seed) x = torch.tensor(x, dtype=torch.float32) y = torch.tensor(y, dtype=torch.float32) n, d = x.shape self.w = torch.randn(d, requires_grad=True) self.w_list = list() # Servira à garder une trace de la descente de gradient self.obj_list = list() for t in range(self.nb_iter+1): loss = torch.mean((x @ self.w - y) ** 2) self.w_list.append(np.array(self.w.detach())) self.obj_list.append(loss.item()) if t == self.nb_iter: break with torch.no_grad(): loss.backward() self.w -= self.eta * self.w.grad self.w.grad.zero_() def predict(self, x): x = torch.tensor(x, dtype=torch.float32) pred = x @ self.w.detach() return pred.numpy()
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Exécution de l'algorithme.
eta = 0.4 # taille du pas nb_iter = 20 # nombre d'itérations algo = moindre_carres(eta, nb_iter) algo.fit(x, y) fig, axes = plt.subplots(1, 2, figsize=(14.5, 4)) aidecours.sgd_trajectoire(algo.w_list, fonction_objectif, w_opt=w_opt, ax=axes[0]) aidecours.sgd_courbe_objectif(algo.obj_list, ax=axes[1], obj_opt=fonction_objectif(w_opt))
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
ExerciceDans cet exercice, nous vous demandons de vous inspirer de la classe `moindre_carrees` ci-haut et de l'adapter au problème de la régression logistique présenté dans les transparents du cours.
from sklearn.datasets import make_blobs xx, yy = make_blobs(n_samples=100, centers=2, n_features=2, cluster_std=1, random_state=0) aidecours.show_2d_dataset(xx, yy)
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Illustrons la fonction à optimiser (avec $\lambda=0.01$): $$\frac1n \sum_{i=1}^n - y_i \wbf\cdot\xbf_i + \log(1+e^{\wbf\cdot\xbf_i})+ \frac\rho2\|\wbf\|^2\,.$$
def sigmoid(x): return 1 / (1+np.exp(-x)) def calc_perte_logistique(w, x, y, rho): pred = sigmoid(x @ w) pred[y==0] = 1-pred[y==0] return np.mean(-np.log(pred)) + rho*w @ w/2 fct_objectif = lambda w: calc_perte_logistique(w, xx, yy, 0.01) aidecours.show_2d_function(fct_objectif, -4, 4, .05)
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Compléter le code de la classe suivante.
class regression_logistique: def __init__(self, rho=.01, eta=0.4, nb_iter=50, seed=None): self.rho = rho self.eta = eta self.nb_iter = nb_iter self.seed = seed def fit(self, x, y): if self.seed is not None: torch.manual_seed(seed) x = torch.tensor(x, dtype=torch.float32) y = torch.tensor(y, dtype=torch.float32) n, d = x.shape self.w = torch.randn(d, requires_grad=True) self.w_list = list() # Servira à garder une trace de la descente de gradient self.obj_list = list() for t in range(self.nb_iter+1): pass # Compléter def predict(self, x): x = torch.tensor(x, dtype=torch.float32) pred = x @ self.w.detach() return np.array(pred.numpy() > .5, dtype=np.int)
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Exécuter le code suivant pour vérifier le bon fonctionnement de votre algorithme. Essayer ensuite de varier les paramètres `rho`, `eta` et `nb_iter` afin d'évaluer leur impact sur le résultat obtenu.
rho = 0.01 eta = 0.4 # taille du pas nb_iter = 20 # nombre d'itérations algo = regression_logistique(rho, eta, nb_iter) algo.fit(xx, yy) fig, axes = plt.subplots(1, 3, figsize=(16, 4)) aidecours.sgd_trajectoire(algo.w_list, fct_objectif, -4, 4, .05, ax=axes[0]) aidecours.sgd_courbe_objectif(algo.obj_list, ax=axes[1]) aidecours.show_2d_predictions(xx, yy, algo.predict, ax=axes[2]);
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
Reprenons l'exercice précédent en ajoutant l'apprentissange d'un *biais* à la régression logistique:$$\frac1n \sum_{i=1}^n - y_i (\wbf\cdot\xbf_i+b) + \log(1+e^{\wbf\cdot\xbf_i+b})+ \frac\rho2\|\wbf\|^2\,.$$
class regression_logistique_avec_biais: def __init__(self, rho=.01, eta=0.4, nb_iter=50, seed=None): self.rho = rho self.eta = eta self.nb_iter = nb_iter self.seed = seed def fit(self, x, y): if self.seed is not None: torch.manual_seed(seed) x = torch.tensor(x, dtype=torch.float32) y = torch.tensor(y, dtype=torch.float32) n, d = x.shape self.w = torch.randn(d, requires_grad=True) self.b = torch.zeros(1, requires_grad=True) self.w_list = list() # Servira à garder une trace de la descente de gradient self.obj_list = list() for t in range(self.nb_iter+1): pass # Compléter def predict(self, x): x = torch.tensor(x, dtype=torch.float32) pred = x @ self.w.detach() + self.b.item() return np.array(pred.numpy() > .5, dtype=np.int) rho = 0.01 eta = 0.4 # taille du pas nb_iter = 20 # nombre d'itérations algo = regression_logistique_avec_biais(rho, eta, nb_iter) algo.fit(xx, yy) fig, axes = plt.subplots(1, 2, figsize=(12, 4)) aidecours.sgd_courbe_objectif(algo.obj_list, ax=axes[0]) aidecours.show_2d_predictions(xx, yy, algo.predict, ax=axes[1]);
_____no_output_____
CC-BY-4.0
travaux_diriges/TD1 - Intro a pyTorch - Partie 1.ipynb
pgermain/cours2018-Intro_aux_r-seaux_de_neurones
View source on GitHub Notebook Viewer Run in Google Colab Install Earth Engine API and geemapInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geemap](https://github.com/giswqs/geemap). The **geemap** Python package is built upon the [ipyleaflet](https://github.com/jupyter-widgets/ipyleaflet) and [folium](https://github.com/python-visualization/folium) packages and implements several methods for interacting with Earth Engine data layers, such as `Map.addLayer()`, `Map.setCenter()`, and `Map.centerObject()`.The following script checks if the geemap package has been installed. If not, it will install geemap, which automatically installs its [dependencies](https://github.com/giswqs/geemapdependencies), including earthengine-api, folium, and ipyleaflet.**Important note**: A key difference between folium and ipyleaflet is that ipyleaflet is built upon ipywidgets and allows bidirectional communication between the front-end and the backend enabling the use of the map to capture user input, while folium is meant for displaying static data only ([source](https://blog.jupyter.org/interactive-gis-in-jupyter-with-ipyleaflet-52f9657fa7a)). Note that [Google Colab](https://colab.research.google.com/) currently does not support ipyleaflet ([source](https://github.com/googlecolab/colabtools/issues/60issuecomment-596225619)). Therefore, if you are using geemap with Google Colab, you should use [`import geemap.eefolium`](https://github.com/giswqs/geemap/blob/master/geemap/eefolium.py). If you are using geemap with [binder](https://mybinder.org/) or a local Jupyter notebook server, you can use [`import geemap`](https://github.com/giswqs/geemap/blob/master/geemap/geemap.py), which provides more functionalities for capturing user input (e.g., mouse-clicking and moving).
# Installs geemap package import subprocess try: import geemap except ImportError: print('geemap package not installed. Installing ...') subprocess.check_call(["python", '-m', 'pip', 'install', 'geemap']) # Checks whether this notebook is running on Google Colab try: import google.colab import geemap.eefolium as geemap except: import geemap # Authenticates and initializes Earth Engine import ee try: ee.Initialize() except Exception as e: ee.Authenticate() ee.Initialize()
_____no_output_____
MIT
JavaScripts/Image/CenterPivotIrrigationDetector.ipynb
OIEIEIO/earthengine-py-notebooks
Create an interactive map The default basemap is `Google MapS`. [Additional basemaps](https://github.com/giswqs/geemap/blob/master/geemap/basemaps.py) can be added using the `Map.add_basemap()` function.
Map = geemap.Map(center=[40,-100], zoom=4) Map
_____no_output_____
MIT
JavaScripts/Image/CenterPivotIrrigationDetector.ipynb
OIEIEIO/earthengine-py-notebooks
Add Earth Engine Python script
# Add Earth Engine dataset # Center-pivot Irrigation Detector. # # Finds circles that are 500m in radius. Map.setCenter(-106.06, 37.71, 12) # A nice NDVI palette. palette = [ 'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901', '66A000', '529400', '3E8601', '207401', '056201', '004C00', '023B01', '012E01', '011D01', '011301'] # Just display the image with the palette. image = ee.Image('LANDSAT/LC08/C01/T1_TOA/LC08_034034_20170608') ndvi = image.normalizedDifference(['B5','B4']) Map.addLayer(ndvi, {'min': 0, 'max': 1, 'palette': palette}, 'Landsat NDVI') # Find the difference between convolution with circles and squares. # This difference, in theory, will be strongest at the center of # circles in the image. This region is filled with circular farms # with radii on the order of 500m. farmSize = 500; # Radius of a farm, in meters. circleKernel = ee.Kernel.circle(farmSize, 'meters') squareKernel = ee.Kernel.square(farmSize, 'meters') circles = ndvi.convolve(circleKernel) squares = ndvi.convolve(squareKernel) diff = circles.subtract(squares) # Scale by 100 and find the best fitting pixel in each neighborhood. diff = diff.abs().multiply(100).toByte() max = diff.focal_max({'radius': farmSize * 1.8, 'units': 'meters'}) # If a pixel isn't the local max, set it to 0. local = diff.where(diff.neq(max), 0) thresh = local.gt(2) # Here, we highlight the maximum differences as "Kernel Peaks" # and draw them in red. peaks = thresh.focal_max({'kernel': circleKernel}) Map.addLayer(peaks.updateMask(peaks), {'palette': 'FF3737'}, 'Kernel Peaks') # Detect the edges of the features. Discard the edges with lower intensity. canny = ee.Algorithms.CannyEdgeDetector(ndvi, 0) canny = canny.gt(0.3) # Create a "ring" kernel from two circular kernels. inner = ee.Kernel.circle(farmSize - 20, 'meters', False, -1) outer = ee.Kernel.circle(farmSize + 20, 'meters', False, 1) ring = outer.add(inner, True) # Highlight the places where the feature edges best match the circle kernel. centers = canny.convolve(ring).gt(0.5).focal_max({'kernel': circleKernel}) Map.addLayer(centers.updateMask(centers), {'palette': '4285FF'}, 'Ring centers')
_____no_output_____
MIT
JavaScripts/Image/CenterPivotIrrigationDetector.ipynb
OIEIEIO/earthengine-py-notebooks
Display Earth Engine data layers
Map.addLayerControl() # This line is not needed for ipyleaflet-based Map. Map
_____no_output_____
MIT
JavaScripts/Image/CenterPivotIrrigationDetector.ipynb
OIEIEIO/earthengine-py-notebooks
Technical TASK 2 :- Prediction using UnSupervised MLIn this task, we are going to predict the optimum number of clusters from the given iris dataset and represent it visually. This includes unsupervised learning. Task Completed for The Sparks Foundation Internship Program Data Science & Business Analytics Internship Task_2 Author: Muhammad Haseeb Aslam Step 0: Importing Libraries needed to perform task
# Importing all the libraries needed in this notebook import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn import datasets
_____no_output_____
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
Step 1 : Reading the data-set
# Loading and Reading the iris dataset # Data available at the link - 'https://bit.ly/3kXTdox' data = pd.read_csv('Iris.csv') print('Data import successfull') data.head(10) # loads the first five rows data.tail() # loads the last five rows # Checking for NaN values data.isna().sum()
_____no_output_____
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
NaN standing for not a number, is a numeric data type used to represent any value that is undefined or unpresentable. For example, 0/0 is undefined as a real number and is, therefore, represented by NaN. So, in this dataset, we don't have such values.
# Checking statistical description data.describe()
_____no_output_____
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
Now, let's check for unique classes in the dataset.
print(data.Species.nunique()) print(data.Species.value_counts())
3 Iris-versicolor 50 Iris-virginica 50 Iris-setosa 50 Name: Species, dtype: int64
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
Step 2: Data Visualization
sns.set(style = 'whitegrid') iris = sns.load_dataset('iris'); ax = sns.stripplot(x ='species',y = 'sepal_length',data = iris); plt.title('Iris Dataset') plt.show() sns.boxplot(x='species',y='sepal_width',data=iris) plt.title("Iris Dataset") plt.show() sns.boxplot(x='species',y='petal_width',data=iris) plt.title("Iris Dataset") plt.show() sns.boxplot(x='species',y='petal_length',data=iris) plt.title("Iris Dataset") plt.show() # Count plot sns.countplot(x='species', data=iris, palette="OrRd") plt.title("Count of different species in Iris dataset") plt.show() #This is needed for the analysis of two variables, for determining the empirical relationship between them. sns.heatmap(data.corr(), annot=True,cmap='RdYlGn') plt.title("Heat-Map") plt.show() iris1 = data.corr() #finding correlation between variables of iris dataset fig,ax=plt.subplots(figsize=(10,10)) sns.heatmap(iris1,vmin=0,vmax=1,square=True,annot=True,linewidth=1)
_____no_output_____
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
Heatmap is a two-dimensional graphical representation of data where the individual values that are contained in a matrix are represented as colors. Or we can also say that these Heat maps display numeric tabular data where the cells are colored depending upon the contained value.Heat maps are great for making trends in this kind of data more readily apparent, particularly when the data is ordered and there is clustering.The columns with the correlation 1 are the best correlated and vice versa.
import seaborn as sns sns.set(style="ticks", color_codes=True) iris = sns.load_dataset("iris") g = sns.pairplot(iris) import matplotlib.pyplot as plt plt.show()
_____no_output_____
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
Pairplots are a really simple way to visualize relationships between each variable. It produces a matrix of relationships between each variable in the data for an instant examination of our data. Step 3 : Finding the optimum number of clusters using k-means clustering
# Finding the optimum number of clusters using k-means x = data.iloc[:,[0,1,2,3]].values from sklearn.cluster import KMeans wcss = [] for i in range(1,11): kmeans = KMeans(n_clusters=i, init='k-means++', max_iter=300, n_init=10, random_state=0) kmeans.fit(x) ## appending the WCSS to the list (kmeans.inertia_ returns the WCSS value for an initialized cluster) wcss.append(kmeans.inertia_) print('k:',i ,"wcss:",kmeans.inertia_) # Plotting the results onto a line graph, allowing us to observe 'The elbow' plt.plot(range(1,11),wcss) plt.title('The Elbow Method') plt.xlabel('Number of Clusters') plt.ylabel('WCSS') plt.show()
_____no_output_____
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
We can see that after 3 the drop in WCSS is minimal. So we choose 3 as the optimal number of clusters. Step 4 : Initializing K-Means With Optimum Number Of Clusters
# Fitting K-Means to the Dataset kmeans = KMeans(n_clusters = 3, init = 'k-means++',max_iter = 300, n_init = 10, random_state = 0) # Returns a label for each data point based on the number of clusters y_kmeans = kmeans.fit_predict(x)
_____no_output_____
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
Step 5 : Predicting Values
y_kmeans
_____no_output_____
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
Step 6 : Visualizing the Clusters
# Visualising the clusters plt.figure(figsize=(10,10)) plt.scatter(x[y_kmeans==0,0],x[y_kmeans==0,1],s=100,c='red',label='Iris-setosa') plt.scatter(x[y_kmeans==1,0],x[y_kmeans==1,1],s=100,c='blue',label='Iris-versicolour') plt.scatter(x[y_kmeans==2,0],x[y_kmeans==2,1],s=100,c='green',label='Iris-virginica') # Plotting the centroids of the clusters plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=100,c='yellow',label='Centroids') plt.title('Iris Flower Clusters') plt.xlabel('Sepal Length in cm') plt.ylabel('Petal Length in cm') plt.legend() plt.show()
_____no_output_____
MIT
Task2/Task_2_TSF(UnSupervised Learning-Prediction).ipynb
HaseebRajput007/The-Spark-Foundation-Internship
[Table of contents](../toc.ipynb) Plotting packages* Until now, we were just able to return results via `print()` command.* However, as humans depend very much on vision, data visualization is urgently needed. Matplotlib* Very common and widely used is the [matplotlib](https://matplotlib.org/) package.* Matplotlib provides with `pyplot` module very similar plotting commands as Matlab.* Matplotlib is packaged and available through pip and conda.* Let's create our first plot.
from matplotlib import pyplot as plt %matplotlib inline
_____no_output_____
MIT
02_tools-and-packages/01_plot-packages.ipynb
FelixBleimund/py-algorithms-4-automotive-engineering
* The first line of code import the pyplot module, which is very convenient for most simple plots.* The second line is a special Jupyter magic command to present the plots instantly. Basic plotting
# First, we create some data to plot, which is not that handy with lists. x = [i for i in range(-20, 20)] y = [x[i]**2 for i in range(0,40)] # Now the plot command plt.plot(x, y) plt.show() # Here the same plot with axis labels plt.plot(x, y) plt.xlabel("samples") plt.ylabel("$x^2$") # You can use LaTeX's math support plt.show() # Some line style arguments and a title plt.plot(x, y, "k--") plt.xlabel("samples") plt.ylabel("$x^2$") # You can use LaTeX's math support plt.title("My parabola") plt.show()
_____no_output_____
MIT
02_tools-and-packages/01_plot-packages.ipynb
FelixBleimund/py-algorithms-4-automotive-engineering
Multiple plots in one figureTo present two time series, we will create an additional list of values.
import math y2 = [math.sin(x[i]) for i in range(0,40)] plt.subplot(2, 1, 1) plt.plot(x, y, 'o-') plt.title('A tale of 2 subplots') plt.ylabel('$x^2$') plt.subplot(2, 1, 2) plt.plot(x, y2, '.-') plt.xlabel('samples') plt.ylabel('$\sin{x}$') plt.show()
_____no_output_____
MIT
02_tools-and-packages/01_plot-packages.ipynb
FelixBleimund/py-algorithms-4-automotive-engineering
* I guess you got the concept here.* Also basic statistical plots are simple to generate.
# Generate random numbers in a list import random y3 = [random.gammavariate(alpha=1.2, beta=2.3) for i in range(0, 5000)] plt.hist(y3, bins=40) plt.xlabel('Data') plt.ylabel('Probability density') plt.title(r'Histogram of Gammadist: $\alpha=1.2$, $\beta=2.3$') plt.show()
_____no_output_____
MIT
02_tools-and-packages/01_plot-packages.ipynb
FelixBleimund/py-algorithms-4-automotive-engineering
Exercise: Matplotlib (10 minutes)Here the task:* Activate your local Python environment and install matplotlib with `conda install matplotlib`.* Either work in Jupyter notebook, in Ipython shell, or Pycharm.* Create a list of 1500 data points.* Add a second list of 1500 data points with Gaussian distribution $\mathcal{N}\sim(0, 1)$.* Create a figure with a histogram of the data. SolutionPlease find one possible solution in [`solution_plotting.py`](solution_plotting.py) file.
%run solution_plotting.py plt.show()
_____no_output_____
MIT
02_tools-and-packages/01_plot-packages.ipynb
FelixBleimund/py-algorithms-4-automotive-engineering
More plot types* Many other plots are as simple as the examples above.* Other typical plots are * Bar plots * 3D plots * Pie charts * Scatter plots * ...* You can find many more plot examples in the [Matlotlib gallery](https://matplotlib.org/gallery/index.html)
IFrame(src='https://matplotlib.org/gallery/index.html', width=700, height=600)
_____no_output_____
MIT
02_tools-and-packages/01_plot-packages.ipynb
FelixBleimund/py-algorithms-4-automotive-engineering
Seaborn* Seaborn is a statistical plot library for Python.* It is based on matplotlib.* Please find it's documentation here [https://seaborn.pydata.org/](https://seaborn.pydata.org/).* You can install it with `conda install seaborn`.* Next comes a snapshot of seaborn's example gallery [https://seaborn.pydata.org/examples/index.html](https://seaborn.pydata.org/examples/index.html).
IFrame(src='https://seaborn.pydata.org/examples/index.html', width=700, height=600)
_____no_output_____
MIT
02_tools-and-packages/01_plot-packages.ipynb
FelixBleimund/py-algorithms-4-automotive-engineering
Bokeh* Add to "static" plots, interactive plots and dashboards can be build with Bokeh library.* Interactive plots are ideal if you want to visualize large data sets.* Real time information is visible like server load,...* Boekh is easy to install via conda and pip.* Please find here the Bokeh gallery [https://docs.bokeh.org/en/latest/docs/gallery.html](https://docs.bokeh.org/en/latest/docs/gallery.html).* And in next cell, an interactive plot of bokeh website is presented.
IFrame(src='https://demo.bokeh.org/crossfilter', width=700, height=600)
_____no_output_____
MIT
02_tools-and-packages/01_plot-packages.ipynb
FelixBleimund/py-algorithms-4-automotive-engineering
Plotly* Plotly is another very simple to use interactive plot library.* You can find more detail in [https://plot.ly/python/](https://plot.ly/python/).* Next, some examples from plotly gallery are presented.
IFrame(src='https://plot.ly/python/', width=700, height=600)
_____no_output_____
MIT
02_tools-and-packages/01_plot-packages.ipynb
FelixBleimund/py-algorithms-4-automotive-engineering
MAT281 - Laboratorio N°03 Objetivos de la clase* Reforzar los conceptos básicos de pandas. Contenidos* [Problema 01](p1) Problema 01EL conjunto de datos se denomina `ocupation.csv`, el cual contiene información tal como: edad ,sexo, profesión, etc.Lo primero es cargar el conjunto de datos y ver las primeras filas que lo componen:
import pandas as pd import os # cargar datos df = pd.read_csv(os.path.join("data","ocupation.csv"), sep="|").set_index('user_id') df.head()
_____no_output_____
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
El objetivo es tratar de obtener la mayor información posible de este conjunto de datos. Para cumplir este objetivo debe resolver las siguientes problemáticas: 1. ¿Cuál es el número de observaciones en el conjunto de datos?
print('El número de observaciones es de',df.shape[0],'elementos')
El número de observaciones es de 943 elementos
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
2. ¿Cuál es el número de columnas en el conjunto de datos?
print('El número de columnas es',df.shape[1])
El número de columnas es 4
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
3. Imprime el nombre de todas las columnas
list(df)
_____no_output_____
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
4. Imprima el índice del dataframe
print("index:") print(df.index)
index: Int64Index([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ... 934, 935, 936, 937, 938, 939, 940, 941, 942, 943], dtype='int64', name='user_id', length=943)
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
5. ¿Cuál es el tipo de datos de cada columna?
df.dtypes
_____no_output_____
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
6. Resumir el conjunto de datos
df.describe()
_____no_output_____
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
7. Resume conjunto de datos con todas las columnas
df.describe(include='all')
_____no_output_____
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
8. Imprimir solo la columna de **occupation**.
df['occupation'].head() print(df['occupation'])
user_id 1 technician 2 other 3 writer 4 technician 5 other ... 939 student 940 administrator 941 student 942 librarian 943 student Name: occupation, Length: 943, dtype: object
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
9. ¿Cuántas ocupaciones diferentes hay en este conjunto de datos?
a=df['occupation'].unique() #Ocupación print('En total hay',len(a),'categorias de ocupaciones') list(a)
_____no_output_____
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
10. ¿Cuál es la ocupación más frecuente?
a=df['occupation'].unique() #Ocupación frec=pd.Series() for ocupa in a: df_aux = df.loc[lambda x: x['occupation'] == ocupa] #print(df_aux) frec[ocupa] = len(df_aux) frec # dataframe with list df_list1 = pd.DataFrame([], columns = ['ocupaciones']) df_list1['ocupaciones']=frec frec_mas=frec[frec==frec.max()] frec_mas print('la ocupación más frecuete es:',frec_mas)
la ocupación más frecuete es: student 196 dtype: int64
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
11. ¿Cuál es la edad media de los usuarios?
import math print('La edad media de los usuarios es :',math.floor(df['age'].mean()))
La edad mediade los usuarios es : 34
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
12. ¿Cuál es la edad con menos ocurrencia?
b=df['age'].unique() frec_edad=pd.Series() #nba_position_duration = pd.Series() for edad in b: df_aux = df.loc[lambda x: x['age'] == edad] edad_str=str(edad) frec_edad[edad_str] = len(df_aux) # dataframe with list df_list = pd.DataFrame([], columns = ["edad"]) df_list['edad']=frec_edad edad_menos=frec_edad[frec_edad==frec_edad.min()] print('Las edades menos concurridas son: 7,66,11,10 y 73 años') edad_menos
Las edades menos concurridas son: 7,66,11,10 y 73 años
MIT
labs/01_python/laboratorio_03.ipynb
andresmontecinos12/mat281_portfolio
Visualising text data with unsupervised learning- branch: master- badges: false- comments: true- author: Theo Rutter- image: images/plot.png- categories: [python, tfidf, pca, clustering, plotly, nlp]
# hide !pip install reed # hide import re import json from html.parser import HTMLParser import numpy as np # hide class MyHTMLParser(HTMLParser): def __init__(self): self.string = '' super().__init__() def handle_data(self, data): self.string = self.string + ' ' + data return (data) def return_data(self): return self.string.strip().replace(' ', ' ') # hide from googleapiclient.discovery import build import io, os from googleapiclient.http import MediaIoBaseDownload from google.colab import auth auth.authenticate_user() drive_service = build('drive', 'v3') results = drive_service.files().list( q="name = 'creds.json'", fields="files(id)").execute() creds = results.get('files', []) results = drive_service.files().list( q="name = 'job_data.csv'", fields="files(id)").execute() data = results.get('files', []) filename = "/content/.reed/creds.json" os.makedirs(os.path.dirname(filename), exist_ok=True) request = drive_service.files().get_media(fileId=creds[0]['id']) fh = io.FileIO(filename, 'wb') downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print("Download %d%%." % int(status.progress() * 100)) os.chmod(filename, 600) filename = "/content/data/job_data.csv" os.makedirs(os.path.dirname(filename), exist_ok=True) request = drive_service.files().get_media(fileId=data[0]['id']) fh = io.FileIO(filename, 'wb') downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print("Download %d%%." % int(status.progress() * 100)) os.chmod(filename, 600) # hide filename = "/content/.reed/creds.json" with open(filename, 'r') as f: creds = json.load(f) api_key=creds['API_KEY']
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
IntroVisualisation is an essential part of working with data. Whether we are delivering regular reports to decision-makers, presenting the results of a regression model to a room of stakeholders, or creating a real-time dashboard for the wider business, we are using data to tell a story, and visuals bring these stories to life.In this post we are going to explore a number of ways to visualise text data in the context of analysing job posts for three data roles: data scientists, data engineers and data analysts. These roles have a lot in common but are fundamentally different; will the content of the job descriptions for these roles reflect the differences between them? And how can we visualise these differences? Getting the dataFirst we need to collect some job descriptions to analyse. There are plenty of job search APIs out there to choose from and we also have the option to scrape directly from job websites. I ended up using the Reed developer API because of the simple process of signing up for credentials. I wrote a python wrapper for the API which I will be using to extract a collection of relevant job posts; you can find it [here](https://pypi.org/project/reed/).It's a simple process to fetch the jobs matching a keywords search query. The response is a list of json objects which in this case are identical to python dictionaries so we can easily place the data in a pandas dataframe.
import pandas as pd from reed import ReedClient client = ReedClient(api_key=api_key) search_params = { 'keywords': 'data+scientist|data+engineer|data+analyst', 'resultsToTake': 600 } response = client.search(**search_params) df = pd.DataFrame(response) df.shape
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
Our search returned 524 jobs in total; let's clean up the job titles and see what we have.
def clean_title(title_str): return title_str.lower().strip().replace(' ', ' ') df['jobTitle'] = [clean_title(x) for x in df.jobTitle] df.groupby('jobTitle').size().sort_values(ascending=False).head(10)
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
We're going to remove all the posts which don't have one of the three most common titles; what we're left with should be broadly similar in terms of representing mid-level roles within each category.
accepted_titles = ['data scientist', 'data engineer', 'data analyst'] df = df[[x in accepted_titles for x in df.jobTitle]].set_index('jobId')
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
The job search API gives a truncated version of the job descriptions so if we want the complete text we'll have to take each individual job id and pull down the details using the job details function one-by-one. To make this process easier I created a dictionary with the three job titles as keys and the items consisting of the list of ids corresponding to each title.
groups = df.groupby('jobTitle').groups groups.keys()
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
Now we can loop over the dictionary pulling down the description from each job in turn. There's another complication in that the job descriptions are returned as html documents. We're only interested in the text data so we're going to have the parse the html to extract the information we want. We can wrap this process inside a function which we call for each id in our dictionary.
def get_job_desc(job_type, job_id, client, html_parser): desc_html = client.job_details(job_id)['jobDescription'] parser.feed(desc_html) desc_str = parser.return_data() # reset parser string parser.string = '' return dict(job=job_type, job_id=job_id, desc=desc_str) parser = MyHTMLParser() job_descriptions = [] for title in groups: for id in groups[title]: job_desc_dict = get_job_desc(title, id, client, parser) job_descriptions.append(job_desc_dict) df = pd.DataFrame(job_descriptions) df.head()
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
In order to visualise the content of the job descriptions we need a numerical representation of the text. One way to do this is with a bag-of-words approach, which consists of separating the text in our documents into tokens and counting the appearances of each token in each document. Before we do this there are some errands we need to run first. Sklearn's Countvectorizer class performs the tokenization step for us, but we need to be careful when using it. By default it splits the text on punctuation marks and discards tokens less than two characters long. For this reason, the word 'Ph.D' which is frequently used would be split into the two meaningless tokens 'Ph' and 'D', for example. The important term 'R' denoting the programming language would also be discarded. We can remedy these issues and others similar using pandas string methods. At the same time we'll remove any rows with duplicate job descriptions.
# hide filename = "/content/data/job_data.csv" df = pd.read_csv(filename, index_col=0) df = df[~df.duplicated('desc')] cicd_pat = "([Cc][Ii]/[Cc][Dd])" phd_pat = "[Pp][Hh].?[Dd]" r_pat = '(\sR\W)' df['desc'] = (df.desc.str.replace(',000', 'k') .str.replace('\xa0', ' ') .str.replace(phd_pat, 'PHD') .str.replace(r_pat, ' RStudio ') .str.replace(cicd_pat, ' CICD') .str.replace('Modis', ''))
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
Now we're finally at a stage where our data is ready to be analysed. After whittling the results down to mid-level roles we were left with 133 unique jobs with a roughly even split between the three roles. When we fit the CountVectorizer transform to an array containing each job description what we get is a document-term matrix: the rows are the job descriptions and the columns are all the words which were found in the collection of documents. The contents of the matrix are the word frequencies.
from sklearn.feature_extraction.text import CountVectorizer count_vectorizer = CountVectorizer(stop_words='english') text_data = np.array(df['desc']) count_matrix = count_vectorizer.fit_transform(text_data) count_matrix_df = pd.DataFrame(count_matrix.toarray(), columns=count_vectorizer.get_feature_names()) count_matrix_df
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
How can we use this implementation to visualise the three different roles? A simple option is to look at the most frequent words across the three classes: if we group the documents into the three roles, sum the word frequencies and sort them in descending order we'll see which words appear the most in each.
# hide_input from plotly.subplots import make_subplots import plotly.graph_objects as go count_matrix_df['job'] = df.job counts_by_job = (count_matrix_df.groupby('job') .sum() .transpose() .reset_index() .rename(columns={'index': 'word'})) da_top = counts_by_job[['word', 'data analyst']].sort_values('data analyst', ascending=False)[:20] de_top = counts_by_job[['word', 'data engineer']].sort_values('data engineer', ascending=False)[:20] ds_top = counts_by_job[['word', 'data scientist']].sort_values('data scientist', ascending=False)[:20] colours_dict = {'data analyst': '#636efa', 'data scientist': '#00cc96', 'data engineer': '#EF553B'} fig = make_subplots(rows=1, cols=3, subplot_titles=("DS top words", "DE top words", "DA top words"), x_title='frequency' ) fig.add_trace(go.Bar( y=ds_top['word'], x=ds_top['data scientist'], orientation='h', name='ds', marker=dict(color=colours_dict['data scientist'])), row=1, col=1 ) fig.add_trace(go.Bar( y=de_top['word'], x=de_top['data engineer'], orientation='h', name='de', marker=dict(color=colours_dict['data engineer'])), row=1, col=2 ) fig.add_trace(go.Bar( y=da_top['word'], x=da_top['data analyst'], orientation='h', name='da', marker=dict(color=colours_dict['data analyst'])), row=1, col=3 ) fig.update_layout( yaxis1=dict(autorange="reversed"), yaxis2=dict(autorange="reversed"), yaxis3=dict(autorange="reversed"), height=600, width=1000, showlegend=False ) fig.show()
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
We can spot a few themes such as the emphasis on machine learning in DS job descriptions while SQL and reporting feature prominently in DA posts. The plot corresponding to Data engineer roles is not as insightful. The appearance of Python, SQL and Azure are promising, but no sign of ETL pipelines and a lower prevalance of cloud-based systems than we'd expect. And why does scientist turn up so much? Across the three plots we can also see another problem with this simple word frequency approach: the most insightful terms are diluted by a saturation of words which are common across the three roles and thus essentially useless, such as 'data', 'experience', 'role' and 'team'. We need a metric which highly ranks frequent words but suppresses words which appear in lots of the documents in our corpus. Luckily for us a metric exists which does exactly as we require. TFIDF or term-frequency inverse-document frequency takes the term frequency of a word in a document and multiplies it by the inverse document freqency of that word, essentially damping those words which appear across a large proportion of the documents. Again sklearn has our back and can perform this process for us.
from sklearn.feature_extraction.text import TfidfVectorizer max_df = 0.6 min_df = 2 vectorizer = TfidfVectorizer(stop_words='english', max_df=max_df, min_df=min_df) text = np.array(df['desc']) tfidf_matrix = vectorizer.fit_transform(text) tfidf = pd.DataFrame(tfidf_matrix.toarray(), columns=vectorizer.get_feature_names()) tfidf
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
As before the TfidfVectorizer returns a term-document matrix, but instead of consisting of word frequencies we have tfidf values for each term-document pair. The parameters 'min_df' and 'max_df' are constraints on the document frequency of the words in our vocabulary. We have used a 'min_df' of 2, so any words that do not appear in at least two documents are thrown out. 'Max_df' is a float which corresponds to a proportion of the documents, so here if any words appear in more than 60 percent of the documents they too are discarded. In the same way as before, we can sum the tfidf values within the three classes and plot the highest aggregate values to hopefully extract the most important terms to characterise the three job types.
# hide_input tfidf_with_job = tfidf.copy() tfidf_with_job['job_type'] = df.job counts_by_job = (tfidf_with_job.groupby('job_type') .sum() .transpose() .reset_index() .rename(columns={'index': 'word'})) da_top = counts_by_job[['word', 'data analyst']].sort_values('data analyst', ascending=False)[:20] de_top = counts_by_job[['word', 'data engineer']].sort_values('data engineer', ascending=False)[:20] ds_top = counts_by_job[['word', 'data scientist']].sort_values('data scientist', ascending=False)[:20] colours_dict = {'data analyst': '#636efa', 'data scientist': '#00cc96', 'data engineer': '#EF553B'} fig = make_subplots(rows=1, cols=3, subplot_titles=("DS top words", "DE top words", "DA top words"), x_title='tfidf score' ) fig.add_trace(go.Bar( y=ds_top['word'], x=ds_top['data scientist'], orientation='h', marker=dict(color=colours_dict['data scientist'])), row=1, col=1 ) fig.add_trace(go.Bar( y=de_top['word'], x=de_top['data engineer'], orientation='h', marker=dict(color=colours_dict['data engineer'])), row=1, col=2 ) fig.add_trace(go.Bar( y=da_top['word'], x=da_top['data analyst'], orientation='h', marker=dict(color=colours_dict['data analyst'])), row=1, col=3 ) fig.update_layout( yaxis1=dict(autorange="reversed"), yaxis2=dict(autorange="reversed"), yaxis3=dict(autorange="reversed"), height=600, width=1000, showlegend=False ) fig.show()
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
This is a big improvement over our first attempt. There are far fewer generic terms because of the introduction of the inverse-document weighting and the document frequency constraints. The data engineering terms are also closer to our expectations than they were before. What are the key insights we can take from these plots? For data scientists machine learning is the most distinguishing feature. R and Python both appear with the latter ranked slightly higher, at least in this sample. We can also see that doctorates are important in data scientist posts but not in the other two roles.Our picture of data engineering posts is clearer from this version of the plot. Cloud technologies, ETL pipelines and databases feature heavily and python seems to be the scripting language of choice within this sample of posts. The impression given by this visual is that tools and technologies are to data engineering what algorithms and models are to data science.Finally, data analyst positions appear to be characterised more by aptitudes and skills than by specific technologies or technical backgrounds. SQL and excel feature heavily but apart from these tools the key terms seem to describe an general analytical mindset and an ability to support other business functions through reporting and analysis. Plotting job descriptions via dimensionality reductionSo far we've used the TF-IDF vectors to gain insight into the key words that describe the different data roles. We haven't, however, used any unsupervised learning as we promised at the beginning. Let's sort that out now. Using TF-IDF we have created a 2038-dimensional representation of the job descriptions in our sample. As it is a bit of a struggle to visualise anything in more than three dimensions, it is common practice to manipulate high-dimensional data into a two or three dimensional space so that it can be visualised and structural patterns in the data can be more easily found. In this case we are going to use Principal Component Analysis, or PCA for short, to project our data onto the two dimensions which retain the highest variability. This will allow us to create a scatterplot of the data.
from sklearn.decomposition import PCA pca = PCA(n_components=2) X = pca.fit_transform(tfidf) X_df = pd.DataFrame(X) X_df['job'] = df.job.values X_df = X_df.rename(columns={0: 'pc_0', 1: 'pc_1'}) X_df.sample(5) pca.explained_variance_
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
Using only a two dimensional representation of the TF-IDF vectors we retain just over half of the variance in our data. The following is a scatterplot of the first two principle components; each point is a job description.
import plotly.express as px fig = px.scatter(X_df, x="pc_0", y="pc_1", color="job", hover_data=["pc_0", "pc_1", X_df.index]) fig.update_layout(title='first two principle components of tfidf matrix') fig.show()
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
Remarkably, the three different job titles are almost perfectly separated into clusters in this two dimensional representation. This is significant because the PCA algorithm has no idea that our dataset contains three distinct classes, but by simply projecting the data onto the coordinate axes retaining the most variability the algorithm has managed to almost perfectly separate them. We can go one step further and demonstrate that the three classes are well-separated by applying k-means clustering first two principle components. The result is the following.
from sklearn.cluster import KMeans kmeans = KMeans(n_clusters=3) # X is the data matrix of the first two PC's kmeans.fit(X) y_kmeans = kmeans.predict(X) centers = kmeans.cluster_centers_ # hide_input fig = make_subplots(rows=2, cols=1, shared_xaxes=False, vertical_spacing=0.15, subplot_titles=("actual job titles","k means clustered job titles")) fig1 = px.scatter(X_df, x="pc_0", y="pc_1", color="job", hover_data=["pc_0", "pc_1", X_df.index]) trace1, trace2, trace3 = fig1['data'][0], fig1['data'][1], fig1['data'][2] trace1['name'] = 'data analyst' trace2['name'] = 'data engineer' trace3['name'] = 'data scientist' plotly_colours = px.colors.qualitative.Plotly c = [plotly_colours[x] for x in y_kmeans] fig2 = px.scatter(X_df, x='pc_0', y='pc_1', color=c, hover_data=['job', 'pc_0', 'pc_1', X_df.index]) trace4, trace5, trace6 = fig2['data'][0], fig2['data'][1], fig2['data'][2] trace4['name'] = 'data analyst' trace5['name'] = 'data engineer' trace6['name'] = 'data scientist' temp_str = '<br>job=%{customdata[0]}' + \ '<br>pc_0=%{customdata[1]}' + \ '<br>pc_1=%{customdata[2]}' + \ '<br>index=%{customdata[3]}' + \ '<extra></extra>' trace4['hovertemplate'] = temp_str trace5['hovertemplate'] = temp_str trace6['hovertemplate'] = temp_str trace4['legendgroup'] = 'job=data analyst' trace4['showlegend'] = False trace5['legendgroup'] = 'job=data engineer' trace5['showlegend'] = False trace6['legendgroup'] = 'job=data scientist' trace6['showlegend'] = False fig.add_trace(trace1, row=1, col=1) fig.add_trace(trace2, row=1, col=1) fig.add_trace(trace3, row=1, col=1) fig.add_trace(trace4, row=2, col=1) fig.add_trace(trace5, row=2, col=1) fig.add_trace(trace6, row=2, col=1) fig.add_trace(go.Scatter( x=centers[:, 0], y=centers[:, 1], name='cluster centers', mode='markers', marker=dict(size=[15, 15, 15], color=[2, 2, 2], opacity=0.7)), row=2, col=1 ) # fig['data'][6]['showlegend'] = False fig.update_layout(height=800, legend=dict(x=1, y=0.5)) fig.layout['xaxis']['title'] = 'pc_0' fig.layout['xaxis2']['title'] = 'pc_0' fig.layout['yaxis']['title'] = 'pc_1' fig.layout['yaxis2']['title'] = 'pc_1' fig.show()
_____no_output_____
Apache-2.0
_notebooks/2020-06-29-Visualising-text-data-with-unsupervised-learning.ipynb
theo-r/datablog
Processing pipeline - PV solar cell output data Modify system path and import pipeline module
from sys import path as syspath syspath.insert(1, '../src/') import pandas as pd from scripts import (process_data, calculations, apply_filters, plotting)
_____no_output_____
MIT
notebooks/run_pipeline.ipynb
lisc119/Soiling-Loss-Analysis
Define paths to data files (output, environmental, & panel capacity)
# PARK 1 # root_path = "../data/raw/New_data/" power_filepath = root_path + "SolarPark1_Jun_2019_Jun2020_string_production.csv" environment_filepath = root_path + "SolarPark1_Jun_2019_Jun2020_environmental.csv" capacity_filepath = root_path + "Solarpark_1_string_capacity.csv" # # PARK 2 # # root_path = "../data/raw/New_data/" # power_filepath, \ # capacity_filepath, \ # environment_filepath = [root_path + i for i in ['SolarPark2_Oct_2019_Oct2020_string_production.csv', # 'Solarpark_2_CB_capacity.csv', # 'Solarpark2_Oct_2019_Oct2020_environmental.csv']]
_____no_output_____
MIT
notebooks/run_pipeline.ipynb
lisc119/Soiling-Loss-Analysis
Set output directory for files to be saved
working_dir = "../data/temp/park1/" # will save all interim files here # working_dir = "../data/temp/park2/" # will save all interim files here
_____no_output_____
MIT
notebooks/run_pipeline.ipynb
lisc119/Soiling-Loss-Analysis
Run processing pipeline Note that two dataframes are created in the process by the function.- **Dataframe 1**: the original output with NAs filtered (by irradiance) & environmental data optionally appended. *Set keep_env_info to True if you want to keep the environmental data in this dataframe.* - **Dataframe 2**: calculated performance ratios with NAs filtered
df, df_PR = process_data.preprocess_data( power_filepath, environment_filepath, capacity_filepath, yearly_degradation_rate = 0.005, keep_env_info = False, save_dir = working_dir )
Data read successfully. Columns renamed. Merged DFs. Adjusting expected power by degradation rate of: 0.5%/year... Calculated performance ratio. (112584, 330) (57991, 330) Cleaned dataframes. Saving dataframes... Saving ../data/temp/park1/preprocessing/df_output.csv... Done. Saving ../data/temp/park1/preprocessing/df_PR.csv... Done. DONE.
MIT
notebooks/run_pipeline.ipynb
lisc119/Soiling-Loss-Analysis
Drop worst strings based on UMAP clustering (Need to cluster first and save labels of worst strings to filter out)
cluster_filepath = '../data/processed/park1/park1_string_clusters_filtered.csv' df_clusters = pd.read_csv(cluster_filepath, delimiter=',') bottom_cluster = df_clusters['bottom'].dropna().tolist() df_PR = df_PR.drop( columns = [ i+"_(kW)" for i in bottom_cluster] + [ col for col in df_PR.columns.to_list( ) if col.startswith( "ST 2.7") or col.startswith( "ST 2.5.4")or col.startswith( "ST 4.4.1") or col.startswith( "ST 4.5.2")])
_____no_output_____
MIT
notebooks/run_pipeline.ipynb
lisc119/Soiling-Loss-Analysis
Filter best time periods & strings Best time window needs to first be determined by ...
#plotting.plot_EPI_daily_window(apply_filters.add_temporal(df_PR, drop_extra = False)) #should do this AFTER filtering strings...? #plotting.plot_EPI_dpm(apply_filters.add_temporal(df_PR, drop_extra = False)) #plotting.plot_EPI_sd_daily_windows(apply_filters.add_temporal(df_PR, drop_extra = False))
_____no_output_____
MIT
notebooks/run_pipeline.ipynb
lisc119/Soiling-Loss-Analysis
Set decided time window
peak_hour_start = "15" #park 1 - "15", park 2 - "16" peak_hour_end = "19" #park 1 - "19", park 2 - "18"
_____no_output_____
MIT
notebooks/run_pipeline.ipynb
lisc119/Soiling-Loss-Analysis
Run filtering steps
df_BDfilt_dayfilt_hour, \ df_BDfilt_dayfilt_day, \ debug = apply_filters.filter_data(df_PR, window_start = peak_hour_start, window_end = peak_hour_end, save_dir = working_dir) df_BDfilt_dayfilt_day.mean(axis=1).plot(legend=False) df_BDfilt_dayfilt_day.mean(axis=1).plot(legend=False)
_____no_output_____
MIT
notebooks/run_pipeline.ipynb
lisc119/Soiling-Loss-Analysis
Estimate soiling
tmp = pd.read_csv("../data/processed/park1/df_park1_allfilters_hourly_timemasked.csv") tmp['datetime'] = pd.to_datetime(tmp['datetime']) tmp = tmp.set_index('datetime') tmp.median().plot(figsize = (15,6), color = "blue", alpha = 0.5, ms=20, use_index = True, style ='.', ylim = (0.94,1)) df_BDfilt_dayfilt_hour.median().plot(use_index=False, color = "red", style = ".", ms=20, alpha = 0.5) tmp.median(axis=0).mean() - df_BDfilt_dayfilt_hour.median(axis=0).median() 4.406552374713879e-05 * 100
_____no_output_____
MIT
notebooks/run_pipeline.ipynb
lisc119/Soiling-Loss-Analysis
Artificial Intelligence Nanodegree Convolutional Neural Networks Project: Write an Algorithm for a Dog Identification App ---In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with **'(IMPLEMENTATION)'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully! > **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "**File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.The rubric contains _optional_ "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this IPython notebook.--- Why We're Here In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!). ![Sample Dog Output](images/sample_dog_output.png)In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience! The Road AheadWe break the notebook into separate steps. Feel free to use the links below to navigate the notebook.* [Step 0](step0): Import Datasets* [Step 1](step1): Detect Humans* [Step 2](step2): Detect Dogs* [Step 3](step3): Create a CNN to Classify Dog Breeds (from Scratch)* [Step 4](step4): Use a CNN to Classify Dog Breeds (using Transfer Learning)* [Step 5](step5): Create a CNN to Classify Dog Breeds (using Transfer Learning)* [Step 6](step6): Write your Algorithm* [Step 7](step7): Test Your Algorithm--- Step 0: Import Datasets Import Dog DatasetIn the code cell below, we import a dataset of dog images. We populate a few variables through the use of the `load_files` function from the scikit-learn library:- `train_files`, `valid_files`, `test_files` - numpy arrays containing file paths to images- `train_targets`, `valid_targets`, `test_targets` - numpy arrays containing onehot-encoded classification labels - `dog_names` - list of string-valued dog breed names for translating labels
from sklearn.datasets import load_files from keras.utils import np_utils import numpy as np from glob import glob # define function to load train, test, and validation datasets def load_dataset(path): data = load_files(path) dog_files = np.array(data['filenames']) dog_targets = np_utils.to_categorical(np.array(data['target']), 133) return dog_files, dog_targets # load train, test, and validation datasets train_files, train_targets = load_dataset('dogImages/train') valid_files, valid_targets = load_dataset('dogImages/valid') test_files, test_targets = load_dataset('dogImages/test') # load list of dog names dog_names = [item[20:-1] for item in sorted(glob("dogImages/train/*/"))] # print statistics about the dataset print('There are %d total dog categories.' % len(dog_names)) print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files]))) print('There are %d training dog images.' % len(train_files)) print('There are %d validation dog images.' % len(valid_files)) print('There are %d test dog images.'% len(test_files))
Using TensorFlow backend.
MIT
dog_app.ipynb
theCydonian/Dog-App
Import Human DatasetIn the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array `human_files`.
import random random.seed(8675309) # load filenames in shuffled human dataset human_files = np.array(glob("lfw/*/*")) random.shuffle(human_files) # print statistics about the dataset print('There are %d total human images.' % len(human_files))
There are 13233 total human images.
MIT
dog_app.ipynb
theCydonian/Dog-App
--- Step 1: Detect HumansWe use OpenCV's implementation of [Haar feature-based cascade classifiers](http://docs.opencv.org/trunk/d7/d8b/tutorial_py_face_detection.html) to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on [github](https://github.com/opencv/opencv/tree/master/data/haarcascades). We have downloaded one of these detectors and stored it in the `haarcascades` directory.In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.
import cv2 import matplotlib.pyplot as plt %matplotlib inline # extract pre-trained face detector face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml') # load color (BGR) image img = cv2.imread(human_files[3]) # convert BGR image to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # find faces in image faces = face_cascade.detectMultiScale(gray) # print number of faces detected in the image print('Number of faces detected:', len(faces)) # get bounding box for each detected face for (x,y,w,h) in faces: # add bounding box to color image cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) # convert BGR image to RGB for plotting cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # display the image, along with bounding box plt.imshow(cv_rgb) plt.show()
('Number of faces detected:', 1)
MIT
dog_app.ipynb
theCydonian/Dog-App
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The `detectMultiScale` function executes the classifier stored in `face_cascade` and takes the grayscale image as a parameter. In the above code, `faces` is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as `x` and `y`) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as `w` and `h`) specify the width and height of the box. Write a Human Face DetectorWe can use this procedure to write a function that returns `True` if a human face is detected in an image and `False` otherwise. This function, aptly named `face_detector`, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path def face_detector(img_path): img = cv2.imread(img_path) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray) return len(faces) > 0
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App
(IMPLEMENTATION) Assess the Human Face Detector__Question 1:__ Use the code cell below to test the performance of the `face_detector` function. - What percentage of the first 100 images in `human_files` have a detected human face? - What percentage of the first 100 images in `dog_files` have a detected human face? Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays `human_files_short` and `dog_files_short`.__Answer:__ detected in dog images: 0.12;detected in human images: 1.0
human_files_short = human_files[:100] dog_files_short = train_files[:100] # Do NOT modify the code above this line. trueDog = 0.0 falseDog = 0.0 trueHum = 0.0 falseHum = 0.0 # human stuff for X in human_files_short: if face_detector(X): trueHum += 1.0; else: falseHum += 1.0; # dog stuff for X in dog_files_short: if face_detector(X): falseDog += 1.0; else: trueDog += 1.0; print "detected in dog images: " + str(falseDog/(trueDog+falseDog)) print "detected in human images: " + str(trueHum/(trueHum+falseHum))
detected in dog images: 0.12 detected in human images: 1.0
MIT
dog_app.ipynb
theCydonian/Dog-App
__Question 2:__ This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?__Answer:__I think it is completely reasonable to need faes shown because the face is such a defining feature for both humans and dogs, so, without it, the entire premise of giving dog breed most similar to a person is pointless.We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this _optional_ task, report performance on each of the datasets.
## (Optional) TODO: Report the performance of another ## face detection algorithm on the LFW dataset ### Feel free to use as many code cells as needed.
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App
--- Step 2: Detect DogsIn this section, we use a pre-trained [ResNet-50](http://ethereon.github.io/netscope//gist/db945b393d40bfa26006) model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on [ImageNet](http://www.image-net.org/), a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of [1000 categories](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a). Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.
from keras.applications.resnet50 import ResNet50 # define ResNet50 model ResNet50_model = ResNet50(weights='imagenet')
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App
Pre-process the DataWhen using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape$$(\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}),$$where `nb_samples` corresponds to the total number of images (or samples), and `rows`, `columns`, and `channels` correspond to the number of rows, columns, and channels for each image, respectively. The `path_to_tensor` function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape$$(1, 224, 224, 3).$$The `paths_to_tensor` function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape $$(\text{nb_samples}, 224, 224, 3).$$Here, `nb_samples` is the number of samples, or number of images, in the supplied array of image paths. It is best to think of `nb_samples` as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!
from keras.preprocessing import image from tqdm import tqdm def path_to_tensor(img_path): # loads RGB image as PIL.Image.Image type img = image.load_img(img_path, target_size=(224, 224)) # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3) x = image.img_to_array(img) # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor return np.expand_dims(x, axis=0) def paths_to_tensor(img_paths): list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)] return np.vstack(list_of_tensors)
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App
Making Predictions with ResNet-50Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function `preprocess_input`. If you're curious, you can check the code for `preprocess_input` [here](https://github.com/fchollet/keras/blob/master/keras/applications/imagenet_utils.py).Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the `predict` method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the `ResNet50_predict_labels` function below.By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this [dictionary](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a).
from keras.applications.resnet50 import preprocess_input, decode_predictions def ResNet50_predict_labels(img_path): # returns prediction vector for image located at img_path img = preprocess_input(path_to_tensor(img_path)) return np.argmax(ResNet50_model.predict(img))
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App
Write a Dog DetectorWhile looking at the [dictionary](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a), you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from `'Chihuahua'` to `'Mexican hairless'`. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the `ResNet50_predict_labels` function above returns a value between 151 and 268 (inclusive).We use these ideas to complete the `dog_detector` function below, which returns `True` if a dog is detected in an image (and `False` if not).
### returns "True" if a dog is detected in the image stored at img_path def dog_detector(img_path): prediction = ResNet50_predict_labels(img_path) return ((prediction <= 268) & (prediction >= 151))
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App
(IMPLEMENTATION) Assess the Dog Detector__Question 3:__ Use the code cell below to test the performance of your `dog_detector` function. - What percentage of the images in `human_files_short` have a detected dog? - What percentage of the images in `dog_files_short` have a detected dog?__Answer:__ detected in dog images: 1.0;detected in human images: 0.01
trueDog = 0.0 falseDog = 0.0 trueHum = 0.0 falseHum = 0.0 # human stuff for X in human_files_short: if dog_detector(X): falseHum += 1.0; else: trueHum += 1.0; # dog stuff for X in dog_files_short: if dog_detector(X): trueDog += 1.0; else: falseDog += 1.0; print "detected in dog images: " + str(trueDog/(trueDog+falseDog)) print "detected in human images: " + str(falseHum/(trueHum+falseHum))
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App
--- Step 3: Create a CNN to Classify Dog Breeds (from Scratch)Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN _from scratch_ (so, you can't use transfer learning _yet_!), and you must attain a test accuracy of at least 1%. In Step 5 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.Be careful with adding too many trainable layers! More parameters means longer training, which means you are more likely to need a GPU to accelerate the training process. Thankfully, Keras provides a handy estimate of the time that each epoch is likely to take; you can extrapolate this estimate to figure out how long it will take for your algorithm to train. We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that *even a human* would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel. Brittany | Welsh Springer Spaniel- | - | It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels). Curly-Coated Retriever | American Water Spaniel- | - | Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed. Yellow Labrador | Chocolate Labrador | Black Labrador- | - | | We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%. Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun! Pre-process the DataWe rescale the images by dividing every pixel in every image by 255.
from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True # pre-process the data for Keras train_tensors = paths_to_tensor(train_files).astype('float32')/255 valid_tensors = paths_to_tensor(valid_files).astype('float32')/255 test_tensors = paths_to_tensor(test_files).astype('float32')/255
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App
(IMPLEMENTATION) Model ArchitectureCreate a CNN to classify dog breed. At the end of your code cell block, summarize the layers of your model by executing the line: model.summary()We have imported some Python modules to get you started, but feel free to import as many modules as you need. If you end up getting stuck, here's a hint that specifies a model that trains relatively fast on CPU and attains >1% test accuracy in 5 epochs:![Sample CNN](images/sample_cnn.png) __Question 4:__ Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.__Answer:__ I started by researching what techniques great architectures for image recognition use. I took some of those techniques and made a very complex model. One of the major one was to have progressively large dropout layers as number of filters increased. It overfitted a lot, so I messed around with the layer layout to try to reduce it. Eventually, I decided to reduce number of filters greatly, and that produced my final model. This model got a 6% accurracy. This model is still overfitting fairly early and has room for improvement. I may try to improve it later.
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D from keras.layers import Dropout, Flatten, Dense from keras.models import Sequential model = Sequential() model.add(Conv2D(filters = 16, kernel_size = 3, padding="same", input_shape=(224, 224, 3))) model.add(Conv2D(filters = 32, kernel_size = 3, padding="same", input_shape=(224, 224, 3))) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.15)) model.add(Conv2D(filters = 32, kernel_size = 3, padding="same", input_shape=(224, 224, 3))) model.add(MaxPooling2D(pool_size=2)) model.add(Conv2D(filters = 48, kernel_size = 3, padding="same", input_shape=(224, 224, 3))) model.add(MaxPooling2D(pool_size=2)) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(512, activation='relu')) model.add(Dropout(0.3)) model.add(Dense(256, activation='relu')) model.add(Dropout(0.1)) model.add(Dense(133, activation='softmax')) model.summary()
_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_1 (Conv2D) (None, 224, 224, 16) 448 _________________________________________________________________ conv2d_2 (Conv2D) (None, 224, 224, 32) 4640 _________________________________________________________________ max_pooling2d_2 (MaxPooling2 (None, 112, 112, 32) 0 _________________________________________________________________ dropout_1 (Dropout) (None, 112, 112, 32) 0 _________________________________________________________________ conv2d_3 (Conv2D) (None, 112, 112, 32) 9248 _________________________________________________________________ max_pooling2d_3 (MaxPooling2 (None, 56, 56, 32) 0 _________________________________________________________________ conv2d_4 (Conv2D) (None, 56, 56, 48) 13872 _________________________________________________________________ max_pooling2d_4 (MaxPooling2 (None, 28, 28, 48) 0 _________________________________________________________________ dropout_2 (Dropout) (None, 28, 28, 48) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 37632) 0 _________________________________________________________________ dense_1 (Dense) (None, 512) 19268096 _________________________________________________________________ dropout_3 (Dropout) (None, 512) 0 _________________________________________________________________ dense_2 (Dense) (None, 256) 131328 _________________________________________________________________ dropout_4 (Dropout) (None, 256) 0 _________________________________________________________________ dense_3 (Dense) (None, 133) 34181 ================================================================= Total params: 19,461,813 Trainable params: 19,461,813 Non-trainable params: 0 _________________________________________________________________
MIT
dog_app.ipynb
theCydonian/Dog-App
Compile the Model
model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App
(IMPLEMENTATION) Train the ModelTrain your model in the code cell below. Use model checkpointing to save the model that attains the best validation loss.You are welcome to [augment the training data](https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html), but this is not a requirement.
from keras.callbacks import ModelCheckpoint ### TODO: specify the number of epochs that you would like to use to train the model. epochs = 100 # high so I can always manually stop ### Do NOT modify the code below this line. checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5', verbose=1, save_best_only=True) model.fit(train_tensors, train_targets, validation_data=(valid_tensors, valid_targets), epochs=epochs, batch_size=20, callbacks=[checkpointer], verbose=1)
_____no_output_____
MIT
dog_app.ipynb
theCydonian/Dog-App