markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Podemos usar la funcion np.linspace para crear valores en un rango, por ejemplo si queremos 100 numeros entre 0 y 10 usamos: | x = np.linspace(0,10,100)
y = x**2 #cuadramos x
plt.plot(x,y)
plt.title("Grafica sencilla")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Y podemos graficar dos cosas al mismo tiempo: | x = np.linspace(0,10,100)
y1 = x # una linea
y2 = x**2 # cuadramos x
plt.plot(x,y1)
plt.plot(x,y2)
plt.title("Dos graficas sencillas")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Que tal si queremos distinguir cada linea? Pues usamos legend(), de leyenda..tambien tenemos que agregarles nombres a cada plot | x = np.linspace(0,10,100)
y1 = x # una linea
y2 = x**2 # cuadramos x
plt.plot(x,y1,label="Linea")
plt.plot(x,y2,label="Cuadrado")
plt.legend()
plt.title("Dos graficas sencillas")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Tambien podemos hacer mas cosas, como dibujar solamente los puntos, o las lineas con los puntos usando linestyle: | x = np.linspace(0,10,100)
y1 = x # una linea
y2 = x**2 # cuadramos x
y3 = np.sqrt(x) # sacamos raiz cuadrada a x
y4 = np.power(x,1.5) # elevamos x a la potencia 1.5
plt.plot(x,y1,label="Linea",linestyle='-') # linea
plt.plot(x,y2,label="Cuadrado",linestyle=':') # puntitos
plt.plot(x,y3,label="Raiz",linestyle='-.') # l... | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Dibujando puntos (scatter)
Aveces no queremos dibujar lineas, sino puntos, esto nos da informacion de donde se encuentras datos de manera espacial. Para esto podemos usarlo de la siguiente manera: | N = 50 # numero de puntos
x = np.random.rand(N) # numeros aleatorios entre 0 y 1
y = np.random.rand(N)
plt.scatter(x, y)
plt.title("Scatter de puntos aleatorios")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Pero ademas podemos meter mas informacion, por ejemplo dar colores cada punto, o darle tamanos diferentes: | N = 50 # numero de puntos
x = np.random.rand(N) # numeros aleatorios entre 0 y 1
y = np.random.rand(N)
colores = np.random.rand(N) # colores aleatorios
radios= 15 * np.random.rand(N) # numeros aleatorios entre 0 y 15
areas = np.pi * radios**2 # la formula de area de un circulo
plt.scatter(x, y, s=areas, c=colores, alph... | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Histogramas (hist)
Los histogramas nos muestran distribuciones de datos, la forma de los datos, nos muestran el numero de datos de diferentes tipos: | N=500
x = np.random.rand(N) # numeros aleatorios entre 0 y 1
plt.hist(x)
plt.title("Histograma aleatorio")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
otro tipo de datos, tomados de una campana de gauss, es decir una distribucion normal: | N=500
x = np.random.randn(N)
plt.hist(x)
plt.title("Histograma aleatorio Normal")
plt.show()
N=1000
x1 = np.random.randn(N)
x2 = 2+2*np.random.randn(N)
plt.hist(x1,20,alpha=0.3)
plt.hist(x2,20,alpha=0.3)
plt.title("Histograma de dos distribuciones")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Bases de datos en el internet
Aveces los datos que queremos se encuentran en el internet. Asumiendo que se encuentran ordenados y en un formato amigable siempre los podemos bajar y guardar como un DataFrame.
Por ejemplo:
Gapminder es una pagina con mas de 500 conjunto de daatos relacionado a indicadores globales como i... | xurl="http://spreadsheets.google.com/pub?key=phAwcNAVuyj2tPLxKvvnNPA&output=xls"
df=pd.read_excel(xurl)
print("Tamano completo es %s"%str(df.shape))
df.head() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Arreglando los Datos
Head nos permite darle un vistazo a los datos... asi a puro ojo vemos que las columnas son anios y los renglones los paises...ponder reversar esto con transpose, pero tambien vemos que esta con indices enumerados, prefeririamos que los indices fueran los paises, entonces los cambiamos y tiramos la ... | df = df.rename(columns={'Life expectancy with projections. Yellow is IHME': 'Life expectancy'})
df.index=df['Life expectancy']
df=df.drop('Life expectancy',axis=1)
df=df.transpose()
df.head() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Entonces ahora podemos ver la calidad de vida en Mexico atravez del tiempo: | df['Mexico'].plot()
print("== Esperanza de Vida en Mexico ==") | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
de esta visualizacion vemos que la caldiad ha ido subiendo apartir de 1900, ademas vemos mucho movimiento entre 1890 y 1950, justo cuando habia muchas guerras en Mexico.
Tambien podemos seleccionar un rango selecto de años, vemos que este rango es interesante entonces | subdf=df[ df.index >= 1890 ]
subdf=subdf[ subdf.index <= 1955 ]
subdf['Mexico'].plot()
plt.title("Esperanza de Vida en Mexico entre 1890 y 1955")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
o sin tanto rollo, podemos restringuir el rango de nuestra grafica con xlim (los limites del eje X) | df['Mexico'].plot()
plt.xlim(1890,1955)
plt.title("Esperanza de Vida en Mexico entre 1890 y 1955")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
Tambien es importante ver como esto se compara con otros paises, podemos comparar con todo Norteamerica: | df[['Mexico','United States','Canada']].plot()
plt.title("Esperanza de Vida en Norte-America")
plt.show() | Dia1/.ipynb_checkpoints/Intro a Matplotlib-checkpoint.ipynb | beangoben/HistoriaDatos_Higgs | gpl-2.0 |
<a href="https://colab.research.google.com/github/google-research/big_transfer/blob/master/colabs/big_transfer_jax.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
BigTransfer (BiT): A step-by-step tutorial for state-of-the-art vision
This colab demon... | !pip install flax
import io
import re
from functools import partial
import numpy as np
import matplotlib.pyplot as plt
import jax
import jax.numpy as jnp
import flax
import flax.nn as nn
import flax.optim as optim
import flax.jax_utils as flax_utils
# Assert that GPU is available
assert 'Gpu' in str(jax.devices(... | colabs/big_transfer_jax.ipynb | google-research/big_transfer | apache-2.0 |
Architecture and function for transforming BiT weights to JAX to format | def fixed_padding(x, kernel_size):
pad_total = kernel_size - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
x = jax.lax.pad(x, 0.0,
((0, 0, 0),
(pad_beg, pad_end, 0), (pad_beg, pad_end, 0),
(0, 0, 0)))
return x
def standardize(x, axis, eps):... | colabs/big_transfer_jax.ipynb | google-research/big_transfer | apache-2.0 |
Run BiT-M-ResNet50x1 already fine-tuned on CIFAR-10
Build model and load weights | with tf.io.gfile.GFile('gs://bit_models/BiT-M-R50x1-CIFAR10.npz', 'rb') as f:
params_tf = np.load(f)
params_tf = dict(zip(params_tf.keys(), params_tf.values()))
for k in params_tf:
params_tf[k] = jnp.array(params_tf[k])
ResNet_cifar10 = ResNet.partial(num_classes=10)
def resnet_fn(params, images):
return ResNe... | colabs/big_transfer_jax.ipynb | google-research/big_transfer | apache-2.0 |
Prepare data | data_builder = tfds.builder('cifar10')
data_builder.download_and_prepare()
def _pp(data):
im = data['image']
im = tf.image.resize(im, [128, 128])
im = (im - 127.5) / 127.5
data['image'] = im
return {'image': data['image'], 'label': data['label']}
data = data_builder.as_dataset(split='test')
data = data.map(... | colabs/big_transfer_jax.ipynb | google-research/big_transfer | apache-2.0 |
Run BiT | correct, n = 0, 0
for batch in data_iter:
preds = resnet_fn(params, batch['image'])
correct += np.sum(np.argmax(preds, axis=1) == batch['label'])
n += len(preds)
print(f"CIFAR-10 accuracy of BiT-M-R50x1: {correct / n:0.3%}") | colabs/big_transfer_jax.ipynb | google-research/big_transfer | apache-2.0 |
Run finetuning on CIFAR-100
Prepare data | data_builder = tfds.builder('cifar100')
data_builder.download_and_prepare()
def get_data(split, repeats, batch_size, images_per_class, shuffle_buffer):
data = data_builder.as_dataset(split=split)
if split == 'train':
data = data.batch(50000)
data = data.as_numpy_iterator().next()
np.random.seed(0)
... | colabs/big_transfer_jax.ipynb | google-research/big_transfer | apache-2.0 |
Build model and load weights | @jax.jit
def resnet_fn(params, images):
return ResNet.partial(num_classes=100).call(params, images)
def cross_entropy_loss(*, logits, labels):
logp = jax.nn.log_softmax(logits)
return -jnp.mean(jnp.sum(logp * labels, axis=1))
def loss_fn(params, images, labels):
logits = resnet_fn(params, images)
return cro... | colabs/big_transfer_jax.ipynb | google-research/big_transfer | apache-2.0 |
Run optimization | def get_lr(step):
lr = 0.003
if step < 100:
return lr * (step / 100)
else:
for s in [200, 300, 400]:
if s < step:
lr /= 10
return lr
opt = optim.Momentum(beta=0.9).create(params)
for step, batch in zip(range(500), data_train.as_numpy_iterator()):
opt, loss_value = update_fn(
... | colabs/big_transfer_jax.ipynb | google-research/big_transfer | apache-2.0 |
initialize the Cosmological models | #CCL cosmology
cosmo_ccl = ccl.Cosmology(Omega_c = 0.30711 - 0.048254, Omega_b = 0.048254, h = 0.677, sigma8 = 0.8822714165197718, n_s=0.96, Omega_k = 0, transfer_function='eisenstein_hu')
#ccl_cosmo_set_high_prec (cosmo_ccl)
cosmo_numcosmo, dist, ps_lin, ps_nln, hmfunc = create_nc_obj (cosmo_ccl)
psf = hmfunc.peek_p... | notebooks/DataNCount/run_ascaso_mcmc_binned.ipynb | NumCosmo/NumCosmo | gpl-3.0 |
Define proxy modelling
Use a mass proxy, define the probability for observing a proxy given a mass and redhsift
$$
P(\log\lambda|M,z) = N(\mu(M,z), \sigma^2(M,z))
$$
the mean is
$$
\mu(M,z) = \mu_0 + a_\mu^M\log_{10}\frac{M}{M_0} + a_\mu^z\log_{10}\frac{1+z}{1+z_0}
$$
variance is
$$
\sigma(M,z) = \sigma_0 + a_\sigma^M... | #CosmoSim_proxy model
#M_0, z_0
theta_pivot = [3e14/0.71, 0.6]
#\mu_0, a_\mu^z, a_\mu^M
theta_mu = [3.19, -0.7, 2]
#\sigma_0, a_\sigma^z, a_\sigma^M
theta_sigma = [0.33, 0.,-0.08]
#Richness object
area = (0.25)*4*np.pi / 100.0
lnRl = 1.0
lnRu = 2.0
zl = 0.25
zu = 1.0
#Numcosmo_proxy model
cluster_z = nc.ClusterRedshi... | notebooks/DataNCount/run_ascaso_mcmc_binned.ipynb | NumCosmo/NumCosmo | gpl-3.0 |
initialize the ClusterAbundance object | #Numcosmo Cluster Abundance
#First we need to define the multiplicity function here we will use the tinker
mulf = nc.MultiplicityFuncTinker.new()
mulf.set_linear_interp (True)
mulf.set_mdef(nc.MultiplicityFuncMassDef.CRITICAL)
mulf.set_Delta(200)
#Second we need to construct a filtered power spectrum
hmf = nc.HaloMa... | notebooks/DataNCount/run_ascaso_mcmc_binned.ipynb | NumCosmo/NumCosmo | gpl-3.0 |
Reading the Data
The necessary files can be downloaded from the Data page. The first file that you'll need is unlabeledTrainData.tsv, which contains 25,000 IMDB movie reviews, each with a positive or negative sentiment label.
Next, read the tab-delimited file into Python. To do this, we can use the pandas package, intr... | train = pd.read_csv("labeledTrainData.tsv", header=0, delimiter="\t", quoting=3)
train.shape # Get the shape, 25000 rows and 3 columns
train.columns.values # Show the column names
print(train["review"][0]) # Looking at some review | word-vector/.ipynb_checkpoints/Word Vector-checkpoint.ipynb | noppanit/machine-learning | mit |
Data Cleaning and Text Preprocessing
Removing HTML Markup: The BeautifulSoup Package
First, we'll remove the HTML tags. For this purpose, we'll use the Beautiful Soup library. If you don't have Beautiful soup installed, do: | # Initialize the BeautifulSoup object on a single movie review
example1 = BeautifulSoup(train["review"][0], 'html.parser')
print(example1.get_text()) | word-vector/.ipynb_checkpoints/Word Vector-checkpoint.ipynb | noppanit/machine-learning | mit |
Dealing with Punctuation, Numbers and Stopwords: NLTK and regular expressions
When considering how to clean the text, we should think about the data problem we are trying to solve. For many problems, it makes sense to remove punctuation. On the other hand, in this case, we are tackling a sentiment analysis problem, and... | import re
# Use regular expressions to do a find-and-replace
# Basically we get rid of all the word that doesn't begin with a-Z or A-Z
letters_only = re.sub("[^a-zA-Z]", # The pattern to search for
" ", # The pattern to replace it with
example1.get... | word-vector/.ipynb_checkpoints/Word Vector-checkpoint.ipynb | noppanit/machine-learning | mit |
Finally, we need to decide how to deal with frequently occurring words that don't carry much meaning. Such words are called "stop words"; in English they include words such as "a", "and", "is", and "the". Conveniently, there are Python packages that come with stop word lists built in. Let's import a stop word list from... | from nltk.corpus import stopwords # Import the stop word list
# Remove stop words from "words"
words = [w for w in words if not w in stopwords.words("english")]
print(words)
def review_to_words( raw_review ):
# Function to convert a raw review to a string of words
# The input is a single string (a raw movie r... | word-vector/.ipynb_checkpoints/Word Vector-checkpoint.ipynb | noppanit/machine-learning | mit |
Let's clean all the data | print("Cleaning and parsing the training set movie reviews...\n")
clean_train_reviews = []
for i in range( 0, num_reviews ):
# If the index is evenly divisible by 1000, print a message
if( (i+1)%1000 == 0 ):
print("Review %d of %d\n" % ( i+1, num_reviews )) ... | word-vector/.ipynb_checkpoints/Word Vector-checkpoint.ipynb | noppanit/machine-learning | mit |
Creating Features from a Bag of Words (Using scikit-learn)
Now that we have our training reviews tidied up, how do we convert them to some kind of numeric representation for machine learning? One common approach is called a Bag of Words. The Bag of Words model learns a vocabulary from all of the documents, then models ... | print("Creating the bag of words...\n")
from sklearn.feature_extraction.text import CountVectorizer
# Initialize the "CountVectorizer" object, which is scikit-learn's
# bag of words tool.
vectorizer = CountVectorizer(analyzer = "word", \
tokenizer = None, \
... | word-vector/.ipynb_checkpoints/Word Vector-checkpoint.ipynb | noppanit/machine-learning | mit |
It has 25,000 rows and 5,000 features (one for each vocabulary word).
Note that CountVectorizer comes with its own options to automatically do preprocessing, tokenization, and stop word removal -- for each of these, instead of specifying "None", we could have used a built-in method or specified our own function to use.... | vocab = vectorizer.get_feature_names()
print(vocab)
# Sum up the counts of each vocabulary word
dist = np.sum(train_data_features, axis=0)
# For each, print the vocabulary word and the number of times it
# appears in the training set
for tag, count in zip(vocab, dist):
print(count, tag) | word-vector/.ipynb_checkpoints/Word Vector-checkpoint.ipynb | noppanit/machine-learning | mit |
Random Forest
At this point, we have numeric training features from the Bag of Words and the original sentiment labels for each feature vector, so let's do some supervised learning! Here, we'll use the Random Forest classifier that we introduced in the Titanic tutorial. The Random Forest algorithm is included in sciki... | print("Training the random forest...")
from sklearn.ensemble import RandomForestClassifier
# Initialize a Random Forest classifier with 100 trees
forest = RandomForestClassifier(n_estimators = 100)
# Fit the forest to the training set, using the bag of words as
# features and the sentiment labels as the response va... | word-vector/.ipynb_checkpoints/Word Vector-checkpoint.ipynb | noppanit/machine-learning | mit |
Creating a Submission
All that remains is to run the trained Random Forest on our test set and create a submission file. If you haven't already done so, download testData.tsv from the Data page. This file contains another 25,000 reviews and ids; our task is to predict the sentiment label.
Note that when we use the Bag ... | # Read the test data
test = pd.read_csv("testData.tsv", header=0, delimiter="\t", quoting=3 )
# Verify that there are 25,000 rows and 2 columns
print(test.shape)
# Create an empty list and append the clean reviews one by one
num_reviews = len(test["review"])
clean_test_reviews = []
print "Cleaning and parsing the t... | word-vector/.ipynb_checkpoints/Word Vector-checkpoint.ipynb | noppanit/machine-learning | mit |
The iris feature values are real valued -- measurements in centimeters. Let's look at histograms of each feature. | # Create a new figure and set the figsize argument so we get square-ish plots of the 4 features.
plt.figure(figsize=(15, 3))
# Iterate over the features, creating a subplot with a histogram for each one.
for feature in range(train_data.shape[1]):
plt.subplot(1, 4, feature+1)
plt.hist(train_data[:,feature], 20)... | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
To make things simple, let's binarize these feature values. That is, we'll treat each measurement as either "short" or "long". I'm just going to choose a threshold for each feature. Binning usually depends on the distribution. There are two ways to bin data: constant bin width and constant bin size. For now let's jus... | # Create a new figure and set the figsize argument so we get square-ish plots of the 4 features.
plt.figure(figsize=(15, 3))
# Iterate over the features, creating a subplot with a histogram for each one.
for feature in range(train_data.shape[1]):
plt.subplot(1, 4, feature+1)
plt.hist(train_data[:,feature], 2)
... | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
Recall that Naive Bayes assumes conditional independence of features. With $Y$ the set of labels and $X$ the set of features ($y$ is a specific label and $x$ is a specific feature), Naive Bayes gives the probability of a label $y$ given input features $X$ as:
$ \displaystyle P(y|X) \approx
\frac { P(y) \prod_{x \in ... | # Initialize counters for all labels to zero.
label_counts = [0 for i in iris.target_names]
''' print label_counts '''
print iris.target_names
# Calculate the counts of labels in the training data set by iterating over labels.
for label in train_labels:
label_counts[label] += 1
print label_counts
# Normalize co... | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
Example of what zip() function does (from https://docs.python.org/2/library/functions.html#zip): | x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
zipped | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
Now, we have estimated the prior probabilities of each label, $P(y)$
Next, let's estimate $P(X|Y)$, that is, the probability of each feature given each label: if I am a flower labeled $y (e.g., setosa)$, what is the probability that my measurements (features) will be $x$?
Remember that we can get the conditional prob... | # Initialize a matrix for joint counts of feature=0 and label.
feature0_and_label_counts = np.zeros([len(iris.feature_names), len(iris.target_names)])
'''print feature0_and_label_counts'''
# Just to check our work, let's also keep track of joint counts of feature=1 and label.
feature1_and_label_counts = np.zeros([len(... | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
We still need to normalize the joint counts to get probabilities: P(feature|label) = P(feature, label) / P(label) | # Initialize new matrices to hold conditional probabilities.
feature0_given_label = np.zeros(feature0_and_label_counts.shape)
feature1_given_label = np.zeros(feature1_and_label_counts.shape)
# P(feature|label) = P(feature, label) / P(label) =~ count(feature, label) / count(label).
# Note that we could do this normaliz... | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
Now that we have all the pieces, let's try making a prediction for the first test example. It looks like this is a setosa (label 0) example with all small measurements -- all the feature values are 0.
We start by assuming the prior distribution , which has a slight preference for virginica, followed by versicolor. Of c... | # What does the feature vector look like? And what's the true label?
index = 0
print 'Feature vector:', binarized_test_data[index]
print 'Label:', test_labels[index]
# Start with the prior distribution over labels.
predictions = label_probs[:]
print 'Prior:', predictions | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
You can think of each feature as an additional piece of evidence. After observing the first feature, we update our belief by multiplying our initial probabilities by the probability of the observation, conditional on each possible label. | # Let's include the first feature. We use feature0_given_label since the feature value is 0.
predictions *= feature0_given_label[0]
# We could wait until we've multiplied by all the feature probabilities, but there's no harm in normalizing after each update.
predictions /= predictions.sum()
print 'After observing sepa... | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
So after observing a short sepal, our updated belief prefers setosa. Let's include the remaining observations. | # Include the second feature.
predictions *= feature0_given_label[1]
predictions *= feature0_given_label[2]
predictions *= feature0_given_label[3]
# print feature0_given_label
# print feature1_given_label
# We could wait until we've multiplied by all the feature probabilities, but there's no harm in normalizing after ... | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
What happened?
Well, it looks like Naive Bayes came up with the right answer. But it seems overconfident!
Let's look again at our conditional probability estimates for the features, feature0_given_label and feature1_given_label. Notice that there are a bunch of zero probabilities. This is bad because as soon as we mult... | class NaiveBayes:
# Initialize an instance of the class.
def __init__(self, alpha=1.0):
self.alpha = alpha # additive (Laplace) smoothing parameter
self.priors = None # estimated by fit()
self.probs = None # estimated by fit()
self.num_labels = 0 # set by fit()
... | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
The NumPy method argmax called with axis=None (default) returns the indices of the array being passed where the value reaches its maximum. For more details, see here: http://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html
Now we can compare our implementation with the sklearn implementation. Do the pred... | alpha = 0
nb = NaiveBayes(alpha=alpha)
nb.fit(binarized_train_data, train_labels)
print "Trained the model on binarized_train_data"
# Compute accuracy on the test data.
print "Using our NB classifier"
preds = nb.predict(binarized_test_data)
correct, total = 0, 0
for pred, label in zip(preds, test_labels):
if pred ... | reference/Naive_Bayes_partially_modified.ipynb | jbocharov-mids/W207-Machine-Learning | apache-2.0 |
We first specify the properties of the two reservoirs, and plot their power spectra. | #parameters and spectra check
options = Options(nsteps=15000, store_states=True, rtol=1e-14, atol=1e-14)
Gamma = 0.01
W = 10**4 #Wide-band limit
T = 0.025851991 #in ev
beta = 1./T
theta = 2.
mu_l = theta/2.
mu_r = -theta/2.
w_list = np.linspace(-2,2,100)
def Gamma_L_w(w):
return Gamma*W**2/((w-mu_l)**2 + W**2)... | examples/heom/heom-5b-fermions-discrete-boson-model.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
Below we give one example data set from Paper
Here we just give one example of the current as a function of bias voltage, but in general one can try different cut-offs of the bosonic Fock space and the expansion of the correlation functions until convergence is found.
One note: for very large problems, this can be slo... | def get_curr(theta,Nk,Ncc,Nbos):
print("------------- theta:",theta)
mu_l = theta/2.
mu_r = -theta/2.
d1 = tensor(destroy(2), qeye(Nbos))
a = tensor(qeye(2), destroy(Nbos))
e1 = 0.3 #d1 = spin up
Omega = 0.2
Lambda = 0.12
H0 = e1*d1.dag() * d1 + Omega * a.dag()*a + Lambda * (a+a.... | examples/heom/heom-5b-fermions-discrete-boson-model.ipynb | qutip/qutip-notebooks | lgpl-3.0 |
We processed some raw data files of the AirBase air quality data. The data contains hourly concentrations of nitrogen dioxide (NO2) for 4 different measurement stations:
FR04037 (PARIS 13eme): urban background site at Square de Choisy
FR04012 (Paris, Place Victor Basch): urban traffic site at Rue d'Alesia
BETR802: urb... | alldata = pd.read_csv('data/airbase_data.csv', index_col=0, parse_dates=True) | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
We only use the data from 1999 onwards: | data = alldata['1999':].copy() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Some first exploration with the typical functions: | data.head() # tail()
data.info()
data.describe(percentiles=[0.1, 0.5, 0.9])
data.plot(figsize=(12,6)) | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-warning">
**ATTENTION!**:
When just using `.plot()` without further notice (selection, aggregation,...)
* Risk of running into troubles by overloading your computer processing (certainly with looooong time series).
* Not always the most informative/interpretable visualisation.
</div>
Plot o... | data.tail(500).plot(figsize=(12,6)) | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Summary figures
Use summary statistics... | data.plot(kind='box', ylim=[0,250]) | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Also with seaborn plots function, just start with some subsets as first impression...
As we already have seen previously, the plotting library seaborn provides some high-level plotting functions on top of matplotlib (check the docs!). One of those functions is pairplot, which we can use here to quickly visualize the co... | import seaborn as sns
sns.pairplot(data.tail(5000).dropna()) | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Is this a tidy dataset ? | data.head() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
In principle this is not a tidy dataset. The variable that was measured is the NO2 concentration, and is divided in 4 columns. Of course those measurements were made at different stations, so one could interpret it as separate variables. But in any case, such format does not always work well with libraries like seaborn... | data_tidy = data.reset_index().melt(id_vars=["datetime"], var_name='station', value_name='no2')
data_tidy.head()
data_tidy['no2'].isna().sum()
data_tidy = data_tidy.dropna() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
In the following exercises we will mostly do our analysis on dataand often use pandas plotting, but once we produced some kind of summary dataframe as the result of an analysis, then it becomes more interesting to convert that result to a tidy format to be able to use the more advanced plotting functionality of seaborn... | fig, ax = plt.subplots()
data.loc['2009':, 'FR04037'].resample('M').mean().plot(ax=ax, label='mean')
data.loc['2009':, 'FR04037'].resample('M').median().plot(ax=ax, label='median')
ax.legend(ncol=2)
ax.set_title("FR04037");
data.loc['2009':, 'FR04037'].resample('M').agg(['mean', 'median']).plot() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
<b>EXERCISE</b>
<ul>
<li>Make a violin plot for January 2011 until August 2011 (check out the documentation to improve the plotting settings)</li>
<li>Change the y-label to 'NO$_2$ concentration (µg/m³)'</li>
</ul><br>
_NOTE:_ In this case, we can use seaborn both with the data... | # with wide dataframe
fig, ax = plt.subplots()
sns.violinplot(data=data['2011-01': '2011-08'], palette="GnBu_d", ax=ax)
ax.set_ylabel("NO$_2$ concentration (µg/m³)")
# with tidy dataframe
data_tidy_subset = data_tidy[(data_tidy['datetime'] >= "2011-01") & (data_tidy['datetime'] < "2011-09")]
fig, ax = plt.subplots()
... | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
<b>EXERCISE</b>
<ul>
<li>Make a bar plot with pandas of the mean of each of the stations in the year 2012 (check the documentation of Pandas plot to adapt the rotation of the labels) and make sure all bars have the same color.</li>
<li>Using the matplotlib objects, change the y-... | fig, ax = plt.subplots()
data['2012':].mean().plot(kind='bar', ax=ax, rot=0, color='C0')
ax.set_ylabel("NO$_2$ concentration (µg/m³)")
ax.axhline(y=40., color='darkorange')
ax.text(0.01, 0.48, 'Yearly limit is 40 µg/m³',
horizontalalignment='left', fontsize=13,
transform=ax.transAxes, color='darkorange... | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
<b>EXERCISE:</b> Did the air quality improve over time?
<ul>
<li>For the data from 1999 till the end, plot the yearly averages</li>
<li>For the same period, add the overall mean (all stations together) as an additional line to the graph, use a thicker black line (<code>linewidth... | fig, ax = plt.subplots()
data['1999':].resample('A').mean().plot(ax=ax)
data['1999':].mean(axis=1).resample('A').mean().plot(color='k',
linestyle='--',
linewidth=4,
ax=ax,
... | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-info">
**REMEMBER**:
`resample` is a special version of a`groupby` operation. For example, taking annual means with `data.resample('A').mean()` is equivalent to `data.groupby(data.index.year).mean()` (but the result of `resample` still has a DatetimeIndex).
Checking the index of the resulting... | # add a column to the dataframe that indicates the month (integer value of 1 to 12):
data['month'] = data.index.month
# now, we can calculate the mean of each month over the different years:
data.groupby('month').mean()
# plot the typical monthly profile of the different stations:
data.groupby('month').mean().plot() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Remove the temporary 'month' column generated in the solution of the previous exercise: | data = data.drop("month", axis=1, errors="ignore") | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Note: Technically, we could reshape the result of the groupby operation to a tidy format (we no longer have a real time series), but since we already have the things we want to plot as lines in different columns, doing .plot already does what we want.
<div class="alert alert-success">
<b>EXERCISE</b>
<ul>
<li>Plot... | # Resample wise
df2011 = data.loc['2011']
df2011[['BETN029', 'BETR801']].resample('W').quantile(0.95).plot()
# Groupby wise
# Note the different x-axis labels
df2011.groupby(df2011.index.isocalendar().week)[['BETN029', 'BETR801']].quantile(0.95).plot() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
<b>EXERCISE</b>
<ul>
<li>Plot the typical diurnal profile (typical hourly averages) for the different stations taking into account the whole time period.</li>
</ul>
</div> | data.groupby(data.index.hour).mean().plot() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
__EXERCISE__
What is the difference in the typical diurnal profile between week and weekend days? (and visualise it)
Start with only visualizing the different in diurnal profile for the 'BETR801' station. In a next step, make the same plot for each station.
<details><summary>Hints<... | data['weekend'] = data.index.dayofweek.isin([5, 6])
data['weekend'] = data['weekend'].replace({True: 'weekend', False: 'weekday'})
data['hour'] = data.index.hour
data_weekend = data.groupby(['weekend', 'hour']).mean()
data_weekend.head()
# using unstack and pandas plotting
data_weekend_BETR801 = data_weekend['BETR801... | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Remove the temporary columns 'hour' and 'weekend' used in the solution of previous exercise: | data = data.drop(['hour', 'weekend'], axis=1, errors="ignore") | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
__EXERCISE__
Calculate the correlation between the different stations (check in the documentation, google "pandas correlation" or use the magic function <code>%psearch</code>)
</div> | data[['BETR801', 'BETN029', 'FR04037', 'FR04012']].corr() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
__EXERCISE__
Count the number of exceedances of hourly values above the European limit 200 µg/m3 for each year and station after 2005. Make a barplot of the counts. Add an horizontal line indicating the maximum number of exceedances (which is 18) allowed per year?
**Hints:**
<detai... | exceedances = data > 200
# group by year and count exceedances (sum of boolean)
exceedances = exceedances.groupby(exceedances.index.year).sum()
# Make a barplot of the yearly number of exceedances
ax = exceedances.loc[2005:].plot(kind='bar')
ax.axhline(18, color='k', linestyle='--') | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
More advanced exercises... | data = alldata['1999':].copy() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
__EXERCISE__
Perform the following actions for the station `'FR04012'` only:
<ul>
<li>Remove the rows containing <code>NaN</code> or zero values</li>
<li>Sort the values of the rows according to the air quality values (low to high values)</li>
<li>Rescale the values to the r... | FR_station = data['FR04012'] # select the specific data series
FR_station = FR_station[(FR_station.notnull()) & (FR_station != 0.0)] # exclude the Nan and zero values
FR_sorted = FR_station.sort_values(ascending=True)
FR_scaled = (FR_sorted - FR_sorted.min())/(FR_sorted.max() - FR_sorted.min())
fig, axfr = plt.subpl... | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
<b>EXERCISE</b>:
<ul>
<li>Create a Figure with two subplots (axes), for which both ax<b>i</b>s are shared</li>
<li>In the left subplot, plot the histogram (30 bins) of station 'BETN029', only for the year 2009</li>
<li>In the right subplot, plot the histogram (30 bins) of stat... | # Mixing an matching matplotlib and Pandas
fig, (ax1, ax2) = plt.subplots(1, 2,
sharex=True,
sharey=True)
data.loc['2009', ['BETN029', 'BETR801']].plot(kind='hist', subplots=True,
bins=30, legend=False,
... | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
<b>EXERCISE</b>
<ul>
<li>Make a selection of the original dataset of the data in January 2009, call the resulting variable <code>subset</code></li>
<li>Add a new column, called 'dayofweek', to the variable <code>subset</code> which defines for each data point the day of the week... | subset = data.loc['2009-01'].copy()
subset["dayofweek"] = subset.index.dayofweek
subset = subset[subset['dayofweek'].isin([0, 6])]
subset["dayofweek"] = subset["dayofweek"].replace(to_replace={0:"Monday", 6:"Sunday"})
sns.set_style("whitegrid")
sns.lmplot(
data=subset, x="BETN029", y="FR04037", hue="dayofweek"
) | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
__EXERCISE__
The maximum daily, 8 hour mean, should be below 100 µg/m³. What is the number of exceedances of this limit for each year/station?
<details><summary>Hints</summary>
- Have a look at the `rolling` method to perform moving window operations.
</details>
<br>_Note:_
This ... | exceedances = data.rolling(8).mean().resample('D').max() > 100
exceedances = exceedances.groupby(exceedances.index.year).sum()
ax = exceedances.plot(kind='bar') | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
<div class="alert alert-success">
<b>EXERCISE</b>:
<ul>
<li>Visualize the typical week profile for station 'BETR801' as boxplots (where the values in one boxplot are the <i>daily means</i> for the different <i>weeks</i> for a certain day of the week).</li><br>
</ul>
**Tip:**<br>
The boxplot method of a DataFr... | data_daily = data.resample('D').mean()
# add a dayofweek column
data_daily['dayofweek'] = data_daily.index.dayofweek
data_daily.head() | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Plotting with seaborn: | # seaborn
sns.boxplot(data=data_daily, x='dayofweek', y='BETR801', color="grey") | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Reshaping and plotting with pandas: | # when using pandas to plot, the different boxplots should be different columns
# therefore, pivot table so that the weekdays are the different columns
data_daily['week'] = data_daily.index.isocalendar().week
data_pivoted = data_daily.pivot_table(columns='dayofweek', index='week',
... | _solved/case4_air_quality_analysis.ipynb | jorisvandenbossche/DS-python-data-analysis | bsd-3-clause |
Step 1: Simulate the flux distribution of the Wild-Type
FBA and PFBA can be used to compute flux distributions for the Wild-Type (model as it as been described) as well as knockouts (next session) | %time
fba_result = simulation.fba(model)
%time
pfba_result = simulation.pfba(model) | examples/Simulation Methods.ipynb | KristianJensen/cameo | apache-2.0 |
Setp 2: Simulate knockouts phenotypes
Although PFBA and FBA can be used to simulate the effect of knockouts, other methods have been proven more valuable for that task: MOMA and ROOM. In cameo we implement a linear version of MOMA.
Simulating knockouts:
Manipulate the bounds of the reaction (or use the shorthand meth... | model.reactions.PGI
model.reactions.PGI.knock_out()
model.reactions.PGI | examples/Simulation Methods.ipynb | KristianJensen/cameo | apache-2.0 |
Simulate using different methods: | %time
fba_knockout_result = simulation.fba(model)
fba_knockout_result[model.objective]
pfba_knockout_result = simulation.pfba(model)
pfba_knockout_result[model.objective] | examples/Simulation Methods.ipynb | KristianJensen/cameo | apache-2.0 |
MOMA and ROOM relly on a reference (wild-type) flux distribution and we can use the one previously computed.
Parsimonious FBA references seem to produce better results using this methods | lmoma_result["2 * EX_glc_lp_e_rp_"]
%time
lmoma_result = simulation.lmoma(model, reference=pfba_result.fluxes)
lmoma_result[model.objective]
%time
room_result = simulation.room(model, reference=pfba_result.fluxes)
room_result[model.objective]
room_result | examples/Simulation Methods.ipynb | KristianJensen/cameo | apache-2.0 |
El archivo tal como se descarga, a pesar de ser tabulados de excel, envia un mensaje de error cuando se intenta abrir directamente como se descargó. Por lo tanto, antes de procesarlo es necesario abrirlo en excel y guardarlo con formato .xlsx | path = r'D:\PCCS\00_RawData\01_CSV\LEED\leed_projects.xlsx'
raw_data = pd.read_excel(path)
raw_data.index.name = 'Building'
raw_data.head()
# Eliminar columnas que no pertenecen a Mexico
print('La tabla tiene {} registros'.format(len(raw_data)))
x = 'United States [us]'
raw_data = raw_data[raw_data['Country'] != x]
p... | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
La base de datos es un listado de edificios que incluye para cada edificio:
- El nombre del edificio
- Una URL de referencia
- La fecha de la certificacion del edificio
- La ciudad, estado y país en el que se ubica el edificio
- El sistema de calificación bajo el ecual se certificó el edificio
- La versión de la certi... | # Descarga el HTML de la pagina
page = requests.get('https://www.usgbc.org/projects/reforma-180')
tree = html.fromstring(page.content)
# Obten variables desde la estructura
street = tree.xpath('//span[@itemprop="streetAddress"]/text()')
locality = tree.xpath('//span[@itemprop="addressLocality"]/text()')
postalcode = t... | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Todos los datos son listas, pero "street" tiene 2 elementos. Entonces para el script lo que voy a hacer será eliminar todos los saltos de linea y concatenar el texto de todos los elementos de la lista | # Script para extraer datos de fichas a partir de la URL
def webcrawler(x):
time.sleep(0.05)
url = x
try:
page = requests.get(x)
tree = html.fromstring(page.content)
except: # Regresa false si no logras entrar a la URL
street = False
locality = False
pos... | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Reemplaza los enters en cada lista
(Voy a saltarme este paso porque lo que me interesa en realidad es el Codigo Postal, pero dejo el codigo por si lo ocupo en el futuro)
def listtotext(x):
templist = []
for element in x:
if element == None or element == False:
templist.append(element)
... | raw_data.head()
# Guarda una copia de raw_data por si es necesario ocupar este dataset de nuevo,
# que no se tenga que hacer nuevamente el webcrawiling porque consume mucho tiempo
writer = pd.ExcelWriter(archivoraw)
raw_data.to_excel(writer, sheet_name = 'DATOS')
writer.save()
# Crea una copia de trabajo de raw_data... | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
A partir de los Codigos Postales ya es posible identificar la ciudad y municipio a la que pertenece cada edificio. Para esto, vamos a utilizar la base de datos de codigos postales del SEPOMEX que se descargó en otra minería de datos: | bd_sepo = r'D:\PCCS\01_Dmine\Datasets\SEPOMEX\sepomex_CP_CVEMUN.xlsx'
SEPOMEX = pd.read_excel(bd_sepo, dtype={'CVE_MUN':'str', 'CP':'str'})
SEPOMEX.head(3) | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Con la base de datos del SEPOMEX ya es posible unir ambos datasets para obtener las claves municipales de cada edificio | datasetfinal.head()
# Copiar CVE_MUN del dataset en base al codigo postal
datasetfinal = datasetfinal.reset_index().merge(SEPOMEX, on='CP', how='left').set_index('Building')
datasetfinal.head() | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Quedan 70 filas en donde no fue posible identificar la clave Municipal | len(datasetfinal[datasetfinal['CVE_MUN'].isnull()]) | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Casos Particulares
Estos 70 registros tienen 33 claves unicas de C que requieren ser asignadas individualmente para conocer la CVE_MUN de cada edificio. Para esto, haremos un script que permita revisar cada clave para realizar la investigación necesaria y asignarle una CVE_MUN | mira = ['City', 'State', 'CP', 'address', 'CVE_MUN'] # El diccionario 'mira' se utilizará en adelante para imprimir subsets de la informacion
sinmun = datasetfinal[datasetfinal['CVE_MUN'].isnull()][mira]
sinmun.head()
len(sinmun['CP'].unique()) | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
En el siguiente diccionario recopila las CVE_MUN que se asignarán a los códigos postales que requieren asignacion individual. Los códigos cuyo valor es None se asignarán mas adelante | # Diccionario creado en donde key = 'CP' y value = 'CVE_MUN'
defmuns = {'00000': None,
'00100': '09010',
'00502': '15024',
'00604': '15121',
'00702': '15051',
'01006': '09010',
'01152': '09010',
'01209': '09004',
'01300': '09004',
'03130': '09014',
'03210': '09014',
'05300': '09004',
'05490': '15104',
'059... | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
El siguiente diccionario incluye códigos postales que requieren ser corregidos | # Diccionario en donde key = Codigo postal listado en el dataset; value = Codigo postal correcto
deberiaser = {'00100': '45620',
'00502': '54830',
'00604': '54713',
'00702': '52004',
'03130': '03103',
'11111': '45620',
'48219': '58218'} | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Asignacion de codigos postales | # Reemplazar las CVE_MUN identificadas en el dataset final
datasetfinal['CVE_MUN'] = datasetfinal['CP'].map(defmuns).fillna(datasetfinal['CVE_MUN']) | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Algunos edificios, marcados con los codigos postales 00000 y 12345 (Intuyo que por desidia del capturista) se tendrán que asignar individualmente | sinmun.loc[sinmun['CP'].isin(['00000', '12345'])]
# Diccionario con edificios que se asignaran individualmente
# Para este diccionario key = Nombre del edificio, value = CVE_MUN que se asignará a este edificio
buildings = {
'Grainger Mexico HQ': '19039',
'La Concha Pearl': '03003',
#'Schneider Electric at... | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
El dataset contiene dos edificios en el dataset que no corresponden a México: | sinmun[sinmun['CP'] == '87131'] | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Se eliminarán del dataset los siguientes edificios: | datasetfinal[datasetfinal['CVE_MUN'].isnull()][mira] | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
El primero por estar repetido y el resto por que no están en los Estados Unidos Mexicanos. | datasetfinal = datasetfinal.dropna(subset=['CVE_MUN'])
datasetfinal.head(3) | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Los edificios que requieren correccion de codigos postales son los siguientes: | datasetfinal[datasetfinal['CP'].isin(list(deberiaser.keys()))][mira]
# Corregir codigos postales erróneos
datasetfinal['CP'] = datasetfinal['CP'].map(deberiaser).fillna(datasetfinal['CP'])
datasetfinal[mira].head()
# Renombrar columnas para crear variables únicas
columns={
'address':'direccion',
'Path': 'URL'... | Datasets/LEED/LEED.ipynb | Caranarq/01_Dmine | gpl-3.0 |
Getting the data
Getting the data from stats.nba.com is pretty straightforward. While there isn't a a public API provided by the NBA,
we can actually access the API that the NBA uses for stats.nba.com using the requests library.
This blog post
by Greg Reda does a great job on explaining how to access this API (or fin... | playerID='2200'
shot_chart_url ='http://stats.nba.com/stats/shotchartdetail?CFID=33&CFPARAMS=2015-16&' \
'ContextFilter=&ContextMeasure=FGA&DateFrom=&DateTo=&GameID=&GameSegment=&LastNGames=0&' \
'LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PaceAdjust=N&' \
'PerMode=PerGame&Period=0&Player... | NBA_stats_visualization/Shot charts Notebook.ipynb | JuanIgnacioGil/basket-stats | mit |
The above url sends us to the JSON file contatining the data we want.
Also note that the url contains the various API parameters used to access the data.
The PlayerID parameter in the url is set to 201935, which is James Harden's PlayerID.
Now lets use requests to get the data we want | # Get the webpage containing the data
response = requests.get(shot_chart_url)
# Grab the headers to be used as column headers for our DataFrame
headers = response.json()['resultSets'][0]['headers']
# Grab the shot chart data
shots = response.json()['resultSets'][0]['rowSet'] | NBA_stats_visualization/Shot charts Notebook.ipynb | JuanIgnacioGil/basket-stats | mit |
Create a pandas DataFrame using the scraped shot chart data. | shot_df = pd.DataFrame(shots, columns=headers)
# View the head of the DataFrame and all its columns
from IPython.display import display
with pd.option_context('display.max_columns', None):
display(shot_df.head()) | NBA_stats_visualization/Shot charts Notebook.ipynb | JuanIgnacioGil/basket-stats | mit |
The above shot chart data contains all the the field goal attempts James Harden took during the 2014-15
regular season. They data we want is found in LOC_X and LOC_Y. These are coordinate values for each shot
attempt, which can then be plotted onto a set of axes that represent the basketball court.
Plotting the Shot ... | sns.set_style("white")
sns.set_color_codes()
plt.figure(figsize=(12,11))
plt.scatter(shot_df.LOC_X, shot_df.LOC_Y)
plt.show() | NBA_stats_visualization/Shot charts Notebook.ipynb | JuanIgnacioGil/basket-stats | mit |
Please note that the above plot misrepresents the data. The x-axis values are the inverse
of what they actually should be. Lets plot the shots taken from only the right side to see
this issue. | right = shot_df[shot_df.SHOT_ZONE_AREA == "Right Side(R)"]
plt.figure(figsize=(12,11))
plt.scatter(right.LOC_X, right.LOC_Y)
plt.xlim(-300,300)
plt.ylim(-100,500)
plt.show() | NBA_stats_visualization/Shot charts Notebook.ipynb | JuanIgnacioGil/basket-stats | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.