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
1.Carregando a Base de Dados de Treino e realizando análise exploratória
dados = pd.read_csv("train_data (1).csv", sep=',', encoding='utf-8', low_memory=False) dados dados.shape dados.dtypes dados.nunique() 6000-5859
_____no_output_____
MIT
Notebooks/Filtro AntiSPAM - parte 1.ipynb
gustavocfv/filtroantispam-PLN
Há 141 mensagens repetidas.
dados = dados.sort_values(by='LABEL', ascending=True) dados[(dados.duplicated(subset="SMS", keep='first'))==True]
_____no_output_____
MIT
Notebooks/Filtro AntiSPAM - parte 1.ipynb
gustavocfv/filtroantispam-PLN
Há mensagens repetidas classificadas tanto como BLOCKED como OK.
dados[(dados.duplicated(subset="SMS", keep='first'))==True].head(20) dados[(dados.duplicated(subset="SMS", keep='first'))==True].tail(20) dados[(dados['LABEL']=="blocked")]
_____no_output_____
MIT
Notebooks/Filtro AntiSPAM - parte 1.ipynb
gustavocfv/filtroantispam-PLN
1500 casos considerados BLOCKED
dados[(dados['LABEL']=="blocked")].head(20) dados[(dados['LABEL']=="blocked")].tail(20)
_____no_output_____
MIT
Notebooks/Filtro AntiSPAM - parte 1.ipynb
gustavocfv/filtroantispam-PLN
Aparentemente, nem todo BLOCKED possui link (vide o registro 0, embora a classificação possa ter considerado BB.COM como um link).
dados[(dados['LABEL']=="ok")]
_____no_output_____
MIT
Notebooks/Filtro AntiSPAM - parte 1.ipynb
gustavocfv/filtroantispam-PLN
4500 casos considerados OK
dados[(dados['LABEL']=="ok")].head(20) dados[(dados['LABEL']=="ok")].tail(20) tamanho_base = len(dados) tamanho_base_ok = len(dados[(dados['LABEL'])=='ok']) tamanho_base_blocked = len(dados[(dados['LABEL'])=='blocked']) porcentagem_ok = (tamanho_base_ok * 100) / tamanho_base porcentagem_blocked = 100 - porcentagem_ok ...
_____no_output_____
MIT
Notebooks/Filtro AntiSPAM - parte 1.ipynb
gustavocfv/filtroantispam-PLN
Não há valores faltantes.
import re
_____no_output_____
MIT
Notebooks/Filtro AntiSPAM - parte 1.ipynb
gustavocfv/filtroantispam-PLN
Hipótese: a classificação é dada de acordo com a presença de URLs no SMS. Vamos tentar verificar a presença de URLs nas amostras de SMS com Status = OK e Status = Blocked. Como na visualização dos primeiros 20 e dos últimos 20 de cada grupo foi possível perceber que há URLs de diferentes formatos (com e sem "http://", ...
dados['SMS'][0] urls = re.findall('\w+\.\w+', dados['SMS'][0]) print(len(urls)) urls dados['SMS'][(dados['LABEL']=="ok")] aux = [] for item in dados['SMS'][(dados['LABEL']=="ok")]: aux.append(re.findall('\w+\.\w+', item)) print(aux) print(len(aux))
4500
MIT
Notebooks/Filtro AntiSPAM - parte 1.ipynb
gustavocfv/filtroantispam-PLN
Analisando as supostas URLs dos SMS com status = ok, percebemos que a maioria é numérica, o que pode indicar excertos de CPFs (quando o segundo elemento é composto de 3 dígitos) ou endereços tipo IP. Também verificamos algumas URLs verdadeiras, como bitnuvem.com, gmail.com, cemporcentoskate.uol.com.br, ocean.overseaweb...
aux = [] for item in dados['SMS'][(dados['LABEL']=="blocked")]: aux.append(re.findall('\w+\.\w+', item)) print(aux) print(len(aux))
1500
MIT
Notebooks/Filtro AntiSPAM - parte 1.ipynb
gustavocfv/filtroantispam-PLN
Building Relation Network Using Tensorflow Relation network is pretty simple, right? Now, we will understand relation network better by implementing it in TensorFlow. We will consider a simple binary classification problem and see how can we solve them using a relation network. First, we import all the required libra...
import tensorflow as tf import numpy as np
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Let us say we have two classes in our dataset, we will randomly generate some 1000 data points for each of these classes.
classA = np.random.rand(1000,18) ClassB = np.random.rand(1000,18)
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Create our dataset by combining both of these classes,
data = np.vstack([classA, ClassB])
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Now we will set the label, we assign label 1 for classA and label 0 for classB.
label = np.vstack([np.ones((len(classA),1)),np.zeros((len(ClassB),1))])
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
So, our dataset will have 2000 records
data.shape label.shape
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Now, we will define the placeholders for our support set $x_i$ and query set $x_j$.
xi = tf.placeholder(tf.float32, [None, 9]) xj = tf.placeholder(tf.float32, [None, 9])
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Define the placeholder for label y,
y = tf.placeholder(tf.float32, [None, 1])
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Now, we will define our embedding function $f_{\varphi}$() to learn the embeddings of support set and query set. We will use a normal feedforward network as our embedding function.
def embedding_function(x): weights = tf.Variable(tf.truncated_normal([9,1])) bias = tf.Variable(tf.truncated_normal([1])) a = (tf.nn.xw_plus_b(x,weights,bias)) embeddings = tf.nn.relu(a) return embeddings
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Compute the embeddings of our support set i.e $f_{\varphi}(x_i) $
f_xi = embedding_function(xi)
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Compute the embeddings of our query set i.e $f_{\varphi}(x_j)$
f_xj = embedding_function(xj)
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Now that we calculated the embeddings and have the feature vectors, we combine both the support set and query set feature vectors i.e $Z(f_{\varphi}(x_i), f_{\varphi}(x_j))$
Z = tf.concat([f_xi,f_xj],axis=1)
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
We define our relation function $g_{\phi}()$ as three layered neural network with relu activations,
def relation_function(x): w1 = tf.Variable(tf.truncated_normal([2,3])) b1 = tf.Variable(tf.truncated_normal([3])) w2 = tf.Variable(tf.truncated_normal([3,5])) b2 = tf.Variable(tf.truncated_normal([5])) w3 = tf.Variable(tf.truncated_normal([5,1])) b3 = tf.Variable(tf.truncated_normal([1...
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
We now pass the concatenated feature vectors of support set and query set to the relation function and get the relation scores,
relation_scores = relation_function(Z)
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
We define our loss function as mean squared error i.e squared difference between relation scores and actual y value.
loss_function = tf.reduce_mean(tf.squared_difference(relation_scores,y))
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
We can minimize the loss using adam optimizer,
optimizer = tf.train.AdamOptimizer(0.1) train = optimizer.minimize(loss_function)
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Now, let's start our tensorflow session
sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer())
_____no_output_____
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Now, we randomly sample data points for our support set $x_i$ and query set $x_j$ and train the network,
for episode in range(1000): _, loss_value = sess.run([train, loss_function], feed_dict={xi:data[:,0:9]+np.random.randn(*np.shape(data[:,0:9]))*0.05, xj:data[:,9:]+np.random.randn(*np.shape(data[:,9:]))*0.05, ...
Episode 0: loss 0.498 Episode 100: loss 0.250 Episode 200: loss 0.248 Episode 300: loss 0.248 Episode 400: loss 0.247 Episode 500: loss 0.248 Episode 600: loss 0.248 Episode 700: loss 0.248 Episode 800: loss 0.247 Episode 900: loss 0.248
MIT
Chapter04/.ipynb_checkpoints/4.5 Building Relation Network Using Tensorflow-checkpoint.ipynb
kvpratama/Hands-On-Meta-Learning-with-Python
Example 9.2: Otto Cycle (Air-Standard)*John F. Maddox, Ph.D., P.E.University of Kentucky - Paducah CampusME 321: Engineering Thermodynamics II* Problem StatementAn Otto cycle with compression ratio of $8$ starts its compression stroke from $p_1=1\ \text{bar}$, $T_1=300\ \text{K}$. The maximum temperature after combu...
from kilojoule.templates.kSI_K import * air = idealgas.Properties('Air', unit_system='SI_C')
_____no_output_____
MIT
examples/ME321-Thermodynamics_II/02 - Chapter 9 Gas Power Cycles/Ex9.2 Otto Cycle (Air-Standard).ipynb
johnfmaddox/kilojoule
Given ParametersWe now define variables to hold our known values.
%%showcalc T[1] = Quantity(300,'K') p[1] = Quantity(1,'bar') T_max = Quantity(1200,'K') r = Quantity(8,'')
_____no_output_____
MIT
examples/ME321-Thermodynamics_II/02 - Chapter 9 Gas Power Cycles/Ex9.2 Otto Cycle (Air-Standard).ipynb
johnfmaddox/kilojoule
Assumptions - Treat air as an ideal gas - Variable Specific Heat
%%showcalc R = air.R
_____no_output_____
MIT
examples/ME321-Thermodynamics_II/02 - Chapter 9 Gas Power Cycles/Ex9.2 Otto Cycle (Air-Standard).ipynb
johnfmaddox/kilojoule
(c) $T$,$p$ at each state
%%showcalc # Isentropic Compression $1\to2$ s[1] = air.s(T[1],p[1]) v[1] = R*T[1]/p[1] v[2] = v[1]/r s[2] = s[1] T[2] = air.T(s[2],v[2]) p[2] = air.p(s[2],v[2]) # Isochoric Heat Addition $2\to3$ v[3] = v[2] T[3] = T_max p[3] = air.p(T=T[3],v=v[3]) # Isentropic Expansion $3\to4$ s[3] = air.s(T[3],v[3]) s[4] = s[3] v[4...
_____no_output_____
MIT
examples/ME321-Thermodynamics_II/02 - Chapter 9 Gas Power Cycles/Ex9.2 Otto Cycle (Air-Standard).ipynb
johnfmaddox/kilojoule
(a) $p$-$v$ diagram
pv = air.pv_diagram() for i in [1,2,3,4]: pv.plot_state(states[i],label_loc='east') pv.plot_process(states[1],states[2], path='isentropic',label='isentropic',pos=.8) pv.plot_process(states[2],states[3], path='isochoric') pv.plot_process(states[3],states[4], path='isentropic',label='isentropic') pv.plot_process(stat...
_____no_output_____
MIT
examples/ME321-Thermodynamics_II/02 - Chapter 9 Gas Power Cycles/Ex9.2 Otto Cycle (Air-Standard).ipynb
johnfmaddox/kilojoule
(b) $T$-$s$ diagram
Ts = air.Ts_diagram() for i in [1,2,3,4]: Ts.plot_state(states[i], label_loc='north east') Ts.plot_process(states[1],states[2], path='isentropic') Ts.plot_process(states[2],states[3], path='isochoric',label='isochoric') Ts.plot_process(states[3],states[4], path='isentropic') Ts.plot_process(states[4],states[1], pat...
_____no_output_____
MIT
examples/ME321-Thermodynamics_II/02 - Chapter 9 Gas Power Cycles/Ex9.2 Otto Cycle (Air-Standard).ipynb
johnfmaddox/kilojoule
(d) $q_{in}$
%%showcalc # Heat transfer only takes place from $2\to3$ and from $4\to1$ u[2] = air.u(T[2],p[2]) u[3] = air.u(T[3],p[3]) q_2_to_3 = u[3]-u[2] q_in = q_2_to_3
_____no_output_____
MIT
examples/ME321-Thermodynamics_II/02 - Chapter 9 Gas Power Cycles/Ex9.2 Otto Cycle (Air-Standard).ipynb
johnfmaddox/kilojoule
(e) $w_{net}$
%%showcalc u[1] = air.u(T[1],p[1]) u[4] = air.u(T[4],p[4]) q_4_to_1 = u[4]-u[1] q_out = q_4_to_1 w_net = q_in-q_out
_____no_output_____
MIT
examples/ME321-Thermodynamics_II/02 - Chapter 9 Gas Power Cycles/Ex9.2 Otto Cycle (Air-Standard).ipynb
johnfmaddox/kilojoule
(f) $\eta_{th}$
%%showcalc # Thermal efficiency eta_th = w_net/q_in Summary() Summary(['q_in','w_net','eta_th']);
_____no_output_____
MIT
examples/ME321-Thermodynamics_II/02 - Chapter 9 Gas Power Cycles/Ex9.2 Otto Cycle (Air-Standard).ipynb
johnfmaddox/kilojoule
Import Statements
import pandas as pd import numpy as np from bs4 import BeautifulSoup import requests import sqlite3 as sql3 import re sqlite_file = 'IL_SAMHSA.db' conn = sql3.connect(sqlite_file)
_____no_output_____
CC0-1.0
Old Notebooks/Facilities_Text_Scraping.ipynb
EchoYueXiong/bdss-notebooks-R
load in csv file with SAMHSA listings and write to SQLite
df_samhsa = pd.read_csv('IL_Behavioral_Health_Treament_Facility_listing_2017.csv') df_samhsa.to_sql('facilities', conn, if_exists='replace', index_label ='FACID') conn.commit()
_____no_output_____
CC0-1.0
Old Notebooks/Facilities_Text_Scraping.ipynb
EchoYueXiong/bdss-notebooks-R
set up a cursor - read back just the facility ids and websites
c = conn.cursor() c2 = conn.cursor() c.execute('SELECT FACID, website FROM facilities;') all_rows = c.fetchall()
_____no_output_____
CC0-1.0
Old Notebooks/Facilities_Text_Scraping.ipynb
EchoYueXiong/bdss-notebooks-R
create new table for the "about us" text for these facilities
c.execute ('CREATE TABLE abouttext (FACID integer, abouturl text, textfromurl text );') conn.commit() c.execute ('CREATE TABLE badurl (FACID integer, level text, badurl text );') conn.commit() c.execute ('CREATE TABLE maintext (FACID integer, maintext text, url1 text, url2 text, url3 text, url4 text, url5 text );') c...
_____no_output_____
CC0-1.0
Old Notebooks/Facilities_Text_Scraping.ipynb
EchoYueXiong/bdss-notebooks-R
Read each facility's website url, pull the soup, look for a tags that link to "about me" or mission or vision pagesinsert appropriate pages into the new text table in the database
about = ['about', 'who we are', 'mission', 'vision'] tags = ["p", "h1", "h2", "h3", "h4", "h5", "h6"] testrow = all_rows[0:3] for row in all_rows: thisfacid = row[0] url = row[1] # print (url) if url is not None: try: page = requests.get(url) except requests.exception...
_____no_output_____
CC0-1.0
Old Notebooks/Facilities_Text_Scraping.ipynb
EchoYueXiong/bdss-notebooks-R
set up united way database education: https://uw-mc.org/our-partners/organizations-we-fund/funded-agencies-education/income: https://uw-mc.org/our-partners/organizations-we-fund/funded-agencies-income/health: https://uw-mc.org/our-partners/organizations-we-fund/funded-agencies-health/safety net: https://uw-mc.org/our-p...
uwsqlite_file = 'IL_unitedway.sqlite' conn = sql3.connect(uwsqlite_file) c = conn.cursor() c2 = conn.cursor() c.execute ('''CREATE TABLE "main"."facilities" ("FACID" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "facname" TEXT, "factype" TEXT, "facurl" TEXT, "facloc" TEXT)''') c.execute ('CREATE TABLE abouttext (FACI...
_____no_output_____
CC0-1.0
Old Notebooks/Facilities_Text_Scraping.ipynb
EchoYueXiong/bdss-notebooks-R
Load UW facilities into all_rows then rerun about scraping routine
c.execute('SELECT FACID, facurl FROM facilities;') all_rows = c.fetchall()
_____no_output_____
CC0-1.0
Old Notebooks/Facilities_Text_Scraping.ipynb
EchoYueXiong/bdss-notebooks-R
Training Neural NetworksThe network we built in the previous part isn't so smart, it doesn't know anything about our handwritten digits. Neural networks with non-linear activations work like universal function approximators. There is some function that maps your input to the output. For example, images of handwritten ...
import torch from torch import nn import torch.nn.functional as F from torchvision import datasets, transforms # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)), ...
_____no_output_____
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
NoteIf you haven't seen `nn.Sequential` yet, please finish the end of the Part 2 notebook.
# Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10)) # Define the loss criterion = nn.CrossEntropyLoss() # Get our data images, labels = next(iter(t...
tensor(2.3165, grad_fn=<NllLossBackward>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
In my experience it's more convenient to build the model with a log-softmax output using `nn.LogSoftmax` or `F.log_softmax` ([documentation](https://pytorch.org/docs/stable/nn.htmltorch.nn.LogSoftmax)). Then you can get the actual probabilities by taking the exponential `torch.exp(output)`. With a log-softmax output, y...
# TODO: Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) # TODO: Define the loss criterion = nn.NLLLoss...
tensor(2.3085, grad_fn=<NllLossBackward>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
AutogradNow that we know how to calculate a loss, how do we use it to perform backpropagation? Torch provides a module, `autograd`, for automatically calculating the gradients of tensors. We can use it to calculate the gradients of all our parameters with respect to the loss. Autograd works by keeping track of operati...
x = torch.randn(2,2, requires_grad=True) print(x) y = x**2 print(y)
tensor([[0.1226, 0.2654], [0.8485, 0.0002]], grad_fn=<PowBackward0>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
Below we can see the operation that created `y`, a power operation `PowBackward0`.
## grad_fn shows the function that generated this variable print(y.grad_fn)
<PowBackward0 object at 0x7fd32c760fd0>
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
The autgrad module keeps track of these operations and knows how to calculate the gradient for each one. In this way, it's able to calculate the gradients for a chain of operations, with respect to any one tensor. Let's reduce the tensor `y` to a scalar value, the mean.
z = y.mean() print(z)
tensor(0.3092, grad_fn=<MeanBackward1>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
You can check the gradients for `x` and `y` but they are empty currently.
print(x.grad)
None
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
To calculate the gradients, you need to run the `.backward` method on a Variable, `z` for example. This will calculate the gradient for `z` with respect to `x`$$\frac{\partial z}{\partial x} = \frac{\partial}{\partial x}\left[\frac{1}{n}\sum_i^n x_i^2\right] = \frac{x}{2}$$
z.backward() print(x.grad) print(x/2)
tensor([[-0.1751, -0.2576], [-0.4606, -0.0064]]) tensor([[-0.1751, -0.2576], [-0.4606, -0.0064]], grad_fn=<DivBackward0>)
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
These gradients calculations are particularly useful for neural networks. For training we need the gradients of the weights with respect to the cost. With PyTorch, we run data forward through the network to calculate the loss, then, go backwards to calculate the gradients with respect to the loss. Once we have the grad...
# Build a feed-forward network model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) criterion = nn.NLLLoss() images, labels = next(iter(...
Before backward pass: None After backward pass: tensor([[ 0.0035, 0.0035, 0.0035, ..., 0.0035, 0.0035, 0.0035], [-0.0012, -0.0012, -0.0012, ..., -0.0012, -0.0012, -0.0012], [ 0.0009, 0.0009, 0.0009, ..., 0.0009, 0.0009, 0.0009], ..., [-0.0028, -0.0028, -0.0028, ..., -0....
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
Training the network!There's one last piece we need to start training, an optimizer that we'll use to update the weights with the gradients. We get these from PyTorch's [`optim` package](https://pytorch.org/docs/stable/optim.html). For example we can use stochastic gradient descent with `optim.SGD`. You can see how to...
from torch import optim # Optimizers require the parameters to optimize and a learning rate optimizer = optim.SGD(model.parameters(), lr=0.01)
_____no_output_____
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
Now we know how to use all the individual parts so it's time to see how they work together. Let's consider just one learning step before looping through all the data. The general process with PyTorch:* Make a forward pass through the network * Use the network output to calculate the loss* Perform a backward pass throug...
print('Initial weights - ', model[0].weight) images, labels = next(iter(trainloader)) images.resize_(64, 784) # Clear the gradients, do this because gradients are accumulated optimizer.zero_grad() # Forward pass, then backward pass, then update weights output = model.forward(images) loss = criterion(output, labels) ...
Updated weights - Parameter containing: tensor([[ 0.0171, 0.0027, 0.0256, ..., -0.0092, 0.0189, -0.0264], [-0.0240, -0.0350, 0.0088, ..., 0.0133, -0.0098, -0.0118], [ 0.0174, -0.0250, 0.0059, ..., 0.0169, -0.0164, 0.0153], ..., [-0.0072, 0.0155, 0.0302, ..., 0.0201, 0.03...
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
Training for realNow we'll put this algorithm into a loop so we can go through all the images. Some nomenclature, one pass through the entire dataset is called an *epoch*. So here we're going to loop through `trainloader` to get our training batches. For each batch, we'll doing a training pass where we calculate the l...
## Your solution here model = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 10), nn.LogSoftmax(dim=1)) criterion = nn.NLLLoss() optimizer = optim.SGD(model.paramet...
Training loss: 1.9357389674257877 Training loss: 0.8827209986730425 Training loss: 0.5358078456890862 Training loss: 0.43495260663568847 Training loss: 0.3874760081232992
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
With the network trained, we can check out it's predictions.
%matplotlib inline import helper images, labels = next(iter(trainloader)) img = images[26].view(1, 784) # Turn off gradients to speed up this part with torch.no_grad(): logits = model.forward(img) # Output of the network are logits, need to take softmax for probabilities ps = F.softmax(logits, dim=1) helper.view...
_____no_output_____
MIT
intro-to-pytorch/Part 3 - Training Neural Networks (Exercises).ipynb
airdenis/Deep-Learning-pythorch
Hex Ed Part 1
hex_dict = {'n': [0, 2], 'ne': [1, 1], 'nw': [-1, 1], 's': [0, -2], 'se': [1, -1], 'sw': [-1, -1]} import csv with open('input.txt', 'rt') as f_input: csv_reader = csv.reader(f_input, delimiter=',') arrows = next(csv_reader) import numpy as np def move(arrow): return np.array(hex_dict[arrow]) def travel(...
_____no_output_____
MIT
2017/ferran/day11/day11.ipynb
bbglab/adventofcode
Test
def test(): assert(fewest(['ne','ne','ne']) == 3) assert(fewest(['ne','ne','sw','sw']) == 0) assert(fewest(['ne','ne','s','s']) == 2) assert(fewest(['se','sw','se','sw','sw']) == 3) test()
_____no_output_____
MIT
2017/ferran/day11/day11.ipynb
bbglab/adventofcode
Solution
fewest(arrows)
_____no_output_____
MIT
2017/ferran/day11/day11.ipynb
bbglab/adventofcode
Part 2
def furthest_position(arrows): max_distance = 0 pos = np.array([0,0]) for arrow in arrows: pos += move(arrow) distance = min_steps(pos) if max_distance < distance: max_distance = distance return max_distance furthest_position(arrows)
_____no_output_____
MIT
2017/ferran/day11/day11.ipynb
bbglab/adventofcode
Export to modules> The functions that transform notebooks in a library The most important function defined in this module is `notebooks2script`, so you may want to jump to it before scrolling though the rest, which explain the details behind the scenes of the conversion from notebooks to library. The main things to re...
show_doc(Config, title_level=3) create_config("nbdev", user='fastai', path='..', tst_flags='tst', cfg_name='test_settings.ini') cfg = Config(cfg_name='test_settings.ini') test_eq(cfg.lib_name, 'nbdev') test_eq(cfg.git_url, "https://github.com/fastai/nbdev/tree/master/") test_eq(cfg.lib_path, Path.cwd().parent/'nbdev') ...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
We derive some useful variables to check what environment we're in:
if not os.environ.get("IN_TEST", None): assert IN_NOTEBOOK assert not IN_COLAB assert IN_IPYTHON
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Then we have a few util functions.
show_doc(last_index) test_eq(last_index(1, [1,2,1,3,1,4]), 4) test_eq(last_index(2, [1,2,1,3,1,4]), 1) test_eq(last_index(5, [1,2,1,3,1,4]), -1) show_doc(compose) f1 = lambda o,p=0: (o*2)+p f2 = lambda o,p=1: (o+1)/p test_eq(f2(f1(3)), compose(f1,f2)(3)) test_eq(f2(f1(3,p=3),p=3), compose(f1,f2)(3,p=3)) test_eq(f2(f1(3...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Reading a notebook What's a notebook? A jupyter notebook is a json file behind the scenes. We can just read it with the json module, which will return a nested dictionary of dictionaries/lists of dictionaries, but there are some small differences between reading the json and using the tools from `nbformat` so we'll u...
#export def read_nb(fname): "Read the notebook in `fname`." with open(Path(fname),'r', encoding='utf8') as f: return nbformat.reads(f.read(), as_version=4)
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
`fname` can be a string or a pathlib object.
test_nb = read_nb('00_export.ipynb')
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
The root has four keys: `cells` contains the cells of the notebook, `metadata` some stuff around the version of python used to execute the notebook, `nbformat` and `nbformat_minor` the version of nbformat.
test_nb.keys() test_nb['metadata'] f"{test_nb['nbformat']}.{test_nb['nbformat_minor']}"
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
The cells key then contains a list of cells. Each one is a new dictionary that contains entries like the type (code or markdown), the source (what is written in the cell) and the output (for code cells).
test_nb['cells'][0]
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Finding patterns The following functions are used to catch the flags used in the code cells.
# export def check_re(cell, pat, code_only=True): "Check if `cell` contains a line with regex `pat`" if code_only and cell['cell_type'] != 'code': return if isinstance(pat, str): pat = re.compile(pat, re.IGNORECASE | re.MULTILINE) return pat.search(cell['source'])
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
`pat` can be a string or a compiled regex, if `code_only=True`, this function ignores markdown cells.
cell = test_nb['cells'][0].copy() assert check_re(cell, '# export') is not None assert check_re(cell, re.compile('# export')) is not None assert check_re(cell, '# bla') is None cell['cell_type'] = 'markdown' assert check_re(cell, '# export') is None assert check_re(cell, '# export', code_only=False) is not None # expor...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
The cells to export are marked with an `export` or `exports` code, potentially with a module name where we want it exported. The default module is given in a cell of the form `default_exp bla` inside the notebook (usually at the top), though in this function, it needs the be passed (the final script will read the whole...
cell = test_nb['cells'][0].copy() test_eq(is_export(cell, 'export'), 'export') cell['source'] = "# exports" test_eq(is_export(cell, 'export'), 'export') cell['source'] = "# export mod" test_eq(is_export(cell, 'export'), 'mod') cell['source'] = "# export mod.file" test_eq(is_export(cell, 'export'), 'mod/file') cell['...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Stops at the first cell containing a ` default_exp` flag (if there are several) and returns the value behind. Returns `None` if there are no cell with that code.
test_eq(find_default_export(test_nb['cells']), 'export') assert find_default_export(test_nb['cells'][2:]) is None
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Listing all exported objects The following functions make a list of everything that is exported to prepare a proper `__all__` for our exported module.
#export _re_patch_func = re.compile(r""" # Catches any function decorated with @patch, its name in group 1 and the patched class in group 2 @patch # At any place in the cell, something that begins with @patch \s*def # Any number of whitespace (including a new line probably) followed by def \s+ ...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
This function only picks the zero-indented objects on the left side of an =, functions or classes (we don't want the class methods for instance) and excludes private names (that begin with `_`) but no dunder names. It only returns func and class names (not the objects) when `func_only=True`. To work properly with fasta...
test_eq(export_names("def my_func(x):\n pass\nclass MyClass():"), ["my_func", "MyClass"]) #Indented funcs are ignored (funcs inside a class) test_eq(export_names(" def my_func(x):\n pass\nclass MyClass():"), ["MyClass"]) #Private funcs are ignored, dunder are not test_eq(export_names("def _my_func():\n pass\nclas...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Sometimes objects are not picked to be automatically added to the `__all__` of the module so you will need to add them manually. To do so, create an exported cell with the following code `_all_ = ["name"]` (the single underscores are intentional)>
test_eq(extra_add('_all_ = ["func", "func1", "func2"]'), (["'func'", "'func1'", "'func2'"],'')) test_eq(extra_add('_all_ = ["func", "func1" , "func2"]'), (["'func'", "'func1'", "'func2'"],'')) test_eq(extra_add("_all_ = ['func','func1', 'func2']\n"), (["'func'", "'func1'", "'func2'"],'')) test_eq(extra_add('code\n\n_...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
When we say from ``` pythonfrom lib_name.module.submodule import bla``` in a notebook, it needs to be converted to something like ```from .module.submodule import bla```or ```from .submodule import bla``` depending on where we are. This function deals with those imports renaming.Note that import of the form```pythonimp...
test_eq(relative_import('nbdev.core', Path.cwd()/'nbdev'/'data.py'), '.core') test_eq(relative_import('nbdev.core', Path('nbdev')/'vision'/'data.py'), '..core') test_eq(relative_import('nbdev.vision.transform', Path('nbdev')/'vision'/'data.py'), '.transform') test_eq(relative_import('nbdev.notebook.core', Path('nbdev')...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Create the library Saving an index To be able to build back a correspondence between functions and the notebooks they are defined in, we need to store an index. It's done in the private module _nbdev inside your library, and the following function are used to define it.
#export _re_patch_func = re.compile(r""" # Catches any function decorated with @patch, its name in group 1 and the patched class in group 2 @patch # At any place in the cell, something that begins with @patch \s*def # Any number of whitespace (including a new line probably) followed by def \s+ ...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Create the modules
# export def create_mod_file(fname, nb_path): "Create a module file for `fname`." fname.parent.mkdir(parents=True, exist_ok=True) with open(fname, 'w') as f: f.write(f"# AUTOGENERATED! DO NOT EDIT! File to edit: {os.path.relpath(nb_path, Config().config_file.parent)} (unless otherwise specified).") ...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
A new module filename is created each time a notebook has a cell marked with ` default_exp`. In your collection of notebooks, you should only have one notebook that creates a given module since they are re-created each time you do a library build (to ensure the library is clean). Note that any file you create manually ...
#export def _notebook2script(fname, silent=False, to_dict=None): "Finds cells starting with `#export` and puts them into a new module" if os.environ.get('IN_TEST',0): return # don't export if running tests sep = '\n'* (int(Config().get('cell_spacing', '1'))+1) fname = Path(fname) nb = read_nb(fname...
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Finds cells starting with `export` and puts them into the appropriate module. If `fname` is not specified, this will convert all notebook not beginning with an underscore in the `nb_folder` defined in `setting.ini`. Otherwise `fname` can be a single filename or a glob expression.`silent` makes the command not print any...
#hide #export #for tests only class DocsTestClass: def test(): pass
_____no_output_____
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Export -
#hide notebook2script()
Converted 00_export.ipynb. Converted 01_sync.ipynb. Converted 02_showdoc.ipynb. Converted 03_export2html.ipynb. Converted 04_test.ipynb. Converted 05_merge.ipynb. Converted 06_cli.ipynb. Converted 07_clean.ipynb. Converted 99_search.ipynb. Converted index.ipynb. Converted tutorial.ipynb.
Apache-2.0
nbs/00_export.ipynb
andaag/nbdev
Testing Performances over the user goal portions Testing Records for 5 User Goals
path_prefix_5_goals = "../5_goals/50_episodes_1_9/" testing_records_pretrain_5_goals = read_performances(path_prefix_5_goals, run_dirs, pretrain_filename, "5") testing_records_scratch_5_goals = read_performances(path_prefix_5_goals, run_dirs, scratch_filename, "5") pprint(len(testing_records_pretrain_5_goals)) pprin...
60 60
MIT
Results/Tourist_Info/warming_up/plots/Testing_Performances_Over_User_Goal_Portions.ipynb
IlievskiV/Master_Thesis_GO_Chatbots
Testing Records for 10 User Goals
path_prefix_10_goals = "../10_goals/50_episodes_1_9/" testing_records_pretrain_10_goals = read_performances(path_prefix_10_goals, run_dirs, pretrain_filename, "10") testing_records_scratch_10_goals = read_performances(path_prefix_10_goals, run_dirs, scratch_filename, "10") pprint(len(testing_records_pretrain_10_goal...
60 60
MIT
Results/Tourist_Info/warming_up/plots/Testing_Performances_Over_User_Goal_Portions.ipynb
IlievskiV/Master_Thesis_GO_Chatbots
Testing Records for 20 User Goals
path_prefix_20_goals = "../20_goals/50_episodes_1_9/" testing_records_pretrain_20_goals = read_performances(path_prefix_20_goals, run_dirs, pretrain_filename, "20") testing_records_scratch_20_goals = read_performances(path_prefix_20_goals, run_dirs, scratch_filename, "20") pprint(len(testing_records_pretrain_20_goal...
60 60
MIT
Results/Tourist_Info/warming_up/plots/Testing_Performances_Over_User_Goal_Portions.ipynb
IlievskiV/Master_Thesis_GO_Chatbots
Testing Records for 30 User Goals
path_prefix_30_goals = "../30_goals/50_episodes_1_9/" testing_records_pretrain_30_goals = read_performances(path_prefix_30_goals, run_dirs, pretrain_filename, "30") testing_records_scratch_30_goals = read_performances(path_prefix_30_goals, run_dirs, scratch_filename, "30") pprint(len(testing_records_pretrain_30_goal...
60 60
MIT
Results/Tourist_Info/warming_up/plots/Testing_Performances_Over_User_Goal_Portions.ipynb
IlievskiV/Master_Thesis_GO_Chatbots
Testing Records for 50 User Goals
path_prefix_50_goals = "../50_goals/50_episodes_1_9/" testing_records_pretrain_50_goals = read_performances(path_prefix_50_goals, run_dirs, pretrain_filename, "50") testing_records_scratch_50_goals = read_performances(path_prefix_50_goals, run_dirs, scratch_filename, "50") pprint(len(testing_records_pretrain_50_goal...
60 60
MIT
Results/Tourist_Info/warming_up/plots/Testing_Performances_Over_User_Goal_Portions.ipynb
IlievskiV/Master_Thesis_GO_Chatbots
Testing Records for 120 User Goals
path_prefix_120_goals = "../120_goals/50_episodes_1_9/" testing_records_pretrain_120_goals = read_performances(path_prefix_120_goals, run_dirs, pretrain_filename, "120") testing_records_scratch_120_goals = read_performances(path_prefix_120_goals, run_dirs, scratch_filename, "120") pprint(len(testing_records_pretrain...
_____no_output_____
MIT
Results/Tourist_Info/warming_up/plots/Testing_Performances_Over_User_Goal_Portions.ipynb
IlievskiV/Master_Thesis_GO_Chatbots
■ Pandas를 이용한 머신러닝 수업 1. Pandas DataFrame & Series 2. 외부 데이터 파일을 파이썬으로 불러오는 방법 3. Pandas DataFrame 기본 활용(통계, 시각화) 4. 데이터 살펴보기 (시각화 : matplotlib, seaborn) 5. 데이터 전처리1 6. 데이터 전처리2 7. 파이썬으로 머신러닝 구현하기 (ncs 평가 = Kaggle 순위) - kNN (유방암, 타이타닉) - naiveBayes (유방암, 타이타닉) - Decision Tree ...
# -*- coding: utf-8 -*- ### 기본 라이브러리 불러오기 import pandas as pd import numpy as np ''' [Step 1] 데이터 준비/ 기본 설정 ''' # Breast Cancer 데이터셋 가져오기 (출처: UCI ML Repository) uci_path = 'https://archive.ics.uci.edu/ml/machine-learning-databases/\ breast-cancer-wisconsin/breast-cancer-wisconsin.data' df = pd.read_csv(uci_path, heade...
id clump cell_size cell_shape adhesion epithlial bare_nuclei \ 0 1000025 5 1 1 1 2 1 1 1002945 5 4 4 5 7 10 2 1015425 3 1 1 1 2 2 3 1016277 ...
MIT
11-1. Pandas DA Decision Tree (200727).ipynb
Adrian123K/pandas_ml
bare_nuclei 컬럼만 object이다. 이 컬럼의 데이터 타입을 int(숫자형)으로 변환 해줘야 한다.
# 데이터 통계 요약정보 확인 print(df.describe()) print('\n') # bare_nuclei 열의 자료형 변경 (문자열 ->숫자) print(df['bare_nuclei'].unique()) # bare_nuclei 열의 고유값 확인 print('\n') df['bare_nuclei'].replace('?', np.nan, inplace=True) # '?'을 np.nan으로 변경 df.dropna(subset=['bare_nuclei'], axis=0, inplace=True) # 누락데이터 행을 삭제 df['bare_nuclei'] = df[...
_____no_output_____
MIT
11-1. Pandas DA Decision Tree (200727).ipynb
Adrian123K/pandas_ml
설명 : 분류정도를 평가하는 기준으로 'entropy' 값을 사용하겠다는 의미 max_depth = 5 는 트리 레벨을 5로 지정해서 가지의 확장을 5단계까지 확장시키겠다는 의미 레벨이 많아질수록 모형 학습에 사용하는 훈련 데이터에 대한 예측은 정확해진다. 그러나 모형이 훈련 데이터에 대해서만 지나치게 최적화 되어 실제 데이터의 예측 능력은 떨어지는 문제가 발생한다. (오버피팅 문제가 발생 ) 머신러닝 데이터 분석시 적절한 max_depth를 찾는게 데이터 분석가의 역할이다. 면접문제 : 8. 의사결정트리에서 트...
# train data를 가지고 모형 학습 tree_model.fit(X_train, y_train) # test data를 가지고 y_hat을 예측 (분류) y_hat = tree_model.predict(X_test) # 2: benign(양성), 4: malignant(악성) print(y_hat[0:10]) print(y_test.values[0:10]) print('\n') # 모형 성능 평가 - Confusion Matrix 계산 from sklearn import metrics tree_matrix = metrics.confusion_matrix(y...
precision recall f1-score support 2 0.98 0.97 0.98 131 4 0.95 0.97 0.96 74 accuracy 0.97 205 macro avg 0.97 0.97 0.97 205 weighted avg 0.97 0.97 0.97 ...
MIT
11-1. Pandas DA Decision Tree (200727).ipynb
Adrian123K/pandas_ml
※ 문제230. class를 value_counts하여 각각 건수가 어떻게 되는지 확인하시오
df['class'].value_counts()
_____no_output_____
MIT
11-1. Pandas DA Decision Tree (200727).ipynb
Adrian123K/pandas_ml
※ 문제231. 위의 의사결정트리 모델을 아산병원에서 사용할 수 있도록 FN을 0을 만드는 max_depth를 알아내시오
''' [Step 4] Decision Tree 분류 모형 - sklearn 사용 ''' # sklearn 라이브러리에서 Decision Tree 분류 모형 가져오기 from sklearn import tree # 모형 객체 생성 (criterion='entropy' 적용) tree_model = tree.DecisionTreeClassifier(criterion='entropy', max_depth=4) # train data를 가지고 모형 학습 tree_model.fit(X_train, y_train) # test data를 가지고 y_hat을 예측 (분류) y_...
[4 4 4 4 4 4 2 2 4 4] [4 4 4 4 4 4 2 2 4 4] [[126 5] [ 0 74]] precision recall f1-score support 2 1.00 0.96 0.98 131 4 0.94 1.00 0.97 74 accuracy 0.98 205 macro avg 0.97 0....
MIT
11-1. Pandas DA Decision Tree (200727).ipynb
Adrian123K/pandas_ml
※ 문제232. seaborn의 타이타닉 데이터를 이용해서 의사결정트리 모델을 만들고 테스트 데이터의 정확도를 확인하시오
import seaborn as sns tt = sns.load_dataset('titanic') pd.set_option('display.max_columns', 15) ''' [Step 2] 데이터 탐색 ''' tt.info() tt.describe() rdf = tt.drop(['deck', 'embark_town'], axis=1) rdf = rdf.dropna(subset=['age'], how='any', axis=0) ndf = rdf[['survived', 'pclass', 'sex', 'age','sibsp', 'parch', 'embarked']] ...
[[109 17] [ 22 67]] precision recall f1-score support 0 0.83 0.87 0.85 126 1 0.80 0.75 0.77 89 accuracy 0.82 215 macro avg 0.81 0.81 0.81 215 weighted avg 0.82 ...
MIT
11-1. Pandas DA Decision Tree (200727).ipynb
Adrian123K/pandas_ml
seaborn의 타이타닉 데이터를 의사결정트리 모델로 생성 할 때 주의사항 1. 결측치가 없어야 한다. 모델 생성할 때 에러가 난다. 2. 명목형 데이터가 없어야 한다. 다 숫자형으로 변환해야한다. ※ 문제233. for loop문을 이용해서 정확도가 높은 max_depth가 무엇인지 알아내시오
from sklearn import metrics import numpy as np # 1단계 csv ---> 데이터 프레임으로 변환 import pandas as pd import seaborn as sns df = sns.load_dataset('titanic') pd.set_option('display.max_columns',15) mask4 = (df.age<10) | (df.sex=='female') df['child_women']=mask4.astype(int) rdf = df.drop(['deck','embark_town'], axis =1) #...
random_state: 1 max_depth: 1 [[125 28] [ 39 76]] 0.75 random_state: 1 max_depth: 1 accuracy: 0.75 max_depth: 2 [[150 3] [ 63 52]] 0.753731343283582 random_state: 1 max_depth: 2 accuracy: 0.753731343283582 max_depth: 3 [[133 20] [ 41 74]] 0.7723880597014925 random_state: 1 max_depth: 3 accurac...
MIT
11-1. Pandas DA Decision Tree (200727).ipynb
Adrian123K/pandas_ml
※ 문제234. (점심시간 문제) 카페에 올린 for loop문 스크립트를 이용해서 정확도가 가장 좋은 random_state와 max_depth를 알아내시오
from sklearn.model_selection import train_test_split from sklearn import tree from sklearn import metrics from sklearn.metrics import accuracy_score b=[] c=[] for i in range(1, 50): X_train,X_test,y_train,y_test = train_test_split(x,y,test_size = 0.3, random_state = i) for k in range(1,50): b.appen...
random_state: 33 max_depth: 5 accuracy: 0.8694029850746269
MIT
11-1. Pandas DA Decision Tree (200727).ipynb
Adrian123K/pandas_ml
Центр непрерывного образования Программа «Python для автоматизации и анализа данных»Неделя 2 - 1*Татьяна Рогович, НИУ ВШЭ* Множества и словари Множества (set)Мы уже знаем списки и кортежи - упорядоченные структуры, которые могут хранить в себе объекты любых типов, к которым мы можем обратиться по индексу. Теперь пог...
x = set() type(x) x = (4, 5, 6) print(set(x)) # передаем список set(range(10)) print(set()) # передаем tuple print(set(range(10))) print(set()) # пустое множество
{10, 20, 30} {4, 5, 6} {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} set()
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Другой способ создать множество - это перечислить его элементы в фигурных скобках (список - в квадратных, кортеж в круглых, а множество - в фигурных)
primes = {2, 3, 5, 7} animals = {"cat", "dog", "horse", 'cat'} print(primes) print(animals) x = [1,2,3,2,2,2,2,2,2,2,'dog',1] print(set(x))
{1, 2, 3, 'dog'}
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Кстати, обратите внимание, что множество может состоять только из уникальных объектов. Выше множество animals включает в себя только одну кошку несмотря на то, что в конструктор мы передали 'cat' два раза. Преобразовать в список в множество - самый простой способ узнать количество уникальных объектов.Со множествами раб...
print(len(primes)) primes = {1,11,22,34,5} 11 in primes animals = {"cat", "dog", "horse", 'cat'} "cow" in animals # длина print(11 in primes) # проверка на наличие элемента in хорошо и быстро работает для множеств print("cow" in animals)
4 False False
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Все возможные операции с множествами: https://docs.python.org/3/library/stdtypes.htmlset-types-set-frozensetОтдельно мы посмотрим на так называемые операции над множествами. Если вы знаете круги Эйлера, то помните как различают объекты множеств - пересечение, объекты, которые принадлежат множеству а, но не принадлежат ...
a = {1, 2, 3, 4} b = {3, 4, 5, 6} c = {2, 3} print(c <= a) print(c >= a) print(a | b) a.intersection(b) a.union(b) a^b b.difference(a) a = {1, 2, 3, 4} b = {3, 4, 5, 6} c = {2, 3} # проверка на подмножество (с подномжество a) print(c <= b) # не подмножество, т.к. в b нет 2 print(a >= c) print(a | b) # объединение a...
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Предыдущие операции не меняли множества, создавали новые. А как менять множество:
s = {1, 2, 3} s.add(10) # добавить print(s) # обратите внимание, что порядок элементов непредсказуем s.remove(1) # удаление элемента s.discard(1) # аналогично, но не будет ошибки, если вдруг такого элемента нет в множестве print(s) x = s.pop() # удаляет и возвращает один произвольный элемент множества (можем сохранить ...
_____no_output_____
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Как мы сокращали арифметические операции раньше (например, +=), так же можно сокращать операции над множествами.
s |= {10, 20} # s = s | {10, 20} # объединение множества s с {10,20} print(s) # s ^=, s &= и т.п.
{10, 20}
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022
Словари (dict)Обычный массив (в питоне это список) можно понимать как функцию, которая сопоставляет начальному отрезку натурального ряда какие-то значения. Давайте посмотрим на списки непривычным способом. Списки - это функции (отображения), которые отображают начальный ряд натуральных чисел в объекты (проще говоря - ...
l = [10, 20, 30, 'a'] print(l[0]) print(l[1]) print(l[2]) print(l[3])
10 20 30 a
MIT
lect2/.ipynb_checkpoints/Set_Dict-checkpoint.ipynb
disimhot/DPO_Python-2021-2022