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],
... | 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.Li... | _____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_outpu... | _____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 Pasca... | %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.dt... | _____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... | _____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 fonc... | _____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_f... | _____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)
... | _____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=fonc... | _____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 =... | _____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=axe... | _____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)
... | _____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://... | # 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 gee... | _____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'... | _____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 ... | # 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 D... | _____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... | 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.inert... | _____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... | _____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 pro... | 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... | _____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 $\mathca... | %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/examp... | 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.bo... | 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 q... | 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... | 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[... | 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... | _____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 storie... | 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 consistin... | 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 ... | 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()
j... | _____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 e... | # 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, ... | _____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-t... | 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... | _____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 = c... | _____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... | 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_name... | _____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 ... | # 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']].... | _____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... | 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 variab... | 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=("actua... | _____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... | _____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*... | 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/preprocessin... | 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... | _____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(legen... | _____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().... | _____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... | 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_categoric... | 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/tre... | 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])
# conv... | ('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 ... | # 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? I... | 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... | 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 w... | ## (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,... | 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 ... | 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)
... | _____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 (expres... | 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 hairl... | ### 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 ima... | 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 "detec... | _____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 _ye... | 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)... | _____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 ge... | 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, pa... | _________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_1 (Conv2D) (None, 224, 224, 16) 448
________________________________________________________... | 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 re... | 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',
... | _____no_output_____ | MIT | dog_app.ipynb | theCydonian/Dog-App |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.