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
이 딕셔너리는 훈련과 검증하는 동안 모니터링할 측정 지표당 하나씩 모두 네 개의 항목을 담고 있습니다. 맷플롯립을 사용해 훈련과 검증 데이터에 대한 손실과 정확도를 그려 보겠습니다:
print(history.history['acc']) import matplotlib.pyplot as plt acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) # ‘bo’는 파란색 점을 의미합니다 (blue dot) plt.plot(epochs, loss, 'bo', label='Training loss') # ‘b...
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
val_loss, val_accuracy, loss, accuracy --> val_loss, val_acc, loss, acc 로 업데이트 됨
plt.clf() # 그래프를 초기화합니다 acc = history_dict['acc'] val_acc = history_dict['val_acc'] plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show()
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
점선은 훈련 손실과 정확도이고 실선은 검증 손실과 정확도입니다. 신경망의 무작위한 초기화 때문에 사람마다 결과거 조금 다를 수 있습니다.여기에서 볼 수 있듯이 훈련 손실이 에포크마다 감소하고 훈련 정확도는 에포크마다 증가합니다. 경사 하강법 최적화를 사용했을 때 반복마다 최소화되는 것이 손실이므로 기대했던 대로입니다. 검증 손실과 정확도는 이와 같지 않습니다. 4번째 에포크에서 그래프가 역전되는 것 같습니다. 이것이 훈련 세트에서 잘 작동하는 모델이 처음 보는 데이터에 잘 작동하지 않을 수 있다고 앞서 언급한 경고의 한 사례입니다. 정확한 용어로 말하면 과대적합되었다...
model = models.Sequential() model.add(layers.Dense(16, activation='relu', input_shape=(10000,))) model.add(layers.Dense(16, activation='relu')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) model.fit(x_...
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
아주 단순한 방식으로도 87%의 정확도를 달성했습니다. 최고 수준의 기법을 사용하면 95%에 가까운 성능을 얻을 수 있습니다. 훈련된 모델로 새로운 데이터에 대해 예측하기모델을 훈련시킨 후에 이를 실전 환경에서 사용하고 싶을 것입니다. `predict` 메서드를 사용해서 어떤 리뷰가 긍정일 확률을 예측할 수 있습니다:
model.predict(x_test)
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
여기에서처럼 이 모델은 어떤 샘플에 대해 확신을 가지고 있지만(0.99 또는 그 이상, 0.01 또는 그 이하) 어떤 샘플에 대해서는 확신이 부족합니다(0.6, 0.4). 추가 실험* 여기에서는 두 개의 은닉층을 사용했습니다. 한 개 또는 세 개의 은닉층을 사용하고 검증과 테스트 정확도에 어떤 영향을 미치는지 확인해 보세요.* 층의 은닉 유닛을 추가하거나 줄여 보세요: 32개 유닛, 64개 유닛 등* `binary_crossentropy` 대신에 `mse` 손실 함수를 사용해 보세요.* `relu` 대신에 `tanh` 활성화 함수(초창기 신경망에서 인기 있었던 함...
model = models.Sequential() model.add(layers.Dense(32, activation='tanh', input_shape=(10000,))) model.add(layers.Dense(32, activation='tanh')) model.add(layers.Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='mse', metrics=['acc']) model.fit(x_train, y_train, epoch...
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
ThaiNER (Bi-LSTM CRF)using pytorchBy Mr.Wannaphong PhatthiyaphaibunBachelor of Science Program in Computer and Information Science, Nong Khai Campus, Khon Kaen Universityhttps://iam.wannaphong.com/E-mail : wannaphong@kkumail.com Thank you Faculty of Applied Science and Engineering, Nong Khai Campus, Khon Kaen Universi...
import torch.nn.functional as F from torch.autograd import Variable import torch import torch.autograd as autograd import torch.nn as nn import torch.optim as optim print(torch.__version__) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") #torch.backends.cudnn.benchmark=torch.cuda.is_available(...
_____no_output_____
CC-BY-3.0
bilstm-crf-model/0.44/thainer.ipynb
Sutthipong/thai-ner
Flight Price Prediction---
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() pip list
Package Version ---------------------------------- ------------------- absl-py 0.12.0 alabaster 0.7.12 altair 4.1.0 anaconda-client 1.7.2 anaconda-navigator 1.10.0 anacond...
MIT
.ipynb_checkpoints/flight_price-checkpoint.ipynb
theAdarshSrivastava/Flight_Fare_Prediction-
Importing dataset1. Check whether any null values are there or not. if it is present then following can be done, 1. Imputing data using Imputation method in sklearn 2. Filling NaN values with mean, median and mode using fillna() method
train_data = pd.read_excel(r"/home/adarshsrivastava/Github/Flight_Fare_Prediction-/dataset/Data_Train.xlsx") #pd.set_option('display.max_columns', None) train_data.head() train_data.info() train_data["Duration"].value_counts() train_data.dropna(inplace = True) train_data.isnull().sum() #To check if there is any NaN v...
_____no_output_____
MIT
.ipynb_checkpoints/flight_price-checkpoint.ipynb
theAdarshSrivastava/Flight_Fare_Prediction-
EDA From description we can see that Date_of_Journey is a object data type,\Therefore, we have to convert this datatype into timestamp so as to use this column properly for predictionFor this we require pandas **to_datetime** to convert object data type to datetime dtype.**.dt.day method will extract only day of that ...
train_data["Journey_day"] = pd.to_datetime(train_data.Date_of_Journey, format="%d/%m/%Y").dt.day train_data["Journey_month"] = pd.to_datetime(train_data["Date_of_Journey"], format = "%d/%m/%Y").dt.month train_data.head() # Since we have converted Date_of_Journey column into integers, Now we can drop as it is of no use....
_____no_output_____
MIT
.ipynb_checkpoints/flight_price-checkpoint.ipynb
theAdarshSrivastava/Flight_Fare_Prediction-
--- Handling Categorical DataOne can find many ways to handle categorical data. Some of them categorical data are,1. **Nominal data** --> data are not in any order --> **OneHotEncoder** is used in this case2. **Ordinal data** --> data are in order --> **LabelEncoder** is used in this case
train_data["Airline"].value_counts() # From graph we can see that Jet Airways Business have the highest Price. # Apart from the first Airline almost all are having similar median # Airline vs Price sns.catplot(y = "Price", x = "Airline", data = train_data.sort_values("Price", ascending = False), kind="boxen", height =...
_____no_output_____
MIT
.ipynb_checkpoints/flight_price-checkpoint.ipynb
theAdarshSrivastava/Flight_Fare_Prediction-
--- Test set
test_data = pd.read_excel(r"/home/adarshsrivastava/Github/Flight_Fare_Prediction-/dataset/Test_set.xlsx") test_data.head() # Preprocessing print("Test data Info") print("-"*75) print(test_data.info()) print() print() print("Null values :") print("-"*75) test_data.dropna(inplace = True) print(test_data.isnull().sum()...
_____no_output_____
MIT
.ipynb_checkpoints/flight_price-checkpoint.ipynb
theAdarshSrivastava/Flight_Fare_Prediction-
--- Feature SelectionFinding out the best feature which will contribute and have good relation with target variable.Following are some of the feature selection methods,1. **heatmap**2. **feature_importance_**3. **SelectKBest**
data_train.shape data_train.columns X = data_train.loc[:, ['Total_Stops', 'Journey_day', 'Journey_month', 'Dep_hour', 'Dep_min', 'Arrival_hour', 'Arrival_min', 'Duration_hours', 'Duration_mins', 'Airline_Air India', 'Airline_GoAir', 'Airline_IndiGo', 'Airline_Jet Airways', 'Airline_Jet Airways Busi...
_____no_output_____
MIT
.ipynb_checkpoints/flight_price-checkpoint.ipynb
theAdarshSrivastava/Flight_Fare_Prediction-
Fitting model using Random Forest1. Split dataset into train and test set in order to prediction w.r.t X_test2. If needed do scaling of data * Scaling is not done in Random forest3. Import model4. Fit the data5. Predict w.r.t X_test6. In regression check **RSME** Score7. Plot graph
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42) from sklearn.ensemble import RandomForestRegressor rf = RandomForestRegressor() rf.fit(X_train, y_train) y_pred=rf.predict(X_test) rf.score(X_train,y_train) rf.score(X_test,...
_____no_output_____
MIT
.ipynb_checkpoints/flight_price-checkpoint.ipynb
theAdarshSrivastava/Flight_Fare_Prediction-
Berater Environment v5 Changes from v4 1. encode observation to local one 1. non existing connection has highest penalty next steps 1. use complex customer graph 1. per episode set certain rewards to 0 to simulate different customers per consultant 1. make sure things generalize well Installation (required f...
!pip install git+https://github.com/openai/baselines >/dev/null !pip install gym >/dev/null
_____no_output_____
MIT
notebooks/rl/berater-v5.ipynb
subodhchhabra/ai
Environment
import numpy import gym from gym.utils import seeding from gym import spaces def state_name_to_int(state): state_name_map = { 'S': 0, 'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'K': 9, 'L': 10, 'M':...
_____no_output_____
MIT
notebooks/rl/berater-v5.ipynb
subodhchhabra/ai
Try out Environment
BeraterEnv.showStep = True BeraterEnv.showDone = True env = BeraterEnv() print(env) observation = env.reset() print(observation) for t in range(1000): action = env.action_space.sample() observation, reward, done, info = env.step(action) if done: print("Episode finished after {} timesteps".format(t...
<BeraterEnv instance> [ 0. 900. 600. 800. -1000.] Episode: 0 Step: 1 S --0-> A R= 0.30 totalR= 0.30 cost= 100 customerR=1000 optimum=3000 Episode: 0 Step: 2 A --3-> A R=-0.33 totalR=-0.03 cost=1000 customerR= 0 optimum=3000 Episode: 0 Step: 3 A --1-> C R= 0.20 totalR= 0.17 cost= 40...
MIT
notebooks/rl/berater-v5.ipynb
subodhchhabra/ai
Train model* 0.73 would be perfect total reward
import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) print(tf.__version__) !rm -r logs !mkdir logs !mkdir logs/berater # https://github.com/openai/baselines/blob/master/baselines/deepq/experiments/train_pong.py # log_dir = logger.get_dir() log_dir = '/content/logs/berater/' import gym from baselines impo...
Logging to /tmp/openai-2019-01-03-11-18-00-870090 ------------------------------------- | approxkl | 0.0015796605 | | clipfrac | 0.0 | | eplenmean | 11.2 | | eprewmean | -0.6935 | | explained_variance | -0.785 | | fps | 159 | | nu...
MIT
notebooks/rl/berater-v5.ipynb
subodhchhabra/ai
Visualizing Resultshttps://github.com/openai/baselines/blob/master/docs/viz/viz.ipynb
!ls -l $log_dir from baselines.common import plot_util as pu results = pu.load_results(log_dir) import matplotlib.pyplot as plt import numpy as np r = results[0] # plt.ylim(-1, 1) # plt.plot(np.cumsum(r.monitor.l), r.monitor.r) plt.plot(np.cumsum(r.monitor.l), pu.smooth(r.monitor.r, radius=100))
_____no_output_____
MIT
notebooks/rl/berater-v5.ipynb
subodhchhabra/ai
Enjoy model
import numpy as np observation = env.reset() state = np.zeros((1, 2*128)) dones = np.zeros((1)) BeraterEnv.showStep = True BeraterEnv.showDone = False for t in range(1000): actions, _, state, _ = model.step(observation, S=state, M=dones) observation, reward, done, info = env.step(actions[0]) if done: ...
_____no_output_____
MIT
notebooks/rl/berater-v5.ipynb
subodhchhabra/ai
Solving Linear Equations with Quantum Circuits Ax = b Attempt to replicate the following paper ![image.png](attachment:image.png) Algorithm for a simpler 2 x 2 example![image.png](attachment:image.png) ![image.png](attachment:image.png) $\newcommand{\ket}[1]{\left|{1}\right\rangle}$$\newcommand{\bra}[1]{\left\langle{1...
#Solving a linear system of equation for 2 dimensional equantion of the form Ax = b ### code specific initialization (importing libraries) import matplotlib.pyplot as plt %matplotlib inline import numpy as np from math import * import scipy # importing Qiskit from qiskit import IBMQ, BasicAer #from qiskit.providers.i...
_____no_output_____
MIT
HHL.ipynb
bluefoxZero/Solving-Linear-Equations-Quantumly
MCMC sampling using the emcee package IntroductionThe goal of Markov Chain Monte Carlo (MCMC) algorithms is to approximate the posterior distribution of your model parameters by random sampling in a probabilistic space. For most readers this sentence was probably not very helpful so here we'll start straight with and ...
%matplotlib inline import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") import numpy as np import astropy.units as u from astropy.coordinates import SkyCoord from gammapy.irf import load_cta_irfs from gammapy.maps import WcsGeom, MapAxis from gammapy.modeling.models import ( ExpCutoffP...
_____no_output_____
BSD-3-Clause
docs/tutorials/mcmc_sampling.ipynb
JohannesBuchner/gammapy
Simulate an observationHere we will start by simulating an observation using the `simulate_dataset` method.
irfs = load_cta_irfs( "$GAMMAPY_DATA/cta-1dc/caldb/data/cta/1dc/bcf/South_z20_50h/irf_file.fits" ) observation = Observation.create( pointing=SkyCoord(0 * u.deg, 0 * u.deg, frame="galactic"), livetime=20 * u.h, irfs=irfs, ) # Define map geometry axis = MapAxis.from_edges( np.logspace(-1, 2, 15), un...
_____no_output_____
BSD-3-Clause
docs/tutorials/mcmc_sampling.ipynb
JohannesBuchner/gammapy
Estimate parameter correlations with MCMCNow let's analyse the simulated data.Here we just fit it again with the same model we had before as a starting point.The data that would be needed are the following: - counts cube, psf cube, exposure cube and background modelLuckily all those maps are already in the Dataset obj...
print(dataset) # Define the free parameters and min, max values parameters = dataset.models.parameters parameters["sigma"].frozen = True parameters["lon_0"].frozen = True parameters["lat_0"].frozen = True parameters["amplitude"].frozen = False parameters["index"].frozen = False parameters["lambda_"].frozen = False p...
_____no_output_____
BSD-3-Clause
docs/tutorials/mcmc_sampling.ipynb
JohannesBuchner/gammapy
Plot the resultsThe MCMC will return a sampler object containing the trace of all walkers.The most important part is the chain attribute which is an array of shape:_(nwalkers, nrun, nfreeparam)_The chain is then used to plot the trace of the walkers and estimate the burnin period (the time for the walkers to reach a s...
plot_trace(sampler, dataset) plot_corner(sampler, dataset, nburn=50)
_____no_output_____
BSD-3-Clause
docs/tutorials/mcmc_sampling.ipynb
JohannesBuchner/gammapy
Plot the model dispersionUsing the samples from the chain after the burn period, we can plot the different models compared to the truth model. To do this we need to the spectral models for each parameter state in the sample.
emin, emax = [0.1, 100] * u.TeV nburn = 50 fig, ax = plt.subplots(1, 1, figsize=(12, 6)) for nwalk in range(0, 6): for n in range(nburn, nburn + 100): pars = sampler.chain[nwalk, n, :] # set model parameters par_to_model(dataset, pars) spectral_model = dataset.models["source"].spe...
_____no_output_____
BSD-3-Clause
docs/tutorials/mcmc_sampling.ipynb
JohannesBuchner/gammapy
Fun ZoneNow that you have the sampler chain, you have in your hands the entire history of each walkers in the N-Dimensional parameter space. You can for example trace the steps of each walker in any parameter space.
# Here we plot the trace of one walker in a given parameter space parx, pary = 0, 1 plt.plot(sampler.chain[0, :, parx], sampler.chain[0, :, pary], "ko", ms=1) plt.plot( sampler.chain[0, :, parx], sampler.chain[0, :, pary], ls=":", color="grey", alpha=0.5, ) plt.xlabel("Index") plt.ylabel("Amplitud...
_____no_output_____
BSD-3-Clause
docs/tutorials/mcmc_sampling.ipynb
JohannesBuchner/gammapy
PeVatrons in CTA ?Now it's your turn to play with this MCMC notebook. For example to test the CTA performance to measure a cutoff at very high energies (100 TeV ?).After defining your Skymodel it can be as simple as this :
# dataset = simulate_dataset(model, geom, pointing, irfs) # sampler = run_mcmc(dataset) # plot_trace(sampler, dataset) # plot_corner(sampler, dataset, nburn=200)
_____no_output_____
BSD-3-Clause
docs/tutorials/mcmc_sampling.ipynb
JohannesBuchner/gammapy
Pix2PixHD*Please note that this is an optional notebook, meant to introduce more advanced concepts if you're up for a challenge, so don't worry if you don't completely follow!*It is recommended that you should already be familiar with: - Residual blocks, from [Deep Residual Learning for Image Recognition](https://arxi...
import torch import torch.nn as nn import torch.nn.functional as F class ResidualBlock(nn.Module): ''' ResidualBlock Class Values channels: the number of channels throughout the residual block, a scalar ''' def __init__(self, channels): super().__init__() self.layers = nn....
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
Multiscale Generator: Generating at multiple scales (resolutions)The Pix2PixHD generator is comprised of two separate subcomponent generators: $G_1$ is called the global generator and operates at low resolution (1024 x 512) to transfer styles. $G_2$ is the local enhancer and operates at high resolution (2048 x 1024) t...
class GlobalGenerator(nn.Module): ''' GlobalGenerator Class: Implements the global subgenerator (G1) for transferring styles at lower resolutions. Values: in_channels: the number of input channels, a scalar out_channels: the number of output channels, a scalar base_channels: the ...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
Local Enhancer Subgenerator ($G_2$)And now onto the local enhancer ($G_2$)! Recall that the local enhancer uses (a pretrained) $G_1$ as part of its architecture. Following our earlier notation, recall that the residual connections from the last layers of $G_2^{(F)}$ and $G_1^{(B)}$ are added together and passed throug...
class LocalEnhancer(nn.Module): ''' LocalEnhancer Class: Implements the local enhancer subgenerator (G2) for handling larger scale images. Values: in_channels: the number of input channels, a scalar out_channels: the number of output channels, a scalar base_channels: the number...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
And voilà! You now have modules for both the global subgenerator and local enhancer subgenerator! Multiscale Discriminator: Discriminating at different scales too!Pix2PixHD uses 3 separate subcomponents (subdiscriminators $D_1$, $D_2$, and $D_3$) to generate predictions. They all have the same architectures but $D_2$ ...
class Discriminator(nn.Module): ''' Discriminator Class Implements the discriminator class for a subdiscriminator, which can be used for all the different scales, just with different argument values. Values: in_channels: the number of channels in input, a scalar base_channels: the n...
torch.Size([1, 64, 129, 129]) torch.Size([1, 128, 65, 65]) torch.Size([1, 256, 33, 33]) torch.Size([1, 1, 35, 35])
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
Now you're ready to implement the multiscale discriminator in full! This puts together the different subdiscriminator scales.
class MultiscaleDiscriminator(nn.Module): ''' MultiscaleDiscriminator Class Values: in_channels: number of input channels to each discriminator, a scalar base_channels: number of channels in first convolutional layer, a scalar n_layers: number of downsampling layers in each discrimin...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
Instance Boundary Map: Learning boundaries between instancesHere's a new method that adds additional information as conditional input!The authors observed that previous approaches have typically taken in a label map (aka. segmentation map) that labels all the pixels to be of a certain class (i.e. car) but doesn't diff...
class Encoder(nn.Module): ''' Encoder Class Values: in_channels: number of input channels to each discriminator, a scalar out_channels: number of channels in output feature map, a scalar base_channels: number of channels in first convolutional layer, a scalar n_layers: number...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
Additional Loss FunctionsIn addition to the architectural and feature-map enhancements, the authors also incorporate a feature matching loss based on the discriminator. Essentially, they output intermediate feature maps at different resolutions from the discriminator and try to minimize the difference between the real...
import torchvision.models as models class VGG19(nn.Module): ''' VGG19 Class Wrapper for pretrained torchvision.models.vgg19 to output intermediate feature maps ''' def __init__(self): super().__init__() vgg_features = models.vgg19(pretrained=True).features self.f1 = nn.Seq...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
Training Pix2PixHDYou now have the Pix2PixHD model coded up! All you have to do now is prepare your dataset. Pix2PixHD is trained on the Cityscapes dataset, which unfortunately requires registration. You'll have to download the dataset and put it in your `data` folder to initialize the dataset code below.Specifically,...
import os import numpy as np import torchvision.transforms as transforms from PIL import Image def scale_width(img, target_width, method): ''' Function that scales an image to target_width while retaining aspect ratio. ''' w, h = img.size if w == target_width: return img target_height = target...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
Now initialize everything you'll need for training. Don't be worried if there looks like a lot of random code, it's all stuff you've seen before!
from tqdm import tqdm from torch.utils.data import DataLoader n_classes = 35 # total number of object classes rgb_channels = n_features = 3 device = 'cuda' train_dir = ['data'] epochs = 200 # total number of train epochs decay_after = 100 # number of epochs with consta...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
And now the training loop, which is pretty much the same between the two phases:
from torchvision.utils import make_grid import matplotlib.pyplot as plt # Parse torch version for autocast # ###################################################### version = torch.__version__ version = tuple(int(n) for n in version.split('.')[:-1]) has_autocast = version >= (1, 6) # ###################################...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
And now you can train your models! Remember to set the local enhancer subgenerator to the global subgenerator that you train in the first phase.In their official repository, the authors don't continue to train the encoder. Instead, they precompute all feature maps upsample them, and concatenate this to the input to the...
# Phase 1: Low Resolution ####################################################################### train( dataloader1, [encoder, generator1, discriminator1], [g1_optimizer, d1_optimizer], [g1_scheduler, d1_scheduler], device, ) # Phase 2: High Resolution ############################################...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
Inference with Pix2PixHDRecall that in inference time, the encoder feature maps from training are saved and clustered with K-means by object class. Again, you'll have to download the Cityscapes dataset into your `data` folder and then run these functions.
from sklearn.cluster import KMeans # Encode features by class label features = {} for (x, _, inst, _) in tqdm(dataloader2): x = x.to(device) inst = inst.to(device) area = inst.size(2) * inst.size(3) # Get pooled feature map with torch.no_grad(): feature_map = encoder(x, inst) for i in...
100%|██████████| 174/174 [02:07<00:00, 1.36it/s]
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
After getting the encoded feature centroids per class, you can now run inference! Remember that the generator is trained to take in a concatenation of the semantic label map, instance boundary map, and encoded feature map.Congrats on making it to the end of this complex notebook! Have fun with this powerful model and b...
def infer(label_map, instance_map, boundary_map): # Sample feature vector centroids b, _, h, w = label_map.shape feature_map = torch.zeros((b, n_features, h, w), device=device).to(label_map.dtype) for i in torch.unique(instance_map): label = i if i < 1000 else i // 1000 label = int(labe...
_____no_output_____
MIT
C3W2_Pix2PixHD_(Optional).ipynb
akanametov/Pix2PixHD
Calibrating Traditional Methods In this notebook, we show how to calibrate a $\mathcal{J}$-invariant denoiser, and compare its performancewith the original denoiser.
%load_ext autoreload %autoreload 2 %matplotlib inline import sys sys.path.append("..") import numpy as np import matplotlib.pyplot as plt from skimage.morphology import disk from skimage.filters import gaussian, median from skimage import data, img_as_float, img_as_ubyte from skimage.color import gray2rgb from skimage....
/Users/josh/anaconda3/envs/pytorch/lib/python3.6/site-packages/skimage/util/dtype.py:141: UserWarning: Possible precision loss when converting from float64 to uint8 .format(dtypeobj_in, dtypeobj_out))
MIT
notebooks/Calibration - Figure.ipynb
XinweiYu/noise2self
We begin by comparing an ordinary median filter to a "donut" median filter, with the center removed.
def mask_center(x): x[len(x)//2,len(x)//2] = 0 return x plot_images([1-disk(4), 1-mask_center(disk(4))]) cm = plt.get_cmap("tab10") orange_regular_disk = (1 - disk(4))[:,:,np.newaxis] + (disk(4))[:,:,np.newaxis]*np.array(cm(1)[:-1])[np.newaxis, np.newaxis] blue_donut_disk = (1 - mask_center(disk(4)))[:,:,np.new...
_____no_output_____
MIT
notebooks/Calibration - Figure.ipynb
XinweiYu/noise2self
Conversion to J-invariance Let $f$ be a classical denoiser, and consider some partition $\mathcal{J}$ of the pixels. Let $s(x)$ be the function replacing each pixel with the average of its neighbors. Then the function $g$ defined by$g(x)_J := f_\theta(\mathbf{1}_{J}\cdot s(x) + \mathbf{1}_{J^c}\cdot x)_J,$will be $J$-...
from scipy.signal import convolve2d def interpolate_image(x, conv_filter=None): # use the mean of 4-connected neighbor to filter the image. if conv_filter is None: conv_filter = np.array([[0, 0.25, 0], [0.25, 0, 0.25], [0, 0.25, 0]]) return convolve2d(x, conv_filter, mode = 'same') def generate_mask...
_____no_output_____
MIT
notebooks/Calibration - Figure.ipynb
XinweiYu/noise2self
Wavelet
from skimage.restoration import denoise_wavelet sigma_range = np.arange(0.08, 0.3, 0.03) reconstructions = [denoise_wavelet(noisy_image, sigma = sigma, mode='hard', multichannel = False) for sigma in sigma_range] reconstructions_mask = [reconstruct(noisy_image, 4, lambda x: ...
_____no_output_____
MIT
notebooks/Calibration - Figure.ipynb
XinweiYu/noise2self
Basic run of NL-Means NL-Means
from skimage.restoration import denoise_nl_means, estimate_sigma # non-local mean denoise. sigma_est = np.mean(estimate_sigma(noisy_image, multichannel=False)) print(sigma_est/255) patch_kw = dict(patch_size=5, # 5x5 patches patch_distance=6, # 13x13 search area multichannel=True)...
_____no_output_____
MIT
notebooks/Calibration - Figure.ipynb
XinweiYu/noise2self
Which method is best?
min(loss_mask_nl), min(loss_mask_wavelet), min(loss_mask_med) min(mse_mask_nl), min(mse_mask_wavelet), min(mse_mask_med) max(psnr_mask_nl), max(psnr_mask_wavelet), max(psnr_mask_med) show(get_inset(reconstructions_nl_mask[np.argmin(loss_mask_nl)])) show(get_inset(reconstructions_mask[np.argmin(loss_mask_wavelet)]))
_____no_output_____
MIT
notebooks/Calibration - Figure.ipynb
XinweiYu/noise2self
Shrinkage Given two uncorrelated and unbiased estimators $u$ and $v$ of some quantity $y$, we may form a linear combination: $\lambda u + (1 - \lambda)v.$The variance of this estimator is$\lambda^2 U + (1 - \lambda)^2 V,$where $U$ and $V$ are the variances of $u$ and $v$ respectively. This expression is minimized a...
log10 x = log e x / log e 10 image_float = img_as_float(image) noisy_image_float = img_as_float(noisy_image) noise_var = mse(noisy_image_float, image_float) idx = np.argmin(loss_mask_wavelet) y_pred = reconstructions_mask[idx] total_var = loss_mask_wavelet[idx] idx = np.argmin(loss_mask_nl) y_pred = reconstructions_nl_...
_____no_output_____
MIT
notebooks/Calibration - Figure.ipynb
XinweiYu/noise2self
Stock Price PredictorThis is a Jupyter notebook that you can use to get prediction of adjusted close stock price per the specified day range after the last day from the training data set. The prediction is made by training the machine learning model with historical trade of the stock data. This is the result of study f...
stock_list = 'ASK.BK GOOGL' training_data_start_date = '08/05/2000' training_data_end_date = '13/05/2020' # ------ DO NOT CHANGE CODE BELOW THIS LINE -------- !pip install yfinance import yfinance as yf import os,sys sys.path.append(os.path.abspath("/content/stock_predictor.py")) from stock_predictor import * tra...
Collecting yfinance Downloading https://files.pythonhosted.org/packages/c2/31/8b374a12b90def92a4e27d0fc595fc43635f395984e36a075244d98bd265/yfinance-0.1.54.tar.gz Requirement already satisfied: pandas>=0.24 in /usr/local/lib/python3.6/dist-packages (from yfinance) (1.0.3) Requirement already satisfied: numpy>=1.15 in ...
MIT
stock_predictor.ipynb
pathompong-y/stock_predictor
How to use (cont.)4. You can query for the predicted stock price by adding the list of stock symbol in `query_list`. The symbol must be subset of `stock_list` that you provided in step 1.5. `prediction_range` is the day range of price prediction after `end_date` in step 2. For example, if `end_date` is 15/05/2020 and `...
query_list = 'ASK.BK GOOGL' prediction_range = 5 # ------ DO NOT CHANGE CODE BELOW THIS LINE -------- query_price(query_list,prediction_range)
ASK.BK price prediction for 5 days : [16.706566 16.835562 16.86699 16.988611 16.975838] Mean square error = [2.76239613] % GOOGL price prediction for 5 days : [1341.0127 1340.9868 1347.199 1344.8762 1349.1017] Mean square error = [268.90700931] %
MIT
stock_predictor.ipynb
pathompong-y/stock_predictor
$ \newcommand{\bra}[1]{\langle 1|} $$ \newcommand{\ket}[1]{|1\rangle} $$ \newcommand{\braket}[2]{\langle 1|2\rangle} $$ \newcommand{\dot}[2]{ 1 \cdot 2} $$ \newcommand{\biginner}[2]{\left\langle 1,2\right\rangle} $$ \newcommand{\mymatrix}[2]{\left( \begin{array}{1} 2\end{array} \right)} $$ \newcommand{\myvector}[1]{\my...
# let's print all numbers between 0 and 9 for i in range(10): print(i) # range(n) represents the list of all numbers from 0 to n-1 # i is the variable to take the values in the range(n) iteratively: 0,1,...,9 in our example # let's write the same code in two lines for i in range(10): # do not forget to use colon pr...
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [55, 66, 77, 88, 99, 110, 121, 132, 143, 154, 165, 176, 187, 198]
MIT
Bronze/python/Python12_Basics_Loops.ipynb
SevdanurGENC/Quantum-Programming-With-Qiskit
Task 1 Calculate the value of summation $ 3+6+9+\cdots+51 $, and then print the result.Your result should be 459.
# # your solution is here #
_____no_output_____
MIT
Bronze/python/Python12_Basics_Loops.ipynb
SevdanurGENC/Quantum-Programming-With-Qiskit
click for our solution Task 2 $ 3^k $ means $ 3 \cdot 3 \cdot \cdots \cdot 3 $ ($ k $ times) for $ k \geq 2 $. Moreover, $ 3^0 $ is 1 and $ 3^1 = 3 $.Calculate the value of summation $ 3^0 + 3^1 + 3^2 + \cdots + 3^8 $, and then print the result.Your result should be 9841.
# # your solution is here #
_____no_output_____
MIT
Bronze/python/Python12_Basics_Loops.ipynb
SevdanurGENC/Quantum-Programming-With-Qiskit
click for our solution While-loop
# let's calculate the summation 1+2+4+8+...+256 by using a while-loop total = 0 i = 1 #while condition(s): # your_code1 # your_code2 # your_code3 while i < 257: # this loop iterates as long as i is less than 257 total = total + i i = i * 2 # i is doubled in each iteration, and so soon it will be great...
_____no_output_____
MIT
Bronze/python/Python12_Basics_Loops.ipynb
SevdanurGENC/Quantum-Programming-With-Qiskit
Consider the summation $ S(n) = 1+ 2+ 3 + \cdots + n $ for some natural number $ n $.Let's find the minimum value of $ n $ such that $ S(n) \geq 1000 $.While-loop works very well for this task. We can iteratively increase $ n $ and update the value of $ S(n) $. The loop iterates as long as $S(n)$ is less than 10...
# summation and n are zeros at the beginning S = 0 n = 0 while S < 1000: # this loop will stop after S exceeds 999 (S = 1000 or S > 1000) n = n +1 S = S + n # let's print n and S print("n =",n," S =",S)
n = 45 S = 1035
MIT
Bronze/python/Python12_Basics_Loops.ipynb
SevdanurGENC/Quantum-Programming-With-Qiskit
Task 3 Consider the summation $ T(n) = 1 + \dfrac{1}{2} + \dfrac{1}{4}+ \dfrac{1}{8} + \cdots + \dfrac{1}{2^n} $ for some natural number $ n $. Remark that $ T(0) = \dfrac{1}{2^0} = \dfrac{1}{1} = 1 $.This summation can be arbitrarily close to $2$. Find the minimum value of $ n $ such that $ T(n) $ is close to $2$ by ...
# three examples for the operator "less than or equal to" #print (4 <= 5) #print (5 <= 5) #print (6 <= 5) # you may comment out the above three lines and see the results by running this cell # # your solution is here #
_____no_output_____
MIT
Bronze/python/Python12_Basics_Loops.ipynb
SevdanurGENC/Quantum-Programming-With-Qiskit
click for our solution Task 4 Randomly pick number(s) between 0 and 9 until hitting 3, and then print the number of attempt(s).We can use randrange function from random module for randomly picking a number in the given range.
# this is the code for including function randrange into our program from random import randrange # randrange(n) picks a number from the list [0,1,2,...,n-1] randomly #r = randrange(100) #print(r) # # your solution is here #
_____no_output_____
MIT
Bronze/python/Python12_Basics_Loops.ipynb
SevdanurGENC/Quantum-Programming-With-Qiskit
click for our solution Task 5 This task is challenging . It is designed for the usage of double nested loops: one loop inside of the other loop.In the fourth task above, the expected number of attempt(s) to hit number 3 is 10. Do a series of experiments by using your solution for Task 4.Experiment 1: Execute your solu...
# here is a schematic example for double nested loops #for i in range(10): # your_code1 # your_code2 # while j != 7: # your_code_3 # your_code_4 # # your solution is here #
_____no_output_____
MIT
Bronze/python/Python12_Basics_Loops.ipynb
SevdanurGENC/Quantum-Programming-With-Qiskit
[Histogram](https://plotly.com/python/histograms/) 1. importar las librerías + csv con los datos de la encuesta.
# importar librerias import pandas as pd import plotly.express as px from dash import Dash, dcc, html, Input, Output #crear un dataframe con toda la informacion de la encuesta df_csv = pd.read_csv ('../data/survey_results_public2021.csv', index_col = [0]) # El indice sera la columna con el ID de la respuesta df_cs...
_____no_output_____
BSD-3-Clause
old/.ipynb_checkpoints/Histogram2-checkpoint.ipynb
albarrom/GII_O_MA_21.05
2. Preprocesar datos.Tratar las columnas/conjunto de datos para comenzar a crear los gráficos. En este caso Age1stcode
df_csv['Age1stCode'].value_counts()
_____no_output_____
BSD-3-Clause
old/.ipynb_checkpoints/Histogram2-checkpoint.ipynb
albarrom/GII_O_MA_21.05
Para lidiar con rangos de edades, algunos de los cuales tienen texto, se va a calcular una nueva columna con la media de todos ellos.
#se hace una copia del df. df= df_csv.copy() #normalizar todos los datos. df = df[df['Age1stCode'].notna()] #eliminar los nulos df.loc[df["Age1stCode"] == "Younger than 5 years", "Age1stCode"] = "04 - 04 years" #ya hay un 05 anyos en el df. df.loc[df["Age1stCode"] == "Older than 64 years", "Age1stCode"] = "65 - 65...
_____no_output_____
BSD-3-Clause
old/.ipynb_checkpoints/Histogram2-checkpoint.ipynb
albarrom/GII_O_MA_21.05
3. Grafico. En este caso, un diagrama de barras.
app = Dash(__name__) server = app.server #heroku app.layout = html.Div([ html.H1("Tipo de desarrollador", style={'text-align': 'center'}), #cabecero h1. Header #primera mini prueba con un menu desplegable. dcc.Dropdown(id="select_opt", options=[ #el usuario va a ver las label. ...
_____no_output_____
BSD-3-Clause
old/.ipynb_checkpoints/Histogram2-checkpoint.ipynb
albarrom/GII_O_MA_21.05
4. run server
app.run_server(debug=True, use_reloader=False)
Dash is running on http://127.0.0.1:8050/ * Serving Flask app "__main__" (lazy loading) * Environment: production  WARNING: This is a development server. Do not use it in a production deployment.  Use a production WSGI server instead. * Debug mode: on
BSD-3-Clause
old/.ipynb_checkpoints/Histogram2-checkpoint.ipynb
albarrom/GII_O_MA_21.05
How to Build a Personalized Trading Dashboard? > A personalized dashboard to viusalize trading actions and stock development- toc: false- badges: true- comments: true- categories: [data analysis, trading, jupternotebook]
# hide from datetime import datetime, timedelta import altair as alt import numpy as np import pandas as pd import panel as pn import yfinance as yf from altair import datum from utility import * alt.renderers.enable("default") pn.extension("vega") copy_to_post = 1
_____no_output_____
Apache-2.0
_notebooks/2021-02-21-portfolio_analysis.ipynb
jinchao-chen/blog_posts
**Update 11-May**: The [web app](https://share.streamlit.io/jinchao-chen/portfolio-dashboard/streamlit/web_app.py) is now deployed on streamlit. Please check it out and let me know how it works. TL;NR: if you are mainly interested in the codes, here is the link to [GitHub](https://github.com/jinchao-chen/portfolio-das...
# hide fln = "dummy_transactions.csv" transactions = read_transactions(fln) # hide title = '# Trading Dashboard' subtitle = 'A personalized visualization tool for **Trading 212** trading activities and market data' companies = transactions["Ticker"].dropna().unique().tolist() ticker = pn.widgets.Select(name="Company",...
copied
Apache-2.0
_notebooks/2021-02-21-portfolio_analysis.ipynb
jinchao-chen/blog_posts
Answer Key to the Data Wrangling with DataFrames Coding QuizHelpful resources:http://spark.apache.org/docs/latest/api/python/pyspark.sql.html
from pyspark.sql import SparkSession from pyspark.sql.functions import isnan, count, when, col, desc, udf, col, sort_array, asc, avg from pyspark.sql.functions import sum as Fsum from pyspark.sql.window import Window from pyspark.sql.types import IntegerType # 1) import any other libraries you might need # 2) instantia...
_____no_output_____
MIT
Code/Spark/example2/6_dataframe_quiz_solution.ipynb
dSalazar10/Course-Exploring_NoSQL_Databases
Question 1Which page did user id "" (empty string) NOT visit?
df.printSchema() # filter for users with blank user id blank_pages = df.filter(df.userId == '') \ .select(col('page') \ .alias('blank_pages')) \ .dropDuplicates() # get a list of possible pages that could be visited all_pages = df.select('page').dropDuplicates() # find values in all_pages that are not in ...
Submit Upgrade Downgrade Logout Upgrade Settings NextSong Error Save Settings Submit Downgrade
MIT
Code/Spark/example2/6_dataframe_quiz_solution.ipynb
dSalazar10/Course-Exploring_NoSQL_Databases
Question 2 - ReflectWhat type of user does the empty string user id most likely refer to? Perhaps it represents users who have not signed up yet or who are signed out and are about to log in. Question 3How many female users do we have in the data set?
df.filter(df.gender == 'F') \ .select('userId', 'gender') \ .dropDuplicates() \ .count()
_____no_output_____
MIT
Code/Spark/example2/6_dataframe_quiz_solution.ipynb
dSalazar10/Course-Exploring_NoSQL_Databases
Question 4How many songs were played from the most played artist?
df.filter(df.page == 'NextSong') \ .select('Artist') \ .groupBy('Artist') \ .agg({'Artist':'count'}) \ .withColumnRenamed('count(Artist)', 'Artistcount') \ .sort(desc('Artistcount')) \ .show(1)
+--------+-----------+ | Artist|Artistcount| +--------+-----------+ |Coldplay| 83| +--------+-----------+ only showing top 1 row
MIT
Code/Spark/example2/6_dataframe_quiz_solution.ipynb
dSalazar10/Course-Exploring_NoSQL_Databases
Question 5 (challenge)How many songs do users listen to on average between visiting our home page? Please round your answer to the closest integer.
# TODO: filter out 0 sum and max sum to get more exact answer function = udf(lambda ishome : int(ishome == 'Home'), IntegerType()) user_window = Window \ .partitionBy('userID') \ .orderBy(desc('ts')) \ .rangeBetween(Window.unboundedPreceding, 0) cusum = df.filter((df.page == 'NextSong') | (df.page == 'Ho...
+------------------+ |avg(count(period))| +------------------+ | 6.898347107438017| +------------------+
MIT
Code/Spark/example2/6_dataframe_quiz_solution.ipynb
dSalazar10/Course-Exploring_NoSQL_Databases
Exploratory Data Analysis Importing the necessary libraries
import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt import re import nltk print(pd.__version__) print(np.__version__) print(nltk.__version__) print(matplotlib.__version__) path_to_input = "../input/" # drop first column containing sr nos df = pd.read_csv(path_to_input + "mtsamples...
(4999, 5)
Apache-2.0
EDA/EDA-1.ipynb
ekdnam/NLP-Summit-Hackathon
There are 4999 records in the dataset
df_v1 = df[['medical_specialty', 'sample_name', 'transcription', 'keywords']] df_v1.head() print(df_v1['medical_specialty'].value_counts()) print("Unique records in medical_specialty :" + str(df_v1['medical_specialty'].value_counts().size)) df_v1['sample_name'].value_counts()
_____no_output_____
Apache-2.0
EDA/EDA-1.ipynb
ekdnam/NLP-Summit-Hackathon
Dropping rows having na values
df_v1 = df_v1.dropna() print(df_v1.shape[0])
3898
Apache-2.0
EDA/EDA-1.ipynb
ekdnam/NLP-Summit-Hackathon
Analysis> The analysis functions help a modeler quickly run a full time series analysis. An analysis consists of:1. Initializing a DGLM, using `define_dglm`.2. Updating the model coefficients at each time step, using `dglm.update`.3. Forecasting at each time step between `forecast_start` and `forecast_end`, using `dgl...
#hide #exporti import numpy as np import pandas as pd from pybats.define_models import define_dglm, define_dcmm, define_dbcm, define_dlmm from pybats.shared import define_holiday_regressors from collections.abc import Iterable
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
Analysis for a DGLM
#export def analysis(Y, X=None, k=1, forecast_start=0, forecast_end=0, nsamps=500, family = 'normal', n = None, model_prior = None, prior_length=20, ntrend=1, dates = None, holidays = [], seasPeriods = [], seasHarmComponents = [], latent_factor = None, ne...
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
This function is core to the PyBATS package, because it allows a modeler to easily run a full time series analysis in one step. Below is a quick example of analysis of quarterly inflation in the US using a normal DLM. We'll start by loading in the data:
from pybats.shared import load_us_inflation from pybats.analysis import analysis import pandas as pd from pybats.plot import plot_data_forecast from pybats.point_forecast import median import matplotlib.pyplot as plt from pybats.loss_functions import MAPE data = load_us_inflation() pd.concat([data.head(3), data.tail(3...
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
And then running an analysis. We're going to use the previous (lag-1) value of inflation as a predictor.
forecast_start = '1990-Q1' forecast_end = '2014-Q3' X = data.Inflation.values[:-1] mod, samples = analysis(Y = data.Inflation.values[1:], X=X, family="normal", k = 1, prior_length = 12, forecast_start = forecast_start, forecast_end = forecast_end, ...
beginning forecasting
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
A couple of things to note here:- `forecast_start` and `forecast_end` were specified as elements in the `dates` vector. You can also specify forecast_start and forecast_end by row numbers in `Y`, and avoid providing the `dates` argument.- `ntrend=2` creates a model with an intercept and a local slope term, and `deltren...
mod.get_coef()
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
It's clear that the lag-1 regression term is dominant, with a mean of $0.92$. The only other large coefficient is the intercept, with a mean of $0.10$.The seasonal coefficients turned out to be very small. Most likely this is because the publicly available dataset for US inflation is pre-adjusted for seasonality.The fo...
forecast = median(samples) # Plot the 1-quarter ahead forecast h = 1 start = data[data.Date == forecast_start].index[0] + h end = data[data.Date == forecast_end].index[0] + h + 1 fig, ax = plt.subplots(figsize=(12, 6)) plot_data_forecast(fig, ax, y = data[start:end].Inflation.values, f = forecast[:...
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
We can see that the forecasts are quite good, and nearly all of the observations fall within the $95\%$ credible interval.There's also a clear pattern - the forecasts look as if they're shifted forward from the data by 1 step. This is because the lag-1 predictor is very strong, with a coefficient mean of $0.91$. The mo...
MAPE(data[start:end].Inflation.values, forecast[:,0]).round(1) assert(MAPE(data[start:end].Inflation.values, forecast[:,0]).round(0) <= 15)
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
Finally, we can use the returned model to forecast $1-$step ahead to Q1 2015, which is past the end of the dataset. We need the `X` value to forecast into the future. Luckily, in this model the predictor `X` is simply the previous value of Inflation from Q4 2014.
x_future = data.Inflation.iloc[-1] one_step_forecast_samples = mod.forecast_marginal(k=1, X=x_future, nsamps=1000000)
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
From here, we can find the mean and standard deviation of the forecast for next quarter's inflation:
print('Mean: ' + str(np.mean(one_step_forecast_samples).round(2))) print('Std Dev: ' + str(np.std(one_step_forecast_samples).round(2)))
Mean: 1.21 Std Dev: 0.29
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
We can also plot the full forecast distribution for Q1 2015:
fig, ax = plt.subplots(figsize=(10,6)) ax.hist(one_step_forecast_samples.reshape(-1), bins=200, alpha=0.3, color='b', density=True, label='Forecast Distribution'); ax.vlines(x=np.mean(one_step_forecast_samples), ymin=0, ymax=ax.get_ylim()[1], label='Forecast Mean'); ax.set_title('1-S...
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
Analysis for a DCMM
#export def analysis_dcmm(Y, X=None, k=1, forecast_start=0, forecast_end=0, nsamps=500, rho=.6, model_prior=None, prior_length=20, ntrend=1, dates=None, holidays=[], seasPeriods=[], seasHarmComponents=[], latent_factor=None, new_...
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
`analysis_dcmm` works identically to the standard `analysis`, but is specialized for a DCMM.The observations must be integer counts, which are modeled as a combination of a Poisson and Bernoulli DGLM. Typically a DCMM is equally good as a Poisson DGLM for modeling series with consistently large integers, while being si...
#export def analysis_dbcm(Y_transaction, X_transaction, Y_cascade, X_cascade, excess, k, forecast_start, forecast_end, nsamps = 500, rho = .6, model_prior=None, prior_length=20, ntrend=1, dates=None, holidays = [], latent_factor = None, new_latent_...
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
`analysis_dbcm` works identically to the standard `analysis`, but is specialized for a DBCM.Separate data must be specified for the DCMM on transactions, `y_transaction` and `X_transaction`, the binomial cascade,`y_cascade`, `X_cascade`, and any excess counts, `excess`.Note that by default, all simulated forecasts made...
#export def analysis_dlmm(Y, X, k=1, forecast_start=0, forecast_end=0, nsamps=500, rho=.6, model_prior=None, prior_length=20, ntrend=1, dates=None, holidays=[], seasPeriods=[], seasHarmComponents=[], latent_factor=None, new_laten...
_____no_output_____
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
`analysis_dlmm` works identically to the standard `analysis`, but is specialized for a DLMM. `analysis_dlmm` returns the model coefficients for the Normal DLM portion of the model only.The observations are continuous and are modeled as a combination of a Bernoulli DGLM and a Normal DLM. Note that by default, all simul...
#hide from nbdev.export import notebook2script notebook2script()
Converted 00_dglm.ipynb. Converted 01_update.ipynb. Converted 02_forecast.ipynb. Converted 03_define_models.ipynb. Converted 04_seasonal.ipynb. Converted 05_analysis.ipynb. Converted 06_conjugates.ipynb. Converted 07_point_forecast.ipynb. Converted 08_loss_functions.ipynb. Converted 09_plot.ipynb. Converted 10_shared.i...
Apache-2.0
nbs/05_analysis.ipynb
royshadmon/pybats
Support Vector MachinesSupport Vector Machines (SVM) are an extension of the linear methods that attempt to separate classes with hyperplans.These extensions come in three steps:1. When classes are linearly separable, maximize the margin between the two classes2. When classes are not linearly separable, maximize the m...
import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as pltcolors from sklearn import linear_model, svm, discriminant_analysis, metrics from scipy import optimize import seaborn as sns
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
Helpers
def plotLine(ax, xRange, w, x0, label, color='grey', linestyle='-', alpha=1.): """ Plot a (separating) line given the normal vector (weights) and point of intercept """ if type(x0) == int or type(x0) == float or type(x0) == np.float64: x0 = [0, -x0 / w[1]] yy = -(w[0] / w[1]) * (xRange - x0[0]) + x0...
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
The data modelLet's use a simple model with two Gaussians that are faraway in order to be separable
colors = ['blue','red'] cmap = pltcolors.ListedColormap(colors) nFeatures = 2 N = 100 def generateBatchBipolar(n, mu=0.5, sigma=0.2): """ Two gaussian clouds on each side of the origin """ X = np.random.normal(mu, sigma, (n, 2)) yB = np.random.uniform(0, 1, n) > 0.5 # y is in {-1, 1} y = 2. * yB - 1...
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
1. Maximum margin separator The following explanation is about the binary classification but generalizes to more classes.Let $X$ be the matrix of $n$ samples of the $p$ features. We want to separate the two classes of $y$ with an hyperplan (a straight line in 2D, that is $p=2$). The separation equation is:$$ w^T x + b...
xTrain0, yTrain0 = generateBatchBipolar(N, sigma=0.2) plotSvm(xTrain0, yTrain0)
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
Implementation of the Maximum margin separator $$\mathcal{L}_d = \sum_{i=0}^n \alpha_i - \frac 12 \sum_{i=0}^n \sum_{k=0}^n \alpha_i \alpha_k y_i y_k x_i^T x_k $$__Subject to :__- $\sum_{i=0}^n \alpha_i y_i = \langle \alpha, y \rangle = 0$- $\alpha_i \ge 0, i\in 1..n$The classifier is built on the scipy.optimize.minim...
class MaxMarginClassifier: def __init__(self): self.alpha = None self.w = None self.supportVectors = None def fit(self, X, y): N = len(y) # Gram matrix of (X.y) Xy = X * y[:, np.newaxis] GramXy = np.matmul(Xy, Xy.T) # Lagrange dual probl...
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
Reference: - https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.htmlscipy.optimize.minimize
model00 = MaxMarginClassifier() model00.fit(xTrain0, yTrain0) model00.w, model00.intercept fig, ax = plt.subplots(1, figsize=(12, 7)) plotSvm(xTrain0, yTrain0, model00.supportVectors, model00.w, model00.intercept, label='Training', ax=ax)
Number of support vectors = 3
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
Maximum margin classifier using Scikit Learn (SVC)SVC is used in place of LinearSVC as the support vectors are provided. These vectors are displayed in the graph here below.Set a high $C$ parameter to disable soft margin
model01 = svm.SVC(kernel='linear', gamma='auto', C = 1e6) model01.fit(xTrain0, yTrain0) model01.coef_[0], model01.intercept_[0] fig, ax = plt.subplots(1, figsize=(11, 7)) plotSvm(xTrain0, yTrain0, model01.support_vectors_, model01.coef_[0], model01.intercept_[0], label='Training', ax=ax)
Number of support vectors = 3
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
The two implementations of the linear SVM agree on the ceofficients and margin. Good ! Comparison of the maximum margin classifier to the Logistic regression and Linear Discriminant Analysis (LDA)Logistic regression is based on the linear regression that is the computation of the square error of any point $x$ to the s...
model02 = linear_model.LogisticRegression(solver='lbfgs') model02.fit(xTrain0, yTrain0) model02.coef_[0], model02.intercept_[0] model03 = discriminant_analysis.LinearDiscriminantAnalysis(solver='svd') model03.fit(xTrain0, yTrain0) model03.coef_[0], model03.intercept_[0]
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
We observe that the coefficients of the three models are very different in amplitude but globally draw a separator line with slope $-\frac \pi4$ in the 2D plan
fig, ax = plt.subplots(1, figsize=(11, 7)) plotSvm(xTrain0, yTrain0, w=model01.coef_[0], intercept=model01.intercept_[0], separatorLabel='Max Margin SVM', label='Training', ax=ax) xx = np.array([-1., 1.]) plotLine(ax, xx, w=model02.coef_[0], x0=model02.intercept_[0], label='Logistic', color='g') plotLine(ax, x...
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
2. Soft Margin Linear SVM for non separable classesThe example above has little interest as the separation is trivial.Using the same SVM implementation on a non separable case would not be possible, the solver would fail.Here comes the soft margin: some $x_i$ are allowed to lie in between the two margin bars. The __So...
xTrain1, yTrain1 = generateBatchBipolar(N, mu=0.3, sigma=0.3) plotSvm(xTrain1, yTrain1, label='Training')
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
Custom implementationChanges to the Maximum margin classifier are identified by " <---"
class LinearSvmClassifier: def __init__(self, C): self.C = C # <--- self.alpha = None self.w = None self.supportVectors = None def fit(self, X, y): N = len(y) # Gram matrix of (X.y) Xy = X * y[:, np.newaxis] ...
Number of support vectors = 38
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
Linear SVM using Scikit Learn
model11 = svm.SVC(kernel='linear', gamma='auto', C = 1) model11.fit(xTrain1, yTrain1) model11.coef_[0], model11.intercept_[0] fig, ax = plt.subplots(1, figsize=(11, 7)) plotSvm(xTrain1, yTrain1, model11.support_vectors_, model11.coef_[0], model11.intercept_[0], label='Training', ax=ax)
Number of support vectors = 38
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
With the soft margin, the support vectors are all the vectors on the boundary or within the margin slab.The custom and SKLearn implementations are matching ! Comparison of the soft margin classifier to the Logistic regression and Linear Discriminant Analysis (LDA)
model12 = linear_model.LogisticRegression(solver='lbfgs') model12.fit(xTrain1, yTrain1) model12.coef_[0], model12.intercept_[0] model13 = discriminant_analysis.LinearDiscriminantAnalysis(solver='svd') model13.fit(xTrain1, yTrain1) model13.coef_[0], model13.intercept_[0]
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science
As shown below, the three models separator hyperplans are very similar, negative slope.
fig, ax = plt.subplots(1, figsize=(11, 7)) plotSvm(xTrain1, yTrain1, w=model11.coef_[0], intercept=model11.intercept_[0], label='Training', separatorLabel='Soft Margin SVM', ax=ax) xx = np.array([-1., 1.]) plotLine(ax, xx, w=model12.coef_[0], x0=model12.intercept_[0], label='Logistic reg', color='orange') plotL...
_____no_output_____
MIT
classification/ClassificationSVM.ipynb
tonio73/data-science