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 |
|---|---|---|---|---|---|
Card | visuals = card.get_visuals()['notebook']
for key in visuals:
display(Markdown(f"### {key}"))
display(visuals[key]) | _____no_output_____ | MIT | notebooks/RPLIB_Card.ipynb | IGARDS/structured_artificial |
Product of lCMDP and DBA with the link to LTL The goal of this notebook is, given an LTL formula over the set $AP$ of atomic proposition and a consumption MDP with states labeled by subsets of $AP$, decide if there is a strategy for the MDP such that the LTL formula is satisfied with probability 1. We ilustrate the wh... | def uniform(dests):
"""Create a uniform distribution for given destinations.
dests: iterable of states
"""
count = len(dests)
mod = 100 % count
decimal.getcontext().prec = 2
prob = Decimal(1)/Decimal(count)
dist = {i: prob for i in dests}
last = dests[-1]
dist[last] = dist[l... | _____no_output_____ | MIT | examples/product.ipynb | MaxDauber/FiMDP |
In the following code, we verify that we can achieve the Büchi objective with targets set `{1,2}` with capacity `5` and that is not enough to visit the state `1`. What we actualy want is to visit **both** of these states infinitely often which we solve later. | mdp = ConsMDP()
mdp.new_states(4)
mdp.set_reload(3)
mdp.add_action(0, uniform([1,2]), "α", 3)
mdp.add_action(0, uniform([2,3]), "β", 1)
mdp.add_action(1, uniform([3]), "r", 3)
mdp.add_action(2, uniform([3]), "r", 1)
mdp.add_action(3, uniform([0]), "s", 3)
solver = BasicES(mdp, 5, [1,2])
solver.get_min_levels(BUCHI)
sol... | _____no_output_____ | MIT | examples/product.ipynb | MaxDauber/FiMDP |
The corresponding strategy confirms that the state 1 won't be visited by the strategy as there is no occurence of the action `α`. | solver.get_selector(4, True) | _____no_output_____ | MIT | examples/product.ipynb | MaxDauber/FiMDP |
LTL and Büchi automataOur goal of visiting both states `1` \& `2` infinitely often can be expressed by the LTL formula $\mathsf{G}\mathsf{F} s_1 \land \mathsf{G}\mathsf{F}s_2$ (or in the box-diamond notation: $\Box \diamond s_1 \land \Box \diamond s_2$) where the atomic proposition $s_1$ corresponds to visiting state ... | f = spot.formula("GF s1 & GF s2")
aut = spot.translate(f, "BA", "deterministic", "complete")
display(aut, aut.is_deterministic()) | _____no_output_____ | MIT | examples/product.ipynb | MaxDauber/FiMDP |
The produced automaton can be used in parallel with our input MDP; this is achieved by a _product_ (alternatively _parallel synchonous composition_) of this automaton an the input MDP. But we need to label states of the MDP with the atomic propositions `s₁` and `s₂`. Labeled CMDPWe create a copy of our CMDP and label ... | lmdp = LabeledConsMDP(AP=["s1","s2"], mdp=mdp)
lmdp.state_labels = [set(), {0}, {1}, set()]
display(lmdp, lmdp.state_labels) | _____no_output_____ | MIT | examples/product.ipynb | MaxDauber/FiMDP |
Product of labeled CMDP and DBA In the following, we explain and show the (simplified) implementation of `LabeledConsMDP.product_with_dba(self, dba)`.The states of the product are tuples `(ms,as)` where `ms` stands for a state of the MDP and `as` stands for a states of the automaton. Let's call the set of states of th... | def product(lmdp, aut):
#TODO check for correct type of mdp
result = ConsMDP()
num_ap = len(lmdp.AP)
# Check the type of automaton and convert it into
# complete DBA if needed
if not aut.is_sba() or not spot.is_complete(aut):
aut = aut.postprocess("BA", "complete")
... | _____no_output_____ | MIT | examples/product.ipynb | MaxDauber/FiMDP |
We can now see the result of the product on the labeled MDP and the automaton for $\mathsf{G}\mathsf{F}s_1 \land \mathsf{G}\mathsf{F} s_2$. We can also see that capacity 5 is no longer sufficient for the Büchi objective (the green ∞ indicate that no initial load is sufficient from given state to satisfy the Büchi objec... | psolver.cap = 9
psolver.get_min_levels(BUCHI, recompute=True)
display_inline(psolver) | _____no_output_____ | MIT | examples/product.ipynb | MaxDauber/FiMDP |
In fact, the function `product` is implemented as a method of `LabeledConsMDP` class. | p, T = lmdp.product_with_dba(aut)
psolver = BasicES(p, 9, T)
psolver.get_min_levels(BUCHI, True)
display_inline(psolver) | _____no_output_____ | MIT | examples/product.ipynb | MaxDauber/FiMDP |
class NodoArbol:
def __init__(self, value, left=None, right=None):
self.data=value
self.left=left
self.right=right
class BinarySearchTree:
def __init__(self):
self.__root=None
def insert(self, value):
if self.__root==None:
self.__root= NodoArbol(value,None,None)
else:
# pregunta... | Dato: 30
None
Recorrido:
50,30,20,recorrido in orden:
20,30,50,recorrido pos:
Formato de recorrido no válido
| MIT | 20enero.ipynb | michelmunoz99/daa_2021_1 | |
Marginalized Gaussian Mixture ModelAuthor: [Austin Rochford](http://austinrochford.com) | %matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
import pymc3 as pm
import seaborn as sns
SEED = 383561
np.random.seed(SEED) # from random.org, for reproducibility | _____no_output_____ | Apache-2.0 | docs/source/notebooks/marginalized_gaussian_mixture_model.ipynb | JvParidon/pymc3 |
Gaussian mixtures are a flexible class of models for data that exhibits subpopulation heterogeneity. A toy example of such a data set is shown below. | N = 1000
W = np.array([0.35, 0.4, 0.25])
MU = np.array([0., 2., 5.])
SIGMA = np.array([0.5, 0.5, 1.])
component = np.random.choice(MU.size, size=N, p=W)
x = np.random.normal(MU[component], SIGMA[component], size=N)
fig, ax = plt.subplots(figsize=(8, 6))
ax.hist(x, bins=30, normed=True, lw=0); | /opt/conda/lib/python3.5/site-packages/matplotlib/font_manager.py:1297: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
| Apache-2.0 | docs/source/notebooks/marginalized_gaussian_mixture_model.ipynb | JvParidon/pymc3 |
A natural parameterization of the Gaussian mixture model is as the [latent variable model](https://en.wikipedia.org/wiki/Latent_variable_model)$$\begin{align*}\mu_1, \ldots, \mu_K & \sim N(0, \sigma^2) \\\tau_1, \ldots, \tau_K & \sim \textrm{Gamma}(a, b) \\\boldsymbol{w} & \sim \textrm{Dir}(\boldsymbol{\alpha}... | with pm.Model() as model:
w = pm.Dirichlet('w', np.ones_like(W))
mu = pm.Normal('mu', 0., 10., shape=W.size)
tau = pm.Gamma('tau', 1., 1., shape=W.size)
x_obs = pm.NormalMixture('x_obs', w, mu, tau=tau, observed=x)
with model:
trace = pm.sample(5000, n_init=10000, tune=1000, random_seed=SE... | Auto-assigning NUTS sampler...
Initializing NUTS using advi...
Average ELBO = -6,663.8: 100%|██████████| 10000/10000 [00:06<00:00, 1582.50it/s]
Finished [100%]: Average ELBO = -6,582.7
100%|██████████| 5000/5000 [-1:54:12<00:00, -0.07s/it]
| Apache-2.0 | docs/source/notebooks/marginalized_gaussian_mixture_model.ipynb | JvParidon/pymc3 |
We see in the following plot that the posterior distribution on the weights and the component means has captured the true value quite well. | pm.traceplot(trace, varnames=['w', 'mu']);
pm.plot_posterior(trace, varnames=['w', 'mu']); | /opt/conda/lib/python3.5/site-packages/matplotlib/font_manager.py:1297: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
| Apache-2.0 | docs/source/notebooks/marginalized_gaussian_mixture_model.ipynb | JvParidon/pymc3 |
We can also sample from the model's posterior predictive distribution, as follows. | with model:
ppc_trace = pm.sample_posterior_predictive(trace, 5000, random_seed=SEED) | 100%|██████████| 5000/5000 [03:28<00:00, 23.93it/s]
| Apache-2.0 | docs/source/notebooks/marginalized_gaussian_mixture_model.ipynb | JvParidon/pymc3 |
We see that the posterior predictive samples have a distribution quite close to that of the observed data. | fig, ax = plt.subplots(figsize=(8, 6))
ax.hist(x, bins=30, normed=True,
histtype='step', lw=2,
label='Observed data');
ax.hist(ppc_trace['x_obs'], bins=30, normed=True,
histtype='step', lw=2,
label='Posterior predictive distribution');
ax.legend(loc=1); | /opt/conda/lib/python3.5/site-packages/matplotlib/font_manager.py:1297: UserWarning: findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans
(prop.get_family(), self.defaultFamily[fontext]))
| Apache-2.0 | docs/source/notebooks/marginalized_gaussian_mixture_model.ipynb | JvParidon/pymc3 |
Major Neural Network Architectures Challenge *Data Science Unit 4 Sprint 3 Challenge*In this sprint challenge, you'll explore some of the cutting edge of Data Science. This week we studied several famous neural network architectures: recurrent neural networks (RNNs), long short-term memory (LSTMs), convolutional neura... | from tensorflow.keras.datasets import reuters
import numpy as np
# save np.load
np_load_old = np.load
# modify the default parameters of np.load
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)
# call load_data with allow_pickle implicitly set to true
(X_train, y_train), (X_test, y_test) = reuters.load_... | Train...
Train on 8982 samples, validate on 2246 samples
8982/8982 [==============================] - 132s 15ms/sample - loss: 4.2270 - acc: 0.3479 - val_loss: 2.4033 - val_acc: 0.3664
2246/2246 [==============================] - 7s 3ms/sample - loss: 2.4033 - acc: 0.3664
Test score: 2.403268739780144
Test accuracy: 0.... | MIT | sprint-challenge/LS_DS_Uni_4_Sprint_3_Challenge.ipynb | DNason1999/DS-Unit-4-Sprint-3-Deep-Learning |
Sequence Data Question *Describe the `pad_sequences` method used on the training dataset. What does it do? Why do you need it?*pad_sequences truncates sequences longer than the maxlen variable, and will add padding to sequences shorter than maxlen.pad_sequences makes all of the sequences the same length. This is neces... | !pip install google_images_download
from google_images_download import google_images_download
response = google_images_download.googleimagesdownload()
arguments = {"keywords": "lilly frog pond", "limit": 5, "print_urls": True}
absolute_image_paths = response.download(arguments) |
Item no.: 1 --> Item name = lilly frog pond
Evaluating...
Starting Download...
Image URL: https://i.pinimg.com/originals/9a/49/08/9a49083d4d7458a194a451eea757a444.jpg
Completed Image ====> 1.9a49083d4d7458a194a451eea757a444.jpg
Image URL: http://www.slrobertson.com/images/usa/georgia/atlanta/atl-botanical-gardens/frog... | MIT | sprint-challenge/LS_DS_Uni_4_Sprint_3_Challenge.ipynb | DNason1999/DS-Unit-4-Sprint-3-Deep-Learning |
At time of writing at least a few do, but since the Internet changes - it is possible your 5 won't. You can easily verify yourself, and (once you have working code) increase the number of images you pull to be more sure of getting a frog. Your goal is to validly run ResNet50 on the input images - don't worry about tuni... | # You've got something to do in this cell. ;)
import numpy as np
from tensorflow.keras.applications.resnet50 import ResNet50
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions
frogs = ['bullfrog', 'tree_frog', 'tailed_frog']
def p... | _____no_output_____ | MIT | sprint-challenge/LS_DS_Uni_4_Sprint_3_Challenge.ipynb | DNason1999/DS-Unit-4-Sprint-3-Deep-Learning |
Stretch Goal: Displaying Predictions | import matplotlib.pyplot as plt
import os
path = './downloads/lilly frog pond/'
paths = os.listdir(path)
for file in paths:
img = process_img_path(path+file)
plt.imshow(img)
plt.show()
prediction = img_contains_frog(img)
print(prediction)
print() | _____no_output_____ | MIT | sprint-challenge/LS_DS_Uni_4_Sprint_3_Challenge.ipynb | DNason1999/DS-Unit-4-Sprint-3-Deep-Learning |
Part 3 - AutoencodersDescribe a use case for an autoencoder given that an autoencoder tries to predict its own input. __*Your Answer:*__ An autoencoder can be used for creating a format to use in the compression of files to the smallest possible size with minimal information loss. This is even more effective if all th... | from IPython.display import HTML
HTML("""<iframe src="https://giphy.com/embed/26xivLqkv86uJzqWk" width="480" height="270" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p><a href="https://giphy.com/gifs/mumm-champagne-saber-26xivLqkv86uJzqWk">via GIPHY</a></p>""") | _____no_output_____ | MIT | sprint-challenge/LS_DS_Uni_4_Sprint_3_Challenge.ipynb | DNason1999/DS-Unit-4-Sprint-3-Deep-Learning |
The Datato see where we got the data go here: https://www.ndbc.noaa.gov/station_history.php?station=42040 | import pandas as pd
import numpy as np
import datetime | _____no_output_____ | Apache-2.0 | code/Old Stuff With Data.ipynb | jxfischer/buoy-data-analysis |
This is the first set of data from 1995 | from utils import read_file, build_median_df
df1995 = read_file('data/42040/buoy_data_1995.txt') #allows you to a table for each year
df1995.head(6)#allows you to print certain sections of the data0
df1995d= df1995.set_index("timestamp").resample("D").mean()
df1995d.head(5)
df1996 = read_file('data/42040/buoy_d... | _____no_output_____ | Apache-2.0 | code/Old Stuff With Data.ipynb | jxfischer/buoy-data-analysis |
Lambda School Data Science*Unit 1, Sprint 2, Module 1*--- _Lambda School Data Science_ Join and Reshape datasetsObjectives- concatenate data with pandas- merge data with pandas- understand tidy data formatting- melt and pivot data with pandasLinks- [Pandas Cheat Sheet](https://github.com/pandas-dev/pandas/blob/master... | # we can use !wget to gt the file.
!wget https://s3.amazonaws.com/instacart-datasets/instacart_online_grocery_shopping_2017_05_01.tar.gz
# use !tar code to unzip a .tar file.
!tar --gunzip --extract --verbose --file=instacart_online_grocery_shopping_2017_05_01.tar.gz
# we can see directory the files are stored in.
%cd ... | -rw-r--r-- 1 502 staff 2.6K May 2 2017 aisles.csv
-rw-r--r-- 1 502 staff 270 May 2 2017 departments.csv
-rw-r--r-- 1 502 staff 551M May 2 2017 order_products__prior.csv
-rw-r--r-- 1 502 staff 24M May 2 2017 order_products__train.csv
-rw-r--r-- 1 502 staff 104M May 2 2017 orders.csv
-rw-r--r-- 1 502 staff 2.... | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Join Datasets Goal: Reproduce this exampleThe first two orders for user id 1: | # we can use this code to displqy an image in our code.
from IPython.display import display, Image
url = 'https://cdn-images-1.medium.com/max/1600/1*vYGFQCafJtGBBX5mbl0xyw.png'
example = Image(url=url, width=600)
display(example) | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Load dataHere's a list of all six CSV filenames | # list out all the .csv files.
!ls -lh *.csv | -rw-r--r-- 1 502 staff 2.6K May 2 2017 aisles.csv
-rw-r--r-- 1 502 staff 270 May 2 2017 departments.csv
-rw-r--r-- 1 502 staff 551M May 2 2017 order_products__prior.csv
-rw-r--r-- 1 502 staff 24M May 2 2017 order_products__train.csv
-rw-r--r-- 1 502 staff 104M May 2 2017 orders.csv
-rw-r--r-- 1 502 staff 2.... | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
For each CSV- Load it with pandas- Look at the dataframe's shape- Look at its head (first rows)- `display(example)`- Which columns does it have in common with the example we want to reproduce? aisles | # import pandas library to load the .csv files to data sets.
import pandas as pd
# label the data set and load with pd.read_csv().
aisles = pd.read_csv('aisles.csv')
# show the shape of the data frame.
print(aisles.shape)
# show the data set with headers.
aisles.head()
# we can always check the 'image' of the data set ... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
departments | # label the data set and load with pd.read_csv().
departments = pd.read_csv('departments.csv')
# show the shape of the data frame.
print(departments.shape)
# show the data set with headers.
departments.head() | (21, 2)
| MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
order_products__prior | # label the data set and load with pd.read_csv().
order_products__prior = pd.read_csv('order_products__prior.csv')
# show the shape of the data frame.
print(order_products__prior.shape)
# show the data set with headers.
order_products__prior.head() | (32434489, 4)
| MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
order_products__train | # label the data set and load with pd.read_csv().
order_products__train = pd.read_csv('order_products__train.csv')
# show the shape of the data frame.
print(order_products__train.shape)
# show the data set with headers.
order_products__train.head()
# we can always check out how much memory we are using and have left to... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
orders | # label the data set and load with pd.read_csv().
orders = pd.read_csv('orders.csv')
# show the shape of the data frame.
print(orders.shape)
# show the data set with headers.
orders.head() | (3421083, 7)
| MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
products | # label the data set and load with pd.read_csv().
products = pd.read_csv('products.csv')
# show the shape of the data frame.
print(products.shape)
# show the data set with headers.
products.head() | (49688, 4)
| MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Concatenate order_products__prior and order_products__train | # check 'order_products__prior' for NA'S.
order_products__prior.isna().sum()
# check 'order_products__train' for NA'S.
order_products__train.isna().sum()
# both these data sets havce the same column names so we will merge all columns of the data sets.
# label the new data set amd use pd.concat() to merge them.
order_pr... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Get a subset of orders — the first two orders for user id 1 From `orders` dataframe:- user_id- order_id- order_number- order_dow- order_hour_of_day | # we can look at the first 2 orders with .head(2).
orders.head(2)
# we first set the columns we want to use that were listed above.
columns = ['order_id','user_id','order_number', 'order_dow','order_hour_of_day']
# we want to set a condition for the 'user_id' ==1 & only the first 2 orders so 'order_number' <=2.
conditi... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Merge dataframes Merge the subset from `orders` with columns from `order_products` | display(example)
# look at the headers data set and headers.
order_products.head(2)
# label the merged data set and use pd.merge with the 2 data sets and the columns of set we are adding to the subset.
merged = pd.merge(subset, order_products[['order_id','add_to_cart_order','product_id']], how='left', on='order_id')
# ... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Merge with columns from `products` | # show the dat set headers.
products.head(1)
# label the merged data set and use pd.merge with the 2 data sets and the columns of set we are adding to the subset.
final = pd.merge(merged, products[['product_id','product_name']], how='left', on='product_id')
# show the merged data set with headers.
final
display(example... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Reshape Datasets Why reshape data? Some libraries prefer data in different formatsFor example, the Seaborn data visualization library prefers data in "Tidy" format often (but not always).> "[Seaborn will be most powerful when your datasets have a particular organization.](https://seaborn.pydata.org/introduction.htmlo... | # import all the libraries we are using.
%matplotlib inline
import pandas as pd
import numpy as np
import seaborn as sns
# create our own data set.
table1 = pd.DataFrame(
[[np.nan, 2],
[16, 11],
[3, 1]],
index=['John Smith', 'Jane Doe', 'Mary Johnson'],
columns=['treatmenta', 'treatmentb... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
"Table 1 provides some data about an imaginary experiment in a format commonly seen in the wild. The table has two columns and three rows, and both rows and columns are labelled." | # show the data set table 1.
table1 | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
"There are many ways to structure the same underlying data. Table 2 shows the same data as Table 1, but the rows and columns have been transposed. The data is the same, but the layout is different." | # show the data set table2.
table2 | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
"Table 3 reorganises Table 1 to make the values, variables and obserations more clear.Table 3 is the tidy version of Table 1. Each row represents an observation, the result of one treatment on one person, and each column is a variable."| name | trt | result ||--------------|-----|--------|| John Smith | a |... | # show data set table1.
table1
# show the columns of table1.
table1.columns
# we can reset the table1 to the original with .reset_index().
table1 = table1.reset_index()
# show the data set table1 with reset.
table1
# label the data set and use .met(id_vars='index') to met into 'tidy' format.
tidy1 = table1.melt(id_vars... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Table 2 --> Tidy | table2 = table2.reset_index()
table2
# show the columns of data set table2.
table2.columns
# label the data set and use .met(id_vars='') to met into 'tidy' format.
tidy2 = table2.melt(id_vars='index')
# show the tidy data set.
tidy2
# we can rename the columns in the tidy data set.
tidy2 = tidy2.rename(columns={'index... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Tidy --> Table 1The `pivot_table` function is the inverse of `melt`. | # label the data set and use.pivot_table().
wide = tidy1.pivot_table(values='result', index='name', columns='trt')
# show the table1 data set.
wide
table1 | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Tidy --> Table 2 | # label the data set and use.pivot_table().
wide2 = tidy2.pivot_table(values='result', index='name', columns='name')
# show the table2 data set.
wide2
table2 | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Seaborn exampleThe rules can be simply stated:- Each variable is a column- Each observation is a rowA helpful mindset for determining whether your data are tidy is to think backwards from the plot you want to draw. From this perspective, a “variable” is something that will be assigned a role in the plot." | # using seaborn we can create bar plots for our tidy data set.
sns.catplot(x='trt', y='result', col='name', kind='bar', data=tidy1, height=2); | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Now with Instacart data | # import the pandas libary to load the data set.
import pandas as pd
# label and load the 'products' csv file.
products = pd.read_csv('products.csv')
# we can use pd.concat() and merge the 'prior' and 'train' data sets here.
order_products = pd.concat([pd.read_csv('order_products__prior.csv'),
... | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Goal: Reproduce part of this exampleInstead of a plot with 50 products, we'll just do two — the first products from each list- Half And Half Ultra Pasteurized- Half Baked Frozen Yogurt | # we can display an image in our code.
from IPython.display import display, Image
url = 'https://cdn-images-1.medium.com/max/1600/1*wKfV6OV-_1Ipwrl7AjjSuw.png'
example = Image(url=url, width=600)
display(example) | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
So, given a `product_name` we need to calculate its `order_hour_of_day` pattern. Subset and MergeOne challenge of performing a merge on this data is that the `products` and `orders` datasets do not have any common columns that we can merge on. Due to this we will have to use the `order_products` dataset to provide the... | # label a data set for the values we want to use.
product_names = ['Half And Half Ultra Pasteurized', 'Half Baked Frozen Yogurt']
# show the columns in the 'products' data set.
products.columns.to_list()
# show the columns in the 'order_products' data set.
order_products.columns.to_list()
# show the columns in the 'ord... | (5978, 4)
| MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
4 ways to reshape and plot 1. value_counts | # we can use groupby() to plot our 'product_name' column vs 'order_hour_of_day', we use unstack to seperate the values.
subset.groupby('order_hour_of_day').product_name.value_counts().unstack().plot(); | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
2. crosstab | # we can use crosstab() to plot our 'product_name' column vs 'order_hour_of_day', we use normalize='columns * 100'.
(pd.crosstab(subset['order_hour_of_day'], subset['product_name'], normalize='columns')*100).plot(); | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
3. Pivot Table | # we can use.pivot to plot our 'product_name' column vs 'order_hour_of_day', we use set the value 'order_id'.
subset.pivot_table(index='order_hour_of_day', columns='product_name', values='order_id', aggfunc=len).plot(); | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
4. melt | # imnport seaborn to create a plot.
import seaborn as sns
table = pd.crosstab(subset['order_hour_of_day'], subset['product_name'], normalize='columns')
melted = table.reset_index().melt(id_vars='order_hour_of_day')
sns.relplot(x='order_hour_of_day', y='value', hue='product_name', data=melted, kind='line'); | _____no_output_____ | MIT | module1-join-and-reshape-data/1.Lecture_JoinandReshapeData.ipynb | CVanchieri/DS-Unit1-Sprint2-DataWranglingandStorytelling |
Model trainingIn this notebook we'll first define a baseline model and then train a couple of ML models to try to better that performance.The dataset is quite small and the features are few, so I'm going to keep it simple in terms of algotrithms. We'll see how a logistic regression model and a random forest model comp... | # Import packages
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.metrics import auc
from sklearn.met... | _____no_output_____ | MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
Define functions | def avg_points_prev_rows(df, num_games):
"""Return the average of column 'won_points' over a set number of rows.
Need data to be sorted ascending by time to return a chonological history
"""
avg_points = (
df.rolling(num_games, min_periods=1, closed='both')
['won_points'].sum()
.... | _____no_output_____ | MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
Load data | # Read training data into a pandas DataFrame : df
df_train = pd.read_csv(data_path + train_data_filename)
df_test = pd.read_csv(data_path + test_data_filename)
X_train, y_train = get_X_and_y(df_train, features)
X_test, y_test = get_X_and_y(df_test, features)
# Display sample rows from feature dataframe X_train
display... | _____no_output_____ | MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
Target balance | print("Share of losses in the training data:",
np.round(y_train.mean(), 2)) | Share of losses in the training data: 0.48
| MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
So, 52% accuracy is the best we could do without knowing or learning anything at all and just always predicting 0. Baseline model In this first step we'll create a simple model to benchmark later models against. Let's use the seemingly strongest feature that measures the difference of ratings (rating_diff). Well alway... | baseline_preds = np.where(X_train['rating_diff'] < 0, 1, 0)
baseline_accuracy = accuracy_score(baseline_preds, y_train)
print("Baseline accuracy:", np.round(baseline_accuracy, 2)) | Baseline accuracy: 0.68
| MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
Logistic regression Let's first train a logistic regression classifier, and use sklearn's GridSearchCV to tune the parameters. | param_grid = {'clf__penalty': ['l1', 'l2'],
'clf__C' : np.logspace(-4, 4, 50)}
pipe = Pipeline([
('scaler', StandardScaler()),
('clf', LogisticRegression(solver='liblinear',
class_weight='balanced',
max_iter=1_000,
... | Chosen parameters: {'clf__C': 0.00021209508879201905, 'clf__penalty': 'l2'}
Best mean cross validation score 0.7
| MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
The cross validated accuracy is better than the beseline model's, but only slightly so. | # Plot kernel densities for predicted probabilities by actual outcome
print_prob_dist(lr_clf, X_train) | _____no_output_____ | MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
The plot above graphically shows the substantial overlap between the distributions meaning that when using a cutoff value of 0.5 there will be quite a lot of misclassification for both labels. | sns.barplot(x=lr_clf.best_estimator_.named_steps['clf'].coef_[0],
y=lr_clf.best_estimator_.feature_names_in_,
color=default_color)
plt.title('Logistic regression classifier feature weights')
plt.show() | _____no_output_____ | MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
The traning pipeline standardized the features so the coefficients can be interpreted as a form of feature impact score in the fitted model. The feature rating_diff stands out. The lower the rating_diff goes (and it's negative when the opponent has the higher rating) the higher the probability of losing. Random Forest... | param_grid = {
'clf__n_estimators': [500, 1_000, 1_500],
'clf__max_features': [2, 'auto', 'sqrt', 'log2'],
'clf__max_depth' : [2, 3, 4, 5],
'clf__criterion' : ['gini', 'entropy']
}
pipe = Pipeline([
('scaler', StandardScaler()),
('clf', RandomForestClassifier(class_weight='balanced',
... | Chosen parameters: {'clf__criterion': 'gini', 'clf__max_depth': 4, 'clf__max_features': 2, 'clf__n_estimators': 500}
Best mean cross validation score 0.69
| MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
The cross validatet accurracy is a little worse for the random forest model than the logistic regression model, but it's very even. | # Visualise the probability
print_prob_dist(rf_clf, X_train) | _____no_output_____ | MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
The random forest model can classify a good chunk of the records correctly as clear wins and losses. But there's also many records in the middle where the model doesn't do that great in telling the classes apart. Conclusion Neither model really improves much on the baseline model which only predicts from who's got the... | baseline_test_preds = np.where(X_test['rating_diff'] < 0, 1, 0)
baseline_test_accuracy = accuracy_score(baseline_test_preds, y_test)
print("Baseline accuracy on test data:",
np.round(baseline_test_accuracy, 2))
print("Logistic regression model accuracy on test data:",
np.round(lr_clf.score(X_test, y_test), ... | _____no_output_____ | MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
Save model | pickle.dump(lr_clf, open(model_output_path + model_filename, 'wb')) | _____no_output_____ | MIT | notebooks/5_model_training.ipynb | erikgrip/chess_eda |
Fake data to visualize MWEM's histogramsMWEM works by first creating a uniformly distributed histogram out of real data. It then iteratively updates this histogram with noisy samples from the real data. In other words, using the multiplicative weights mechanism, MWEM updates the histograms "weights" via the DP exponen... | import os
import pandas as pd
import numpy as np
import random
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from snsynth.mwem import MWEMSynthesizer
def plot_histo(title,histo):
fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot(111)
ax.set_title(titl... | /var/folders/nx/9gd39tcx2lq7c3vmpmfk8vjc0000gn/T/ipykernel_59986/3611354744.py:11: MatplotlibDeprecationWarning: Starting from Matplotlib 3.6, colorbar() will steal space from the mappable's axes, rather than from the current axes, to place the colorbar. To silence this warning, explicitly pass the 'ax' argument to co... | MIT | synth/samples/mwem_sample/Visualizing MWEM.ipynb | shlomihod/smartnoise-sdk |
Effect of Bin CountHere we can visualize the effect of specifying a max_bin_count. In the original data, we have 100 bins. If we halve that, we see that we still do a pretty good job at capturing the overall distribution. | synth = MWEMSynthesizer(10.0, 400, 30, 20,[[0,1]], max_bin_count=50)
synth.fit(df)
plot_histo('"Real" Data', synth.synthetic_histograms[0][1])
plot_histo('"Fake" Data', synth.synthetic_histograms[0][0]) | /Users/joshuaallen/opt/anaconda3/envs/synth/lib/python3.8/site-packages/snsynth/mwem.py:307: Warning: Bin count 101 in column: 0 exceeds max_bin_count, defaulting to: 50. Is this a continuous variable?
warnings.warn(
/Users/joshuaallen/opt/anaconda3/envs/synth/lib/python3.8/site-packages/snsynth/mwem.py:307: Warning:... | MIT | synth/samples/mwem_sample/Visualizing MWEM.ipynb | shlomihod/smartnoise-sdk |
定义特征构造方法 | eps = 1e-5
# 交叉特征方式
func_dict = {
'add':lambda x, y: x + y,
'multi':lambda x, y: x * y,
'div':lambda x, y: x / (y + eps),
}
# 特征构造方法
def auto_features(train_data, test_data, func_dict, col_list):
train_data, test_data = train_data.copy(), test_data.copy()
for col_i in col_list:
for col_j in... | _____no_output_____ | MIT | 01.蒸汽量预测/.ipynb_checkpoints/5.Feature_Optimization-checkpoint.ipynb | XiaoyuBi/TianChi_Case |
构造特征并降维 | # 构造特征
train_data2, test_data2 = auto_features(train_data,test_data,func_dict,col_list=test_data.columns)
# PCA降维
from sklearn.decomposition import PCA
pca = PCA(n_components = 500)
train_data2_pca = pca.fit_transform(train_data2.iloc[:,0:-1])
test_data2_pca = pca.transform(test_data2)
train_data2_pca = pd.DataFrame(t... | _____no_output_____ | MIT | 01.蒸汽量预测/.ipynb_checkpoints/5.Feature_Optimization-checkpoint.ipynb | XiaoyuBi/TianChi_Case |
LGB模型训练 | # ls_validation i
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error
import lightgbm as lgb
import numpy as np
# 5折交叉验证
Folds = 5
kf = KFold(n_splits = Folds, random_state = 0, shuffle = True)
# 记录训练和预测MSE
MSE_DICT = {
'train_mse':[],
'test_mse':[]
}
# 线下训练预测
for i, (trai... | Training until validation scores don't improve for 100 rounds.
[600] Train's l2: 0.0429543 Test's l2: 0.117409
[1200] Train's l2: 0.0206657 Test's l2: 0.11418
Early stopping, best iteration is:
[1698] Train's l2: 0.0119091 Test's l2: 0.112934
第0折 训练和预测 训练MSE 预测MSE
------ 训练MSE 0.011909097708741524 ------
------ 预测M... | MIT | 01.蒸汽量预测/.ipynb_checkpoints/5.Feature_Optimization-checkpoint.ipynb | XiaoyuBi/TianChi_Case |
module name here> API details. | #hide
from nbdev.showdoc import *
from fastcore.test import *
#export
def say_hello(to):
"Say hello to somebody"
return f'Hello {to}!'
say_hello("toto")
test_eq(say_hello("Jeremy"), "Hello Jeremy!")
#export
class HelloSayer:
"Say hello to `to` using `say_hello`"
def __init__(self, to): self.to = to
... | _____no_output_____ | Apache-2.0 | 00_core.ipynb | ericct/hello_nbdev |
first jupyter notebook | print('hello world')
a=3
b=4
a+b | _____no_output_____ | MIT | lab10.ipynb | MorganEstep/IA241 |
test print | print(c) | 5
| MIT | lab10.ipynb | MorganEstep/IA241 |
define new variable | c = 5 | _____no_output_____ | MIT | lab10.ipynb | MorganEstep/IA241 |
1. this is line12. this is line23. this is line3 * item1* item2* item3 [JMU](https://www.jmu.edu) ![jmu image] (https://www.jmu.edu/_images/_story-rotator/full-width-images/choices4-2000x666.jpg) | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
plt.plot(X, C)
plt.plot(X, S)
plt.show() | _____no_output_____ | MIT | lab10.ipynb | MorganEstep/IA241 |
基于注意力的神经机器翻译 此笔记本训练一个将波斯语翻译为英语的序列到序列(sequence to sequence,简写为 seq2seq)模型。此例子难度较高,需要对序列到序列模型的知识有一定了解。训练完此笔记本中的模型后,你将能够输入一个波斯语句子,例如 *"من می دانم."*,并返回其英语翻译 *"I know."*对于一个简单的例子来说,翻译质量令人满意。但是更有趣的可能是生成的注意力图:它显示在翻译过程中,输入句子的哪些部分受到了模型的注意。请注意:运行这个例子用一个 P100 GPU 需要花大约 10 分钟。 | import tensorflow as tf
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from sklearn.model_selection import train_test_split
import unicodedata
import re
import numpy as np
import os
import io
import time | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
下载和准备数据集我们将使用 http://www.manythings.org/anki/ 提供的一个语言数据集。这个数据集包含如下格式的语言翻译对:```May I borrow this book? ¿Puedo tomar prestado este libro?```这个数据集中有很多种语言可供选择。我们将使用英语 - 波斯语数据集。为方便使用,我们在谷歌云上提供了此数据集的一份副本。但是你也可以自己下载副本。下载完数据集后,我们将采取下列步骤准备数据:1. 给每个句子添加一个 *开始* 和一个 *结束* 标记(token)。2. 删除特殊字符以清理句子。3. 创建一个单词索引和一个反向单词索引(即一个从单词映射至 id ... | '''
# 下载文件
path_to_zip = tf.keras.utils.get_file(
'spa-eng.zip', origin='http://storage.googleapis.com/download.tensorflow.org/data/spa-eng.zip',
extract=True)
path_to_file = os.path.dirname(path_to_zip)+"/spa-eng/spa.txt"
'''
path_to_file = "./lan/pes.txt"
# 将 unicode 文件转换为 ascii
def unicode_to_ascii(s):
... | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
限制数据集的大小以加快实验速度(可选)在超过 10 万个句子的完整数据集上训练需要很长时间。为了更快地训练,我们可以将数据集的大小限制为 3 万个句子(当然,翻译质量也会随着数据的减少而降低): | # 尝试实验不同大小的数据集
num_examples = 30000
input_tensor, target_tensor, inp_lang, targ_lang = load_dataset(path_to_file, num_examples)
# 计算目标张量的最大长度 (max_length)
max_length_targ, max_length_inp = max_length(target_tensor), max_length(input_tensor)
# 采用 80 - 20 的比例切分训练集和验证集
input_tensor_train, input_tensor_val, target_tensor_... | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
创建一个 tf.data 数据集 | BUFFER_SIZE = len(input_tensor_train)
BATCH_SIZE = 64
steps_per_epoch = len(input_tensor_train)//BATCH_SIZE
embedding_dim = 256
units = 1024
vocab_inp_size = len(inp_lang.word_index)+1
vocab_tar_size = len(targ_lang.word_index)+1
dataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).s... | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
编写编码器 (encoder) 和解码器 (decoder) 模型实现一个基于注意力的编码器 - 解码器模型。关于这种模型,你可以阅读 TensorFlow 的 [神经机器翻译 (序列到序列) 教程](https://github.com/tensorflow/nmt)。本示例采用一组更新的 API。此笔记本实现了上述序列到序列教程中的 [注意力方程式](https://github.com/tensorflow/nmtbackground-on-the-attention-mechanism)。下图显示了注意力机制为每个输入单词分配一个权重,然后解码器将这个权重用于预测句子中的下一个单词。下图和公式是 [Luong 的论文](h... | class Encoder(tf.keras.Model):
def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):
super(Encoder, self).__init__()
self.batch_sz = batch_sz
self.enc_units = enc_units
self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)
self.gru = tf.keras.layers.GRU(self.enc_units... | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
定义优化器和损失函数 | optimizer = tf.keras.optimizers.Adam()
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(
from_logits=True, reduction='none')
def loss_function(real, pred):
mask = tf.math.logical_not(tf.math.equal(real, 0))
loss_ = loss_object(real, pred)
mask = tf.cast(mask, dtype=loss_.dtype)
loss_ *= mask
... | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
检查点(基于对象保存) | checkpoint_dir = './training_checkpoints'
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt")
checkpoint = tf.train.Checkpoint(optimizer=optimizer,
encoder=encoder,
decoder=decoder) | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
训练1. 将 *输入* 传送至 *编码器*,编码器返回 *编码器输出* 和 *编码器隐藏层状态*。2. 将编码器输出、编码器隐藏层状态和解码器输入(即 *开始标记*)传送至解码器。3. 解码器返回 *预测* 和 *解码器隐藏层状态*。4. 解码器隐藏层状态被传送回模型,预测被用于计算损失。5. 使用 *教师强制 (teacher forcing)* 决定解码器的下一个输入。6. *教师强制* 是将 *目标词* 作为 *下一个输入* 传送至解码器的技术。7. 最后一步是计算梯度,并将其应用于优化器和反向传播。 | @tf.function
def train_step(inp, targ, enc_hidden):
loss = 0
with tf.GradientTape() as tape:
enc_output, enc_hidden = encoder(inp, enc_hidden)
dec_hidden = enc_hidden
dec_input = tf.expand_dims([targ_lang.word_index['<start>']] * BATCH_SIZE, 1)
# 教师强制 - 将目标词作为下一个输入
for t in range(1, targ.sha... | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
翻译* 评估函数类似于训练循环,不同之处在于在这里我们不使用 *教师强制*。每个时间步的解码器输入是其先前的预测、隐藏层状态和编码器输出。* 当模型预测 *结束标记* 时停止预测。* 存储 *每个时间步的注意力权重*。请注意:对于一个输入,编码器输出仅计算一次。 | def evaluate(sentence):
attention_plot = np.zeros((max_length_targ, max_length_inp))
sentence = preprocess_sentence(sentence)
inputs = [inp_lang.word_index[i] for i in sentence.split(' ')]
inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs],
... | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
恢复最新的检查点并验证 | # 恢复检查点目录 (checkpoint_dir) 中最新的检查点
checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))
translate(u'hace mucho frio aqui.')
translate(u'esta es mi vida.')
translate(u'¿todavia estan en casa?')
# 错误的翻译
translate(u'trata de averiguarlo.') | _____no_output_____ | MIT | nmt/Persian-English_pes-eng.ipynb | WangXingqiu/machine-translation |
This is from a "Getting Started" competition from Kaggle [Titanic competition](https://www.kaggle.com/c/titanic) to showcase how we can use Auto-ML along with datmo and docker, in order to track our work and make machine learning workflow reprocible and usable. Some part of data analysis is inspired from this [kernel]... | %matplotlib inline
import numpy as np
import pandas as pd
import re as re
train = pd.read_csv('./input/train.csv', header = 0, dtype={'Age': np.float64})
test = pd.read_csv('./input/test.csv' , header = 0, dtype={'Age': np.float64})
full_data = [train, test]
print (train.info()) | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
PassengerId 891 non-null int64
Survived 891 non-null int64
Pclass 891 non-null int64
Name 891 non-null object
Sex 891 non-null object
Age 714 non-null float64
SibSp ... | MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
1. Exploratory Data Analysis To understand how each feature has the contribution to Survive a. `Sex` | print (train[["Sex", "Survived"]].groupby(['Sex'], as_index=False).mean()) | Sex Survived
0 female 0.742038
1 male 0.188908
| MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
b. `Pclass` | print (train[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False).mean()) | Pclass Survived
0 1 0.629630
1 2 0.472826
2 3 0.242363
| MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
c. `SibSp and Parch`With the number of siblings/spouse and the number of children/parents we can create new feature called Family Size. | for dataset in full_data:
dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1
print (train[['FamilySize', 'Survived']].groupby(['FamilySize'], as_index=False).mean()) | FamilySize Survived
0 1 0.303538
1 2 0.552795
2 3 0.578431
3 4 0.724138
4 5 0.200000
5 6 0.136364
6 7 0.333333
7 8 0.000000
8 11 0.000000
| MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
`FamilySize` seems to have a significant effect on our prediction. `Survived` has increased until a `FamilySize` of 4 and has decreased after that. Let's categorize people to check they are alone or not. | for dataset in full_data:
dataset['IsAlone'] = 0
dataset.loc[dataset['FamilySize'] == 1, 'IsAlone'] = 1
print (train[['IsAlone', 'Survived']].groupby(['IsAlone'], as_index=False).mean()) | IsAlone Survived
0 0 0.505650
1 1 0.303538
| MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
d. `Embarked` we fill the missing values with most occured value `S` | for dataset in full_data:
dataset['Embarked'] = dataset['Embarked'].fillna('S')
print (train[['Embarked', 'Survived']].groupby(['Embarked'], as_index=False).mean()) | Embarked Survived
0 C 0.553571
1 Q 0.389610
2 S 0.339009
| MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
e. `Fare`Fare also has some missing values which will be filled with the median | for dataset in full_data:
dataset['Fare'] = dataset['Fare'].fillna(train['Fare'].median())
train['CategoricalFare'] = pd.qcut(train['Fare'], 4)
print (train[['CategoricalFare', 'Survived']].groupby(['CategoricalFare'], as_index=False).mean()) | CategoricalFare Survived
0 (-0.001, 7.91] 0.197309
1 (7.91, 14.454] 0.303571
2 (14.454, 31.0] 0.454955
3 (31.0, 512.329] 0.581081
| MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
It shows the `Fare` has a significant affect on survival, showcasing that people haivng paid higher fares had higher chances of survival f. `Age`There are plenty of missing values in this feature. generate random numbers between (mean - std) and (mean + std). then we categorize age into 5 range. | for dataset in full_data:
age_avg = dataset['Age'].mean()
age_std = dataset['Age'].std()
age_null_count = dataset['Age'].isnull().sum()
age_null_random_list = np.random.randint(age_avg - age_std, age_avg + age_std, size=age_null_count)
dataset['Age'][np.isnan(dataset['Age'])] = age_null_random_... | CategoricalAge Survived
0 (-0.08, 16.0] 0.523810
1 (16.0, 32.0] 0.347345
2 (32.0, 48.0] 0.389764
3 (48.0, 64.0] 0.434783
4 (64.0, 80.0] 0.090909
| MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
g. `Name`Let's the title of people | def get_title(name):
title_search = re.search(' ([A-Za-z]+)\.', name)
# If the title exists, extract and return it.
if title_search:
return title_search.group(1)
return ""
for dataset in full_data:
dataset['Title'] = dataset['Name'].apply(get_title)
print("=====Title vs Sex=====")
print(pd... | =====Title vs Sex=====
Sex female male
Title
Capt 0 1
Col 0 2
Countess 1 0
Don 0 1
Dr 1 6
Jonkheer 0 1
Lady 1 0
Major 0 2
Master 0 40
Miss 182 0
Mlle 2 ... | MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
Let's categorize it and check the title impact on survival rate convert the rare titles to `Rare` | for dataset in full_data:
dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess','Capt', 'Col',\
'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')
dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')
dataset['T... | _____no_output_____ | MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
Creating a datmo snapshot to save my work, this helps me save my current work before proceeding onto data cleaning ```bashhome:~/datmo-tutorials/auto-ml$ datmo snapshot create -m "EDA"Creating a new snapshotCreated snapshot with id: 30803662ab49bb1ef67a5d0861eecf91cff1642fhome:~/datmo-tutorials/auto-ml$ datmo snapshot... | train_copy = train.copy()
test_copy = test.copy()
full_data_copy = [train_copy, test_copy]
for dataset in full_data_copy:
# Mapping Sex
dataset['Sex'] = dataset['Sex'].map( {'female': 0, 'male': 1} ).astype(int)
# Mapping titles
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": ... | _____no_output_____ | MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
3. Using Auto-ML to figure out the best algorithm and hyperparameter Now we have cleaned our data it's time to use auto-ml in order to get the best algorithm for this data | from tpot import TPOTClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X = train_copy[0::, 1::]
y = train_copy[0::, 0]
X_train, X_test, y_train, y_test = train_test_split(X, y,
train_size=0.75, test_size=0.25)
... | _____no_output_____ | MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
Let's again create a datmo snapshot to save my work, this helps me save my current work before changing my feature selection```bashhome:~/datmo-tutorials/auto-ml$ datmo snapshot create -m "auto-ml-1"Creating a new snapshotCreated snapshot with id: adf76fa7d0800cc6eec033d4b00f97536bcb0c20home:~/datmo-tutorials/auto-ml$... | train_copy = train.copy()
test_copy = test.copy()
full_data_copy = [train_copy, test_copy]
for dataset in full_data_copy:
# Mapping Sex
dataset['Sex'] = dataset['Sex'].map( {'female': 0, 'male': 1} ).astype(int)
# Mapping titles
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": ... | _____no_output_____ | MIT | kaggle-titanic/cli/.ipynb_checkpoints/experimentation-checkpoint.ipynb | datmo/datmo-tutorials |
Extract from JSON and XMLYou'll now get practice extracting data from JSON and XML. You'll extract the same population data from the previous exercise, except the data will be in a different format.Both JSON and XML are common formats for storing data. XML was established before JSON, and JSON has become more popular ... | ###
# Run the following cell.
# This cell loads a function that prints the first n lines of
# a file.
#
# Then this function is called on the JSON file to print out
# the first line of the population_data.json file
###
def print_lines(n, file_name):
f = open(file_name)
for i in range(n):
pri... | _____no_output_____ | MIT | lessons/ETLPipelines/2_extract_exercise/.ipynb_checkpoints/2_extract_exercise-checkpoint.ipynb | rabadzhiyski/Data_Science_Udacity |
The first "line" in the file is actually the entire file. JSON is a compact way of representing data in a dictionary-like format. Luckily, pandas has a method to [read in a json file](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html). If you open the link with the documentation, you'll see t... | # TODO: Read in the population_data.json file using pandas's
# read_json method. Don't forget to specific the orient option
# store the results in df_json
import pandas as pd
df_json = None
# TODO: Use the head method to see the first few rows of the resulting
# dataframe | _____no_output_____ | MIT | lessons/ETLPipelines/2_extract_exercise/.ipynb_checkpoints/2_extract_exercise-checkpoint.ipynb | rabadzhiyski/Data_Science_Udacity |
Notice that this population data is the same as the data from the previous exercise. The column order might have changed, but the data is otherwise the same. Other Ways to Read in JSONBesides using pandas to read JSON files, you can use the json library. Run the code cell below to see an example of reading in JSON wit... | import json
# read in the JSON file
with open('population_data.json') as f:
json_data = json.load(f)
# print the first record in the JSON file
print(json_data[0])
print('\n')
# show that JSON data is essentially a dictionary
print(json_data[0]['Country Name'])
print(json_data[0]['Country Code']) | _____no_output_____ | MIT | lessons/ETLPipelines/2_extract_exercise/.ipynb_checkpoints/2_extract_exercise-checkpoint.ipynb | rabadzhiyski/Data_Science_Udacity |
Extract XMLNext, you'll work with the same data except now the data is in xml format. Run the next code cell to see what the first fifteen lines of the data file look like. | # Run the code cell to print out the first 15 lines of the xml file
print_lines(15, 'population_data.xml') | _____no_output_____ | MIT | lessons/ETLPipelines/2_extract_exercise/.ipynb_checkpoints/2_extract_exercise-checkpoint.ipynb | rabadzhiyski/Data_Science_Udacity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.