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
Each variable plotted against loss:
plt.scatter('latent_dims', "valid_loss", data=df_res, marker="+", color='r') plt.ylabel("Loss") plt.xlabel("latent dimensions") plt.ylim(16000, 70000) plt.scatter('first_channel', "valid_loss", data=df_res, marker="+", color='r') plt.ylabel("Loss") plt.xlabel("First channel") plt.ylim(16000, 80000) plt.scatter('batch_n...
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
Investigate "band" in loss-model plot Extract the different bands and inpsect
band1 = df_res[df_res.valid_loss < 20000] band2 = df_res[(df_res.valid_loss > 20000) & (df_res.valid_loss < 23000)] band3 = df_res[(df_res.valid_loss > 23000) & (df_res.valid_loss < 26000)] band1.head() band3.head()
_____no_output_____
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
Investigate Duplicates
#eg1: /data/home/jfm1118/DA/experiments/CAE_zoo2/32 and /data/home/jfm1118/DA/experiments/CAE_zoo2/12 #eg2: /data/home/jfm1118/DA/experiments/CAE_zoo2/31 and /data/home/jfm1118/DA/experiments/CAE_zoo2/27 def get_data_from_path(path): for res in results: if res["path"] == path: return res els...
CAE2 ModuleList( (0): Conv3d(1, 8, kernel_size=(3, 3, 3), stride=(1, 1, 1)) (1): Conv3d(8, 8, kernel_size=(3, 3, 2), stride=(2, 2, 2), padding=(1, 0, 0)) (2): Conv3d(8, 8, kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=(1, 1, 0)) (3): Conv3d(8, 8, kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=(0, 1, 0)) ...
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
Investigate Best
path = "/data/home/jfm1118/DA/experiments/CAE_zoo2/17" exp = get_data_from_path(base_exp + str(17))["settings"] print_model(exp_1)
CAE2 ModuleList( (0): Conv3d(1, 8, kernel_size=(3, 3, 3), stride=(1, 1, 1)) (1): Conv3d(8, 8, kernel_size=(3, 3, 2), stride=(2, 2, 2), padding=(1, 0, 0)) (2): Conv3d(8, 8, kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=(1, 1, 0)) (3): Conv3d(8, 8, kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=(0, 1, 0)) ...
MIT
notebooks/.ipynb_checkpoints/CAE_zoo_analysis-checkpoint.ipynb
scheng1992/Data_Assimilation
`np.tile` vs. `np.repeat`
np.tile([1, 2, 3], reps=2) np.repeat([1, 2, 3], 2)
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
multidimensional
np.tile(np.repeat([1, 2, 3, 4], 2), 3) d = {'b': 12} dict({'a': 2}, **d) a = np.arange(4).reshape(2, -1) np.tile(a, (2, 3)) a = np.arange(4).reshape(2, -1) np.repeat(a, (2, 5), axis=0) a = np.arange(4).reshape(2, -1) np.repeat(a, (2, 5), axis=1)
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Set operations
a = np.array([1, 2, 3, 2, 3, 4, 3, 4, 5, 6]) b = np.array([7, 2, 10, 2, 7, 4, 9, 4, 9, 8]) np.intersect1d(a, b), np.setdiff1d(a, b)
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Matching positions and elements
a = np.array([1, 2, 3, 2, 3, 4, 3, 4, 5, 6]) b = np.array([7, 2, 10, 2, 7, 4, 9, 4, 9, 8]) np.where(a == b), a[a==b]
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Boolean indexing
a[a > 4]
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Swapping columns
a = np.arange(10).reshape(2, -1) a[:, [1, 2, 3, 0, 4]]
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Standardizing and normalizingStandardizing: mean 0, std 1
a = np.random.uniform(size=(5, 4), low=-5, high=10) a (a - a.mean()) / a.std()
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Normalizing: squash into range [0, 1)
(a - a.min()) / a.ptp()
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
`np.digitize`
a = np.arange(1, 11).reshape(2, -1) a = np.array([20, -2, 3, 5, 8, 7]) np.digitize(a, bins=[1, 4, 8])
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Local peaks
a = np.array([1, 3, 7, 1, 2, 6, 0, 1]) diff1 = a - np.hstack((a[1:], 0)) diff2 = a - np.hstack((0, a[:-1])) np.where((diff1>0) & (diff2>0)) a = np.array([[3,3,3],[4,4,4],[5,5,5]]) b = np.array([1,2,3]) a - b[:, None] x = np.array([1, 2, 1, 1, 3, 4, 3, 1, 1, 2, 1, 1, 2]) np.where(x == 1)[0][4]
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Date range
np.arange(np.datetime64("2018-01-02"), np.datetime64("2018-01-15"), 3)
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Strides
a = np.arange(15) stride = 2 window = 4 np.array([a[i:i+window] for i in range(0, a.shape[0]-window+1, stride)])
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Trim digital signalTrim each consecutive block of ones to `min(cut, len(block))`.
import itertools x = [0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1] plt.step(np.arange(len(x)), x) cut = 2 x = np.array([0] + x + [0]) up = np.where(np.diff(x) == 1)[0] + 1 down = np.where(np.diff(x) == -1)[0] + 1 delta = down - up delta[delta > cut] = cut x[:] = 0 x[list(itertools.chain(*(list(range...
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Permutations
a = np.array([4, 3, 0, 10, 1]) order = np.argsort(-a) a[order] order, a[order][np.argsort(order)] a = np.array([[1, -1, 2], [5, 0, 0]]) np.argmax(a, -1) a.argmax(-1)
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
argsort
a = np.array([3, -1, 2, 0, 5, 2]) order = np.argsort(-a) a[order] a[order][np.argsort(order)] [1, 2] * -1
_____no_output_____
MIT
lectures/11_Numpy_extra_stuff.ipynb
juditacs/bprof-python
Welcome!Below, we will learn to implement and train a policy to play atari-pong, using only the pixels as input. We will use convolutional neural nets, multiprocessing, and pytorch to implement and train our policy. Let's get started!
# install package for displaying animation !pip install JSAnimation # custom utilies for displaying animation, collecting rollouts and more import pong_utils %matplotlib inline # check which device is being used. # I recommend disabling gpu until you've made sure that the code runs device = pong_utils.device print(...
List of available actions: ['NOOP', 'FIRE', 'RIGHT', 'LEFT', 'RIGHTFIRE', 'LEFTFIRE']
MIT
pong/pong-PPO.ipynb
thomasgui76/deep-reinforcement-learning
PreprocessingTo speed up training, we can simplify the input by cropping the images and use every other pixel
import matplotlib import matplotlib.pyplot as plt # show what a preprocessed image looks like env.reset() _, _, _, _ = env.step(0) # get a frame after 20 steps for _ in range(20): frame, _, _, _ = env.step(1) plt.subplot(1,2,1) plt.imshow(frame) plt.title('original image') plt.subplot(1,2,2) plt.title('preproces...
_____no_output_____
MIT
pong/pong-PPO.ipynb
thomasgui76/deep-reinforcement-learning
Policy Exercise 1: Implement your policy Here, we define our policy. The input is the stack of two different frames (which captures the movement), and the output is a number $P_{\rm right}$, the probability of moving left. Note that $P_{\rm left}= 1-P_{\rm right}$
import torch import torch.nn as nn import torch.nn.functional as F # set up a convolutional neural net # the output is the probability of moving right # P(left) = 1-P(right) class Policy(nn.Module): def __init__(self): super(Policy, self).__init__() ######## ## ## Modify y...
_____no_output_____
MIT
pong/pong-PPO.ipynb
thomasgui76/deep-reinforcement-learning
Game visualizationpong_utils contain a play function given the environment and a policy. An optional preprocess function can be supplied. Here we define a function that plays a game and shows learning progress
pong_utils.play(env, policy, time=200) # try to add the option "preprocess=pong_utils.preprocess_single" # to see what the agent sees
_____no_output_____
MIT
pong/pong-PPO.ipynb
thomasgui76/deep-reinforcement-learning
Function DefinitionsHere you will define key functions for training. Exercise 2: write your own function for training(what I call scalar function is the same as policy_loss up to a negative sign) PPOLater on, you'll implement the PPO algorithm as well, and the scalar function is given by$\frac{1}{T}\sum^T_t \min\left...
def clipped_surrogate(policy, old_probs, states, actions, rewards, discount = 0.995, epsilon=0.1, beta=0.01): ######## ## ## WRITE YOUR OWN CODE HERE ## ######## actions = torch.tensor(actions, dtype=torch.int8, device=device) # convert states to policy (or prob...
_____no_output_____
MIT
pong/pong-PPO.ipynb
thomasgui76/deep-reinforcement-learning
TrainingWe are now ready to train our policy!WARNING: make sure to turn on GPU, which also enables multicore processing. It may take up to 45 minutes even with GPU enabled, otherwise it will take much longer!
from parallelEnv import parallelEnv import numpy as np # keep track of how long training takes # WARNING: running through all 800 episodes will take 30-45 minutes # training loop max iterations episode = 500 # widget bar to display progress !pip install progressbar import progressbar as pb widget = ['training loop: '...
_____no_output_____
MIT
pong/pong-PPO.ipynb
thomasgui76/deep-reinforcement-learning
Optimization Opt 1 parameter
def run(Plot, Save): return import numpy as np from PyMieSim import Material from PyMieSim.Scatterer import Sphere from PyMieSim.Detector import Photodiode, LPmode from PyMieSim.Source import PlaneWave from PyMieSim.Experiment import ScatSet, SourceSet, Setup, DetectorSet ...
_____no_output_____
MIT
docs/source/auto_examples/ExperimentOptimization/Optimization:Opt-1-parameter.ipynb
ejetzer/PyMieSim
6. Hidden Markov Models with Theano and TensorFlowIn the last section we went over the training and prediction procedures of Hidden Markov Models. This was all done using only vanilla numpy the Expectation Maximization algorithm. I now want to introduce how both `Theano` and `Tensorflow` can be utilized to accomplish ...
import numpy as np import theano import theano.tensor as T import seaborn as sns import matplotlib.pyplot as plt from hmm.utils import get_obj_s3, random_normalized %matplotlib inline %config InlineBackend.figure_format = 'retina' sns.set(style="white", palette="husl") sns.set_context("talk") sns.set_style("ticks")...
A learned from training: [[0.50000007 0.49999993] [0.50000005 0.49999995]] B learned from training: [[0.52666344 0.47333656] [0.52666383 0.47333617]] pi learned from training: [0.50007189 0.49992811]
MIT
Machine_Learning/05-Hidden_Markov_Models-06-Hidden-Markov-Models-Hidden-Markov-Models-Discrete-Observations-Deep-Learning-Libraries.ipynb
NathanielDake/NathanielDake.github.io
3. HMM's with Theano $\rightarrow$ Optimization via SoftmaxOne of the challenges of the approach we took is that gradient descent is _unconstrained_; it simply goes in the direction of the gradient. This presents a problem for us in the case of HMM's. Remember, the parameters of an HMM are $\pi$, $A$, and $B$, and eac...
np.set_printoptions(suppress=True) A = np.array([ [1,2], [4,5], [9,5] ]) expA = np.exp(A) print("A exponentiated element wise: \n", np.round_(expA, decimals=3), "\n") # Keep dims ensures a column vector (vs. row) output output = expA / expA.sum(axis=1, keepdims=True) print("Exponentiated A divided row s...
A exponentiated element wise: [[ 2.718 7.389] [ 54.598 148.413] [8103.084 148.413]] Exponentiated A divided row sum: [[0.269 0.731] [0.269 0.731] [0.982 0.018]]
MIT
Machine_Learning/05-Hidden_Markov_Models-06-Hidden-Markov-Models-Hidden-Markov-Models-Discrete-Observations-Deep-Learning-Libraries.ipynb
NathanielDake/NathanielDake.github.io
Now you may be wondering: Why can't we just perform standard normalization? Why does the exponetial need to be used? For an answer to that I recommend reading up [here](https://stackoverflow.com/questions/17187507/why-use-softmax-as-opposed-to-standard-normalization), [here](https://stats.stackexchange.com/questions/16...
class HMM: def __init__(self, M): self.M = M def fit(self, X, learning_rate=0.001, max_iter=10, V=None, p_cost=1.0, print_period=10): """Train HMM model using stochastic gradient descent.""" # Determine V, the vocabulary size if V is None: V = max(max(x) for x in X)...
_____no_output_____
MIT
Machine_Learning/05-Hidden_Markov_Models-06-Hidden-Markov-Models-Hidden-Markov-Models-Discrete-Observations-Deep-Learning-Libraries.ipynb
NathanielDake/NathanielDake.github.io
4. Hidden Markov Models with TensorFlowI now want to expose everyone to an HMM implementation in TensorFlow. In order to do so, we will need to first go over the `scan` function in Tensorflow. Just like when dealing with Theano, we need to ask "What is the equivalent of a for loop in TensorFlow?". And why should we ca...
import tensorflow as tf x = tf.placeholder(tf.int32, shape=(None,), name="x") def square(last, current): """Last is never used, but must be included based on interface requirements of tf.scan""" return current*current # Essentially doing what a for loop would normally do # It applies the square function to e...
WARNING:tensorflow:From /Users/natedake/.virtualenvs/intuitiveml/lib/python3.6/site-packages/tensorflow/python/ops/tensor_array_ops.py:162: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version. Instructions for updating: Colocations handled automatically by placer. ...
MIT
Machine_Learning/05-Hidden_Markov_Models-06-Hidden-Markov-Models-Hidden-Markov-Models-Discrete-Observations-Deep-Learning-Libraries.ipynb
NathanielDake/NathanielDake.github.io
Now, of course `scan` can do more complex things than this. We can implement another argument, `initializer`, that allows us to compute recurrence relationships. ```outputs = tf.scan( fn=some_function, Function applied to every element in sequence elems=thing_to_loop_over, Actual sequence that is pa...
# N is the number fibonacci numbers that we want N = tf.placeholder(tf.int32, shape=(), name="N") def fibonacci(last, current): # last[0] is the last value, last[1] is the second last value return (last[1], last[0] + last[1]) fib_op = tf.scan( fn=fibonacci, elems=tf.range(N), initializer=(0, 1), ...
Output: (array([ 1, 1, 2, 3, 5, 8, 13, 21], dtype=int32), array([ 1, 2, 3, 5, 8, 13, 21, 34], dtype=int32))
MIT
Machine_Learning/05-Hidden_Markov_Models-06-Hidden-Markov-Models-Hidden-Markov-Models-Discrete-Observations-Deep-Learning-Libraries.ipynb
NathanielDake/NathanielDake.github.io
Another example of what we can do with the theano `scan` is create a **low pass filter** (also known as a **moving average**). In this case, our recurrence relation is given by:$$s(t) = \text{decay_rate} \cdot s(t-1) + (1 - \text{decay_rate}) \cdot x(t)$$Where $x(t)$ is the input and $s(t)$ is the output. The goal here...
original = np.sin(np.linspace(0, 3*np.pi, 300)) X = 2*np.random.randn(300) + original fig = plt.figure(figsize=(15,5)) plt.subplot(1, 2, 1) ax = plt.plot(X, c="g", lw=1.5) plt.title("Original") # Setup placeholders decay = tf.placeholder(tf.float32, shape=(), name="decay") sequence = tf.placeholder(tf.float32, shape=...
_____no_output_____
MIT
Machine_Learning/05-Hidden_Markov_Models-06-Hidden-Markov-Models-Hidden-Markov-Models-Discrete-Observations-Deep-Learning-Libraries.ipynb
NathanielDake/NathanielDake.github.io
4.2 Discrete HMM With TensorflowLet's now take a moment to walk through the creation of a discrete HMM class utilizing Tensorflow.
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from hmm.utils import get_obj_s3 class HMM: def __init__(self, M): self.M = M # number of hidden states def set_session(self, session): self.session = session def fit(self, X, max_iter=10, print_period=1): ...
Number of train samples: 50
MIT
Machine_Learning/05-Hidden_Markov_Models-06-Hidden-Markov-Models-Hidden-Markov-Models-Discrete-Observations-Deep-Learning-Libraries.ipynb
NathanielDake/NathanielDake.github.io
Automagically making a table of all protein-protein interactions for two structuresIf two structures use the same or essentially the same, you can use Python to make a table of all the pairs of the protein-protein interactions by the two structures that can be used as input for the pipeline described in an earlier not...
structure1 = "6kiz" structure2 = "6kix"
_____no_output_____
MIT
notebooks/Automagically making a table of all protein-protein interactions for two structures.ipynb
fomightez/pdbsum-binder
The next cell gets the script `pdb_code_to_prot_prot_interactions_via_PDBsum.py` (see [here](https://github.com/fomightez/structurework/tree/master/pdbsum-utilities)) that will get the 'Interface Summary' information for each individual structure. This is the equivalent to the Summary on the left side of the 'Prot-prot...
import os file_needed = "pdb_code_to_prot_prot_interactions_via_PDBsum.py" if not os.path.isfile(file_needed): !curl -OL https://raw.githubusercontent.com/fomightez/structurework/master/pdbsum-utilities/{file_needed}
_____no_output_____
MIT
notebooks/Automagically making a table of all protein-protein interactions for two structures.ipynb
fomightez/pdbsum-binder
Import the main function of that script by running the next cell.
from pdb_code_to_prot_prot_interactions_via_PDBsum import pdb_code_to_prot_prot_interactions_via_PDBsum
_____no_output_____
MIT
notebooks/Automagically making a table of all protein-protein interactions for two structures.ipynb
fomightez/pdbsum-binder
The next cell gets the interaction summary for each structure and to get the pairs need to build the table described at the top of [Using snakemake to highlight changes in multiple protein-protein interactions via PDBsum data](Using%20snakemake%20to%20highlight%20changes%20in%20multiple%20protein-protein%20interactions...
structure1_il = pdb_code_to_prot_prot_interactions_via_PDBsum(structure1) structure2_il = pdb_code_to_prot_prot_interactions_via_PDBsum(structure2) i_union = set(structure1_il).union(set(structure2_il))
_____no_output_____
MIT
notebooks/Automagically making a table of all protein-protein interactions for two structures.ipynb
fomightez/pdbsum-binder
In this case the pairs of both are the same; however, the script is written to not fail if there was extra proteins present in the other. Specficially, the interacting pairs of proteins for both are checked because if one had additional chain, by getting the listing of both structures and making the union, the combinat...
s = "" for pair in list(i_union): s+= f"{structure1} {pair[0]} {pair[1]} {structure2} {pair[0]} {pair[1]}\n" %store s >int_matrix.txt
Writing 's' (str) to file 'int_matrix.txt'.
MIT
notebooks/Automagically making a table of all protein-protein interactions for two structures.ipynb
fomightez/pdbsum-binder
The table has now been stored as `int_matrix.txt`. Open the file from the Jupyter dashboard to verify. Or just run the next cell to see the contents of the file.
!cat int_matrix.txt
6kiz K R 6kix K R 6kiz B H 6kix B H 6kiz C E 6kix C E 6kiz B D 6kix B D 6kiz G H 6kix G H 6kiz F H 6kix F H 6kiz D F 6kix D F 6kiz A N 6kix A N 6kiz N T 6kix N T 6kiz C D 6kix C D 6kiz A B 6kix A B 6kiz C F 6kix C F 6kiz K T 6kix K T 6kiz A E 6kix A E 6kiz A G 6kix A G 6kiz C K 6kix C K 6kiz E F 6kix E ...
MIT
notebooks/Automagically making a table of all protein-protein interactions for two structures.ipynb
fomightez/pdbsum-binder
That's the table in the file that needed to be made. The rest of the process pickes up with 'Step 3' of [Using snakemake to highlight changes in multiple protein-protein interactions via PDBsum data](Using%20snakemake%20to%20highlight%20changes%20in%20multiple%20protein-protein%20interactions%20via%20PDBsum%20data.ipyn...
!snakemake --cores 1
Building DAG of jobs... Using shell: /bin/bash Provided cores: 1 (use --cores to define parallelism) Rules claiming more threads will be scaled down. Job counts: count jobs 1 all 23 convert_scripts_to_nb_and_run_using_jupytext 1 make_archive 1 read_table_and_create_py 26[...
MIT
notebooks/Automagically making a table of all protein-protein interactions for two structures.ipynb
fomightez/pdbsum-binder
Car Decor Sales Forecasting - Perfumes
Summary of the Code below : 1. Establish MySQL Connection and load data 2. Data Preprocessing (Typecasting and Resampling daily data to monthly) 3. Visualizing Rolling statistics to observe variation in mean and standard deviation for selected Feature. 4. Checking for Data Stationarity using Augmented Dickey-Fuller Tes...
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Importing Libraries
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline from sklearn.metrics import mean_squared_error from math import sqrt # Connecting Python to MySQL for fetching data import mysql.connector import warnings from statsmodels.tools.sm_exceptions import Conve...
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
MySQL Connection to fetch data
try: connection = mysql.connector.connect(host='localhost', database='car_decors', user='root', password='***********') sql_select_Query = "SELECT * FROM decorsales" cursor = connection...
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Data Cleaning and Exploratory Data Analysis Converting fetched records to Pandas dataframe
records = np.array(records) records = records[:,0:25] decor_sales=pd.DataFrame(records,columns=columns)
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Type Casting Date and other features
decor_sales.dtypes decor_sales.Date = pd.to_datetime(decor_sales.Date) decor_sales.iloc[:,1:] = decor_sales.iloc[:,1:].astype("int32") decor_sales.dtypes
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Creating Subset of Decor Sales Dataset and resampling Monthly Time Series
df = decor_sales df = df.set_index('Date') df = df.resample("MS").sum()
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Note : Time period options when resampling a time series MS - Monthly ; W - Weekly ; QS - Quarterly ; YS - Yearly
###### Data Visualization
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
plt.rc("figure", figsize=(16,8))sns.set_style('darkgrid')
###### Rolling statistics to observe variation in mean and standard deviation.
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
timeseries = df ['Perfumes']timeseries.rolling(12).mean().plot(label='12 Month Rolling Mean', marker='.')timeseries.rolling(12).std().plot(label='12 Month Rolling Std', marker='.')timeseries.plot(marker='.')plt.title('Rolling Statistics to observe variation in Mean and Standard Deviation', fontsize = 18, fontweight = '...
# The plot shows, there is nearly a constant mean and standard deviation except noise in Qtr 2 - 2020 (Lockdown period)
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Checking Seasonalty and Trend components for the feature
from statsmodels.tsa.seasonal import seasonal_decompose add = seasonal_decompose(df["Perfumes"],model="additive",period=12) add.plot();
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Decomposition plot shows constant trend with noise in Qtr 2 - 2020 and seasonality is additive in nature. The data is seasonal and follows constant trend. Also, the average value or the mean of the residuals seem to be zero which holds our assumption.
##### Checking for Data Stationarity using Augmented Dickey-Fuller Test
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
from statsmodels.tsa.stattools import adfullerdef check_adf(time_series): test_result = adfuller(df['Perfumes']) print ('ADF Test:') labels = ['ADF Statistic','p-value','No. of Lags Used','Number of Observations Used'] for value,label in zip(test_result,labels): print (label+': '+str(value)+str("\n")...
If the data is non-stationary so we need to apply differencing to make our data stationary. df ['Perfumes'] = df ['Perfumes'] - df ['Perfumes']. shift (1) adf_check(df['Perfumes'].dropna()) If again data is non-stationary we need to differencing with subsequent shifts.
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
check_adf(df['Perfumes'])
# Adfuller test Results for all variables
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
from statsmodels.tsa.stattools import adfullerdef adfuller_parameter(x): P = [] columns = [] used_lag = [] for i in x.columns: test_stats,p,used_lags,nobs,critical_value,ic_best = adfuller(x[i]) columns.append(i) P.append(p) used_lag.append(used_lags) return pd.DataFrame({"COL...
By looking at adfuller test result we conclude that we need differencing by 0 shifts to make our data stationary for android headunits.
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Hyper-parameter Tuning Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF) plots
# By looking at ACF pot and PACF plot we decide the value p(Auto regressive) and q(Moving average) # p = sudden shuts off in pacf plot. # q = Exponential drop in acf plot. # d = degree of differencing/shift by adfuller test #Auto Regressive (p) # Identification of an AR model is often best done with the PACF. # For an...
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
from statsmodels.graphics.tsaplots import plot_acf, plot_pacfimport statsmodels.api as smfig, ax = plt.subplots(1,2, figsize=(15,5))sm.graphics.tsa.plot_acf(df["Perfumes"], lags=12, title = 'ACF Plot', ax=ax[0])sm.graphics.tsa.plot_pacf(df["Perfumes"], lags=12, title = 'PACF Plot',ax=ax[1])plt.show()
### Model Building - SARIMA Model ( Seasonal ARIMA Model ) ###### Train Test Split
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
train_df = df["Perfumes"].iloc[0:int(len(df)*.95)] train model with approx 95% datatest_df = df["Perfumes"].iloc[int(len(train_df)):] test model with 5% dataprint("Train_df : ",len(train_df))print("Test_df : ",len(test_df))
###### User Defined Function to calculate the MAPE value
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
def mape(y_true, y_pred): y_true, y_pred = np.array(y_true), np.array(y_pred) return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
###### Automated Hyperparameter tuning
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
import itertools as i p = range(0,3) d = range(0,2)q = range(0,3)pdq_combo = list(i.product(p,d,q)) this will all combination of p,d,q throgh a tuple error = []aic_sarima = []order_arima = []order_sarima = []seasonality = 12for pdq in pdq_combo: for PDQ in pdq_combo: try: SEASONAL_ORDER = list(PDQ...
###### Model with best parameter
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
sarima_model = sm.tsa.SARIMAX(train_df, order=(p_d_q), seasonal_order=(P_D_Q))sarima_results = sarima_model.fit(disp = 0)sarima_pred = sarima_results.predict(start=test_df.index[0],end=test_df.index[-1])sarima_pred_large = sarima_results.predict(start=75,end=86,dynamic=True) print(sarima_results.summary())sarima_diagno...
# Insights from these diagnostic plot : # 1.The top left plot shows the residuals over time. # The plot shows our residuals are fluctuating around mean 0 there is uniform deviation over time # except some noise in second quarter of 2021 due to lockdown imposed by government with effect of COVID-19 pandemic. # 2.In the...
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Predicted values Point estimationsarima_prediction = sarima_results.get_prediction(start = test_df.index[0], end = test_df.index[-1], dynamic = True, full_results = True)sarima_point_estimation = sarima_prediction.predicted_meansarima_point_estimation Checking MAPEmape(test_df, sarima_point_estimation) At 95% confide...
############################################################################################################################
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Holt Winters Exponential Smoothing with Additive Seasonality and Additive Trend
from statsmodels.tsa.seasonal import seasonal_decompose from statsmodels.tsa.holtwinters import ExponentialSmoothing # hwe_model_add_add = ExponentialSmoothing(train_df, seasonal ="add", trend = "add", seasonal_periods = 12).fit() pred_hwe_add_add = hwe_model_add_add.predict(start = test_df.index[0], end = test_df.in...
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Plotting Holt Winters Model
plt.plot(train_df,color="g",label="Train Data") plt.plot(test_df,color="b",label="Test Data") plt.plot(pred_hwe_add_add,color="r",label="Forecast (Test Data)") plt.suptitle('Model : Holt Winters', fontsize = 12, fontweight = 'bold') plt.title('Car Decors - ANDROID HEAD UNITS', fontsize = 18, fontweight = 'bold') plt.fi...
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
### FB Prophet Model
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Loading Librariesfrom fbprophet import Prophetfrom fbprophet.plot import plot_plotlydf1 = decor_salesdf1 = df1.set_index('Date')df1 = df1.resample("MS").sum()df1.reset_index(inplace=True) train_df1 = df1[["Date","Perfumes"]].iloc[0:int(len(df1)*.95)] train model with approx 95% datatest_df1 = df1[["Date","Perfumes"]]....
############################################################################################################################
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Auto Time Series Model
from auto_ts import auto_timeseries train_df2 = train_df1 test_df2 = test_df1 ts_model = auto_timeseries( score_type='rmse', time_interval='MS', non_seasonal_pdq=(12,12,12), seasonality=True, seasonal_period=12, model_type="best", verbose=2) ts_model.fit(traindata= train_df2, ts_column="ds", target="y") ts_model.get_le...
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
### Models Evaluation
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
from sklearn.metrics import mean_squared_error as mseprint("\nSARIMA Trend : ", p_d_q)print("SARIMA Seasonal Order : ", P_D_Q)print("SARIMA AIC : ", sarima_results.aic)print("SARIMA RMSE : ", np.sqrt(mse(test_df,sarima_point_estimation)))print("SARIMA MAPE : ", mape(test_df,...
############################################################################################################################
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Saving Model
import pickle filename = 'sarima_model_perfumes.pkl' pickle.dump(sarima_model, open(filename, 'wb'))
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Testing saved Model for prediction
####### Model summary and diagnstics plot ####### with open(filename, "rb") as file: load_model = pickle.load(file) result = load_model.fit() #print(result.summary()) #diagnostics = result.plot_diagnostics(figsize=(16,8)) pred = result.get_prediction(start = 76, end = 87, dynamic = False) # Point estimation p...
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Closing connection to MySQL and clearing variables from memory.
#if connection.is_connected(): # connection.close() # cursor.close() # print("MySQL connection is closed") # Clear all variables from memory #globals().clear() #####################################################################
_____no_output_____
MIT
Model Buidling/Perfumes.ipynb
sangram6n/inventory_management_car-decors_sales_forecasting
Battle of the Neighbourhoods - Toronto Author: Ganesh ChunneThis notebook contains Questions 1, 2 & 3 of the Assignment. They have been segregated by Section headers
import pandas as pd
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Question 1 Importing Data
import requests url = "https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M" wiki_url = requests.get(url) wiki_url
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Response 200 means that we are able to make the connection to the page
wiki_data = pd.read_html(wiki_url.text) wiki_data len(wiki_data), type(wiki_data)
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
We need the first table alone, so dropping the other tables
wiki_data = wiki_data[0] wiki_data
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Dropping Borough which are not assigned
df = wiki_data[wiki_data["Borough"] != "Not assigned"] df
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Grouping the records based on Postal Code
df = df.groupby(['Postal Code']).head() df
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Checking for number of records where Neighbourhood is "Not assigned"
df.Neighbourhood.str.count("Not assigned").sum() df = df.reset_index() df df.drop(['index'], axis = 'columns', inplace = True) df df.shape
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Answer to Question 1: We have 103 rows and 3 columns Question 2 Installing geocoder
pip install geocoder import geocoder # import geocoder
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Tried the below approach, ran for 20 mins, then killed it. Changing the code cell to Text for now so that the run all execution doesn't stop. ```python initialize your variable to Nonelat_lng_coords = Nonepostal_code = 'M3A' loop until you get the coordinateswhile(lat_lng_coords is None): g = geocoder.google('{}, Toro...
data = pd.read_csv("https://cocl.us/Geospatial_data") data print("The shape of our wiki data is: ", df.shape) print("the shape of our csv data is: ", data.shape)
The shape of our wiki data is: (103, 3) the shape of our csv data is: (103, 3)
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Since the dimensions are the same, we can try to join on the postal codes to get the required data.Checking the column types of both the dataframes, especially Postal Code column since we are trying to join on it
df.dtypes data.dtypes combined_data = df.join(data.set_index('Postal Code'), on='Postal Code', how='inner') combined_data combined_data.shape
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
**Solution:** We get 103 rows as expected when we do a inner join, so we have good data. Question 3 Drawing inspiration from the previous lab where we cluster the neighbourhood of NYC, We cluster Toronto based on the similarities of the venues categories using Kmeans clustering and Foursquare API.
from geopy.geocoders import Nominatim address = 'Toronto, Ontario' geolocator = Nominatim(user_agent="toronto_explorer") location = geolocator.geocode(address) latitude = location.latitude longitude = location.longitude print('The coordinates of Toronto are {}, {}.'.format(latitude, longitude))
The coordinates of Toronto are 43.6534817, -79.3839347.
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Let's visualize the map of Toronto
import folium # Creating the map of Toronto map_Toronto = folium.Map(location=[latitude, longitude], zoom_start=11) # adding markers to map for latitude, longitude, borough, neighbourhood in zip(combined_data['Latitude'], combined_data['Longitude'], combined_data['Borough'], combined_data['Neighbourhood']): label ...
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Initializing Foursquare API credentials
CLIENT_ID = '2GQBW5PR0QFXTOGCHKTRFWJBTGOFOHXW1TRTNRAFURQ5FE1X' CLIENT_SECRET = '3QH40WMZIIDSQN1RFAVAEQHUIMOQUJPKYPABQVNTSDQJN2YD' VERSION = 20202808 radius = 500 LIMIT = 100 print('Your credentails:') print('CLIENT_ID: ' + CLIENT_ID) print('CLIENT_SECRET:' + CLIENT_SECRET)
Your credentails: CLIENT_ID: 2GQBW5PR0QFXTOGCHKTRFWJBTGOFOHXW1TRTNRAFURQ5FE1X CLIENT_SECRET:3QH40WMZIIDSQN1RFAVAEQHUIMOQUJPKYPABQVNTSDQJN2YD
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Next, we create a function to get all the venue categories in Toronto
def getNearbyVenues(names, latitudes, longitudes): venues_list=[] for name, lat, lng in zip(names, latitudes, longitudes): print(name) # create the API request URL url = 'https://api.foursquare.com/v2/venues/explore?&client_id={}&client_secret={}&v={}&ll={},{}&radius={}...
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Collecting the venues in Toronto for each Neighbourhood
venues_in_toronto = getNearbyVenues(combined_data['Neighbourhood'], combined_data['Latitude'], combined_data['Longitude']) venues_in_toronto.shape
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
So we have 1317 records and 5 columns. Checking sample data
venues_in_toronto.head()
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Checking the Venues based on Neighbourhood
venues_in_toronto.groupby('Neighbourhood').head()
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
So there are 405 records for each neighbourhood.Checking for the maximum venue categories
venues_in_toronto.groupby('Venue Category').max()
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
There are around 232 different types of Venue Categories. Interesting! One Hot encoding the venue Categories
toronto_venue_cat = pd.get_dummies(venues_in_toronto[['Venue Category']], prefix="", prefix_sep="") toronto_venue_cat
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Adding the neighbourhood to the encoded dataframe
toronto_venue_cat['Neighbourhood'] = venues_in_toronto['Neighbourhood'] # moving neighborhood column to the first column fixed_columns = [toronto_venue_cat.columns[-1]] + list(toronto_venue_cat.columns[:-1]) toronto_venue_cat = toronto_venue_cat[fixed_columns] toronto_venue_cat.head()
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
We will group the Neighbourhoods, calculate the mean venue categories in each Neighbourhood
toronto_grouped = toronto_venue_cat.groupby('Neighbourhood').mean().reset_index() toronto_grouped.head()
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Let's make a function to get the top most common venue categories
def return_most_common_venues(row, num_top_venues): row_categories = row.iloc[1:] row_categories_sorted = row_categories.sort_values(ascending=False) return row_categories_sorted.index.values[0:num_top_venues] import numpy as np
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
There are way too many venue categories, we can take the top 10 to cluster the neighbourhoods
num_top_venues = 10 indicators = ['st', 'nd', 'rd'] # create columns according to number of top venues columns = ['Neighbourhood'] for ind in np.arange(num_top_venues): try: columns.append('{}{} Most Common Venue'.format(ind+1, indicators[ind])) except: columns.append('{}th Most Common Venue'....
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Let's make the model to cluster our Neighbourhoods
# import k-means from clustering stage from sklearn.cluster import KMeans # set number of clusters k_num_clusters = 5 toronto_grouped_clustering = toronto_grouped.drop('Neighbourhood', 1) # run k-means clustering kmeans = KMeans(n_clusters=k_num_clusters, random_state=0).fit(toronto_grouped_clustering) kmeans
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Checking the labelling of our model
kmeans.labels_[0:100]
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Let's add the clustering Label column to the top 10 common venue categories
neighborhoods_venues_sorted.insert(0, 'Cluster Labels', kmeans.labels_)
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Join toronto_grouped with combined_data on neighbourhood to add latitude & longitude for each neighborhood to prepare it for plotting
toronto_merged = combined_data toronto_merged = toronto_merged.join(neighborhoods_venues_sorted.set_index('Neighbourhood'), on='Neighbourhood') toronto_merged.head()
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Drop all the NaN values to prevent data skew
toronto_merged_nonan = toronto_merged.dropna(subset=['Cluster Labels'])
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider
Plotting the clusters on the map
import matplotlib.cm as cm import matplotlib.colors as colors map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11) # set color scheme for the clusters x = np.arange(k_num_clusters) ys = [i + x + (i*x)**2 for i in range(k_num_clusters)] colors_array = cm.rainbow(np.linspace(0, 1, len(ys))) rainbow =...
_____no_output_____
Apache-2.0
appliedDataScienceCapstoneWeek3.ipynb
Margchunne28/Location-data-provider