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
compare size of subpopulations in healthy and AML individuals (within sample analysis)
fig, axarr = plt.subplots(2, 1,sharey=True) for id in range(0,5): axarr[0].plot(population_size_H[id],color = 'g') axarr[0].set_title('healty') for id in range(0,16): axarr[1].plot(population_size_SJ[id],color = 'r') axarr[1].set_title('AML') plt.show() X = np.array(population_size_H + population_size_SJ) Y = ...
_____no_output_____
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Diagnosis
# reload data! data = [data_dict[_].head(20000).applymap(f)[markers].values for _ in ['H1','H2','H3','H4',\ 'H5','SJ01','SJ02','SJ03','SJ04','SJ05','SJ06','SJ07','SJ08','SJ09','SJ10',\ 'SJ11','SJ12','SJ13','SJ14','SJ15','SJ16']] # compute data range data_ranges = np.array([[[data[_][:,d].min...
_____no_output_____
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Logistic regression with cell population of under 2 templates as features
# step 1: learn cell populations of all samples, under 2 template MPs, 5 chains # V: cell proportion for 21 samples under healthy template V_H = [[None for chain in range(n_mcmc_chain)] for _ in range(21)] V_SJ = [[None for chain in range(n_mcmc_chain)] for _ in range(21)] for id in range(21): print id res_H ...
[0.99841206336111987, 0.99966800288254687, 0.87316854492456542, 0.99999926620800161, 0.99984613432778913, 1.3459889647293721e-08, 0.0026811637112176268, 0.00010195742044638578, 1.5442242625729463e-05, 1.8254518332594394e-05, 0.003338405513243603, 0.00011531545835186119, 0.00034991109377846552, 0.033424769452122471, 0.0...
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Baseline 1: one tree for each group (without random effects)
# fit 1 tree to pooled healthy samples global_MP_H = [] global_MP_SJ = [] n_iter = 1000 data_H = np.concatenate(data[0:5]) for chain in range(n_mcmc_chain): global_MP_H.append(init_mp(theta_space, table, data_H, n_iter,mcmc_gaussin_std)) data_SJ = np.concatenate(data[5:]) for chain in range(n_mcmc_chain): ...
_____no_output_____
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Compare classification error(both gives perfect classification):
V_H_Global = [None for _ in range(21)] V_SJ_Global = [None for _ in range(21)] for id in range(21): V_H_Global[id] = compute_cell_population(data[id], global_MP_H, table, cell_type_name2idx) V_SJ_Global[id] = compute_cell_population(data[id], global_MP_SJ, table, cell_type_name2idx) X_Global = [V_H_Global[id...
_____no_output_____
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Compare log likelihood $P(data_i|MP_i)$
# individual MP with random effects log_lik_H = [[] for _ in range(5)] # 5 * n_chain log_lik_SJ = [[] for _ in range(16)] # 5 * n_chain for id in range(5): data_subset = data[id] burnt_samples = [i for _ in range(n_mcmc_chain) for i in \ accepts_indiv_mp_lists_H[_][id][-1:]] for sampl...
_____no_output_____
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Baseline 2: K means (use centers of pooled healthy data and pooled AML data as feature extractors)
V_Kmeans_H = [[None for chain in range(n_mcmc_chain)] for _ in range(21)] V_Kmeans_SJ = [[None for chain in range(n_mcmc_chain)] for _ in range(21)] from sklearn.cluster import KMeans from scipy.spatial import distance for chain in range(n_mcmc_chain): cluster_centers_H = KMeans(n_clusters=14, random_state=chain)...
_____no_output_____
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Random Effect Analysis
def find_first_cut(theta_space): # find the dimension and location of first cut when there is a cut root_rec = theta_space[0] left_rec = theta_space[1][0] for _ in range(root_rec.shape[0]): if root_rec[_,1] != left_rec[_,1]: break dim, pos = _, left_rec[_,1]...
_____no_output_____
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Compare magnitude of random effects in 2 groups
random_effect_H = [[None for chain in range(n_mcmc_chain)] for id in range(5)] random_effect_SJ = [[None for chain in range(n_mcmc_chain)] for id in range(16)] for id in range(5): for chain in range(n_mcmc_chain): random_effect_H[id][chain] = compute_diff_mp(accepts_template_mp_H[chain][-1],\ ...
_____no_output_____
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Visualize random effects(find chains and dimensions what random effects are obvious)
chain = 1 random_effect_H_set = [random_effect_H_flattened[id][chain][0] for id in range(5)] random_effect_SJ_set = [random_effect_SJ_flattened[id][chain][0] for id in range(16)] # bins = 20 # plt.hist(random_effect_H_set,bins = bins) # plt.show() # plt.hist(random_effect_SJ_set, bins = bins) # plt.show() # kde_H = Ke...
_____no_output_____
MIT
small_run/Flow_Cytometry_Mondrian_Processes-Random-Effects-Final_n_chain_5_n_sample_1000.ipynb
disiji/fc_mondrian
Classifying Surnames with a Multilayer Perceptron Imports
from argparse import Namespace from collections import Counter import json import os import string import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader from tqdm import tqdm_notebook
_____no_output_____
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
Data Vectorization classes The Vocabulary
class Vocabulary(object): """Class to process text and extract vocabulary for mapping""" def __init__(self, token_to_idx=None, add_unk=True, unk_token="<UNK>"): """ Args: token_to_idx (dict): a pre-existing map of tokens to indices add_unk (bool): a flag that indicates w...
_____no_output_____
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
The Vectorizer
class SurnameVectorizer(object): """ The Vectorizer which coordinates the Vocabularies and puts them to use""" def __init__(self, surname_vocab, nationality_vocab): """ Args: surname_vocab (Vocabulary): maps characters to integers nationality_vocab (Vocabulary): maps nati...
_____no_output_____
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
The Dataset
class SurnameDataset(Dataset): def __init__(self, surname_df, vectorizer): """ Args: surname_df (pandas.DataFrame): the dataset vectorizer (SurnameVectorizer): vectorizer instatiated from dataset """ self.surname_df = surname_df self._vectorizer = vect...
_____no_output_____
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
The Model: SurnameClassifier
class SurnameClassifier(nn.Module): """ A 2-layer Multilayer Perceptron for classifying surnames """ def __init__(self, input_dim, hidden_dim, output_dim): """ Args: input_dim (int): the size of the input vectors hidden_dim (int): the output size of the first Linear layer...
_____no_output_____
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
Training Routine Helper functions
def make_train_state(args): return {'stop_early': False, 'early_stopping_step': 0, 'early_stopping_best_val': 1e8, 'learning_rate': args.learning_rate, 'epoch_index': 0, 'train_loss': [], 'train_acc': [], 'val_loss': [], ...
_____no_output_____
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
general utilities
def set_seed_everywhere(seed, cuda): np.random.seed(seed) torch.manual_seed(seed) if cuda: torch.cuda.manual_seed_all(seed) def handle_dirs(dirpath): if not os.path.exists(dirpath): os.makedirs(dirpath)
_____no_output_____
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
Settings and some prep work
args = Namespace( # Data and path information surname_csv="data/surnames/surnames_with_splits.csv", vectorizer_file="vectorizer.json", model_state_file="model.pth", save_dir="model_storage/ch4/surname_mlp", # Model hyper parameters hidden_dim=300, # Training hyper parameters seed=13...
Expanded filepaths: model_storage/ch4/surname_mlp/vectorizer.json model_storage/ch4/surname_mlp/model.pth Using CUDA: False
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
Initializations
if args.reload_from_files: # training from a checkpoint print("Reloading!") dataset = SurnameDataset.load_dataset_and_load_vectorizer(args.surname_csv, args.vectorizer_file) else: # create dataset and vectorizer print("Creating fresh!") ...
Creating fresh!
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
Training loop
classifier = classifier.to(args.device) dataset.class_weights = dataset.class_weights.to(args.device) loss_func = nn.CrossEntropyLoss(dataset.class_weights) optimizer = optim.Adam(classifier.parameters(), lr=args.learning_rate) scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer, ...
Test loss: 1.7435305690765381; Test Accuracy: 47.875
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
Inference
def predict_nationality(surname, classifier, vectorizer): """Predict the nationality from a new surname Args: surname (str): the surname to classifier classifier (SurnameClassifer): an instance of the classifier vectorizer (SurnameVectorizer): the corresponding vectorizer Return...
Enter a surname to classify: McMahan McMahan -> Irish (p=0.55)
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
Top-K Inference
vectorizer.nationality_vocab.lookup_index(8) def predict_topk_nationality(name, classifier, vectorizer, k=5): vectorized_name = vectorizer.vectorize(name) vectorized_name = torch.tensor(vectorized_name).view(1, -1) prediction_vector = classifier(vectorized_name, apply_softmax=True) probability_values, i...
Enter a surname to classify: McMahan How many of the top predictions to see? 5 Top 5 predictions: =================== McMahan -> Irish (p=0.55) McMahan -> Scottish (p=0.21) McMahan -> Czech (p=0.05) McMahan -> German (p=0.04) McMahan -> English (p=0.03)
Apache-2.0
chapters/chapter_4/4_2_mlp_surnames/4_2_Classifying_Surnames_with_an_MLP.ipynb
prampampam/PyTorchNLPBook
Task 2 dpm.load_task2()
dpm.load_task2() data = dpm.train_task2_df data["keyword"].value_counts().keys() data["text"][0] def get_text_for(data,label = 0): """ Returns text that corresponds to the label as a single string. """ text = [] for i in range(len(data["text"])): if data["label"][i][label] == 1: ...
zip warning: name not matched: task2.txt updating: task1.txt (deflated 92%)
MIT
proto_two.ipynb
sarveshbhatnagar/PCL_DETECTION
Pre-processing mouse dataLoad the clusters obtained from previous section, so that we can bootsrap on them.
### Load DataFrame of log-transfromed averaged time-series for each cluster # (1) Healthy Group df_log_healthy = pd.read_pickle("data/df_log_healthy.pkl") # (2) IBD Group df_log_ibd = pd.read_pickle("data/df_log_ibd.pkl") ### Load cluster memberships for every OTU # (1) Healthy Group tree_healthy = pd.read_pickle( "da...
_____no_output_____
MIT
Bootstrapping_augmentation.ipynb
sytseng/CS109b_Final_Project_Spring_2019
Bootstrapping Step A. Subset df by cluster MembershipRecall that we have three methods to generate clusters: - Tree based: 3 clusters- NMF correlation: 9 clusters- Time correlation: 5 clustersAnd we have loaded the cluster membership for every OTU above. In this section, we will subset the OTU into those different clu...
### Function to subset the dataframe by cluster membership def subset_df_by_membership(df, tree, NMF, time): # get the total number of otu and time points (otu_length,time_length) = df.shape # add the membership as the last column df['tree']=tree df['NMF']=NMF df['time']=time # loop th...
_____no_output_____
MIT
Bootstrapping_augmentation.ipynb
sytseng/CS109b_Final_Project_Spring_2019
Step B. Bootstrap to generate more mice dataNow that we have the clusters, we do bootstrap:- For each single sample step, within every cluster, we randomly choose 30% of the OTUs, took the average of them to generate one time series representing that cluster.- We repeated the sampling for 30 times, to generate the 30 ...
### Function to Bootstrap: def bootrapping(method_list, mice_count): methods = list() for method in range(3): mice = list() for time in range(mice_count): clusters = list() for cluster in range(len(method_list[method])): one_sample = method_list[method][cl...
_____no_output_____
MIT
Bootstrapping_augmentation.ipynb
sytseng/CS109b_Final_Project_Spring_2019
Data Structure ExampleThese are the simulated absolute values (not the log-transformed, they have already been transformed back).
####################################################################### # For example: tree_healthy_30_mice # # tree_healthy_30_mice: the first mice data # # tree_healthy_30_mice[0]: the first cluster in the first mice data # # tree_healthy_30_mice[0][0]: th...
the nunmber of simulated mice data is: 30 within each mouse, the number of the tree_based clusters is: 3 for each cluster, the number of the time points is: 75
MIT
Bootstrapping_augmentation.ipynb
sytseng/CS109b_Final_Project_Spring_2019
Fashion MNIST
from keras.datasets import fashion_mnist from sklearn.metrics import roc_auc_score from sklearn.metrics import mean_squared_error _, (fashion_x_test, _) = fashion_mnist.load_data() fashion_x_test = fashion_x_test.astype('float32') / 255. fashion_x_test = np.reshape(fashion_x_test, (len(x_test), 28, 28, 1)) show_10_i...
AUROC: 0.99937089
MIT
notebooks/autoencoders/MNIST10/one_anomaly_detector.ipynb
tayden/NoveltyDetection
EMNIST Letters
from torchvision.datasets import EMNIST emnist_letters = EMNIST('./', "letters", train=False, download=True) emnist_letters = emnist_letters.test_data.numpy() emnist_letters = emnist_letters.astype('float32') / 255. emnist_letters = np.swapaxes(emnist_letters, 1, 2) emnist_letters = np.reshape(emnist_letters, (len(em...
AUROC: 0.9604927475961538
MIT
notebooks/autoencoders/MNIST10/one_anomaly_detector.ipynb
tayden/NoveltyDetection
Gaussian Noise
mnist_mean = np.mean(x_train) mnist_std = np.std(x_train) gaussian_data = np.random.normal(mnist_mean, mnist_std, size=(10000, 28, 28, 1)) show_10_images(gaussian_data) show_10_images(autoencoder.predict(gaussian_data)) labels = len(x_test) * [0] + len(gaussian_data) * [1] test_samples = np.concatenate((x_test, gaussi...
AUROC: 1.0
MIT
notebooks/autoencoders/MNIST10/one_anomaly_detector.ipynb
tayden/NoveltyDetection
Uniform Noise
import math b = math.sqrt(3.) * mnist_std a = -b + mnist_mean b += mnist_mean uniform_data = np.random.uniform(low=a, high=b, size=(10000, 28, 28, 1)) show_10_images(uniform_data) show_10_images(autoencoder.predict(uniform_data)) labels = len(x_test) * [0] + len(uniform_data) * [1] test_samples = np.concatenate((x_te...
AUROC: 1.0
MIT
notebooks/autoencoders/MNIST10/one_anomaly_detector.ipynb
tayden/NoveltyDetection
Check River Flows
from __future__ import division import matplotlib.pyplot as plt import netCDF4 as nc import numpy as np from salishsea_tools import nc_tools %matplotlib inline def find_points(flow): for i in range(390,435): for j in range(280,398): if flow1[0,i,j] > 0: print i,j, lat[i,j], lo...
_____no_output_____
Apache-2.0
Susan/Check River Files.ipynb
SalishSeaCast/analysis
import pandas as pd ws = pd.read_csv('winshares.txt') ws.head() ws.shape # clean up player name column ws['Player'] = ws['Player'].str.split('/').str[0] ws.head() sals = pd.read_csv('salaries.txt') sals.head() sals.shape sals['Player'] = sals['Player'].str.split('/').str[0] sals.head() # merge columns 2019-2020 salari...
_____no_output_____
MIT
dataproject.ipynb
mugilc/mugilc.github.io
- How many items are NaN in the is hk column?- How many items are known housekeeping genes?- How many items are known tissue specific genes?
print("NaN %s" % len(data[data["is_hk"].isnull()])) print("Housekeeping %s" % len(data[data["is_hk"] == 1])) print("Specific %s" % len(data[data["is_hk"] == 0])) def split_train_test(data): split = (int) (len(data) * 0.9) return data[0:split], data[split:] def split_data(data): # Shuffle data data = da...
_____no_output_____
MIT
gene-prediction-gaussian.ipynb
neungkl/MLE-and-naive-bayes-classification
How many bins have zero counts?
print("Total %s" % len(hist)) print("Zeros %s" % sum(hist == 0))
Total 1000 Zeros 823
MIT
gene-prediction-gaussian.ipynb
neungkl/MLE-and-naive-bayes-classification
**cDNA Density Plot**
train_set_clength_no_nan_sorted = data["cDNA_length"][data["cDNA_length"].notnull()].sort_values() bin_edge = np.unique(train_set_clength_no_nan_sorted[0::70]) hist = np.bincount(np.digitize(train_set_clength_no_nan_sorted, bin_edge)) hist = hist[1:-1] bin_plot(hist, bin_edge)
_____no_output_____
MIT
gene-prediction-gaussian.ipynb
neungkl/MLE-and-naive-bayes-classification
**CDS Density Plot**
train_set_clength_no_nan_sorted = data["cds_length"][data["cds_length"].notnull()].sort_values() bin_edge = np.unique(train_set_clength_no_nan_sorted[0::100]) hist = np.bincount(np.digitize(train_set_clength_no_nan_sorted, bin_edge)) hist = hist[1:-1] bin_plot(hist, bin_edge) for feature in list(train_set): if fea...
_____no_output_____
MIT
gene-prediction-gaussian.ipynb
neungkl/MLE-and-naive-bayes-classification
MLE calculation
def calc_mean_var(data): data = data[data.notnull()] u = data.mean() v = data.var() return u, v def calc_prob_eq_zero(data): data = data[data.notnull()] return len(data[data == 0]) * 1.0 / len(data) likelihood = {} for feature in list(train_set): if feature == "is_hk": continue ...
Accuracy: 0.923077 Precision: 0.647059 Recall: 1.000000 F1: 0.785714
MIT
gene-prediction-gaussian.ipynb
neungkl/MLE-and-naive-bayes-classification
Baseline 1\. Random Choice Baseline
def create_random_pred(): return np.random.random_sample((len(y_test),)) - 0.5 y_pred = activate_predict(create_random_pred()) measure_metrics(y_test, y_pred)
Accuracy: 0.435897 Precision: 0.133333 Recall: 0.545455 F1: 0.214286
MIT
gene-prediction-gaussian.ipynb
neungkl/MLE-and-naive-bayes-classification
2\. Majority
def create_majority_pred(): return np.ones(len(y_test)) * test_set["is_hk"].mode().values.astype(int) y_pred = create_majority_pred() measure_metrics(y_test, y_pred)
Accuracy: 0.858974 Precision: 0.000000 Recall: 0.000000 F1: 0.000000
MIT
gene-prediction-gaussian.ipynb
neungkl/MLE-and-naive-bayes-classification
ROC
t = np.arange(-5,5,0.01) tp = [] tp_random = [] tp_majority = [] fp = [] fp_random = [] fp_majority = [] y_test = test_set["is_hk"] y_pred = predict(test_set) y_random = create_random_pred() y_act_majority = create_majority_pred() for t_i in t: y_act_pred = activate_predict(y_pred, threshold = t_i) y_...
_____no_output_____
MIT
gene-prediction-gaussian.ipynb
neungkl/MLE-and-naive-bayes-classification
Getting started with TensorFlow (Graph Mode)**Learning Objectives** - Understand the difference between Tensorflow's two modes: Eager Execution and Graph Execution - Get used to deferred execution paradigm: first define a graph then run it in a `tf.Session()` - Understand how to parameterize a graph using `tf.place...
import tensorflow as tf print(tf.__version__)
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/02_tensorflow/b_tfstart_graph.ipynb
KayvanShah1/training-data-analyst
Graph Execution Adding Two Tensors Build the GraphUnlike eager mode, no concrete value will be returned yet. Just a name, shape and type are printed. Behind the scenes a directed graph is being created.
a = tf.constant(value = [5, 3, 8], dtype = tf.int32) b = tf.constant(value = [3, -1, 2], dtype = tf.int32) c = tf.add(x = a, y = b) print(c)
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/02_tensorflow/b_tfstart_graph.ipynb
KayvanShah1/training-data-analyst
Run the GraphA graph can be executed in the context of a `tf.Session()`. Think of a session as the bridge between the front-end Python API and the back-end C++ execution engine. Within a session, passing a tensor operation to `run()` will cause Tensorflow to execute all upstream operations in the graph required to cal...
with tf.Session() as sess: result = sess.run(fetches = c) print(result)
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/02_tensorflow/b_tfstart_graph.ipynb
KayvanShah1/training-data-analyst
Parameterizing the Grpah What if values of `a` and `b` keep changing? How can you parameterize them so they can be fed in at runtime? *Step 1: Define Placeholders*Define `a` and `b` using `tf.placeholder()`. You'll need to specify the data type of the placeholder, and optionally a tensor shape.*Step 2: Provide feed_di...
a = tf.placeholder(dtype = tf.int32, shape = [None]) b = tf.placeholder(dtype = tf.int32, shape = [None]) c = tf.add(x = a, y = b) with tf.Session() as sess: result = sess.run(fetches = c, feed_dict = { a: [3, 4, 5], b: [-1, 2, 3] }) print(result)
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/02_tensorflow/b_tfstart_graph.ipynb
KayvanShah1/training-data-analyst
Linear Regression Toy DatasetWe'll model the following:\begin{equation}y= 2x + 10\end{equation}
X = tf.constant(value = [1,2,3,4,5,6,7,8,9,10], dtype = tf.float32) Y = 2 * X + 10 print("X:{}".format(X)) print("Y:{}".format(Y))
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/02_tensorflow/b_tfstart_graph.ipynb
KayvanShah1/training-data-analyst
2.2 Loss FunctionUsing mean squared error, our loss function is:\begin{equation}MSE = \frac{1}{m}\sum_{i=1}^{m}(\hat{Y}_i-Y_i)^2\end{equation}$\hat{Y}$ represents the vector containing our model's predictions:\begin{equation}\hat{Y} = w_0X + w_1\end{equation}Note below we introduce TF variables for the first time. Unl...
with tf.variable_scope(name_or_scope = "training", reuse = tf.AUTO_REUSE): w0 = tf.get_variable(name = "w0", initializer = tf.constant(value = 0.0, dtype = tf.float32)) w1 = tf.get_variable(name = "w1", initializer = tf.constant(value = 0.0, dtype = tf.float32)) Y_hat = w0 * X + w1 loss_mse = tf.reduce_mea...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/02_tensorflow/b_tfstart_graph.ipynb
KayvanShah1/training-data-analyst
OptimizerAn optimizer in TensorFlow both calculates gradients and updates weights. In addition to basic gradient descent, TF provides implementations of several more advanced optimizers such as ADAM and FTRL. They can all be found in the [tf.train](https://www.tensorflow.org/versions/r1.15/api_docs/python/tf/train) m...
LEARNING_RATE = tf.placeholder(dtype = tf.float32, shape = None) optimizer = tf.train.GradientDescentOptimizer(learning_rate = LEARNING_RATE).minimize(loss = loss_mse)
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/02_tensorflow/b_tfstart_graph.ipynb
KayvanShah1/training-data-analyst
Training LoopNote our results are identical to what we found in Eager mode.
STEPS = 1000 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # initialize variables for step in range(STEPS): #1. Calculate gradients and update seights sess.run(fetches = optimizer, feed_dict = {LEARNING_RATE: 0.02}) #2. Periodically print MSE ...
_____no_output_____
Apache-2.0
courses/machine_learning/deepdive/02_tensorflow/b_tfstart_graph.ipynb
KayvanShah1/training-data-analyst
This is only the tested and reported cases John Hopkins CCSE has data for this is by no means a definitive view of the global epidemic. The repo is updated daily around 5:00pm PDT
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt confirmed_url = "https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv" recovered_url = "https://github.com/CSSEGISandData/COVID-19/raw/mast...
_____no_output_____
MIT
Covid19.ipynb
BryanSouza91/COVID-19
Plots total confirmed cases by country Changing the logx=False to True shows the logarithmic scales of x-axis Changing the logy=False to True shows the logarithmic scales of y-axis Changing the loglog=False to True shows the logarithmic scales of both axes
conf_df.loc[:,'1/22/20':].loc[conf_df['Country/Region'] == 'China'].sum().plot(figsize=(25,6),logx=False,logy=False,loglog=True); conf_df.loc[:,'1/22/20':].loc[conf_df['Country/Region'] == 'US'].sum().plot(figsize=(25,6),logx=False,logy=False,loglog=False); conf_df.loc[:,'1/22/20':].loc[conf_df['Country/Region'] == 'Ja...
_____no_output_____
MIT
Covid19.ipynb
BryanSouza91/COVID-19
World report
# Create reusable series objects conf_sum = conf_df.loc[:,'1/22/20':].sum() recv_sum = recv_df.loc[:,'1/22/20':].sum() death_sum = death_df.loc[:,'1/22/20':].sum() conf_sum_dif = difference(conf_sum, 1).values recv_sum_dif = difference(recv_sum, 1).values death_sum_dif = difference(death_sum, 1).values # Print world...
World numbers current as of 4/5/20 New cases: 74710 Total confirmed cases: 1272115 New case rate: 6.239% New case 7-day Moving Average: 78857 New case 30-day Moving Average: 39010 New Recovered cases: 13860 Total recover...
MIT
Covid19.ipynb
BryanSouza91/COVID-19
Report for each country reporting cases
# define report function def report(country): # Create reusable series objects country_conf_sum = conf_df.loc[:,'1/22/20':].loc[conf_df['Country/Region'] == country].sum() country_recv_sum = recv_df.loc[:,'1/22/20':].loc[conf_df['Country/Region'] == country].sum() country_death_sum = death_df.loc[:,'1/...
_____no_output_____
MIT
Covid19.ipynb
BryanSouza91/COVID-19
!git clone https://github.com/AadSah/fixmatch.git !scp -r ./fixmatch/* ./ !pip install -r ./requirements.txt !mkdir datasets !pip uninstall tensorflow !pip uninstall tensorflow-gpu !pip install tensorflow-gpu==1.14.0 !pip install libml import os os.environ['ML_DATA'] = './datasets' %set_env PYTHONPATH=$PYTHONPATH:. !CU...
_____no_output_____
Apache-2.0
covid_fixmatch_xray.ipynb
AadSah/fixmatch
Get NFL Player Data
import requests from pandas.io.json import json_normalize import pandas as pd import requests # https://sportsdata.io/developers/api-documentation/nfl # Player overall information #url = "https://api.sportsdata.io/v3/nfl/scores/json/Players?key=d072122708d34423857116889b72f55b" # Player Season stats for 20...
_____no_output_____
Apache-2.0
NFL (1).ipynb
humberhutch/NFLAnalysis
Show the first few rows of data returned - All players
df.head()
_____no_output_____
Apache-2.0
NFL (1).ipynb
humberhutch/NFLAnalysis
Focus on Wide Receivers
wr = df[ df['Position'] =='WR' ] print (wr.shape) # Number of players (rows) and attributes (columns) # remove players with few games played or less than 10 Receiving Yards wr = wr[ wr['Played'] >10] wr = wr[ wr['ReceivingYards'] >10] wr.describe() yardsPerGame = wr['ReceivingYards']/wr['Played'] wr['yardsPerG...
_____no_output_____
Apache-2.0
NFL (1).ipynb
humberhutch/NFLAnalysis
Create a histogram of the Yards Per Game
wr['yardsPerGame'].hist()
_____no_output_____
Apache-2.0
NFL (1).ipynb
humberhutch/NFLAnalysis
Boxplot to show distribution
wr['yardsPerGame'].plot.box();
_____no_output_____
Apache-2.0
NFL (1).ipynb
humberhutch/NFLAnalysis
Keep the main columns for analysis
colsKeep = ['PlayerID', 'Season','Team', 'Activated','Played','Started','ReceivingTargets', 'Receptions', 'ReceivingYards', 'ReceivingYardsPerReception','ReceivingTouchdowns','ReceivingLong','yardsPerGame'] new_wr = wr[colsKeep] new_wr.head()
_____no_output_____
Apache-2.0
NFL (1).ipynb
humberhutch/NFLAnalysis
Retrieve data for all players for past 3 years and add salary for analysis
new_wr.groupby(['Team']).mean()['yardsPerGame']
_____no_output_____
Apache-2.0
NFL (1).ipynb
humberhutch/NFLAnalysis
Dummy Variables ExerciseIn this exercise, you'll create dummy variables from the projects data set. The idea is to transform categorical data like this:| Project ID | Project Category ||------------|------------------|| 0 | Energy || 1 | Transportation || 2 | Health || ...
import pandas as pd import numpy as np # read in the projects data set and do basic wrangling projects = pd.read_csv('../data/projects_data.csv', dtype=str) projects.drop('Unnamed: 56', axis=1, inplace=True) projects['totalamt'] = pd.to_numeric(projects['totalamt'].str.replace(',', '')) projects['countryname'] = proj...
_____no_output_____
MIT
lessons/ETLPipelines/12_dummyvariables_exercise/12_dummyvariables_exercise.ipynb
rabadzhiyski/Data_Science_Udacity
Run the code cell below. This cell shows the percentage of each variable that is null. Notice the mjsector1 through mjsector5 variables are all null. The mjtheme1name through mjtheme5name are also all null as well as the theme variable. Because these variables contain so many null values, they're probably not very usef...
# output percentage of values that are missing 100 * sector.isnull().sum() / sector.shape[0]
_____no_output_____
MIT
lessons/ETLPipelines/12_dummyvariables_exercise/12_dummyvariables_exercise.ipynb
rabadzhiyski/Data_Science_Udacity
The sector1 variable looks promising; it doesn't contain any null values at all. In the next cell, store the unique sector1 values in a list and output the results. Use the sort_values() and unique() methods.
# TODO: Create a list of the unique values in sector1. Use the sort_values() and unique() pandas methods. # And then convert those results into a Python list uniquesectors1 = list(sector['sector1'].sort_values().unique()) uniquesectors1 # run this code cell to see the number of unique values print('Number of unique va...
Number of unique values in sector1: 3060
MIT
lessons/ETLPipelines/12_dummyvariables_exercise/12_dummyvariables_exercise.ipynb
rabadzhiyski/Data_Science_Udacity
3060 different categories is quite a lot! Remember that with dummy variables, if you have n categorical values, you need n - 1 new variables! That means 3059 extra columns! Exercise 2There are a few issues with this 'sector1' variable. First, there are values labeled '!$!0'. These should be substituted with NaN.Furthe...
# TODO: In the sector1 variable, replace the string '!$10' with nan # HINT: you can use the pandas replace() method and numpy.nan sector['sector1'] = sector['sector1'].replace('!$!0', np.nan) # TODO: In the sector1 variable, remove the last 10 or 11 characters from the sector1 variable. # HINT: There is more than one ...
Number of unique sectors after cleaning: 156 Percentage of null values after cleaning: 3.4962735642262164
MIT
lessons/ETLPipelines/12_dummyvariables_exercise/12_dummyvariables_exercise.ipynb
rabadzhiyski/Data_Science_Udacity
Now there are 156 unique categorical values. That's better than 3060. If you were going to use this data with a supervised learning machine model, you could try converting these 156 values to dummy variables. You'd still have to train and test a model to see if those are good features.But can you do anything else with ...
sector['sector']
_____no_output_____
MIT
lessons/ETLPipelines/12_dummyvariables_exercise/12_dummyvariables_exercise.ipynb
rabadzhiyski/Data_Science_Udacity
What else can you do? If you look at all of the diferent sector1 categories, it might be useful to combine a few of them together. For example, there are various categories with the term "Energy" in them. And then there are other categories that seem related to energy but don't have the word energy in them like "Therma...
import re # Create the sector1_aggregates variable sector.loc[:,'sector1_aggregates'] = sector['sector1'] # TODO: The code above created a new variable called sector1_aggregates. # Currently, sector1_aggregates has all of the same values as sector1 # For this task, find all the rows in sector1_aggregates...
Number of unique sectors after cleaning: 145
MIT
lessons/ETLPipelines/12_dummyvariables_exercise/12_dummyvariables_exercise.ipynb
rabadzhiyski/Data_Science_Udacity
The number of unique sectors continues to go down. Keep in mind that how much to consolidate will depend on your machine learning model performance and your hardware's ability to handle the extra features in memory. If your hardware's memory can handle 3060 new features and your machine learning algorithm performs bett...
# TODO: Create dummy variables from the sector1_aggregates data. Put the results into a dataframe called dummies # Hint: Use the get_dummies method dummies = pd.DataFrame(pd.get_dummies(sector['sector1_aggregates'])) # TODO: Filter the projects data for the totalamt, the year from boardapprovaldate, and the dummy vari...
_____no_output_____
MIT
lessons/ETLPipelines/12_dummyvariables_exercise/12_dummyvariables_exercise.ipynb
rabadzhiyski/Data_Science_Udacity
load data
DATASET_ID = 'BIRD_DB_Vireo_cassinii' df_loc = DATA_DIR / 'syllable_dfs' / DATASET_ID / 'cassins.pickle' syllable_df = pd.read_pickle(df_loc) del syllable_df['audio'] syllable_df[:3] np.shape(syllable_df.spectrogram.values[0])
_____no_output_____
MIT
notebooks/02.5-make-projection-dfs/higher-spread/.ipynb_checkpoints/cassins-umap-checkpoint.ipynb
xingjeffrey/avgn_paper
project
specs = list(syllable_df.spectrogram.values) specs = [i/np.max(i) for i in tqdm(specs)] specs_flattened = flatten_spectrograms(specs) np.shape(specs_flattened) cuml_umap = cumlUMAP(min_dist = 0.5) embedding = cuml_umap.fit_transform(specs_flattened) fig, ax = plt.subplots() ax.scatter(embedding[:,0], embedding[:,1], s=...
_____no_output_____
MIT
notebooks/02.5-make-projection-dfs/higher-spread/.ipynb_checkpoints/cassins-umap-checkpoint.ipynb
xingjeffrey/avgn_paper
Save
ensure_dir(DATA_DIR / 'embeddings' / DATASET_ID / 'full') syllable_df.to_pickle(DATA_DIR / 'embeddings' / DATASET_ID / (str(min_dist) + '_full.pickle'))
_____no_output_____
MIT
notebooks/02.5-make-projection-dfs/higher-spread/.ipynb_checkpoints/cassins-umap-checkpoint.ipynb
xingjeffrey/avgn_paper
Qualitatively replicate: [1] Elman, J. L. (1990). Finding structure in time. Cognitive Science, 14(2), 179–211. https://doi.org/10.1016/0364-0213(90)90002-E[2] Saffran, J. R., Aslin, R. N., & Newport, E. L. (1996). Statistical learning by 8-month-old infants. Science, 274(5294), 1926–1928. https://doi.org/10.1126/scien...
import os import time import warnings import itertools import numpy as np from sklearn.preprocessing import OneHotEncoder import torch import torch.nn as nn import matplotlib.pyplot as plt import seaborn as sns warnings.filterwarnings("ignore") sns.set(style='white', context='poster', font_scale=.8, rc={"lines.lin...
_____no_output_____
MIT
elman_pytorch.ipynb
qihongl/demo-elman-1990
Pandas II More indexing tricks We'll start out with some data from Beer Advocate (see [Tom Augspurger](https://github.com/TomAugspurger/pydata-chi-h2t/blob/master/3-Indexing.ipynb) for some cool details on how he extracted this data)
import numpy as np import pandas as pd pd.options.display.max_rows = 10 df = pd.read_csv('data/beer_subset.csv.gz', parse_dates=['time'], compression='gzip')
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Boolean indexingLike a where clause in SQL. The indexer (or boolean mask) should be 1-dimensional and the same length as the thing being indexed.
df.loc[((df['abv'] < 5) & (df['time'] > pd.Timestamp('2009-06'))) | (df['review_overall'] >= 4.5)].head()
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Be careful with the order of operations... Safest to use parentheses... Select just the rows where the `beer_style` contains `'IPA'`: Find the rows where the beer style is either `'American IPA'` or `'Pilsner'`:
(df['beer_style'] == 'American IPA')
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Or more succinctly:
df[df['beer_style'].isin(['American IPA', 'Pilsner'])].head()
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Mini Exercise- Select the rows where the scores of the 5 review_cols ('review_appearance', 'review_aroma', 'review_overall', 'review_palate', 'review_taste') are all at least 4.0.- _Hint_: Like NumPy arrays, DataFrames have an any and all methods that check whether it contains any or all True values. These methods als...
reviews = df.set_index(['profile_name', 'beer_id', 'time'])
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Top ReviewersLet's select all the reviews by the top reviewers, by label. The syntax is a bit trickier when you want to specify a row Indexer *and* a column Indexer:
reviews.loc[(top_reviewers, 99, :), ['beer_name', 'brewer_name']] reviews.loc[pd.IndexSlice[top_reviewers, 99, :], ['beer_name', 'brewer_id']]
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Use `.loc` to select the `beer_name` and `beer_style` for the 10 most popular beers, as measured by number of reviews: Beware "chained indexing"You can sometimes get away with using `[...][...]`, but try to avoid it!
df.loc[df['beer_style'].str.contains('IPA')]['beer_name'] df.loc[df['beer_style'].str.contains('IPA')]['beer_name'] = 'yummy' df.loc[df['beer_style'].str.contains('IPA')]['beer_name']
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Dates and Times - Date and time data are inherently problematic - An unequal number of days in every month - An unequal number of days in a year (due to leap years) - Time zones that vary over space - etc - The datetime built-in library handles temporal information down to the nanosecond Having a custom...
segments = pd.read_csv('data/AIS/transit_segments.csv')
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
For example, we might be interested in the distribution of transit lengths, so we can plot them as a histogram: Though most of the transits appear to be short, there are a few longer distances that make the plot difficult to read. This is where a transformation is useful: We can see that although there are date/time fi...
datetime.strptime(segments['st_time'].ix[0], '%m/%d/%y %H:%M')
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
As a convenience, Pandas has a `to_datetime` method that will parse and convert an entire Series of formatted strings into `datetime` objects. Pandas also has a custom NA value for missing datetime objects, `NaT`.
pd.to_datetime([None])
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Finally, if `to_datetime()` has problems parsing any particular date/time format, you can pass the spec in using the `format=` argument. Merging and joining `DataFrame`s In Pandas, we can combine tables according to the value of one or more *keys* that are used to identify rows, much like an index.
df1 = pd.DataFrame({'id': range(4), 'age': np.random.randint(18, 31, size=4)}) df2 = pd.DataFrame({'id': list(range(3))*2, 'score': np.random.random(size=6)})
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Notice that without any information about which column to use as a key, Pandas did the right thing and used the `id` column in both tables. Unless specified otherwise, `merge` will used any common column names as keys for merging the tables. Notice also that `id=3` from `df1` was omitted from the merged table. This is...
vessels = pd.read_csv('data/AIS/vessel_information.csv', index_col='mmsi')
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
We see that there is a `mmsi` value (a vessel identifier) in each table, but it is used as an index for the `vessels` table. In this case, we have to specify to join on the index for this table, and on the `mmsi` column for the other. Notice that `mmsi` field that was an index on the `vessels` table is no longer an ind...
cdystonia = pd.read_csv('data/cdystonia.csv', index_col=None)
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
This dataset includes repeated measurements of the same individuals (longitudinal data). Its possible to present such information in (at least) two ways: showing each repeated measurement in their own row, or in multiple columns representing multiple measurements. `.stack()` rotates the data frame so that columns are r...
cdystonia2 = cdystonia.set_index(['patient','obs'])
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
If we want to transform this data so that repeated measurements are in columns, we can `unstack` the `twstrs` measurements according to `obs`: And if we want to keep the other variables:
cdystonia_wide = (cdystonia[['patient','site','id','treat','age','sex']] .drop_duplicates() .merge(twstrs_wide, right_index=True, left_on='patient', how='inner') .head())
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Or to simplify things, we can set the patient-level information as an index before unstacking:
(cdystonia.set_index(['patient','site','id','treat','age','sex','week'])['twstrs'] .unstack('week').head())
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
[`.melt()`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html)- To convert our "wide" format back to long, we can use the `melt` function. - This function is useful for `DataFrame`s where one or more columns are identifier variables (`id_vars`), with the remaining columns being measured variables ...
pd.melt(cdystonia_wide, id_vars=['patient','site','id','treat','age','sex'], var_name='obs', value_name='twsters').head()
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
Pivoting The `pivot` method allows a DataFrame to be transformed easily between long and wide formats in the same way as a pivot table is created in a spreadsheet. It takes three arguments: `index`, `columns` and `values`, corresponding to the DataFrame index (the row headers), columns and cell values, respectively. F...
cdystonia.pivot(index='patient', columns='obs', values='twstrs').head()
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
If we omit the `values` argument, we get a `DataFrame` with hierarchical columns, just as when we applied `unstack` to the hierarchically-indexed table: A related method, `pivot_table`, creates a spreadsheet-like table with a hierarchical index, and allows the values of the table to be populated using an arbitrary aggr...
cdystonia.head() cdystonia.pivot_table(index=['site', 'treat'], columns='week', values='twstrs', aggfunc=max).head(20)
_____no_output_____
CC-BY-3.0
Lecture 4/Lecture 4 - Pandas II (Template).ipynb
iEvidently/ihme-python-course
PrefacedescriptionAbout notebookLoad librariesLoad DatasetColumn DescriptionCleaning DatasetEDA- Null values- Via which channel did user visited - Mobile users- Browser based - Device Category- Operating system- Continent Based- Metro Based- Network Domain- Region- Country Based- Sub Continent Based- Page view V/S bou...
import numpy as np import pandas as pd import plotly.graph_objs as go import plotly.offline as py from plotly.offline import init_notebook_mode, iplot, download_plotlyjs import plotly.graph_objs as go from plotly import tools import matplotlib.pyplot as plt init_notebook_mode(connected=True) from plotly.tools import Fi...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
Load Dataset
train = pd.read_csv("../input/train.csv") test = pd.read_csv("../input/test.csv") # train_df = pd.read_csv('flatten_train.csv') # test_df = pd.read_csv('flatten_test.csv') # helper functions def constant_cols(df): cols = [] columns = df.columns.values for col in columns: if df[col].nunique(dropna = ...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
Column Description - fullVisitorId- A unique identifier for each user of the Google Merchandise Store.- channelGrouping - The channel via which the user came to the Store.- date - The date on which the user visited the Store.- device - The specifications for the device used to access the Store.- geoNetwork - This sect...
def load_df(csv_path='../input/train.csv', nrows=None): JSON_COLUMNS = ['device', 'geoNetwork', 'totals', 'trafficSource'] df = pd.read_csv(csv_path, converters={column: json.loads for column in JSON_COLUMNS}, dtype={'fullVisitorId': 'str'}, # Important!! ...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
Since totals transaction Revenue is what we are going to predict.and there is no campaignCode in test set Cleaning Dataset
train_constants = constant_cols(train_df) test_constants = constant_cols(test_df) print(train_constants) print(test_constants) train_df["totals.transactionRevenue"] = train_df["totals.transactionRevenue"].astype('float') train_df['totals.transactionRevenue'] = train_df['totals.transactionRevenue'].fillna(0) train_df['d...
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
both the df has same cols with constant values lets remove them
train_constants = constant_cols(train_df) test_constants = constant_cols(test_df) train_df = train_df.drop(columns=train_constants,axis = 1) test_df = test_df.drop(columns=test_constants, axis = 1)
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
EDA Null values
null_values = train_df.isna().sum(axis = 0).reset_index() null_values = null_values[null_values[0] > 50] null_chart = [go.Bar(y = null_values['index'],x = null_values[0]*100/len(train_df), orientation = 'h')] py.iplot(null_chart)
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- So many coloumns has null values- we will find why these columns are null and we will also see how we can manage them. Via which channel did user visited
data = train_df[['channelGrouping','totals.transactionRevenue']] temp = data['channelGrouping'].value_counts() chart = [go.Pie(labels = temp.index, values = temp.values)] py.iplot(chart)
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- Most of the users came via organic search.- Paid search and affilate users are very less. Mobile users
temp = train_df['device.isMobile'].value_counts() chart = go.Bar(x = ["False","True"], y = temp.values) py.iplot([chart])
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects
**Summary**- Many users browse the site from desktop or tablet Browser based
count_mean('device.browser',"#7FDBFF","#3D9970")
_____no_output_____
MIT
9 google customer revenue prediction/exploratory-google-store-analysis.ipynb
MLVPRASAD/KaggleProjects