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 |
|---|---|---|---|---|---|
נגדיר רשימת גילים, ונבקש מ־filter לסנן אותם לפי הפונקציה שהגדרנו: | ages = [0, 1, 4, 10, 20, 35, 56, 84, 120]
mature_ages = filter(is_mature, ages)
print(tuple(mature_ages)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
כפי שלמדנו, filter מחזירה לנו רק גילים השווים ל־18 או גדולים ממנו. נחדד שהפונקציה שאנחנו מעבירים ל־filter לא חייבת להחזיר בהכרח True או False. הערך 0, לדוגמה, שקול ל־False, ולכן filter תסנן כל ערך שעבורו הפונקציה תחזיר 0: | to_sum = [(1, -1), (2, 5), (5, -3, -2), (1, 2, 3)]
sum_is_not_zero = filter(sum, to_sum)
print(tuple(sum_is_not_zero)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
בתא האחרון העברנו ל־filter את sum כפונקציה שאותה אנחנו רוצים להפעיל, ואת to_sum כאיברים שעליהם אנחנו רוצים לפעול. ה־tuple־ים שסכום איבריהם היה 0 סוננו, וקיבלנו חזרה iterator שהאיברים בו הם אך ורק אלו שסכומם שונה מ־0. כטריק אחרון, נלמד ש־filter יכולה לקבל גם None בתור הפרמטר הראשון, במקום פונקציה. זה יגרום... | to_sum = [0, "", None, 0.0, True, False, "Hello"]
equivalent_to_true = filter(None, to_sum)
print(tuple(equivalent_to_true)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
כתבו פונקציה שמקבלת רשימת מחרוזות, ומחזירה רק את המחרוזות הפלינדרומיות שבה. מחרוזת נחשבת פלינדרום אם קריאתה מימין לשמאל ומשמאל לימין יוצרת אותו ביטוי. השתמשו ב־filter. חשוב! פתרו לפני שתמשיכו! פונקצ... | def add(num1, num2):
return num1 + num2 | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
ונגדיר את אותה הפונקציה בדיוק בצורה אנונימית: | add = lambda num1, num2: num1 + num2
print(add(5, 2)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
לפני שנסביר איפה החלק של ה"פונקציה בלי שם" נתמקד בצד ימין של ההשמה. כיצד מנוסחת הגדרת פונקציה אנונימית? הצהרנו שברצוננו ליצור פונקציה אנונימית בעזרת מילת המפתח lambda. מייד אחריה, ציינו את שמות כל הפרמטרים שהפונקציה תקבל, כשהם מופרדים בפסיק זה מזה. כדי להפריד בין רשימת הפרמטרים לערך ההחזרה של הפונקציה,... | def is_positive(number):
return number > 0
numbers = [-2, -1, 0, 1, 2]
positive_numbers = filter(is_positive, numbers)
print(tuple(positive_numbers)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
במקום להגדיר פונקציה חדשה שנקראת is_positive, נוכל להשתמש בפונקציה אנונימית: | numbers = [-2, -1, 0, 1, 2]
positive_numbers = filter(lambda n: n > 0, numbers)
print(tuple(positive_numbers)) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
איך זה עובד? במקום להעביר ל־filter פונקציה שיצרנו מבעוד מועד, השתמשנו ב־lambda כדי ליצור פונקציה ממש באותה השורה. הפונקציה שהגדרנו מקבלת מספר (n), ומחזירה True אם הוא חיובי, או False אחרת. שימו לב שבצורה זו באמת לא היינו צריכים לתת שם לפונקציה שהגדרנו. השימוש בפונקציות אנונימיות לא מוגבל ל־map ול־filte... | closet = [
{'name': 'Peter', 'year_of_birth': 1927, 'gender': 'Male'},
{'name': 'Edmund', 'year_of_birth': 1930, 'gender': 'Male'},
{'name': 'Lucy', 'year_of_birth': 1932, 'gender': 'Female'},
{'name': 'Susan', 'year_of_birth': 1928, 'gender': 'Female'},
{'name': 'Jadis', 'year_of_birth': 0, 'gender... | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
נרצה שסידור הרשימה יתבצע לפי המפתח year_of_birth. כלומר, בהינתן מילון שמייצג דמות בשם d, יש להשיג את d['year_of_birth'], ולפיו לבצע את סידור הרשימה. ניגש למלאכה: | sorted(closet, key=lambda d: d['year_of_birth']) | _____no_output_____ | CC-BY-4.0 | week6/2_Functional_Behavior.ipynb | BrandMan2299/Notebooks |
Identificar Perfil de Consumo de Clientes de uma Instituição Financeira Uma breve introdução Uma Instituição Financeira X tem o interesse em identificar o perfil de gastos dos seus clientes. Identificando os clientes certos, eles podem melhorar a comunicação dos ativos promocionais, utilizar com mais eficiência os ca... | # pip install --upgrade kmodes
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
import random
import plotly.express as px
# pacote do modelo
from kmodes.kmodes import KModes
# from sklearn.model_selection import train_test_split
import warnings
warnings.filterwarni... | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
Leitura dos dados | # Carregar os dados
dados = pd.read_csv('../../dados_gasto_rmat.csv', sep=',')
dados.head(10)
print('O arquivo possui ' + str(dados.shape[0]) + ' linhas e ' + str(dados.shape[1]) + ' colunas.')
# Tipos dos dados
dados.dtypes
# Verificando valores nulos
dados.isnull().values.any() | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
A base não possui valores nulos. Visualização dos dados | # Total de clientes
len(dados['CLIENTE'].unique()) | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
Soma do valor gasto em cada ramo de atividade. | # Dados agregados por RMAT e o percentual gasto
dados_agreg = dados.groupby(['RMAT'])['VALOR_GASTO'].sum().reset_index()
dados_agreg['percentual'] = round(dados_agreg['VALOR_GASTO']/sum(dados_agreg['VALOR_GASTO'])*100,2)
dados_agreg.head()
# Traz o 30 RMATs que tiveram maior gasto dos clientes
top_rotulos = dados_agreg... | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
Supermercados, postos de combustível e drogarias são os ramos com maior consumo dos clientes, representando 13.48%, 7.07% e 5.75%, respectivamente. Construção da base para o modelo Vamos construir uma base que seja a nível cliente e as colunas serão os percentuais de consumo em cada ramo de atividade. Aqui, temos mui... | dados.head() | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
A função pivot faz a transposição dos dados, transformando o valor de "RMAT" em colunas. | # Inverter o data frame (colocar nos rmats como coluna)
cli_pivot = dados.pivot(index='CLIENTE', columns='RMAT', values='VALOR_GASTO')
cli_pivot.fillna(0, inplace = True)
# Calcular o percentual de volume transacionado de cada cliente por rmat
cli_pivot = cli_pivot.apply(lambda x: x.apply(lambda y: 100*y/sum(x)),axis ... | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
Abaixo, uma função que quebra os valores de cada coluna em quantidade de categorias escolhido. Nesse caso, utilizamos 8 quebras. | # Funnção para fazer categorização das variaveis
def hcut(df, colunas, nlevs, prefixo=''):
x = df.copy()
for c in colunas:
x[prefixo+c] = pd.cut(x[c] , bins=nlevs, include_lowest = False, precision=0)
return x
base_cluster = hcut(cli_pivot, cli_pivot
.columns, 8, 'e... | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
Agora, filtraremos as variáveis necessárias para a modelagem. | # Selecionar somentes as colunas categorizadas que serão utilizadas no modelo
filter_col = [col for col in base_cluster if
col.startswith('esc_')]
df1 = base_cluster.loc[:,filter_col].reset_index()
df1.head() | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
Criação do modelo Para nosso caso, utilizaremos o método de clusterização chamado K-modes. Esse método é uma extensão do K-means. Em vez de distâncias, ele usa dissimilaridade (isto é, quantificação das incompatibilidades totais entre dois objetos: quanto menor esse número, masi semelhantes são os dois objetos). Além... | km_huang = KModes(n_clusters=7, init = "Huang", n_init = 5, verbose=1, random_state=2020)
fitClusters = km_huang.fit_predict(df1)
# Adiciona os clusters na base
df1['cluster'] = fitClusters
base_cluster['cluster'] = fitClusters | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
Percentual de clientes por cluster. | df1['cluster'].value_counts()/len(df1)*100
df2 = base_cluster.drop(columns=filter_col)
df2.head()
# Para visualização dos clusters
# from sklearn.decomposition import PCA
# pca_2 = PCA(2)
# plot_columns = pca_2.fit_transform(base_cluster.iloc[:,0:65])
# plt.scatter(x=plot_columns[:,0], y=plot_columns[:,1], c=fitCluste... | _____no_output_____ | MIT | Script/kmodes-cluster-perfil-consumo-cliente.ipynb | helenacypreste/cluster-cliente-perfil-consumo |
Iterators and Generators Homework Problem 1Create a generator that generates the squares of numbers up to some number N. | # option 1
def gensquares(N):
end = N
start = 0
while start<end:
yield start**2
start += 1
# option 2
def gensquares2(N):
for num in range(N):
yield num**2
for x in gensquares2(10):
print(x) | 0
1
4
9
16
25
36
49
64
81
| DOC | Code/9.generadores/02-Iterators and Generators Homework.ipynb | davidMartinVergues/PYTHON |
Problem 2Create a generator that yields "n" random numbers between a low and high number (that are inputs). Note: Use the random library. For example: | import random
random.randint(1,10)
def rand_num(low,high,n):
for times in range(n):
yield random.randint(low,high)
for num in rand_num(1,10,12):
print(num) | 1
5
4
6
9
5
5
4
2
7
9
6
| DOC | Code/9.generadores/02-Iterators and Generators Homework.ipynb | davidMartinVergues/PYTHON |
Problem 3Use the iter() function to convert the string below into an iterator: | s = 'hello'
#code here
s_iter = iter() | _____no_output_____ | DOC | Code/9.generadores/02-Iterators and Generators Homework.ipynb | davidMartinVergues/PYTHON |
Problem 4Explain a use case for a generator using a yield statement where you would not want to use a normal function with a return statement. Extra Credit!Can you explain what *gencomp* is in the code below? (Note: We never covered this in lecture! You will have to do some Googling/Stack Overflowing!) | my_list = [1,2,3,4,5]
gencomp = (item for item in my_list if item > 3)
for item in gencomp:
print(item) | 4
5
| DOC | Code/9.generadores/02-Iterators and Generators Homework.ipynb | davidMartinVergues/PYTHON |
Copyright 2019 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | MIT | Improving_Computer_Vision_Using_CNN.ipynb | snalahi/Introduction-to-TensorFlow-for-Artificial-Intelligence-Machine-Learning-and-Deep-Learning |
Improving Computer Vision Accuracy using ConvolutionsIn the previous lessons you saw how to do fashion recognition using a Deep Neural Network (DNN) containing three layers -- the input layer (in the shape of the data), the output layer (in the shape of the desired output) and a hidden layer. You experimented with the ... | import tensorflow as tf
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images / 255.0
test_images=test_images / 255.0
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activa... | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz
32768/29515 [=================================] - 0s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz
26427392/26421880 [=====================... | MIT | Improving_Computer_Vision_Using_CNN.ipynb | snalahi/Introduction-to-TensorFlow-for-Artificial-Intelligence-Machine-Learning-and-Deep-Learning |
Your accuracy is probably about 89% on training and 87% on validation...not bad...But how do you make that even better? One way is to use something called Convolutions. I'm not going to details on Convolutions here, but the ultimate concept is that they narrow down the content of the image to focus on specific, distinc... | import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
# Reshaping the images to tell the convolutional layers that the images are in greyscale by adding an extra dimension of 1
training_images=training_ima... | 2.5.0
Model: "sequential_3"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d_4 (Conv2D) (None, 26, 26, 64) 640
____________________________... | MIT | Improving_Computer_Vision_Using_CNN.ipynb | snalahi/Introduction-to-TensorFlow-for-Artificial-Intelligence-Machine-Learning-and-Deep-Learning |
It's likely gone up to about 93% on the training data and 91% on the validation data. That's significant, and a step in the right direction!Try running it for more epochs -- say about 20, and explore the results! But while the results might seem really good, the validation results may actually go down, due to something... | print(test_labels[:100])
import matplotlib.pyplot as plt
f, axarr = plt.subplots(3,4)
FIRST_IMAGE=0
SECOND_IMAGE=7
THIRD_IMAGE=26
CONVOLUTION_NUMBER = 1
from tensorflow.keras import models
layer_outputs = [layer.output for layer in model.layers]
activation_model = tf.keras.models.Model(inputs = model.input, outputs = l... | _____no_output_____ | MIT | Improving_Computer_Vision_Using_CNN.ipynb | snalahi/Introduction-to-TensorFlow-for-Artificial-Intelligence-Machine-Learning-and-Deep-Learning |
EXERCISES1. Try editing the convolutions. Change the 32s to either 16 or 64. What impact will this have on accuracy and/or training time.2. Remove the final Convolution. What impact will this have on accuracy or training time?3. How about adding more Convolutions? What impact do you think this will have? Experiment wit... | import tensorflow as tf
print(tf.__version__)
mnist = tf.keras.datasets.mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images.reshape(60000, 28, 28, 1)
training_images=training_images / 255.0
test_images = test_images.reshape(10000, 28, 28, 1)
test_imag... | 2.5.0
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step
Epoch 1/10
1875/1875 [==============================] - 34s 18ms/step - loss: 0.1424 - accuracy: 0.9569
Epoch 2/10
1875/1875 [==============================]... | MIT | Improving_Computer_Vision_Using_CNN.ipynb | snalahi/Introduction-to-TensorFlow-for-Artificial-Intelligence-Machine-Learning-and-Deep-Learning |
Fundamentals, introduction to machine learningThe purpose of these guides is to go a bit deeper into the details behind common machine learning methods, assuming little math background, and teach you how to use popular machine learning Python packages. In particular, we'll focus on the Numpy and PyTorch libraries.I'll... | import numpy as np | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
You may have encountered vectors before in high school or college -- to use Python terms, a vector is like a list of numbers. The mathematical notation is quite similar to Python code, e.g. `[5,4]`, but `numpy` has its own way of instantiating a vector: | v = np.array([5, 4]) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$v = \begin{bmatrix} 5 \\ 4 \end{bmatrix}$$Vectors are usually represented with lowercase variables.Note that we never specified how _many_ numbers (also called _components_) a vector has - because it can have any amount. The amount of components a vector has is called its _dimensionality_. The example vector above ha... | np.array([6, 2]) + np.array([-4, 4]) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\begin{bmatrix} 6 \\ 2 \end{bmatrix} + \begin{bmatrix} -4 \\ 4 \end{bmatrix} = \begin{bmatrix} 6 + -4 \\ 2 + 4 \end{bmatrix} = \begin{bmatrix} 2 \\ 6 \end{bmatrix}$$However, when it comes to vector multiplication there are many different kinds.The simplest is _vector-scalar_ multiplication: | 3 * np.array([2, 1]) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$3\begin{bmatrix} 2 \\ 1 \end{bmatrix} = \begin{bmatrix} 3 \times 2 \\ 3 \times 1\end{bmatrix} = \begin{bmatrix} 6 \\ 3 \end{bmatrix}$$But when you multiply two vectors together you have a few options. I'll cover the two most important ones here.The one you might have thought of is the _element-wise product_, also cal... | np.array([6, 2]) * np.array([-4, 4]) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\begin{bmatrix} 6 \\ 2 \end{bmatrix} \odot \begin{bmatrix} -4 \\ 4 \end{bmatrix} = \begin{bmatrix} 6 \times -4 \\ 2 \times 4 \end{bmatrix} = \begin{bmatrix} -24 \\ 8 \end{bmatrix}$$The other vector product, which you'll encounter a lot, is the _dot product_, also called _inner product_, usually notated with $\cdot$ (... | np.dot(np.array([6, 2]), np.array([-4, 4])) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\begin{bmatrix} 6 \\ 2 \end{bmatrix} \cdot \begin{bmatrix} -4 \\ 4 \end{bmatrix} = (6 \times -4) + (2 \times 4) = -16$$The more general formulation is: | # a slow pure-Python dot product
def dot(a, b):
assert len(a) == len(b)
return sum(a_i * b_i for a_i, b_i in zip(a,b)) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\begin{aligned}\vec{a} \cdot \vec{b} &= \begin{bmatrix} a_1 \\ a_2 \\ \vdots \\ a_n \end{bmatrix} \cdot \begin{bmatrix} b_1 \\ b_2 \\ \vdots \\ b_n \end{bmatrix} = a_1b_1 + a_2b_2 + \dots + a_nb_n \\&= \sum^n_{i=1} a_i b_i\end{aligned}$$Note that the vectors in these operations must have the same dimensions!Perhaps t... | # this is so clumsy in python;
# this will become more concise in a bit
def f(x0, x1, x2, x3, theta0, theta1, theta2, theta3):
return theta0 * x0\
+ theta1 * x1\
+ theta2 * x2\
+ theta3 * x3 | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$y = \theta_0 x_0 + \theta_1 x_1 + \theta_2 x_2 + \theta_3 x_3$$This kind of looks like the dot product, doesn't it? In fact, we can re-write this entire function as a dot product. We define our feature vector $x = [x_0, x_1, x_2, x_3]$ and our parameter vector $\theta = [\theta_0, \theta_1, \theta_2, \theta_3]$, then... | def f(x, theta):
return x.dot(theta) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$y = \theta x$$So that's how we incorporate multiple features in a representation.There's a whole lot more to vectors than what's presented here, but this is the ground-level knowledge you should have of them. Other aspects of vectors will be explained as they come up. LearningSo machine learning algorithms learn para... | A = np.array([
[6, 8, 0],
[8, 2, 7],
[3, 3, 9],
[3, 8, 6]
]) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\mathbf A =\begin{bmatrix}6 & 8 & 0 \\8 & 2 & 7 \\3 & 3 & 9 \\3 & 8 & 6\end{bmatrix}$$Matrices are usually represented with uppercase variables.Note that the "vectors" in the matrix must have the same dimension. The matrix's dimensions are expressed in the form $m \times n$, meaning that there are $m$ rows and $n$ co... | A[1,2] | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
Basic matrix operationsLike vectors, matrix addition and subtraction is straightforward (again, they must be of the same dimensions): | B = np.array([
[8, 3, 7],
[2, 9, 6],
[2, 5, 6],
[5, 0, 6]
])
A + B | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\begin{aligned}\mathbf B &=\begin{bmatrix}8 & 3 & 7 \\2 & 9 & 6 \\2 & 5 & 6 \\5 & 0 & 6\end{bmatrix} \\A + B &=\begin{bmatrix}8+6 & 3+8 & 7+0 \\2+8 & 9+2 & 6+7 \\2+3 & 5+3 & 6+9 \\5+3 & 0+8 & 6+6\end{bmatrix} \\&=\begin{bmatrix}14 & 11 & 7 \\10 & 11 & 13 \\5 & 8 & 15 \\8 & 8 & 12\end{bmatrix} \\\end{aligned}$$Matrice... | # a slow pure-Python matrix-vector product,
# using our previous dot product implementation
def matrix_vector_product(M, v):
return [np.dot(row, v) for row in M]
# or, with numpy, you could use np.matmul(A,v) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\mathbf M v =\begin{bmatrix}M_{1} \cdot v \\\vdots \\M_{m} \cdot v \\\end{bmatrix}$$We have a few options when it comes to multiplying matrices with matrices.However, before we go any further we should talk about the _tranpose_ operation - this just involves switching the columns and rows of a matrix. The transpose o... | A = np.array([
[1,2,3],
[4,5,6]
])
np.transpose(A) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\begin{aligned}\mathbf A &=\begin{bmatrix}1 & 2 & 3 \\4 & 5 & 6\end{bmatrix} \\\mathbf A^T &=\begin{bmatrix}1 & 4 \\2 & 5 \\3 & 6\end{bmatrix}\end{aligned}$$For matrix-matrix products, the matrix on the lefthand must have the same number of columns as the righthand's rows. To be more concrete, we'll represent a matri... | # a slow pure-Python matrix Hadamard product
def matrix_matrix_product(A, B):
_, a_cols = np.shape(A)
b_rows, _ = np.shape(B)
assert a_cols == b_rows
result = []
# tranpose B so we can iterate over its columns
for col in np.tranpose(B):
# using our previous implementation
result... | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\mathbf AB =\begin{bmatrix}A B^T_1 \\\vdots \\A B^T_p\end{bmatrix}^T$$Finally, like with vectors, we also have Hadamard (element-wise) products: | # a slow pure-Python matrix-matrix product
# or, with numpy, you can use A * B
def matrix_matrix_hadamard(A, B):
result = []
for a_row, b_row in zip(A, B):
result.append(
zip(a_i * b_i for a_i, b_i in zip(a_row, b_row))) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\mathbf A \odot B =\begin{bmatrix}A_{1,1} B_{1,1} & \dots & A_{1,n} B_{1,n} \\\vdots & \dots & \vdots \\A_{m,1} B_{m,1} & \dots & A_{m,n} B_{m,n}\end{bmatrix}$$Like vector Hadamard products, this requires that the two matrices share the same dimensions. TensorsWe've seen vectors, which is like a list of numbers, and ... | positions = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, # moving forward
9, 9, 9, 9, 9, 9, 9, 9, 9, 9, # pausing
9, 8, 7, 6, 5, 4, 3, 2, 1, 0] # moving backwards
t_0 = 0
t_n = 29
(positions[t_n] - positions[t_0])/t_n | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$v = \frac{p_n - p_0}{n}$$This kind of makes it look like the cyclist didn't move at all. It would probably be more useful to identify the velocity at a given second $t$. Thus we want to come up with some function $v(t)$ which gives us the velocity at some second $t$. We can apply the same approach we just used to get... | def g(x):
return x**2
def h(x):
return x**3
def f(x):
return g(h(x))
# derivatives
def g_(x):
return 2*x
def h_(x):
return 3*(x**2) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
$$\begin{aligned}g(x) &= x^2 \\h(x) &= x^3 \\f(x) &= g(h(x)) \\g'(x) &= 2x \\h'(x) &= 3x^2\end{aligned}$$We're interested in understanding how $f(x)$ changes with respect to $x$, so we want to compute the derivative of $f(x)$. The chain rule allows us to individually differentiate the component functions of $f(x)$ and ... | def f_(x):
return g_(x) * h_(x) | _____no_output_____ | MIT | examples/fundamentals/fundamentals.ipynb | yo252yo/ml4a |
Check EnvironmentThis notebook checks that you have correctly created the environment and that all packages needed are installed. EnvironmentThe next command should return a line like (Mac/Linux): //anaconda/envs/ztdl/bin/pythonor like (Windows 10): C:\\\\Anaconda3\\envs\\ztdl\\python.exeIn particular you shoul... | import os
import sys
sys.executable | _____no_output_____ | MIT | course/0_Check_Environment.ipynb | tetsu/zero-deep-learning |
Python 3.6The next line should say that you're using Python 3.6.x from Continuum Analytics. At the time of publication it looks like this (Mac/Linux): Python 3.6.7 |Anaconda, Inc.| (default, Oct 23 2018, 14:01:38) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", ... | import sys
sys.version | _____no_output_____ | MIT | course/0_Check_Environment.ipynb | tetsu/zero-deep-learning |
JupyterCheck that Jupyter is running from within the environment. The next line should look like (Mac/Linux): //anaconda/envs/ztdl/lib/python3.6/site-packages/jupyter.py'or like this (Windows 10): C:\\Users\\paperspace\\Anaconda3\\envs\\ztdl\\lib\\site-packages\\jupyter.py | import jupyter
jupyter.__file__ | _____no_output_____ | MIT | course/0_Check_Environment.ipynb | tetsu/zero-deep-learning |
Other packagesHere we will check that all the packages are installed and have the correct versions. If everything is ok you should see: Using TensorFlow backend. Houston we are go!If there's any issue here please make sure you have checked the previous steps and if it's all good please send us a question... | import pip
import numpy
import jupyter
import matplotlib
import sklearn
import scipy
import pandas
import PIL
import seaborn
import h5py
import tensorflow
import keras
def check_version(pkg, version):
actual = pkg.__version__.split('.')
if len(actual) == 3:
actual_major = '.'.join(actual[:2])
elif... | Houston we are go!
| MIT | course/0_Check_Environment.ipynb | tetsu/zero-deep-learning |
Preprocessing | # Import our dependencies
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import pandas as pd
import tensorflow as tf
# Import and read the charity_data.csv.
import pandas as pd
application_df = pd.read_csv("charity_data.csv")
application_df.head()
# Drop the non... | _____no_output_____ | ADSL | Alphabet_Soup_Charity_Final.ipynb | serastva/Deep_learning_challenge |
Compile, Train and Evaluate the Model | # Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer.
input_features = len(X_train_scaled[0])
hidden_nodes_layer1 = 80
hidden_nodes_layer2 = 30
#hidden_nodes_layer3 = 60
nn = tf.keras.models.Sequential()
# First hidden layer
nn.add(tf.keras.layers.Dense(units=hidden... | _____no_output_____ | ADSL | Alphabet_Soup_Charity_Final.ipynb | serastva/Deep_learning_challenge |
**Optimization 1** | # Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer.
input_features = len(X_train_scaled[0])
hidden_nodes_layer1 = 43
hidden_nodes_layer2 = 25
#hidden_nodes_layer3 = 15
nn2 = tf.keras.models.Sequential()
# First hidden layer
nn2.add(tf.keras.layers.Dense(units=hidd... | _____no_output_____ | ADSL | Alphabet_Soup_Charity_Final.ipynb | serastva/Deep_learning_challenge |
**Optimization 2** | # Define the model - deep neural net, i.e., the number of input features and hidden nodes for each layer.
input_features = len(X_train_scaled[0])
hidden_nodes_layer1 = 20
hidden_nodes_layer2 = 40
hidden_nodes_layer3 = 80
nn3 = tf.keras.models.Sequential()
# First hidden layer
nn3.add(tf.keras.layers.Dense(units=hidde... | _____no_output_____ | ADSL | Alphabet_Soup_Charity_Final.ipynb | serastva/Deep_learning_challenge |
Numpy We have seen python basic data structures in our last section. They are great but lack specialized features for data analysis. Like, adding rows, columns, operating on 2d matrices aren't readily available. So, we will use *numpy* for such functions. | import numpy as np | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl |
Numpy operates on *nd* arrays. These are similar to lists but contains homogenous elements but easier to store 2-d data. | l1 = [1,2,3,4]
nd1 = np.array(l1)
print(nd1)
l2 = [5,6,7,8]
nd2 = np.array([l1,l2])
print(nd2) | [1 2 3 4]
[[1 2 3 4]
[5 6 7 8]]
| MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl |
Sum functions on np.array() | print(nd2.shape)
print(nd2.size)
print(nd2.dtype) | (2, 4)
8
int64
| MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl |
Question 1Create an identity 2d-array or matrix (with ones across the diagonal).[ **Hint:** You can also use **np.identity()** function ] | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl | |
Question 2Create a 2d-array or matrix of order 3x3 with values = 9,8,7,6,5,4,3,2,1 arranged in the same order.Use: **np.array()** function | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl | |
Question 3Interchange both the rows and columns of the given matrix.Hint: You can use the transpose **.T**) | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl | |
Question 4Add + 1 to all the elements in the given matrix. | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl | |
Similarly you can do operations like scalar substraction, division, multiplication (operating on each element in the matrix) Question 5Find the mean of all elements in the given matrix nd6.nd6 = [[ 1 4 9 121 144 169] [ 16 25 36 196 225 256] [ 49 64 81 289 324 361]] Use: **.mean()** function | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl | |
Question 7Find the dot product of two given matrices.[**Hint:** Use **np.dot()**] | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl | |
Array Slicing/Indexing:- Now we'll learn to access multiple elements or a range of elements from an array. | x = np.arange(20)
x | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl |
Question 8Print the array elements from start to 4th position | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl | |
Question 9- Return elements from first position with step size 2. (Difference between consecutive elements is 2) | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl | |
Question 10Reverse the array using array indexing: | _____no_output_____ | MIT | notebooks/PE_Numpy.ipynb | NickBaynham/aimldl | |
The Graph Data AccessIn this notebook, we read in the data that was generated and saved as a csv from the [TheGraphDataSetCreation](TheGraphDataSetCreation.ipynb) notebook. Goals of this notebook are to obtain:* Signals, states, event and sequences* Volatility metrics* ID perceived shocks (correlated with announcement... | # import libraries
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import scipy as sp
from statsmodels.distributions.empirical_distribution import ECDF
import scipy.stats as stats | _____no_output_____ | MIT | notebooks/analysis/TheGraphDataAnalysis.ipynb | trangnv/geb-simulations-h20 |
Import data and add additional attributes | graphData = pd.read_csv('saved_results/RaiLiveGraphData.csv')
del graphData['Unnamed: 0']
graphData.head()
graphData.describe()
graphData.plot(x='blockNumber',y='redemptionPriceActual',kind='line',title='redemptionPriceActual')
graphData.plot(x='blockNumber',y='redemptionRateActual',kind='line',title='redemptionRateAct... | _____no_output_____ | MIT | notebooks/analysis/TheGraphDataAnalysis.ipynb | trangnv/geb-simulations-h20 |
Error experimentation Note: not taking into account control period | kp = 2e-7
#ki = (-kp * error)/(integral_error)
# computing at each time, what would the value of ki need to be such that the redemption price would be constant
graphData['equilibriation_ki'] = (-kp * graphData.error)/graphData.error_integral
# todo iterate through labels and append negative
graphData['equilibriation_ki... | _____no_output_____ | MIT | notebooks/analysis/TheGraphDataAnalysis.ipynb | trangnv/geb-simulations-h20 |
Counterfactual if intergral control rate had been median the whole time | graphData['counterfactual_redemption_rate'] = (kp * graphData['error'] + graphData['equilibriation_ki'].median())/ graphData['error_integral']
subsetGraph = graphData.iloc[50:]
sns.lineplot(data=subsetGraph,x="blockNumber", y="counterfactual_redemption_rate",label='Counterfactual')
ax2 = plt.twinx()
# let reflexer know... | _____no_output_____ | MIT | notebooks/analysis/TheGraphDataAnalysis.ipynb | trangnv/geb-simulations-h20 |
Goodness of fit testsWhether or not counterfactual is far enough from actual to reject null that they are from the same distributions. | # fit a cdf
ecdf = ECDF(subsetGraph.redemptionRateActual.values)
ecdf2 = ECDF(subsetGraph.counterfactual_redemption_rate.values)
plt.plot(ecdf.x,ecdf.y,color='r')
plt.title('redemptionRateActual ECDF')
plt.show()
plt.plot(ecdf2.x,ecdf2.y,color='b')
plt.title('counterfactual_redemption_rate ECDF')
plt.show()
alpha = ... | _____no_output_____ | MIT | notebooks/analysis/TheGraphDataAnalysis.ipynb | trangnv/geb-simulations-h20 |
Based on our analysis using the Kolmogorov-Smirnov Goodness-of-Fit Test, the distributions are very different. As can be seen above from their EDCF plots, you can see a different in their distributions, however pay close attention to the x axis and you can see the distribution difference is significant. | # scatterplot of linear regressoin residuals
sns.residplot(x='blockNumber', y='redemptionRateActual', data=subsetGraph, label='redemptionRateActual')
plt.title('redemptionRateActual regression residuals')
sns.residplot(x='blockNumber', y='counterfactual_redemption_rate', data=subsetGraph,label='counterfactual_redemptio... | _____no_output_____ | MIT | notebooks/analysis/TheGraphDataAnalysis.ipynb | trangnv/geb-simulations-h20 |
Recurrent Neural Networks | import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt | _____no_output_____ | MIT | course/.ipynb_checkpoints/8 Recurrent Neural Networks-checkpoint.ipynb | ResitKadir1/aws-DL |
Time series forecasting | df = pd.read_csv('../data/cansim-0800020-eng-6674700030567901031.csv',
skiprows=6, skipfooter=9,
engine='python')
df.head()
from pandas.tseries.offsets import MonthEnd
df['Adjustments'] = pd.to_datetime(df['Adjustments']) + MonthEnd(1)
df = df.set_index('Adjustments')
df.head()
df.plot... | _____no_output_____ | MIT | course/.ipynb_checkpoints/8 Recurrent Neural Networks-checkpoint.ipynb | ResitKadir1/aws-DL |
Fully connected predictor | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import tensorflow.keras.backend as K
from tensorflow.keras.callbacks import EarlyStopping
K.clear_session()
model = Sequential()
model.add(Dense(12, #12 nodes
input_dim=1, #one input
activation='re... | _____no_output_____ | MIT | course/.ipynb_checkpoints/8 Recurrent Neural Networks-checkpoint.ipynb | ResitKadir1/aws-DL |
Recurrent predictor | from tensorflow.keras.layers import LSTM
X_train.shape
#3D tensor with shape (batch_size, timesteps, input_dim)
X_train[:, None].shape
X_train_t = X_train[:, None]
X_test_t = X_test[:, None]
K.clear_session()
model = Sequential()
model.add(LSTM(6,
input_shape=(1, 1)#1 timestep ,1 number
)... | _____no_output_____ | MIT | course/.ipynb_checkpoints/8 Recurrent Neural Networks-checkpoint.ipynb | ResitKadir1/aws-DL |
Windows | train_sc.shape
train_sc_df = pd.DataFrame(train_sc, columns=['Scaled'], index=train.index)
test_sc_df = pd.DataFrame(test_sc, columns=['Scaled'], index=test.index)
train_sc_df.head()
#12 months back shifts
for s in range(1, 13):
train_sc_df['shift_{}'.format(s)] = train_sc_df['Scaled'].shift(s)
test_sc_df['shif... | _____no_output_____ | MIT | course/.ipynb_checkpoints/8 Recurrent Neural Networks-checkpoint.ipynb | ResitKadir1/aws-DL |
Fully Connected on Windows | K.clear_session()
model = Sequential()
model.add(Dense(12, input_dim=12, activation='relu'))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.summary()
model.fit(X_train, y_train, epochs=200,
batch_size=1, verbose=1, callbacks=[early_stop])
y_pred = model.predict(X_test)
p... | WARNING:tensorflow:5 out of the last 13 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7fde7bc085f0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with differen... | MIT | course/.ipynb_checkpoints/8 Recurrent Neural Networks-checkpoint.ipynb | ResitKadir1/aws-DL |
LSTM on Windows | X_train_t = X_train.reshape(X_train.shape[0], 1, 12)
X_test_t = X_test.reshape(X_test.shape[0], 1, 12)
X_train_t.shape #one time instance with 12 vector coordinates
K.clear_session()
model = Sequential()
model.add(LSTM(6, input_shape=(1, 12)#our shaped dimensions,parameter 6*12*3?
))
model.add(Dense(1))... | WARNING:tensorflow:5 out of the last 12 calls to <function Model.make_predict_function.<locals>.predict_function at 0x7fde7ca8ad40> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with differen... | MIT | course/.ipynb_checkpoints/8 Recurrent Neural Networks-checkpoint.ipynb | ResitKadir1/aws-DL |
Handwritten Digits Classifier with Improved Accuracy using Data Augmentation In previous steps, we trained a model that could recognize handwritten digits using the MNIST dataset. We were able to achieve above 98% accuracy on our validation dataset. However, when you deploy the model in an Android app and test it, you... | import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import random
print(tf.__version__) | 2.6.0
| Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
Import the MNIST dataset | mnist = keras.datasets.mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Normalize the input image so that each pixel value is between 0 to 1.
train_images = train_images / 255.0
test_images = test_images / 255.0
# Add a color dimension to the images in "train" and "validate" datase... | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step
11501568/11490434 [==============================] - 0s 0us/step
| Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
Define an utility function so that we can create quickly create multiple models with the same model architecture for comparison. | def create_model():
model = keras.Sequential(
[
keras.layers.InputLayer(input_shape=(28,28,1)),
keras.layers.Conv2D(filters=32, kernel_size=(3,3), activation=tf.nn.relu),
keras.layers.Conv2D(filters=64, kernel_size=(3,3), activation=tf.nn.relu),
keras.layers.MaxPooling2D(pool_size=(2... | _____no_output_____ | Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
Confirm that our model can achieve above 98% accuracy on MNIST Dataset. | base_model = create_model()
base_model.fit(
train_images,
train_labels,
epochs=5,
validation_data=(test_images, test_labels)
) | Epoch 1/5
1875/1875 [==============================] - 43s 7ms/step - loss: 0.1418 - accuracy: 0.9569 - val_loss: 0.0580 - val_accuracy: 0.9815
Epoch 2/5
1875/1875 [==============================] - 12s 7ms/step - loss: 0.0544 - accuracy: 0.9836 - val_loss: 0.0515 - val_accuracy: 0.9829
Epoch 3/5
1875/1875 [===========... | Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
Troubleshoot the accuracy dropLet's see the digit images in MNIST again and guess the cause of the accuracy drop we experienced in deployment. | # Show the first 25 images in the training dataset.
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(np.squeeze(train_images[i], axis=2), cmap=plt.cm.gray)
plt.xlabel(train_labels[i])
plt.show() | _____no_output_____ | Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
We can see from the 25 images above that the digits are about the same size, and they are in the center of the images. Let's verify if this assumption is true across the MNIST dataset. | # An utility function that returns where the digit is in the image.
def digit_area(mnist_image):
# Remove the color axes
mnist_image = np.squeeze(mnist_image, axis=2)
# Extract the list of columns that contain at least 1 pixel from the digit
x_nonzero = np.nonzero(np.amax(mnist_image, 0))
x_min = np.min(x_... | _____no_output_____ | Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
Now for the histogram, you can confirm that the digit in MNIST images are fitted nicely in an certain area at the center of the images.[MNIST Range](https://download.tensorflow.org/models/tflite/digit_classifier/mnist_range.png)However, when you wrote digits in your Android app, you probably did not pay attention to ma... | # Define data augmentation
datagen = keras.preprocessing.image.ImageDataGenerator(
rotation_range=30,
width_shift_range=0.25,
height_shift_range=0.25,
shear_range=0.25,
zoom_range=0.2
)
# Generate augmented data from MNIST dataset
train_generator = datagen.flow(train_images, train_labels)
test_gen... | _____no_output_____ | Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
Let's see what our digit images look like after augmentation. You can see that we now clearly have much more variation on how the digits are placed in the images. | augmented_images, augmented_labels = next(train_generator)
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5, 5, i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(np.squeeze(augmented_images[i], axis=2), cmap=plt.cm.gray)
plt.xlabel('Label: %d' % augmented_labels[i])
plt.show() | _____no_output_____ | Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
Let's evaluate the digit classifier model that we trained earlier on this augmented test dataset and see if it makes accuracy drop. | base_model.evaluate(test_generator) | 313/313 [==============================] - 6s 18ms/step - loss: 5.6356 - accuracy: 0.3272
| Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
You can see that accuracy significantly dropped to below 40% in augmented test dataset. Improve accuracy with data augmentationNow let's train our model using augmented dataset to make it perform better in deployment. | improved_model = create_model()
improved_model.fit(train_generator, epochs=5, validation_data=test_generator) | Epoch 1/5
1875/1875 [==============================] - 41s 22ms/step - loss: 0.9860 - accuracy: 0.6849 - val_loss: 0.5181 - val_accuracy: 0.8516
Epoch 2/5
1875/1875 [==============================] - 40s 22ms/step - loss: 0.5070 - accuracy: 0.8491 - val_loss: 0.3765 - val_accuracy: 0.8877
Epoch 3/5
1875/1875 [=========... | Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
We can see that as the models saw more distorted digit images during training, its accuracy evaluated distorted test digit images were significantly improved to about 90%. Convert to TensorFlow LiteLet's convert the improved model to TensorFlow Lite and redeploy the Android app. | # Convert Keras model to TF Lite format and quantize.
converter = tf.lite.TFLiteConverter.from_keras_model(improved_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_quantized_model = converter.convert()
# Save the Quantized Model to file to the Downloads Directory
f = open('mnist-improved.tflite', "... | _____no_output_____ | Apache-2.0 | notebooks/handwritten_digits_tunning.ipynb | dgavieira/handwritten-digits-recognition-app |
_____no_output_____ | MIT | nltk_treinar_etiquetador.ipynb | ilexistools/ebralc2021 | ||
Treinar um etiquetador morfossintáticoPara realizar a etiquetagem morfossintática de textos, é preciso obter um etiquetador. O NLTK possui diversas opções para a criação de classificadores e etiquetadores de palavras: DefaultTagger, RegexpTagger, UnigramTagger, BigramTagger, TrigramTagger, BrillTagger, além de outros ... | import nltk
nltk.download('mac_morpho')
nltk.download('punkt')
import nltk
import pickle
from nltk.corpus import mac_morpho
# prepara dados de treinamento e teste
sents = mac_morpho.tagged_sents()
trein = sents[0:30000]
teste = sents[13000:]
# treina um etiquetador sequencial
etq1 = nltk.DefaultTagger('N')
etq2 = n... | DefaultTagger 0.20087708474599295
UnigramTagger 0.8237940367746194
BigramTagger 0.842816406510894
| MIT | nltk_treinar_etiquetador.ipynb | ilexistools/ebralc2021 |
No exemplo, carregamos os dados etiquetados para treinamento e teste do etiquetador. Separamos uma quantidade maior de sentenças para treino (70%) e outra menor para teste (30%).Em seguida, iniciamos o processo de treinamento de um etiquetador sequencial a partir de três modelos diferentes combinados. O etiquetador 'De... | import nltk
import pickle
# carrega o etiquetador treinado
with open('etq.pickle','rb') as fh:
etiquetador = pickle.load(fh)
# armazena um texto a ser etiquetado como teste
texto = 'Estamos realizando um teste agora.'
# itemiza o texto
itens = nltk.word_tokenize(texto,language='portuguese')
# etiqueta os itens
it... | [('Estamos', 'V'), ('realizando', 'V'), ('um', 'ART'), ('teste', 'N'), ('agora', 'ADV'), ('.', '.')]
| MIT | nltk_treinar_etiquetador.ipynb | ilexistools/ebralc2021 |
An example of an optimal pruning based routing algorithm- based on a simple graph and Dijkstra's algorithm with concave cost function- Create a simple graph with multiple edge's attributes¶ - weight = w_ij - concave = c_ij where i,j is nodes | import networkx as nx
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Python_Graph/A simple graph with optimal pruning based routing.ipynb | phoophoo187/Privacy_SDN_Edge_IoT |
Define functions | def add_multi_link_attributes(G,attr1,attr2):
"""
This funtion is to add the multiple link attributes to graph G
input: G : graph
attr1 : link attribute 1
attr2 : link attribute 2
output : G
"""
i = 0
for (u, v) in G.edges():
G.add_edge(u,v,w=attr1[i],c=attr2[... | _____no_output_____ | MIT | Python_Graph/A simple graph with optimal pruning based routing.ipynb | phoophoo187/Privacy_SDN_Edge_IoT |
Create a graph | G = nx.Graph()
edge_list = [('S', 'B'), ('S', 'A'), ('S','E'), ('B','A'), ('B','D'), ('A','D'), ('E','D')]
Weight_edge_list = [2, 2, 3, 2, 1, 2, 2]
Concave_edge_list = [1, 3, 3, 1, 4, 3, 1]
pos = { 'S': (0,50), 'B': (50, 100), 'A': (50, 50), 'E': (50, 0), 'D': (100, 50)} # draw by position
G.add_edges_from(edge_list)
... | _____no_output_____ | MIT | Python_Graph/A simple graph with optimal pruning based routing.ipynb | phoophoo187/Privacy_SDN_Edge_IoT |
Run the optimum-pruning-based-routing algorithm | Optimum_prun_based_routing(G,'S','D',5) | 3
{'w': 2, 'c': 1}
{'w': 2, 'c': 3}
{'w': 3, 'c': 3}
{'w': 2, 'c': 1}
{'w': 1, 'c': 4}
[('B', 'D')]
{'w': 2, 'c': 3}
{'w': 2, 'c': 1}
4
{'w': 2, 'c': 1}
{'w': 2, 'c': 3}
[('S', 'A')]
{'w': 3, 'c': 3}
[('S', 'A'), ('S', 'E')]
{'w': 2, 'c': 1}
{'w': 2, 'c': 3}
[('S', 'A'), ('S', 'E'), ('A', 'D')]
{'w': 2, 'c': 1}
| MIT | Python_Graph/A simple graph with optimal pruning based routing.ipynb | phoophoo187/Privacy_SDN_Edge_IoT |
Machine Learning Engineer Nanodegree Introduction and Foundations Project: Titanic Survival ExplorationIn 1912, the ship RMS Titanic struck an iceberg on its maiden voyage and sank, resulting in the deaths of most of its passengers and crew. In this introductory project, we will explore a subset of the RMS Titanic pas... | # Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Import supplementary visualizations code visuals.py
import visuals as vs
# Pretty display for notebooks
%matplotlib inline
# Load the dataset
in_file... | _____no_output_____ | MIT | titanic_survival_exploration.ipynb | numanyilmaz/titanic_survival_exploration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.