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 |
|---|---|---|---|---|---|
Let's verify each of our clustersCluster 1 | toronto_merged_nonan.loc[toronto_merged_nonan['Cluster Labels'] == 0, toronto_merged_nonan.columns[[1] + list(range(5, toronto_merged_nonan.shape[1]))]] | _____no_output_____ | Apache-2.0 | appliedDataScienceCapstoneWeek3.ipynb | Margchunne28/Location-data-provider |
Cluster 2 | toronto_merged_nonan.loc[toronto_merged_nonan['Cluster Labels'] == 1, toronto_merged_nonan.columns[[1] + list(range(5, toronto_merged_nonan.shape[1]))]] | _____no_output_____ | Apache-2.0 | appliedDataScienceCapstoneWeek3.ipynb | Margchunne28/Location-data-provider |
Cluster 3 | toronto_merged_nonan.loc[toronto_merged_nonan['Cluster Labels'] == 2, toronto_merged_nonan.columns[[1] + list(range(5, toronto_merged_nonan.shape[1]))]] | _____no_output_____ | Apache-2.0 | appliedDataScienceCapstoneWeek3.ipynb | Margchunne28/Location-data-provider |
Cluster 4 | toronto_merged_nonan.loc[toronto_merged_nonan['Cluster Labels'] == 3, toronto_merged_nonan.columns[[1] + list(range(5, toronto_merged_nonan.shape[1]))]] | _____no_output_____ | Apache-2.0 | appliedDataScienceCapstoneWeek3.ipynb | Margchunne28/Location-data-provider |
Cluster 5 | toronto_merged_nonan.loc[toronto_merged_nonan['Cluster Labels'] == 4, toronto_merged_nonan.columns[[1] + list(range(5, toronto_merged_nonan.shape[1]))]] | _____no_output_____ | Apache-2.0 | appliedDataScienceCapstoneWeek3.ipynb | Margchunne28/Location-data-provider |
Time Series - collecting dxata at regular intervales**ADDITIVE MODEL**- represent a TS as a combinatino fo patterns at diffferent scales.- Decompose pieces QUANDL FINANCIAL LIBRARY- https://www.quandl.com/tools/python- https://github.com/quandl/quandl-python | #!pip install quandl
import quandl
import pandas as pd
# quandl.ApiConfig.api_key = 'getyourownkey!'
tesla = quandl.get('WIKI/TSLA')
gm = quandl.get('WIKI/GM')
gm.head()
tesla_copy = tesla.copy()
gm_copy = gm.copy() | _____no_output_____ | BSD-2-Clause | Misc Learning/Untitled.ipynb | hamil168/Data-Science-Misc |
EDA | import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.plot(gm.index, gm['Adj. Close'])
plt.title('GM Stock Prices')
plt.ylabel('Price USD')
plt.show()
plt.plot(tesla.index, tesla['Adj. Close'], 'r')
plt.title('Tesla Stock Price')
plt.ylabel('Price USD')
plt.show()
# Yearly average number of shares outstanding fo... | Tesla was valued higher than GM from 2017-04-10 to 2018-03-23.
| BSD-2-Clause | Misc Learning/Untitled.ipynb | hamil168/Data-Science-Misc |
Code Transfer TestThe code transfer test is designed to test your coding skills that is learnt during the lecture training. The allotted time for the subsequent problem set is approximately 30 minutes. You are allowed to refer to Jupyter notebook throughout the test. Good luck!Jupyter notebook resource: Timer extensio... | # First, let's import the pandas and numpy libraries
import pandas as pd
import numpy as np
# In addition, I want to show some plots, so we'll import matplotlib as well
import matplotlib.pyplot as plt
# Finally, we'll bring in the scipy stats libraries
from scipy import stats
# Hide
import pandas.util.testing as pdt
... | <ipython-input-2-b71c00b51b7e>:2: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
import pandas.util.testing as pdt
| MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
Transfer Test QuestionWhat's the probability that a NFL player makes a field goal? In this problem we are interested in predicting the probability of NFL players to make a field goal. After assuming that the probability of NFL players to make a field goal follows a beta distribution, we observe the field goals data du... | # Answer
file = 'nfl.csv'
def read_csv(file):
"""Read the nfl.csv data and return the first few lines of
the csv file.
"""
### BEGIN SOLUTION
data = pd.read_csv(file)
# And let's look at the first few lines
return data.head()
### END SOLUTION
read_csv(file)
# Basic Test Case
"""Chec... | _____no_output_____ | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
Question 2: Column MeanLet us define the column_mean function which takes the csv file and the column name as inputs, and returns the mean probability of making field goals. (Look at the FG column) | # Sample Answer
column = 'FG'
def column_mean(file, column):
"""Take the nfl.csv file and a specific column as input.
Compute the mean value for a column in pandas dataframe.
"""
### BEGIN SOLUTION
data = pd.read_csv(file)
return data[column].mean()
### END SOLUTION
column_mean(file, col... | _____no_output_____ | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
Question 3: Specify Prior and LikelihoodLet us specify the prior and likelihood. We are going to split two code chunks to perform the following steps:In the first code chunk, we initialize a random number generator as 123 to make the random numbers predictable. Then, we assign the hyperparameters of prior. In this que... | # Sample answer
### BEGIN SOLUTION
# We initialize random number generator seed for reproducible results
np.random.seed(123)
# We assign the hyperparameters of prior
# We assign the shape parameters alpha and beta as 40 and 20.
alpha, beta = 40, 20
# Then we make up the sample size as 100
size = 100
### END SOLUTI... | _____no_output_____ | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
Optional QuestionYou can run the following code to generate a plot for the beta distribution based on the alpha and beta parameters you defined above. Here the scipy.stats.beta function and matplotlib package are used to generate the probability density function plot. | # We define the linestyle and set up a linear space to clearly plot the beta distribution
x = np.linspace(0,1,1002)[1:-1]
# Then, we use scipy.stats.beta function to set up beta distribution
dist = stats.beta(alpha, beta)
# Now we want to define a plot_beta_pdf function to generate a figure
# showing the probability... | _____no_output_____ | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
You will see that the beta distribution curve surprisingly resembles the case when we conduct binomial trials with roughly 40 successes and 20 failures.In fact, we can think of $\alpha - 1$ as the number of successes and $\beta - 1$ as the number of failures. You can choose the $\alpha$ and $\beta$ parameters however y... | import pymc3 as pm
# Hide
import unittest | _____no_output_____ | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
Question 4: Train MCMC samplerLet us train the Markov Chain Monte Carlo sampler. In this example, we use the default NUTS algorithm to sample the posterior distribution. We need to perform the following steps:First we set a variable called niter, the number of draw, to 1000.Second, we instantiate the model object.Thir... | # Sample answer
seed = 1000
def sampler(alpha, beta, size, observed, seed):
"""Train a MCMC sampler to generate posterior samples for the
field goal probability.
"""
### BEGIN SOLUTION
niter = 1000
model = pm.Model()
with model:
p = pm.Beta('p', alpha=alpha, beta=beta)
... | _____no_output_____ | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
Posterior Diagnostics Question 5Now we look at the posterior diagnostics. Recall we will plot a traceplot to visualize the posterior distribution of parameters of interest. In addition, we also obtain Gelman-Rubin statistics to check whether the parameter of interest converges.a) Define a function named traceplot whi... | # Answer 5a
# Plot results Traceplot
def traceplot(trace):
"""Generate the posterior density plot and trajectory plot for the field goal probability."""
# BEGIN SOLUTION
return pm.traceplot(trace, varnames = ['p'])
# END SOLUTION
traceplot(trace)
plt.show()
# Test cases
"""Check the length data typ... | C:\Users\sonso\Anaconda3\lib\site-packages\pymc3\plots\__init__.py:35: UserWarning: Keyword argument `varnames` renamed to `var_names`, and will be removed in pymc3 3.8
warnings.warn('Keyword argument `{old}` renamed to `{new}`, and will be removed in pymc3 3.8'.format(old=old, new=new))
C:\Users\sonso\Anaconda3\lib\... | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
b) (Optional) What trends do you see in the posterior distribution of the probability of making a field goal? c) Define a function named posterior_summary which takes a trace object as input and displays a table-based summary of posterior statistics rounded by 2 digits. | # Answer 5c
# Obtain summary statistics for posterior distributions
def posterior_summary(trace):
"""Generate a table-based summary for the field goal probability."""
# BEGIN SOLUTION
return pm.summary(trace).round(2)
# END SOLUTION
# Test Cases
"""Check whether the summary output is correctly generated... | C:\Users\sonso\Anaconda3\lib\site-packages\arviz\data\io_pymc3.py:87: FutureWarning: Using `from_pymc3` without the model will be deprecated in a future release. Not using the model will return less accurate and less useful results. Make sure you use the model argument or call from_pymc3 within a model context.
warni... | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
d) What is the posterior mean and standard deviation of the probability of making a field goal? Define a function posterior_statistics which takes a trace object as input and return the posterior mean and posterior standard deviation as a tuple looks like (mean, sd). | # Answer 5d
def posterior_statistics(trace):
return (posterior_summary(trace).iloc[0,0], posterior_summary(trace).iloc[0,1])
posterior_statistics(trace)
# Test Cases
"""Check whether the posterior mean and posterior standard deviation are correctly generated."""
assert_equal(posterior_statistics(trace),
... | C:\Users\sonso\Anaconda3\lib\site-packages\arviz\data\io_pymc3.py:87: FutureWarning: Using `from_pymc3` without the model will be deprecated in a future release. Not using the model will return less accurate and less useful results. Make sure you use the model argument or call from_pymc3 within a model context.
warni... | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
e) Define a function named gelman_rubin which takes a trace object as input and return the Gelman-Rubin statistics. Does the posterior distribution converge? | # Answer
# Get Gelman-Rubin Convergence Criterion
def gelman_rubin(trace):
"""Compute Gelman-Rubin statistics for the posterior samples of field goal probability."""
### BEGIN SOLUTION
return print(pm.rhat(trace,
varnames=['p']))
### END SOLUTION
gelman_rubin(trace)
# Test cases
ass... | _____no_output_____ | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
Bonus Section: Effective sample sizeThe calculation of effective sample size is given by the following formula:$$\hat{n}_{eff} = \frac{mn}{1 + 2 \sum_{t=1}^T \hat{\rho}_t}$$where m is the number of chains, n the number of steps per chain, T the time when the autocorrelation first becomes negative, and ρ̂_t the autoco... | ## Calculate effective sample size
pm.effective_n(trace) | /Users/son520804/anaconda3/lib/python3.6/site-packages/pymc3/stats/__init__.py:50: UserWarning: effective_n has been deprecated. In the future, use ess instead.
warnings.warn("effective_n has been deprecated. In the future, use ess instead.")
| MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
As you can see, the effective sample size is 1271 for the total of the 3 chains. Since by default, the tuning sample is 500, leaving 500 samples to be resampled. So that means the autocorrelation is not extreme, the MCMC converges well. Geweke StatisticsAs an alternative of Gelman-Rubin statistics, Geweke provides a s... | # We can create a plot to show the trajectory of Geweke statistics
plt.plot(pm.geweke(trace['p'])[:,1], 'o')
plt.axhline(1, c='red')
plt.axhline(-1, c='red')
plt.gca().margins(0.05)
plt.show()
pass | _____no_output_____ | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
Since the Geweke statistics are less than 1 in absolute value, it indicates a good convergence in the MCMC chains. Debug QuestionThe following question requires you to read the code carefully and correct the codes with errors. A Umich cognitive science research team want to produce an elegant code to run a MCMC sample... | # IQ test results for the 100 students
np.random.seed(123)
y = np.random.normal(100, 15, 100)
# Hierarchical Bayesian Modeling
seed = 123
niter = 1000
nchains = 3
with pm.Model() as model:
"""Deploy NUTS sampler to update the distribution for students' IQ."""
### BEGIN CODE
mu = pm.Normal('mu', mu = 1... | _____no_output_____ | MIT | PyMC3_Transfer_Test.ipynb | son520804/Video_Composition_Project |
Creating Provenance an Example Using a Python Notebook | import prov, requests, pandas as pd, io, git, datetime, urllib
from prov.model import ProvDocument | _____no_output_____ | MIT | prov/Provenance using KN resource.ipynb | CSIRO-enviro-informatics/jupyter-examples |
Initialising a Provenance DocumentFirst we use the prov library to create a provenance and initialise it with some relevant namespaces that can be used later to define provenance activities and entities | pg = ProvDocument()
kn_id = "data/data-gov-au/number-of-properties-by-suburb-and-planning-zone-csv"
pg.add_namespace('kn', 'http://oznome.csiro.au/id/')
pg.add_namespace('void', 'http://vocab.deri.ie/void#')
pg.add_namespace('foaf', 'http://xmlns.com/foaf/0.1/')
pg.add_namespace('dc', 'http://purl.org/dc/elements/1.1/... | _____no_output_____ | MIT | prov/Provenance using KN resource.ipynb | CSIRO-enviro-informatics/jupyter-examples |
Processing the DataProcessing could be anything and represents one or more provenance activities. In this example we use a KN metadata record to retrieve data on residential properities. We intersperse definition of provenance into this processing but we could have easily seperated it out and performed it after the pr... | input_identifier = 'kn:'+ kn_id
input_entity = pg.entity(input_identifier, {'prov:label': 'road static parking off street', 'prov:type': 'void:Dataset'}) | _____no_output_____ | MIT | prov/Provenance using KN resource.ipynb | CSIRO-enviro-informatics/jupyter-examples |
Then we proceed to drill down to get detailed data that we've found associated with this record | start_time = datetime.datetime.now()
response = requests.get('https://data.sa.gov.au/data/dataset/d080706c-2c05-433d-b84d-9aa9b6ccae73/resource/4a47e89b-4be8-430d-8926-13b180025ac6/download/city-of-onkaparinga---number-of-properties-by-suburb-and-planning-zone-2016.csv')
url_data = response.content
dataframe = pd.read_... | _____no_output_____ | MIT | prov/Provenance using KN resource.ipynb | CSIRO-enviro-informatics/jupyter-examples |
Our processing is very simple we are subsetting the original dataset here and creating a new dataset called residential_frame that we will then save to disk | residential_frame = dataframe[dataframe['Zone_Description'] == 'Residential']
residential_frame_file_name = "filtered_residential_data.csv"
residential_frame.to_csv(residential_frame_file_name)
end_time = datetime.datetime.now() | _____no_output_____ | MIT | prov/Provenance using KN resource.ipynb | CSIRO-enviro-informatics/jupyter-examples |
Completing ProvenanceWe have began to build a provenance record but we are missing a record of the activity that transforms our input into the output and we are also missing a description of the output Generating an output provenance entityIdeally we would store our output provenance entity somewhere known and pers... | import subprocess
output = subprocess.check_output("sha1sum "+ residential_frame_file_name, shell=True)
sha1 = str(output).split(' ')[0][2:]
output_identifier = 'kn:' + sha1
output_entity = pg.entity(output_identifier , {'prov:label': residential_frame_file_name, 'prov:type': 'void:Dataset'}) | _____no_output_____ | MIT | prov/Provenance using KN resource.ipynb | CSIRO-enviro-informatics/jupyter-examples |
Describing the activity We need to connect the entity representing the input data to the entity representing the output data and we may want to describe the activity that transforms the input into the output. In this case the activity is this Jupyter Notebook. One way of storing provenance information in it is to make... | import re, ipykernel, json
%%javascript
var nb = Jupyter.notebook;
var port = window.location.port;
nb.kernel.execute("NB_Port = '" + port + "'");
kernel_id = re.search('kernel-(.*).json', ipykernel.connect.get_connection_file()).group(1)
response = requests.get('http://127.0.0.1:{port}/jupyter/api/sessions'.format(por... | _____no_output_____ | MIT | prov/Provenance using KN resource.ipynb | CSIRO-enviro-informatics/jupyter-examples |
One gotcha here is that we need to make sure this notebooks relevant version has been committed and pushed to the remote. So do that and then execute these cells. | repo = git.Repo('./', search_parent_directories=True)
current_git_sha = repo.head.object.hexsha
current_git_remote = list(repo.remotes['origin'].urls)[0]
current_git_sha
current_git_remote
process_identifier = 'kn:' + 'notebook/' + urllib.parse.quote(notebook_file_name + current_git_sha, safe='')
process_identifier
p... | _____no_output_____ | MIT | prov/Provenance using KN resource.ipynb | CSIRO-enviro-informatics/jupyter-examples |
Cython in Jupyter notebooks To use cython in a Jupyter notebook, the extension has to be loaded. | %load_ext cython | _____no_output_____ | CC-BY-4.0 | source-code/cython/cython.ipynb | gjbex/Python-for-HPC |
Pure Python To illustrate the performance difference between a pure Python function and a cython implementation, consider a function that computes the list of the first $k_{\rm max}$ prime numbers. | from array import array
def primes(kmax, p=None):
if p is None:
p = array('i', [0]*kmax)
result = []
k, n = 0, 2
while k < len(p):
i = 0
while i < k and n % p[i] != 0:
i += 1
if i == k:
p[k] = n
k += 1
result.append(n)
... | _____no_output_____ | CC-BY-4.0 | source-code/cython/cython.ipynb | gjbex/Python-for-HPC |
Checking the results for the 20 first prime numbers. | primes(20) | _____no_output_____ | CC-BY-4.0 | source-code/cython/cython.ipynb | gjbex/Python-for-HPC |
Note that this is not the most efficient method to check whether $k$ is prime. | %timeit primes(1_000)
p = array('i', [0]*10_000)
%timeit primes(10_000, p) | 7.65 s ± 993 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
| CC-BY-4.0 | source-code/cython/cython.ipynb | gjbex/Python-for-HPC |
Cython The cython implementation differs little from that in pure Python, type annotations have been added for the function's argument, and the variables `n`, `k`, `i`, and `p`. Note that cython expects a constant array size, hence the upper limit on `kmax`. | %%cython
def c_primes(int kmax):
cdef int n, k, i
cdef int p[10_000]
if kmax > 10_000:
kmax = 10_000
result = []
k, n = 0, 2
while k < kmax:
i = 0
while i < k and n % p[i] != 0:
i += 1
if i == k:
p[k] = n
k += 1
resu... | _____no_output_____ | CC-BY-4.0 | source-code/cython/cython.ipynb | gjbex/Python-for-HPC |
Checking the results for the 20 first prime numbers. | c_primes(20)
%timeit c_primes(1_000)
%timeit c_primes(10_000) | 195 ms ± 15 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
| CC-BY-4.0 | source-code/cython/cython.ipynb | gjbex/Python-for-HPC |
It is clear that the cython implementation is more than 30 times faster than the pure Python implementation. Dynamic memory allocation The cython implementation can be improved by adding dynamic memory allocation for the array `p`. | %%cython
from libc.stdlib cimport calloc, free
def c_primes(int kmax):
cdef int n, k, i
cdef int *p = <int *> calloc(kmax, sizeof(int))
result = []
k, n = 0, 2
while k < kmax:
i = 0
while i < k and n % p[i] != 0:
i += 1
if i == k:
p[k] = n
... | _____no_output_____ | CC-BY-4.0 | source-code/cython/cython.ipynb | gjbex/Python-for-HPC |
Checking the results for the 20 first prime numbers. | c_primes(20) | _____no_output_____ | CC-BY-4.0 | source-code/cython/cython.ipynb | gjbex/Python-for-HPC |
This has no noticeable impact on performance. | %timeit c_primes(1_000)
%timeit c_primes(10_000) | 243 ms ± 32.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
| CC-BY-4.0 | source-code/cython/cython.ipynb | gjbex/Python-for-HPC |
Plotly's Python graphing library makes interactive, publication-quality graphs. Examples of how to make line plots, scatter plots, area charts, bar charts, error bars, box plots, histograms, heatmaps, subplots, multiple-axes, polar charts, and bubble charts. | !pip install plotly_express | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
Plotly Express is a terse, consistent, high-level wrapper around Plotly.py for rapid data exploration and figure generation. | !pip install calmap | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
Calendar heatmaps (calmap) Plot Pandas time series data sampled by day in a heatmap per calendar year, similar to GitHub’s contributions plot, using matplotlib. | !pip install squarify | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
Pure Python implementation of the squarify treemap layout algorithm. Based on algorithm from Bruls, Huizing, van Wijk, "Squarified Treemaps", but implements it differently. | !pip install pycountry_convert | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
Using country data derived from wikipedia, pycountry-convert provides conversion functions between ISO country names, country-codes, and continent names. | !pip install GoogleMaps | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
Use Python? Want to geocode something? Looking for directions? Maybe matrices of directions? This library brings the Google Maps Platform Web Services to your Python application. | !pip install xgboost | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
XGBoost is an optimized distributed gradient boosting library designed to be highly efficient, flexible and portable. It implements machine learning algorithms under the Gradient Boosting framework. XGBoost provides a parallel tree boosting (also known as GBDT, GBM) that solve many data science problems in a fast and a... | !pip install lightgbm | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
LightGBM is a gradient boosting framework that uses tree based learning algorithms. It is designed to be distributed and efficient with the following advantages:* Faster training speed and higher efficiency.* Lower memory usage.* Better accuracy.* Support of parallel and GPU learning.* Capable of handling large-scale d... | !pip install altair | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
Altair is a declarative statistical visualization library for Python. With Altair, you can spend more time understanding your data and its meaning. Altair's API is simple, friendly and consistent and built on top of the powerful Vega-Lite JSON specification. This elegant simplicity produces beautiful and effective visu... | !pip install folium | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
folium builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js library. Manipulate your data in Python, then visualize it in a Leaflet map via folium. | !pip install fbprophet | _____no_output_____ | MIT | 1_Required_Python_Library_Installation.ipynb | chahatmax/World_VS_India_COVID-19 |
Análise do eleitorado brasileiroFonte -> http://www.tse.jus.br/eleicoes/estatisticas/estatisticas-eleitorais | # importando as bibliotecas
import pandas as pd
# Carregando o arquivo csv
df = pd.read_csv('eleitorado_municipio_2020.csv', encoding='latin1', sep=';')
df.head().T
# Tamanho do arquivo
df.info()
# As cinco cidades com o maior número de eleitores deficientes.
df.nlargest(5,'QTD_ELEITORES_DEFICIENTE')
# As cinco cidade... | _____no_output_____ | MIT | 09.Eleitorado_2020/09_csv_eleitores_2020.ipynb | alexfviana/Python_LabHacker |
Gun Deaths in the US, 2012-2014This is an analysis of gun deaths in the US between the years 2012 and 2014. The data comes from FiveThirtyEight, specifcally [here](https://github.com/fivethirtyeight/guns-data). | import csv
f = open("guns.csv", "r")
data = list(csv.reader(f))
print(data[:5])
headers = data[0]
data = data[1:]
print(headers)
print(data[:5])
import datetime
dates = [datetime.datetime(year=int(d[1]), month=int(d[2]), day=1) for d in data]
print(dates[:5])
date_counts = {}
for d in dates:
if d in date_counts:... | {'F': 14449, 'M': 86349}
{'Native American/Native Alaskan': 917, 'Hispanic': 9022, 'White': 66237, 'Asian/Pacific Islander': 1326, 'Black': 23296}
| MIT | dataquest/gun_deaths/.ipynb_checkpoints/Gun_Deaths-checkpoint.ipynb | arturbacu/data-science |
Patterns so far* Most gun deaths are for race = white and sex = M, but is there a further correlation here?* It may help to explore this further to find more patterns like age, education status, and if police were involved | f2 = open("census.csv", "r")
census = list(csv.reader(f2))
census
mapping = {"Asian/Pacific Islander": 15834141,
"Black": 40250635,
"Native American/Native Alaskan": 3739506,
"Hispanic": 44618105,
"White": 197318956}
race_per_hundredk = {}
for r, v in race_counts.items():... | {'Native American/Native Alaskan': 14.841532544673013, 'Hispanic': 7.106980451097149, 'White': 28.06217969245692, 'Asian/Pacific Islander': 4.705023152187416, 'Black': 8.278130270491385}
| MIT | dataquest/gun_deaths/.ipynb_checkpoints/Gun_Deaths-checkpoint.ipynb | arturbacu/data-science |
Módulo 2: Scraping con Selenium LATAM AirlinesVamos a scrapear el sitio de Latam para averiguar datos de vuelos en funcion el origen y destino, fecha y cabina. La información que esperamos obtener de cada vuelo es:- Precio(s) disponibles- Horas de salida y llegada (duración)- Información de las escalas¡Empecemos! | url = 'https://www.latam.com/es_ar/apps/personas/booking?fecha1_dia=20&fecha1_anomes=2019-12&auAvailability=1&ida_vuelta=ida&vuelos_origen=Buenos%20Aires&from_city1=BUE&vuelos_destino=Madrid&to_city1=MAD&flex=1&vuelos_fecha_salida_ddmmaaaa=20/12/2019&cabina=Y&nadults=1&nchildren=0&ninfants=0&cod_promo='
from selenium i... | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C5. Demoras inteligentes - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Obtenemos la información de la hora de salida, llegada y duración del vuelo | # Hora de salida
vuelo.find_element_by_xpath('.//div[@class="departure"]/time').get_attribute('datetime')
# Hora de llegada
vuelo.find_element_by_xpath('.//div[@class="arrival"]/time').get_attribute('datetime')
# Duración del vuelo
vuelo.find_element_by_xpath('.//span[@class="duration"]/time').get_attribute('datetime')... | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C5. Demoras inteligentes - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Clase 15Ya tenemos el scraper casi listo. Unifiquemos las 3 funciones de la clase anterior en una sola | def obtener_info(driver):
vuelos = driver.find_elements_by_xpath('//li[@class="flight"]')
print(f'Se encontraron {len(vuelos)} vuelos.')
print('Iniciando scraping...')
info = []
for vuelo in vuelos:
# Obtenemos los tiempos generales del vuelo
tiempos = obtener_tiempos(vuelo)
... | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C5. Demoras inteligentes - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Ahora podemos cargar la página con el driver y pasárselo a esta función | driver = webdriver.Chrome(executable_path='../../chromedriver', options=options)
driver.get(url)
obtener_info(driver) | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C5. Demoras inteligentes - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Se encontraron 0 vuelos porque la página no terminó de cargar Lo más simple que podemos hacer es agregar una demora fija lo suficientemente grande para asegurarnos que la página terminó de cargar. | import time
options = webdriver.ChromeOptions()
options.add_argument('--incognito')
driver = webdriver.Chrome(executable_path='../../chromedriver', options=options)
driver.get(url)
time.sleep(10)
vuelos = driver.find_elements_by_xpath('//li[@class="flight"]')
vuelos
driver.close() | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C5. Demoras inteligentes - Script.ipynb | Alejandro-sin/Learning_Notebooks |
Esto funciona pero no es muy eficiente. Lo mejor sería esperar a que la página termine de cargar y luego recuperar los elementos. | from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
options = webdriver.ChromeOptions()
options.add_argument('--incognito')
driver = webdriver.Chrome(e... | _____no_output_____ | MIT | NoteBooks/Curso de WebScraping/Unificado/web-scraping-master/Clases/Módulo 3_ Scraping con Selenium/M3C5. Demoras inteligentes - Script.ipynb | Alejandro-sin/Learning_Notebooks |
RIHAD VARIAWA, Data Scientist - Who has fun LEARNING, EXPLORING & GROWING2D Numpy in Python Welcome! This notebook will teach you about using Numpy in the Python Programming Language. By the end of this lab, you'll know what Numpy is and the Numpy operations. Table of Contents Create a 2D Numpy Array ... | # Import the libraries
import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
Consider the list a, the list contains three nested lists **each of equal size**. | # Create a list
a = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]
a | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
We can cast the list to a Numpy Array as follow | # Convert list to Numpy Array
# Every element is the same type
A = np.array(a)
A | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
We can use the attribute ndim to obtain the number of axes or dimensions referred to as the rank. | # Show the numpy array dimensions
A.ndim | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
Attribute shape returns a tuple corresponding to the size or number of each dimension. | # Show the numpy array shape
A.shape | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
The total number of elements in the array is given by the attribute size. | # Show the numpy array size
A.size | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
Accessing different elements of a Numpy Array We can use rectangular brackets to access the different elements of the array. The correspondence between the rectangular brackets and the list and the rectangular representation is shown in the following figure for a 3x3 array: We can access the 2nd-row 3rd column as s... | # Access the element on the second row and third column
A[1, 2] | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
We can also use the following notation to obtain the elements: | # Access the element on the second row and third column
A[1][2] | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
Consider the elements shown in the following figure We can access the element as follows | # Access the element on the first row and first column
A[0][0] | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
We can also use slicing in numpy arrays. Consider the following figure. We would like to obtain the first two columns in the first row This can be done with the following syntax | # Access the element on the first row and first and second columns
A[0][0:2] | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
Similarly, we can obtain the first two rows of the 3rd column as follows: | # Access the element on the first and second rows and third column
A[0:2, 2] | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
Corresponding to the following figure: Basic Operations We can also add arrays. The process is identical to matrix addition. Matrix addition of X and Y is shown in the following figure: The numpy array is given by X and Y | # Create a numpy array X
X = np.array([[1, 0], [0, 1]])
X
# Create a numpy array Y
Y = np.array([[2, 1], [1, 2]])
Y | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
We can add the numpy arrays as follows. | # Add X and Y
Z = X + Y
Z | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
Multiplying a numpy array by a scaler is identical to multiplying a matrix by a scaler. If we multiply the matrix Y by the scaler 2, we simply multiply every element in the matrix by 2 as shown in the figure. We can perform the same operation in numpy as follows | # Create a numpy array Y
Y = np.array([[2, 1], [1, 2]])
Y
# Multiply Y with 2
Z = 2 * Y
Z | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
Multiplication of two arrays corresponds to an element-wise product or Hadamard product. Consider matrix X and Y. The Hadamard product corresponds to multiplying each of the elements in the same position, i.e. multiplying elements contained in the same color boxes together. The result is a new matrix that is the same s... | # Create a numpy array Y
Y = np.array([[2, 1], [1, 2]])
Y
# Create a numpy array X
X = np.array([[1, 0], [0, 1]])
X
# Multiply X with Y
Z = X * Y
Z | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
We can also perform matrix multiplication with the numpy arrays A and B as follows: First, we define matrix A and B: | # Create a matrix A
A = np.array([[0, 1, 1], [1, 0, 1]])
A
# Create a matrix B
B = np.array([[1, 1], [1, 1], [-1, 1]])
B | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
We use the numpy function dot to multiply the arrays together. | # Calculate the dot product
Z = np.dot(A,B)
Z
# Calculate the sine of Z
np.sin(Z) | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
We use the numpy attribute T to calculate the transposed matrix | # Create a matrix C
C = np.array([[1,1],[2,2],[3,3]])
C
# Get the transposed of C
C.T | _____no_output_____ | MIT | Data Science Professional/2 - Python For Data Science/5.2 Numpy2D.ipynb | 2series/DataScience-Courses |
Master Notebook: Bosques aleatorios Como ya vímos en scikit-learn gran parte de codigo es reciclable. Particularmente, leyendo variables y preparando los datos es lo mismo, independientemente del clasificador que usamos. Leyendo datos Para que no esta tan aburrido (también para mi) esta vez nos vamos a escribir una f... | import numpy as np
from collections import Counter
def lea_datos(archivo, i_clase=-1, encabezado=True, delim=","):
'''Una funcion para leer archivos con datos de clasificación.
Argumentos:
archivo - direccion del archivo
i_clase - indice de columna que contiene las clases.
d... | _____no_output_____ | MIT | rf_master.ipynb | MidoriR/Antimicrobial_compound_classifier |
Ahora importando datos se hace muy simple en el futuro. Para datos de csv con cabezazo por ejemplo: | datos, clases, encabezado = lea_datos("datos_peña.csv") # _ significa que no nos interesa este valor
clases.shape | Clases
b'1' : 9
b'0' : 14
| MIT | rf_master.ipynb | MidoriR/Antimicrobial_compound_classifier |
Balanceando datos Normalizacion de datos no es necesario para bosques aleatorios o arboles porque son invariantes al respeto de los magnitudes de variables. Lo unico que podría ser un problema es los clases son imbalanceados bajo nuestra percepción. Esto significa que a veces ni esperamos que nuestros datos van a ser ... | def balance(datos, clases, estrategia="down"):
'''Balancea unos datos así que cada clase aparece en las mismas proporciones.
Argumentos:
datos - los datos. Filas son muestras y columnas variables.
clases - las clases para cada muestra.
estrategia - "up" para up-scaling y "down" para down... | _____no_output_____ | MIT | rf_master.ipynb | MidoriR/Antimicrobial_compound_classifier |
Y vamos a ver si funciona... | datos_b, clases_b = balance(datos, clases)
print Counter(clases_b)
print datos_b.shape | _____no_output_____ | MIT | rf_master.ipynb | MidoriR/Antimicrobial_compound_classifier |
Entrenando el bosque Corriendo un bosque aleatorio para la clasificación es casi lo mismo como todos los otros clasificadores. Nada más importamos de una libreria diferente. | from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(oob_score=True)
clf.fit(datos_b, clases_b)
print "Exactitud estimado:", clf.oob_score_ | _____no_output_____ | MIT | rf_master.ipynb | MidoriR/Antimicrobial_compound_classifier |
Ya sabemos que los hiper-parametros mas importantes para los bosques son el numero de arboles dado por `n_estimators` y la profundidad del arbol dado por `max_depth`. Porque son monotonos los podemos variar por separado. | %matplotlib inline
from sklearn.cross_validation import StratifiedKFold
from sklearn.grid_search import GridSearchCV
import matplotlib.pyplot as plt
cv = StratifiedKFold(y=clases, n_folds=4)
arboles_vals = np.arange(5,200,5)
busqueda = GridSearchCV(clf, param_grid=dict(n_estimators=arboles_vals), cv=cv)
busqueda.fit(d... | _____no_output_____ | MIT | rf_master.ipynb | MidoriR/Antimicrobial_compound_classifier |
Y para la profundidad: | prof_vals = np.arange(1,12)
busqueda = GridSearchCV(clf, param_grid=dict(max_depth=prof_vals), cv=cv)
busqueda.fit(datos, clases)
print 'Mejor profundidad=',busqueda.best_params_,',exactitud =',busqueda.best_score_
scores = [x[1] for x in busqueda.grid_scores_]
plt.plot(prof_vals, scores)
plt.xlabel('profundidad maxi... | _____no_output_____ | MIT | rf_master.ipynb | MidoriR/Antimicrobial_compound_classifier |
Viendo unas buenas valores podemos escoger un bosque con la menor numero de arboles y profundidad para una buena exactitud. También esta vez vamos a sacar las importancias de variables de una vez. | clf = RandomForestClassifier(n_estimators=101, oob_score=True)
clf.fit(datos, clases)
print "Exactitud estimada:", clf.oob_score_
print cabeza
print clf.feature_importances_ | _____no_output_____ | MIT | rf_master.ipynb | MidoriR/Antimicrobial_compound_classifier |
Predecir nuevas variables | datos_test, clases_test, _ = lea_datos("titanic_test.csv")
clases_pred = clf.predict(datos_test)
print "Predicho:", clases_pred
print "Verdad: ", clases_test | _____no_output_____ | MIT | rf_master.ipynb | MidoriR/Antimicrobial_compound_classifier |
Initialize estimator class | from __future__ import annotations
from typing import NoReturn
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import RocCurveDisplay, accuracy_score
from IMLearn.base import BaseEstimator
import re
from copy import copy
from datetime import datetime
f... | _____no_output_____ | MIT | challenge/data_challenge_1.ipynb | rasegiIML/IML.HUJI |
Helper Functions | def read_data_file(path: str) -> pd.DataFrame:
return pd.read_csv(path).drop_duplicates() \
.astype({'checkout_date': 'datetime64',
'checkin_date': 'datetime64',
'hotel_live_date': 'datetime64',
'booking_datetime': 'datetime64'})
def get_days_between_date... | _____no_output_____ | MIT | challenge/data_challenge_1.ipynb | rasegiIML/IML.HUJI |
Define pipeline | def create_pipeline_from_data(filename: str):
NONE_OUTPUT_COLUMNS = ['checkin_date',
'checkout_date',
'booking_datetime',
'hotel_live_date',
'hotel_country_code',
'origin_country_co... | _____no_output_____ | MIT | challenge/data_challenge_1.ipynb | rasegiIML/IML.HUJI |
Train, predict and export | def evaluate_and_export(estimator: BaseEstimator, X: pd.DataFrame, filename: str):
preds = (~estimator.predict(X)).astype(int)
pd.DataFrame(preds, columns=["predicted_values"]).to_csv(filename, index=False)
def create_estimator_from_data(path="../datasets/agoda_cancellation_train.csv", threshold: float = 0.47... | C:\conda\envs\iml.env\lib\site-packages\ipykernel_launcher.py:117: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.h... | MIT | challenge/data_challenge_1.ipynb | rasegiIML/IML.HUJI |
Machine learning to predict age from rs-fmriThe goal is to extract data from several rs-fmri images, and use that data as features in a machine learning model. We will integrate what we've learned in the previous machine learning lecture to build an unbiased model and test it on a left out sample.We're going to use a ... | # change this to the location where you downloaded the data
wdir = '/data/ml_tutorial/'
# Now fetch the data
from glob import glob
import os
data = sorted(glob(os.path.join(wdir,'*.gz')))
confounds = sorted(glob(os.path.join(wdir,'*regressors.tsv'))) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
How many individual subjects do we have? | #len(data.func)
len(data) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Extract features In order to do our machine learning, we will need to extract feature from our rs-fmri images.Specifically, we will extract signals from a brain parcellation and compute a correlation matrix, representing regional coac... | from nilearn import datasets
parcellations = datasets.fetch_atlas_basc_multiscale_2015(version='sym')
atlas_filename = parcellations.scale064
print('Atlas ROIs are located in nifti image (4D) at: %s' %
atlas_filename) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Let's have a look at that atlas | from nilearn import plotting
plotting.plot_roi(atlas_filename, draw_cross=False) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Great, let's load an example 4D fmri time-series for one subject | fmri_filenames = data[0]
print(fmri_filenames) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Let's have a look at the image! Because it is a 4D image, we can only look at one slice at a time. Or, better yet, let's look at an average image! | from nilearn import image
averaged_Img = image.mean_img(image.mean_img(fmri_filenames))
plotting.plot_stat_map(averaged_Img) | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Extract signals on a parcellation defined by labelsUsing the NiftiLabelsMaskerSo we've loaded our atlas and 4D data for a single subject. Let's practice extracting features! | from nilearn.input_data import NiftiLabelsMasker
masker = NiftiLabelsMasker(labels_img=atlas_filename, standardize=True,
memory='nilearn_cache', verbose=1)
# Here we go from nifti files to the signal time series in a numpy
# array. Note how we give confounds to be regressed out during sign... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
So what did we just create here? | type(time_series)
time_series.shape | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
What are these "confounds" and how are they used? | import pandas
conf_df = pandas.read_table(conf)
conf_df.head()
conf_df.shape | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Compute and display a correlation matrix | from nilearn.connectome import ConnectivityMeasure
correlation_measure = ConnectivityMeasure(kind='correlation')
correlation_matrix = correlation_measure.fit_transform([time_series])[0]
correlation_matrix.shape | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Plot the correlation matrix | import numpy as np
# Mask the main diagonal for visualization:
np.fill_diagonal(correlation_matrix, 0)
# The labels we have start with the background (0), hence we skip the
# first label
plotting.plot_matrix(correlation_matrix, figure=(10, 8),
labels=range(time_series.shape[-1]),
... | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Extract features from the whole datasetHere, we are going to use a for loop to iterate through each image and use the same techniques we learned above to extract rs-fmri connectivity features from every subject. | # Here is a really simple for loop
for i in range(10):
print('the number is', i)
container = []
for i in range(10):
container.append(i)
container | _____no_output_____ | BSD-3-Clause | notebooks/.ipynb_checkpoints/machine_learning_tutorial-checkpoint.ipynb | orchid00/nipype_arcana_workshop |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.