3. import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data_set=pd.read_csv(“/Users/naubergois/
Churn_Modelling.csv")
X=data_set.iloc[:,3:13]
y=data_set.iloc[:,13]
Analisando a saida de clientes de um banco
4. import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.metrics import r2_score
from sklearn.metrics import confusion_matrix
from sklearn.preprocessing import LabelEncoder,OneHotEncoder
le=LabelEncoder()
one=OneHotEncoder(categorical_features=[1])
data_set=pd.read_csv("/Users/naubergois/Churn_Modelling.csv")
data_set.Geography=le.fit_transform(data_set.Geography)
data_set.Gender=le.fit_transform(data_set.Gender)
X=data_set.iloc[:,3:12].values
y=data_set.iloc[:,13].values
21. Ao contrário da regressão real,
a regressão logística não tenta
prever o valor de uma variável
numérica dado um conjunto de
entradas. Em vez disso, a saída
é uma probabilidade de que o
dado ponto de entrada pertence
a uma determinada classe. Para
simplificar, vamos supor que
temos apenas duas classes
(para problemas multiclasse,
você pode olhar para
Multinomial Logistic
Regression), e a probabilidade
em questão é P_ + -> a
probabilidade de que um
determinado ponto de dados
pertence à classe '+'. Claro, P_-
= 1 - P_ +. Assim, a saída da
Regressão Logística encontra-
se sempre em [0, 1].
22. A premissa central da Regressão
Logística é a suposição de que seu
espaço de entrada pode ser separado
em duas "regiões" agradáveis, uma
para cada classe, por um limite linear
(ler: reto). Então, o que significa uma
fronteira "linear"? Para duas
dimensões, é uma linha reta, sem
curvar. Para três dimensões, é um
plano. E assim por diante. Esta
fronteira será, obviamente, decidida
pelos seus dados de entrada e pelo
algoritmo de aprendizagem. Mas para
que isso faça sentido, é claro que os
pontos de dados devem ser
separáveis nas duas regiões acima
mencionadas por um limite linear. Se
seus pontos de dados satisfazem
essa restrição, eles são considerados
como sendo linearmente separáveis.
23. The softmax function is important in the field of machine
learning because it can map a vector to a probability of a
given output in binary classification.
34. import tensorflow as tf
import sys
# change this as you see fit
image_path = '/Users/naubergois/Star-wars-classifier/star_wars/Darth Vader/
pic_001.jpg'
# read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line in tf.gfile.GFile("retrained_labels.txt")]
# Unpersists graph from file
with tf.gfile.FastGFile("retrained_graph.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
35. with tf.Session() as sess:
# Feed the image_data as input to the graph and get first prediction
softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
predictions = sess.run(softmax_tensor,
{'DecodeJpeg/contents:0': image_data})
# Sort to show labels of first prediction in order of confidence
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
for node_id in top_k:
human_string = label_lines[node_id]
score = predictions[0][node_id]
print('%s (score = %.5f)' % (human_string, score))
36. William Shakespeare foi um poeta,
dramaturgo e ator inglês, tido
como o maior escritor do idioma
inglês e o mais influente
dramaturgo do mundo. É
chamado frequentemente de
poeta nacional da Inglaterra e de
"Bardo do Avon". Wikipédia
37. from __future__ import absolute_import, division, print_function
import os
import pickle
from six.moves import urllib
import tflearn
from tflearn.data_utils import *
path = "shakespeare_input.txt"
char_idx_file = 'char_idx.pickle'
if not os.path.isfile(path):
urllib.request.urlretrieve("https://raw.githubusercontent.com/tflearn/
tflearn.github.io/master/resources/shakespeare_input.txt", path)
maxlen = 25
39. g = tflearn.input_data([None, maxlen, len(char_idx)])
g = tflearn.lstm(g, 512, return_seq=True)
g = tflearn.dropout(g, 0.5)
g = tflearn.lstm(g, 512, return_seq=True)
g = tflearn.dropout(g, 0.5)
g = tflearn.lstm(g, 512)
g = tflearn.dropout(g, 0.5)
g = tflearn.fully_connected(g, len(char_idx),
activation='softmax')
40. g = tflearn.regression(g, optimizer='adam',
loss='categorical_crossentropy',
learning_rate=0.001)
m = tflearn.SequenceGenerator(g, dictionary=char_idx,
seq_maxlen=maxlen,
clip_gradients=5.0,
checkpoint_path='model_shakespeare')
41. for i in range(50):
seed = random_sequence_from_textfile(path, maxlen)
m.fit(X, Y, validation_set=0.1, batch_size=128,
n_epoch=1, run_id='shakespeare')
print("-- TESTING...")
print("-- Test with temperature of 1.0 --")
print(m.generate(600, temperature=1.0, seq_seed=seed))
print("-- Test with temperature of 0.5 --")
print(m.generate(600, temperature=0.5, seq_seed=seed))