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 |
|---|---|---|---|---|---|
Validation with test data | xTest1, yTest1 = generateBatchBipolar(2*N, mu=0.3, sigma=0.3) | _____no_output_____ | MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
Helpers for binary classification performance | def plotHeatMap(X, classes, title=None, fmt='.2g', ax=None, xlabel=None, ylabel=None):
""" Fix heatmap plot from Seaborn with pyplot 3.1.0, 3.1.1
https://stackoverflow.com/questions/56942670/matplotlib-seaborn-first-and-last-row-cut-in-half-of-heatmap-plot
"""
ax = sns.heatmap(X, xticklabels=classes... | _____no_output_____ | MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
Confusion matrices | fig, axes = plt.subplots(1, 3, figsize=(16, 3))
for model, ax, title in zip([model10, model12, model13], axes, ['Custom linear SVM', 'Logistic reg', 'LDA']):
yEst = model.predict(xTest1)
plotConfusionMatrix(yTest1, yEst, colors, title, ax=ax) | _____no_output_____ | MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
There is no clear winner, all models are performing equally well. | fig, ax = plt.subplots(1, figsize=(11, 7))
plotSvm(xTest1, yTest1, w=model10.w, intercept=model10.intercept, separatorLabel='Cust. linear SVM', ax=ax)
xx = np.array([-1., 1.])
plotLine(ax, xx, w=model12.coef_[0], x0=model12.intercept_[0], label='Logistic reg', color='orange')
plotLine(ax, xx, w=model13.coef_[0], x0=mod... | _____no_output_____ | MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
3. The "kernel trick" for non linearly separable classesLet's use a very famous dataset showing the main limitation of the Logistic regression and LDA : the XOR. | def generateBatchXor(n, mu=0.5, sigma=0.5):
""" Four gaussian clouds in a Xor fashion """
X = np.random.normal(mu, sigma, (n, 2))
yB0 = np.random.uniform(0, 1, n) > 0.5
yB1 = np.random.uniform(0, 1, n) > 0.5
# y is in {-1, 1}
y0 = 2. * yB0 - 1
y1 = 2. * yB1 - 1
X[:,0] *= y0
X[:,1] *=... | _____no_output_____ | MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
Logistic regression and LDA on XOR problem | model32 = linear_model.LogisticRegression(solver='lbfgs')
model32.fit(xTrain3, yTrain3)
model32.coef_[0], model32.intercept_[0]
model33 = discriminant_analysis.LinearDiscriminantAnalysis(solver='svd')
model33.fit(xTrain3, yTrain3)
model33.coef_[0], model33.intercept_[0] | _____no_output_____ | MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
The linear separators are sometimes mitigating the issue by isolating a single class within a corner. Or they are simply fully failing (separator is of limit). | fig, ax = plt.subplots(1, figsize=(11, 7))
plotSvm(xTrain3, yTrain3, w=model32.coef_[0], intercept=model32.intercept_[0], label='Training',
separatorLabel='Logistic reg', ax=ax)
xx = np.array([-1., 1.])
plotLine(ax, xx, w=model33.coef_[0], x0=model33.intercept_[0], label='LDA', color='c')
ax.legend(); | _____no_output_____ | MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
Introducing the Kernel trickWhen using linear separators like the regression, the traditional way to deal with non linear functions is to expand the feature space using powers and products of the initial features. This is also necessary in case of multiclass problems as shown in [1 chap. 4.2].There are limits to this ... | class KernelSvmClassifier:
def __init__(self, C, kernel):
self.C = C
self.kernel = kernel # <---
self.alpha = None
self.supportVectors = None
def fit(self, X, y):
N = len(y)
# --->
# Gram matrix of h(x) y
... | Number of support vectors = 34
| MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
Scikit Learn SVM with Radial basis kernel | model31 = svm.SVC(kernel='rbf', C=10, gamma=1/2, shrinking=False)
model31.fit(xTrain3, yTrain3);
fig, ax = plt.subplots(1, figsize=(11, 7))
plotSvm(xTrain3, yTrain3, support=model31.support_vectors_, label='Training', ax=ax)
# Estimate and plot decision boundary
Y31 = model31.predict(xy).reshape(X0.shape)
ax.contour(X... | Number of support vectors = 39
| MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
SVM with RBF performance on XOR | fig, axes = plt.subplots(1, 2, figsize=(11, 3))
for model, ax, title in zip([model30, model31], axes, ["Custom SVM with RBF", "SKLearn SVM with RBF"]):
yEst3 = model.predict(xTest3)
plotConfusionMatrix(yTest3, yEst3, colors, title, ax=ax) | _____no_output_____ | MIT | classification/ClassificationSVM.ipynb | tonio73/data-science |
Loading the model | model_def = 'example_caffe_mnist_model.prototxt'
model_weights = 'mnist.caffemodel'
net = caffe.Net(model_def, model_weights, caffe.TEST) | _____no_output_____ | MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
A Caffe net offers a layer dict that maps layer names to layer objects. These objects do not provide very much information though, but access to their weights and the type of the layer. | net.layer_dict
conv_layer = net.layer_dict['conv2d_1']
conv_layer.type, conv_layer.blobs[0].data.shape | _____no_output_____ | MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
Getting input and output shape.The net provides a `blobs dict`. These blobs contain `data`, i.e. all the intermediary computation results and `diff`, i.e. the gradients. | for name, blob in net.blobs.items():
print('{}: \t {}'.format(name, blob.data.shape)) | data: (64, 1, 28, 28)
label: (64,)
conv2d_1: (64, 32, 26, 26)
max_pooling2d_1: (64, 32, 13, 13)
conv2d_2: (64, 32, 11, 11)
dropout_1: (64, 32, 11, 11)
dense_1: (64, 64)
dropout_2: (64, 64)
dense_2: (64, 10)
loss: ()
| MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
Getting the weigths.The net provides access to a `param dict` that contains the weights. The first entry in param corresponds to the weights, the second corresponds to the bias. | net.params
for name, param in net.params.items():
print('{}:\t {} \t{}'.format(name, param[0].data.shape, param[1].data.shape)) | conv2d_1: (32, 1, 3, 3) (32,)
conv2d_2: (32, 32, 3, 3) (32,)
dense_1: (64, 3872) (64,)
dense_2: (10, 64) (10,)
| MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
The weights are also accessible through the layer blobs. | for layer in net.layers:
try:
print (layer.type + '\t' + str(layer.blobs[0].data.shape), str(layer.blobs[1].data.shape))
except:
continue
weights = net.params['conv2d_1'][0].data
weights.shape | _____no_output_____ | MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
For visualizing the weights the axis still have to be moved around. | for i in range(32):
plt.imshow(np.moveaxis(weights[i], 0, -1)[..., 0])
plt.show() | _____no_output_____ | MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
Layers that have no weights simply keep empty lists as their blob vector. | list(net.layer_dict['dropout_1'].blobs) | _____no_output_____ | MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
Getting the activations and the net input.For getting activations, first data has to be passed through the network. Then the activations can be read out from the blobs. If the activations are defined as in place operations, the net input will not be stored in any blob and can therefore not be recovered. This problem c... | def remove_inplace(model_def):
protonet = caffe_pb2.NetParameter()
with open(model_def, 'r') as fp:
google.protobuf.text_format.Parse(str(fp.read()), protonet)
replaced_tops = {}
for layer in protonet.layer:
# Check whehter bottoms were renamed.
for i in range(len(layer.... | (28, 28)
(1, 28, 28)
| MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
Feeding the input and forwarding it. | net_no_inplace.blobs['data'].data[...] = seven
output = net_no_inplace.forward()
output['prob'][0].argmax()
activations = net_no_inplace.blobs['relu_1'].data
for i in range(32):
plt.imshow(activations[0, i, :, :])
plt.title('Feature map %d' % i)
plt.show()
net_input = net_no_inplace.blobs['conv2d_1'].data
... | _____no_output_____ | MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
Getting layer propertiesFrom the layer object not more then type information is available. There the original .prototxt has to be parsed to access attributes such as kernel size. | model_def = 'example_caffe_mnist_model.prototxt'
f = open(model_def, 'r')
protonet = caffe_pb2.NetParameter()
google.protobuf.text_format.Parse(str(f.read()), protonet)
f.close()
protonet
type(protonet) | _____no_output_____ | MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
Parsed messages for the layer can be found in `message.layer` list. | for i in range(0, len(protonet.layer)):
if protonet.layer[i].type == 'Convolution':
print('layer %s has kernel_size %d'
% (protonet.layer[i].name,
protonet.layer[i].convolution_param.kernel_size[0]))
lconv_proto = protonet.layer[i]
len(protonet.layer), len(net.layers... | _____no_output_____ | MIT | notebooks/caffe/introspection.ipynb | Petr-By/qtpyvis |
Transpose convolution: UpsamplingIn section 10.5.3, we discussed how transpose convolutions are can be used to upsample a lower resolution input into a higher resolution output. This notebook contains fully functional PyTorch code for the same. | import matplotlib.pyplot as plt
import torch
import math | _____no_output_____ | MIT | python/ch10/10.5.3-transpose-conv-upsampling.ipynb | krishnonwork/mathematical-methods-in-deep-learning |
First, let's look at how transpose convolution works on a simple input tensor. Then we will look at a real image. For this purpose, we will consider the example described in Figure 10.17. The input is a 2x2 array as follows:$$x = \begin{bmatrix}5 & 6 \\7 & 8 \\\end{bmatrix}$$and the transpose convolution kernel is also... | x = torch.tensor([
[5., 6.],
[7., 8.]
])
w = torch.tensor([
[1., 2.],
[3., 4.]
])
x = x.unsqueeze(0).unsqueeze(0)
w = w.unsqueeze(0).unsqueeze(0)
transpose_conv2d = torch.nn.ConvTranspose2d(1, 1, kernel_size=2, stride=1, bias=False)
# set weights of the TransposeConv2d object
... | _____no_output_____ | MIT | python/ch10/10.5.3-transpose-conv-upsampling.ipynb | krishnonwork/mathematical-methods-in-deep-learning |
Transpose conv 2D with stride 2In the above example, we did not get a truly upsampled version of the input because we used a kernel stride of 1. Thei increase in resolution from 2 to 3 comes because of padding. Now, let's see how to truly upsample the image - we will run transpose convolution with stride 2. The step b... | x = torch.tensor([
[5., 6.],
[7., 8.]
])
w = torch.tensor([
[1., 2.],
[3., 4.]
])
x = x.unsqueeze(0).unsqueeze(0)
w = w.unsqueeze(0).unsqueeze(0)
transpose_conv2d = torch.nn.ConvTranspose2d(1, 1, kernel_size=2, stride=2, bias=False)
# set weights of the TransposeConv2d object
... | _____no_output_____ | MIT | python/ch10/10.5.3-transpose-conv-upsampling.ipynb | krishnonwork/mathematical-methods-in-deep-learning |
Now, let's take a sample image and see how the input compares to the output post transpose convolution with stride 2. | import cv2
x = torch.tensor(cv2.imread("./Figures/dog2.jpg", 0), dtype=torch.float32)
w = torch.tensor([
[1., 1.],
[1., 1.]
])
x = x.unsqueeze(0).unsqueeze(0)
w = w.unsqueeze(0).unsqueeze(0)
transpose_conv2d = torch.nn.ConvTranspose2d(1, 1, kernel_size=2,
... | Input shape: torch.Size([1, 1, 168, 300])
Output shape: torch.Size([1, 1, 336, 600])
| MIT | python/ch10/10.5.3-transpose-conv-upsampling.ipynb | krishnonwork/mathematical-methods-in-deep-learning |
As expected, the output is twice the size of the input. The images below should make this clear | def display_image_in_actual_size(im_data, title):
dpi = 80
height, width = im_data.shape
# What size does the figure need to be in inches to fit the image?
figsize = width / float(dpi), height / float(dpi)
# Create a figure of the right size with one axes that takes up the full figure
fig = p... | _____no_output_____ | MIT | python/ch10/10.5.3-transpose-conv-upsampling.ipynb | krishnonwork/mathematical-methods-in-deep-learning |
Now that we have the time series, let's split it so we can start forecasting | split_time = 1000
time_train = time[:split_time]
x_train = series[:split_time]
time_valid = time[split_time:]
x_valid = series[split_time:]
plt.figure(figsize=(10, 6))
plot_series(time_train, x_train)
plt.show()
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid)
plt.show() | _____no_output_____ | MIT | legacy/arkady TF legacy/TF_2020_course4_week1_forcasting.ipynb | 21kc-caracol/Acoustic_data_Image_vs_Mean |
Naive Forecast | naive_forecast = series[split_time - 1:-1]
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid)
plot_series(time_valid, naive_forecast)
x = [1,2, 3, 4, 5, 6, 7, 8, 9, 10]
print(x)
split=7
naive=x[split - 1:-1]
print(naive)
x_val = x[split:]
print(x_val) | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[7, 8, 9]
[8, 9, 10]
| MIT | legacy/arkady TF legacy/TF_2020_course4_week1_forcasting.ipynb | 21kc-caracol/Acoustic_data_Image_vs_Mean |
Let's zoom in on the start of the validation period: | plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid, start=0, end=150)
plot_series(time_valid, naive_forecast, start=1, end=151) | _____no_output_____ | MIT | legacy/arkady TF legacy/TF_2020_course4_week1_forcasting.ipynb | 21kc-caracol/Acoustic_data_Image_vs_Mean |
You can see that the naive forecast lags 1 step behind the time series.Now let's compute the mean squared error and the mean absolute error between the forecasts and the predictions in the validation period: | print(keras.metrics.mean_squared_error(x_valid, naive_forecast).numpy())
print(keras.metrics.mean_absolute_error(x_valid, naive_forecast).numpy()) | 61.827538
5.937908
| MIT | legacy/arkady TF legacy/TF_2020_course4_week1_forcasting.ipynb | 21kc-caracol/Acoustic_data_Image_vs_Mean |
That's our baseline, now let's try a moving average: | def moving_average_forecast(series, window_size):
"""Forecasts the mean of the last few values.
If window_size=1, then this is equivalent to naive forecast"""
forecast = []
for time in range(len(series) - window_size):
forecast.append(series[time:time + window_size].mean())
return np.array(forecast)
mo... | 106.674576
7.142419
| MIT | legacy/arkady TF legacy/TF_2020_course4_week1_forcasting.ipynb | 21kc-caracol/Acoustic_data_Image_vs_Mean |
That's worse than naive forecast! The moving average does not anticipate trend or seasonality, so let's try to remove them by using differencing. Since the seasonality period is 365 days, we will subtract the value at time t – 365 from the value at time t. | diff_series = (series[365:] - series[:-365])
diff_time = time[365:]
plt.figure(figsize=(10, 6))
plot_series(diff_time, diff_series)
plt.show() | _____no_output_____ | MIT | legacy/arkady TF legacy/TF_2020_course4_week1_forcasting.ipynb | 21kc-caracol/Acoustic_data_Image_vs_Mean |
Great, the trend and seasonality seem to be gone, so now we can use the moving average: | diff_moving_avg = moving_average_forecast(diff_series, 50)[split_time - 365 - 50:]
plt.figure(figsize=(10, 6))
plot_series(time_valid, diff_series[split_time - 365:])
plot_series(time_valid, diff_moving_avg)
plt.show() | _____no_output_____ | MIT | legacy/arkady TF legacy/TF_2020_course4_week1_forcasting.ipynb | 21kc-caracol/Acoustic_data_Image_vs_Mean |
Now let's bring back the trend and seasonality by adding the past values from t – 365: | diff_moving_avg_plus_past = series[split_time - 365:-365] + diff_moving_avg
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid)
plot_series(time_valid, diff_moving_avg_plus_past)
plt.show()
print(keras.metrics.mean_squared_error(x_valid, diff_moving_avg_plus_past).numpy())
print(keras.metrics.mean_absolute_er... | 52.97366
5.839311
| MIT | legacy/arkady TF legacy/TF_2020_course4_week1_forcasting.ipynb | 21kc-caracol/Acoustic_data_Image_vs_Mean |
Better than naive forecast, good. However the forecasts look a bit too random, because we're just adding past values, which were noisy. Let's use a moving averaging on past values to remove some of the noise: | diff_moving_avg_plus_smooth_past = moving_average_forecast(series[split_time - 370:-360], 10) + diff_moving_avg
plt.figure(figsize=(10, 6))
plot_series(time_valid, x_valid)
plot_series(time_valid, diff_moving_avg_plus_smooth_past)
plt.show()
print(keras.metrics.mean_squared_error(x_valid, diff_moving_avg_plus_smooth_p... | 33.45226
4.569442
| MIT | legacy/arkady TF legacy/TF_2020_course4_week1_forcasting.ipynb | 21kc-caracol/Acoustic_data_Image_vs_Mean |
Dataset | RAW_DATASET_ROOT_FOLDER = '/content/data/bronze'
PREP_DATASET_ROOT_FOLDER = '/content/data/silver'
FNL_DATASET_ROOT_FOLDER = '/content/data/gold'
import pickle
import shutil
import tempfile
import os
from datetime import date
from pathlib import Path
import gzip
from abc import *
import numpy as np
import pandas as pd... | _____no_output_____ | Apache-2.0 | _docs/nbs/T728835-Black-box-Attack-Model-DVC-Training-Pipeline.ipynb | sparsh-ai/recohut |
Negative Sampling | from abc import *
from pathlib import Path
import pickle
class AbstractNegativeSampler(metaclass=ABCMeta):
def __init__(self, train, val, test, user_count, item_count, sample_size, seed, flag, save_folder):
self.train = train
self.val = val
self.test = test
self.user_count = user_c... | _____no_output_____ | Apache-2.0 | _docs/nbs/T728835-Black-box-Attack-Model-DVC-Training-Pipeline.ipynb | sparsh-ai/recohut |
Dataloader | from abc import *
import random
class AbstractDataloader(metaclass=ABCMeta):
def __init__(self, args, dataset):
self.args = args
self.rng = random.Random()
self.save_folder = dataset._get_preprocessed_folder_path()
dataset = dataset.load_dataset()
self.train = dataset['trai... | _____no_output_____ | Apache-2.0 | _docs/nbs/T728835-Black-box-Attack-Model-DVC-Training-Pipeline.ipynb | sparsh-ai/recohut |
Args | import numpy as np
import random
import torch
import argparse
def set_template(args):
args.min_uc = 5
args.min_sc = 5
args.split = 'leave_one_out'
dataset_code = {'1': 'ml-1m', '20': 'ml-20m', 'b': 'beauty', 'bd': 'beauty_dense' , 'g': 'games', 's': 'steam', 'y': 'yoochoose'}
args.dataset_code = dat... | Raw file doesn't exist. Downloading...
| Apache-2.0 | _docs/nbs/T728835-Black-box-Attack-Model-DVC-Training-Pipeline.ipynb | sparsh-ai/recohut |
Model | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class TokenEmbedding(nn.Embedding):
def __init__(self, vocab_size, embed_size=512):
super().__init__(vocab_size, embed_size, padding_idx=0)
class PositionalEmbedding(nn.Module):
def __init__(self, max_len, d_model):
... | _____no_output_____ | Apache-2.0 | _docs/nbs/T728835-Black-box-Attack-Model-DVC-Training-Pipeline.ipynb | sparsh-ai/recohut |
Run | if args.model_code == 'bert':
model = BERT(args)
# elif args.model_code == 'sas':
# model = SASRec(args)
# elif args.model_code == 'narm':
# model = NARM(args)
export_root = 'experiments/' + args.model_code + '/' + args.dataset_code
resume=False
if resume:
try:
model.load_state_dict(torch.load(... | _____no_output_____ | Apache-2.0 | _docs/nbs/T728835-Black-box-Attack-Model-DVC-Training-Pipeline.ipynb | sparsh-ai/recohut |
Trainer | STATE_DICT_KEY = 'model_state_dict'
OPTIMIZER_STATE_DICT_KEY = 'optimizer_state_dict'
import os
import torch
from abc import ABCMeta, abstractmethod
def save_state_dict(state_dict, path, filename):
torch.save(state_dict, os.path.join(path, filename))
class LoggerService(object):
def __init__(self, train_log... | _____no_output_____ | Apache-2.0 | _docs/nbs/T728835-Black-box-Attack-Model-DVC-Training-Pipeline.ipynb | sparsh-ai/recohut |
Run | if args.model_code == 'bert':
trainer = BERTTrainer(args, model, train_loader, val_loader, test_loader, export_root)
if args.model_code == 'sas':
trainer = SASTrainer(args, model, train_loader, val_loader, test_loader, export_root)
eli f args.model_code == 'narm':
args.num_epochs = 100
trainer = RNNTrai... | _____no_output_____ | Apache-2.0 | _docs/nbs/T728835-Black-box-Attack-Model-DVC-Training-Pipeline.ipynb | sparsh-ai/recohut |
Introductionrefer to this solution :https://www.kaggle.com/jsaguiar/lightgbm-7th-place-solutionhttps://www.tinymind.cn/articles/3655https://github.com/Featuretools/Automated-Manual-Comparison/tree/master/Loan%20Repaymenthttps://www.kaggle.com/willkoehrsen/start-here-a-gentle-introduction/ Read Data | # import packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import featuretools as ft
import lightgbm as lgb
%matplotlib inline
import seaborn as sns
RSEED = 50
# read in data and check basic info
def read_check_data(file_path):
data = pd.read_csv(file_path)
print('Training data sh... | Training data shape: (1716428, 17)
SK_ID_CURR SK_ID_BUREAU CREDIT_ACTIVE CREDIT_CURRENCY DAYS_CREDIT \
0 215354 5714462 Closed currency 1 -497
1 215354 5714463 Active currency 1 -208
2 215354 5714464 Active currency 1 ... | CNRI-Python | EDA.ipynb | haataa/Home-Credit-Default-Risk |
Check Missing Values | def check_missing_col(df):
missing_num = df.isnull().sum().sort_values(ascending = False)
minssing_percent = (df.isnull().mean()*100).sort_values(ascending = False)
missing_info = pd.concat([missing_num, minssing_percent], axis=1, keys=['missing_num', 'minssing_percent'])
print(missing_info.head())
... | missing_num minssing_percent
793046 6 35.294118
773821 6 35.294118
871866 6 35.294118
468959 6 35.294118
701505 6 35.294118
missing_num minssing_percent
count 1.716428e+06 1.716428e+06
mean 2.295434e... | CNRI-Python | EDA.ipynb | haataa/Home-Credit-Default-Risk |
Select and Re-Encode Features | def select_feature_type(df,data_type):
return df.select_dtypes(include=[data_type])
def count_feature_type(df):
return df.dtypes.value_counts()
def count_col_unique(df,data_type):
'''count the total unique value number of each colunm
data_type could be object,category'''
return df.select_dtypes(data... | _____no_output_____ | CNRI-Python | EDA.ipynb | haataa/Home-Credit-Default-Risk |
check value type and correct wrong values | count_feature_type(app)
count_col_unique(app_train,'object')
count_col_each_unique(app,'CODE_GENDER')
check_distribution(app,'AMT_INCOME_TOTAL')
# this discussion https://www.kaggle.com/c/home-credit-default-risk/discussion/57247#332033
# says 365243 means NA
check_distribution(app,'DAYS_EMPLOYED')
# total number of 1 ... | count 1.716415e+06
mean 3.549946e+05
std 1.149811e+06
min 0.000000e+00
25% 5.130000e+04
50% 1.255185e+05
75% 3.150000e+05
max 5.850000e+08
Name: AMT_CREDIT_SUM, dtype: float64
Total missing value number: 13
| CNRI-Python | EDA.ipynb | haataa/Home-Credit-Default-Risk |
Baseline Model | app_base_train = app_clean[app_clean['TARGET'].notnull()]
app_base_test = app_clean[app_clean['TARGET'].isnull()]
app_base_test.head()
def cross_validate(train):
"""Compute cross validation ROC AUC of a gradient boosting model for a given training dataset"""
# Extract the labels
train_labels = np.array... | _____no_output_____ | CNRI-Python | EDA.ipynb | haataa/Home-Credit-Default-Risk |
Semi-Auto Feature | def agg_numeric(df_child, parent_var, df_col_name):
"""
Groups and aggregates the numeric values in a child dataframe
by the parent variable.
Parameters
--------
df_child (dataframe):
the child dataframe to calculate the statistics on
parent_var (string):
... | _____no_output_____ | CNRI-Python | EDA.ipynb | haataa/Home-Credit-Default-Risk |
Genentech Cervical Cancer - Feature Selectionhttps://www.kaggle.com/c/cervical-cancer-screening/ | # imports
import sys # for stderr
import numpy as np
import pandas as pd
import sklearn as skl
from sklearn import metrics
import matplotlib.pyplot as plt
%matplotlib inline
# settings
%logstop
%logstart -o 'cc_feature_selection.log' rotate
plt.style.use('ggplot')
# constants
# plt.rcParams['figure.figsize'] = (10.0,... | _____no_output_____ | BSD-2-Clause | cervical-cancer-screening/data/cc_feature_selection.ipynb | Ravirajadrangi/projects6 |
Load | fdir = './features/'
train_file = './input/patients_train.csv.gz'
train = pd.read_csv(train_file)
train.drop('patient_gender', axis=1, inplace=True)
train.set_index('patient_id', inplace=True)
train[:3]
files =[
'diag_code_0_1000.csv.gz',
'diag_code_1000_2000.csv.gz',
'diag_code_2000_3000.csv.gz',
'diag_code_3000_4000.... | _____no_output_____ | BSD-2-Clause | cervical-cancer-screening/data/cc_feature_selection.ipynb | Ravirajadrangi/projects6 |
Run | nnn = 4
import datetime
start = datetime.datetime.now()
print(start)
tab = pd.read_csv(fdir+files[nnn])
tab.set_index('patient_id', inplace=True)
tab.shape
dfall = pd.merge(train, tab, left_index=True, right_index=True, how='left')
cat_cols = ['patient_age_group','patient_state','ethinicity','household_income','educati... | _____no_output_____ | BSD-2-Clause | cervical-cancer-screening/data/cc_feature_selection.ipynb | Ravirajadrangi/projects6 |
Merge feature values | diag_top_features = [
'diagnosis_top_0.csv',
'diagnosis_top_3.csv',
'diagnosis_top_4.csv',
'diagnosis_top_6.csv',
'diagnosis_top_10.csv',
'diagnosis_top_12.csv',
'diagnosis_top_15.csv'
]
dff = pd.read_csv(diag_top_features[0])
dff.set_index('patient_id', inplace=True)
print(dff.shape)
f... | _____no_output_____ | BSD-2-Clause | cervical-cancer-screening/data/cc_feature_selection.ipynb | Ravirajadrangi/projects6 |
Procedures | procs = pd.read_csv(fdir+'procedure/procedure_counts_selected.csv.gz')
procs.shape
procs.set_index('patient_id', inplace=True)
procs[:2]
print(bigt.shape)
bigtp = bigt.merge(procs, left_index=True, right_index=True, how='left')
bigtp.shape
bigtp.to_csv(fdir+'train_big_table.csv')
print(bigte.shape)
bigtep = bigte.merge... | _____no_output_____ | BSD-2-Clause | cervical-cancer-screening/data/cc_feature_selection.ipynb | Ravirajadrangi/projects6 |
test_top | test_diagnosis_top = pd.read_csv('test_diagnosis_top.csv')
test_diagnosis_top.shape
#test_diagnosis_top.set_index('patient_id', inplace=True)
test_diagnosis_top[:5]
test_pivot = test_diagnosis_top.pivot(index='patient_id', columns='diagnosis_code', values='diagnosis_code_count')
test_pivot[:5]
test_pivot.shape
test_big... | _____no_output_____ | BSD-2-Clause | cervical-cancer-screening/data/cc_feature_selection.ipynb | Ravirajadrangi/projects6 |
Check results | train_diagnosis_top = fdir+'train_diagnosis_top.csv.gz'
train_diagnosis_top = pd.read_csv(train_diagnosis_top)
train_diagnosis_top.set_index('patient_id', inplace=True)
train_diagnosis_top[:3]
train_diagnosis_top.shape
test_diagnosis_top = fdir+'test_diagnosis_top.csv.gz'
test_diagnosis_top = pd.read_csv(test_diagnosis... | _____no_output_____ | BSD-2-Clause | cervical-cancer-screening/data/cc_feature_selection.ipynb | Ravirajadrangi/projects6 |
Data ScienceWhat's that? | from IPython.display import Image
Image(url='http://static.squarespace.com/static/5150aec6e4b0e340ec52710a/t/51525c33e4b0b3e0d10f77ab/1364352052403/Data_Science_VD.png?format=750w')
| _____no_output_____ | CC0-1.0 | Day01_ComputerBasics/notebooks/01 - Data Science.ipynb | LucaFoschini/UCSBDataScienceBootcamp2015 |
Read the full story:http://lucafoschini.com/notebooks/Agile%20Data%20Science%20Meetup.slides.html/Source (Another feature of Notebooks: Make slides out of them!):https://github.com/LucaFoschini/lucafoschini.github.io/blob/master/notebooks/Agile%20Data%20Science%20Meetup.ipynb Getting startedThis section focuses on the ... | Image(url='https://upload.wikimedia.org/wikipedia/en/c/cb/Windows_Explorer_Windows_7.png') | _____no_output_____ | CC0-1.0 | Day01_ComputerBasics/notebooks/01 - Data Science.ipynb | LucaFoschini/UCSBDataScienceBootcamp2015 |
Choosing the priorAs a prior we will use a beta distribution, which is a very common distribution:\begin{equation}p\left(\theta\right) = \frac{\Gamma\left(\alpha+\beta\right)}{\Gamma\left(\alpha\right)\Gamma\left(\beta\right)}\theta^(\alpha - 1)\left(1-\theta\right)^{\beta -1}\end{equation}The beta distribution is a c... | params = [0.5, 1, 2, 3]
x = np.linspace(0, 1, 100)
f, ax = plt.subplots(len(params), len(params), sharex=True,
sharey=True,
figsize=(8, 7), constrained_layout=True)
for i in range(4):
for j in range(4):
a = params[i]
b = params[j]
y = stats.beta(a, ... | _____no_output_____ | MIT | Chapter1/bayesian_introduction.ipynb | nathdipankar/Bayesian-Statistics |
Homework 1The maximum score of this homework is 100+10 points. Grading is listed in this table:| Grade | Score range || --- | --- || 5 | 85+ || 4 | 70-84 || 3 | 55-69 || 2 | 40-54 || 1 | 0-39 |Most exercises include tests which should pass if your solution is correct.However successful test do not guarantee that your ... | keyboard = [
['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'],
['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'],
['z', 'x', 'c', 'v', 'b', 'n', 'm'],
]
keyboard_mapping = {}
for i, row in enumerate(keyboard):
for j, c in enumerate(row):
keyboard_mapping[c] = (i, j)
def keyboard_edit_distance(str1... | _____no_output_____ | MIT | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring |
2. Replace rare words (10 points)Write a function that takes a text and a number $N$ as parameters and replaces every word other than the most common $N$ in the text with a common symbol. The symbol by default is `__RARE__` but it can be redefined.Your code should split on spaces only.You can derive the function defin... | # YOUR CODE HERE
raise NotImplementedError()
assert replace_rare_words("a b a a a b b b c d d d", 2) == "a b a a a b b b __RARE__ __RARE__ __RARE__ __RARE__"
assert replace_rare_words("a b a b b c", 2, rare_symbol="rare") == "a b a b b rare" | _____no_output_____ | MIT | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring |
3. MutableString (30 points)Python strings are immutable. Create a mutable string class. The internal representation should be mutable too.Implement the following features (see the tests below).- initialization from `str`,- initialization from text file (loads the file's content into the string),- assignment (i.e. mod... | class MutableString(object):
# YOUR CODE HERE
raise NotImplementedError() | _____no_output_____ | MIT | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring |
Briefly describe what internal representation you chose and why you chose it.What other possibilities did you think about?(double-click on the text to edit it) YOUR ANSWER HERE MutableString tests | # initialization
m = MutableString()
assert m == "" and len(m) == 0
# initialization from file
import tempfile
import os
with tempfile.NamedTemporaryFile(mode="w+b", delete=False) as tmpfile:
tmpfile.write("abc".encode("utf8"))
m = MutableString.from_file(tmpfile.name)
assert m == "abc"
os.remove(tmpfile.name)
# i... | _____no_output_____ | MIT | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring |
Text generation 3.1 (Same as a laboratory exercise) Write a function that computes N-gram frequencies in a string. (0 point) | # YOUR CODE HERE
raise NotImplementedError()
assert(count_ngram_freqs("abcc", 1) == {"a": 1, "b": 1, "c": 2})
assert(count_ngram_freqs("abccab", 2) == {"ab": 2, "bc": 1, "cc": 1, "ca": 1}) | _____no_output_____ | MIT | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring |
3.2 Define a random text generator function (20 points).The function takes 4 arguments:1. starting text (at least $N-1$ long),2. target length: length of the output string,3. n-gram frequency dictionary,4. N, length of the n-grams.The function generates one character at a time given the last $N-1$ characters.The proba... | # YOUR CODE HERE
raise NotImplementedError()
toy_freqs = count_ngram_freqs("abcabcda", 3)
gen = generate_text("abc", 5, toy_freqs, 3)
assert(len(gen) == 5)
assert(set(gen) <= set("abcd")) | _____no_output_____ | MIT | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring |
3.3 Test your solution on a small Wikipedia corpus (10 points).Collect a sample of at least 1 million characters from Wikipedia using the wikipedia module. | # YOUR CODE HERE
raise NotImplementedError() | _____no_output_____ | MIT | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring |
\*3.4 Smoothing (extra exercise, 10 points)Implement one or more smoothing methods such as Jelinek-Mercer smoothing or Katz's backoff. Train it on your Wikipedia corpus and generate an example.https://nlp.stanford.edu/~wcmac/papers/20050421-smoothing-tutorial.pdf | # YOUR CODE HERE
raise NotImplementedError() | _____no_output_____ | MIT | homeworks/homework1/homework1.ipynb | aseifert/python_nlp_2018_spring |
Optimiztion with `mystic` | %matplotlib notebook | _____no_output_____ | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
`mystic`: approximates that `scipy.optimize` interface | """
Example:
- Minimize Rosenbrock's Function with Nelder-Mead.
- Plot of parameter convergence to function minimum.
Demonstrates:
- standard models
- minimal solver interface
- parameter trajectories using retall
"""
# Nelder-Mead solver
from mystic.solvers import fmin
# Rosenbrock function
from... | _____no_output_____ | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
Diagnostic tools * Callbacks | """
Example:
- Minimize Rosenbrock's Function with Nelder-Mead.
- Dynamic plot of parameter convergence to function minimum.
Demonstrates:
- standard models
- minimal solver interface
- parameter trajectories using callback
- solver interactivity
"""
# Nelder-Mead solver
from mystic.solvers im... | NOTE: while solver is running, press 'Ctrl-C' in console window
Press any key to continue and press enter
Optimization terminated successfully.
Current function value: 0.000000
Iterations: 120
Function evaluations: 215
[ 1.00000328 1.00000565 1.00001091]
Press any key to continue and press... | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
**NOTE** IPython does not handle shell prompt interactive programs well, so the above should be run from a command prompt. An IPython-safe version is below. | """
Example:
- Minimize Rosenbrock's Function with Powell's method.
- Dynamic print of parameter convergence to function minimum.
Demonstrates:
- standard models
- minimal solver interface
- parameter trajectories using callback
"""
# Powell's Directonal solver
from mystic.solvers import fmi... | Generation 0 has best fit parameters: [ 0.8 1.2 0.7]
Generation 1 has best fit parameters: [ 0.8 1.2 0.7]
Generation 2 has best fit parameters: [ 1.096641 0.92316246 0.85222892]
Generation 3 has best fit parameters: [ 0.96098383 0.92341029 0.85268657]
Generation 4 has best fit parameters: [ 0.96116068 0.9236... | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
* Monitors | """
Example:
- Minimize Rosenbrock's Function with Powell's method.
Demonstrates:
- standard models
- minimal solver interface
- customized monitors
"""
# Powell's Directonal solver
from mystic.solvers import fmin_powell
# Rosenbrock function
from mystic.models import rosen
# tools
from mystic.monit... | _____no_output_____ | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
* Solution trajectory and model plotting | import mystic
mystic.model_plotter(mystic.models.rosen, 'log.txt', kwds='-d -x 1 -b "-2:2:.1, -2:2:.1, 1"') | _____no_output_____ | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
Solver "tuning" and extension * Solver class interface | """
Example:
- Solve 8th-order Chebyshev polynomial coefficients with DE.
- Callable plot of fitting to Chebyshev polynomial.
- Monitor Chi-Squared for Chebyshev polynomial.
Demonstrates:
- standard models
- expanded solver interface
- built-in random initial guess
- customized monitors and... | Collapse
Collapsed
Finalize
SaveSolver
SetConstraints
SetEvaluationLimits
SetEvaluationMonitor
SetGenerationMonitor
SetInitialPoints
SetMultinormalInitialPoints
SetObjective
SetPenalty
SetRandomInitialPoints
SetReducer
SetSampledInitialPoints
SetSaveFrequency
SetStrictRanges
SetTermination
Solution
Solve
Step
Terminate... | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
* Algorithm configurability * Termination conditions | from mystic.termination import VTR, ChangeOverGeneration, And, Or
stop = Or(And(VTR(), ChangeOverGeneration()), VTR(1e-8))
from mystic.models import rosen
from mystic.monitors import VerboseMonitor
from mystic.solvers import DifferentialEvolutionSolver
solver = DifferentialEvolutionSolver(3,40)
solver.SetRandomInitia... | Generation 0 has Chi-Squared: 587.458970
Generation 10 has Chi-Squared: 2.216492
Generation 20 has Chi-Squared: 1.626018
Generation 30 has Chi-Squared: 0.229984
Generation 40 has Chi-Squared: 0.229984
Generation 50 has Chi-Squared: 0.008647
Generation 60 has Chi-Squared: 0.000946
Generation 70 has Chi-Squared: 0.000109... | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
* Solver population | from mystic.solvers import DifferentialEvolutionSolver
from mystic.math import Distribution
import numpy as np
import pylab
# build a mystic distribution instance
dist = Distribution(np.random.normal, 5, 1)
# use the distribution instance as the initial population
solver = DifferentialEvolutionSolver(3,20)
solver.Set... | _____no_output_____ | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
**EXERCISE:** Use `mystic` to find the minimum for the `peaks` test function, with the bound specified by the `mystic.models.peaks` documentation. **EXERCISE:** Use `mystic` to do a fit to the noisy data in the `scipy.optimize.curve_fit` example (the least squares fit). Constraints "operators" (i.e. kernel transformati... | from mystic.constraints import *
from mystic.penalty import quadratic_equality
from mystic.coupler import inner
from mystic.math import almostEqual
from mystic.tools import random_seed
random_seed(213)
def test_penalize():
from mystic.math.measures import mean, spread
def mean_constraint(x, target):
r... | _____no_output_____ | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
In addition to being able to generically apply information as a penalty, `mystic` provides the ability to construct constraints "operators" -- essentially applying kernel transformations that reduce optimizer search space to the space of solutions that satisfy the constraints. This can greatly accelerate convergence t... | """
Example:
- Minimize Rosenbrock's Function with Powell's method.
Demonstrates:
- standard models
- minimal solver interface
- parameter constraints solver and constraints factory decorator
- statistical parameter constraints
- customized monitors
"""
# Powell's Directonal solver
from mystic... | Powell's Method
===============
Generation 0 has Chi-Squared: 81.100247
Generation 1 has Chi-Squared: 0.000000
Generation 2 has Chi-Squared: 0.000000
Optimization terminated successfully.
Current function value: 0.000000
Iterations: 2
Function evaluations: 81
STOP("NormalizedChangeOverGenerat... | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
* Range (i.e. 'box') constraints Use `solver.SetStrictRange`, or the `bounds` keyword on the solver function interface. * Symbolic constraints interface | %%file spring.py
"a Tension-Compression String"
def objective(x):
x0,x1,x2 = x
return x0**2 * x1 * (x2 + 2)
bounds = [(0,100)]*3
# with penalty='penalty' applied, solution is:
xs = [0.05168906, 0.35671773, 11.28896619]
ys = 0.01266523
from mystic.symbolic import generate_constraint, generate_solvers, solve
f... | CONVERTED SYMBOLIC TO SINGLE CONSTRAINTS FUNCTIONS
(<function inequality_4606002448 at 0x111d18488>, <function inequality_4604414640 at 0x111d181e0>, <function inequality_4606003984 at 0x112733b70>, <function inequality_4605118704 at 0x1127331e0>)
()
THE INDIVIDUAL INEQUALITIES
1.0 - (x[1]**3 * x[2])/(71785*x[0]**4) -... | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
* Penatly functions | equations = """
1.0 - (x1**3 * x2)/(71785*x0**4) <= 0.0
(4*x1**2 - x0*x1)/(12566*x0**3 * (x1 - x0)) + 1./(5108*x0**2) - 1.0 <= 0.0
1.0 - 140.45*x0/(x2 * x1**2) <= 0.0
(x0 + x1)/1.5 - 1.0 <= 0.0
"""
"a Tension-Compression String"
from spring import objective, bounds, xs, ys
from mystic.penalty import quadratic_inequal... | Optimization terminated successfully.
Current function value: 0.012665
Iterations: 540
Function evaluations: 21640
[ 0.05168906 0.35671772 11.28896693]
| BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
* "Operators" that directly constrain search space | """
Crypto problem in Google CP Solver.
Prolog benchmark problem
'''
Name : crypto.pl
Original Source: P. Van Hentenryck's book
Adapted by : Daniel Diaz - INRIA France
Date : September 1992
'''
"""
def objective(x):
return 0.0
nletters = 26
bounds = [(1,nletters)]*nlette... | Generation 0 has Chi-Squared: 1495.000000
Generation 50 has Chi-Squared: 469.000000
Generation 100 has Chi-Squared: 270.000000
Generation 150 has Chi-Squared: 142.000000
Generation 200 has Chi-Squared: 124.000000
Generation 250 has Chi-Squared: 106.000000
Generation 300 has Chi-Squared: 74.000000
Generation 350 has Chi... | BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
Special cases * Integer and mixed integer programming | """
Eq 10 in Google CP Solver.
Standard benchmark problem.
"""
def objective(x):
return 0.0
bounds = [(0,10)]*7
# with penalty='penalty' applied, solution is:
xs = [6., 0., 8., 4., 9., 3., 9.]
ys = 0.0
# constraints
equations = """
98527*x0 + 34588*x1 + 5872*x2 + 59422*x4 + 65159*x6 - 1547604 - 30704*x3 - 2... | Optimization terminated successfully.
Current function value: 0.000000
Iterations: 1
Function evaluations: 14
[ 6. 0. 8. 4. 9. 3. 9.]
| BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
**EXERCISE:** Solve the `chebyshev8.cost` example exactly, by applying the knowledge that the last term in the chebyshev polynomial will always be be one. Use `numpy.round` or `mystic.constraints.integers` or to constrain solutions to the set of integers. Does using `mystic.suppressed` to supress small numbers acceler... | "Pressure Vessel Design"
def objective(x):
x0,x1,x2,x3 = x
return 0.6224*x0*x2*x3 + 1.7781*x1*x2**2 + 3.1661*x0**2*x3 + 19.84*x0**2*x2
bounds = [(0,1e6)]*4
# with penalty='penalty' applied, solution is:
xs = [0.72759093, 0.35964857, 37.69901188, 240.0]
ys = 5804.3762083
from mystic.symbolic import generate_c... | Optimization terminated successfully.
Current function value: 5804.376208
Iterations: 950
Function evaluations: 38040
[ 0.72759093 0.35964857 37.69901188 240. ]
| BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
* Linear and quadratic constraints | """
Minimize: f = 2*x[0] + 1*x[1]
Subject to: -1*x[0] + 1*x[1] <= 1
1*x[0] + 1*x[1] >= 2
1*x[1] >= 0
1*x[0] - 2*x[1] <= 4
where: -inf <= x[0] <= inf
"""
def objective(x):
x0,x1 = x
return 2*x0 + x1
equations = """
-x0 + x1 - 1.0 <=... | Optimization terminated successfully.
Current function value: 2.499688
Iterations: 6
Function evaluations: 277
[ 0.49974959 1.49987526]
| BSD-3-Clause | mystic.ipynb | jingxlim/tutmom |
libraries | import sys
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import en_core_web_sm
from spacy.matcher import Matcher
%matplotlib inline
# to import Database class from data_collection folder
module_path = os.path.abspath(os.path.join('../..')+'/data/data_collection... | _____no_output_____ | FTL | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter |
Import reviews data and target feature | db = Database()
# get halal-reviews (reviews that include the word 'halal')
reviews_sql = '''SELECT * FROM reviews'''
reviews_df = db.select_df(reviews_sql)
print('- {} reviews containing the word halal were scraped'.format(reviews_df.shape[0]))
# get target restaurants-of-interest list
file_path = '/Users/wesamazai... | - 5092 reviews containing the word halal were scraped
- 73% of the 838 restaurants-of-interest are halal
| FTL | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter |
Feature Engineering 1. 'halal' in business name | # patch missing platform_ids and mismatch in target data
# import original businesses data
rest_sql = '''SELECT * FROM businesses WHERE url LIKE '%yelp%' '''
rest_df = db.select_df(rest_sql)
# drop Aya Kitchen
aya_id = 'y6BfLt9Gvrq2JsJvjkjdIQ'
reviews_df.drop(reviews_df[reviews_df['restaurant_id'] == aya_id].index, i... | _____no_output_____ | FTL | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter |
2. Percentage of reviews including the word halal out of all reviews | # calculate percentage of halal-containing reviews out of total reviews
grouped_reviews_df['halal_review_percent'] = grouped_reviews_df.apply(lambda row: row['halal_review_count']/row['total_review_count'], axis =1)
# plot distribution for halal vs non-halal restaurants
halal_target = grouped_reviews_df[grouped_review... | _____no_output_____ | FTL | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter |
- The higher percentage of halal-related reviews in non-halal restaurants is probably related to food carts or restaurants with few reviews to start with and they have comparison to halal-guys or halal street cuisine 3. Spacy nlp to find text patterns 3.1. tokenize and match pattern [lemma=be, lower=halal] | # # run nlp of grouped review text and save Doc to dataframe
# nlp = en_core_web_sm.load()
# grouped_reviews_df['doc'] = grouped_reviews_df['review_text'].apply(lambda x: nlp(x))
# initialize matcher
matcher = Matcher(nlp.vocab)
# specify match pattern
pattern = [{'LEMMA': 'be'},{'LOWER': 'halal'}]
matcher.add('be_ha... | _____no_output_____ | FTL | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter |
3.2. Match pattern 'halal guys/ truck' and count how many it occurs out of all the mentiones of halal | # initialize matcher
matcher = Matcher(nlp.vocab)
# find all incidences of halal
pattern = [{'LOWER': 'halal'}]
matcher.add('halal', None, pattern)
for i, doc in grouped_reviews_df['doc'].iteritems():
match = matcher(doc)
grouped_reviews_df.loc[i, 'halal_match_count'] = len(match)
# reinitialize matcher
match... | _____no_output_____ | FTL | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter |
3.3. mention of halal chicken vs. halal burger | # initialize matcher
matcher = Matcher(nlp.vocab)
# contains halal chicken
pattern1 = [{'LOWER': 'halal'}, {'LOWER': 'chicken'}]
matcher.add('chicken', None, pattern1)
for i, doc in grouped_reviews_df['doc'].iteritems():
match = matcher(doc)
grouped_reviews_df.loc[i, 'chicken'] = True if len(match) else False
... | _____no_output_____ | FTL | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter |
- When combined with halal chicken and burger do not provide significant information. - Consider trying more combinations with 'chicken', such as 'chicken over rice' or chicken as DEP=compound noun.- CreekStone has 2:1 chance of being mentioned in non-halal vs. halal restaurant. 3.4. Mention of '100% halal' | # initialize matcher
matcher = Matcher(nlp.vocab)
# contains halal chicken
pattern3 = [{'IS_DIGIT': True, 'LOWER': '100'},
{'IS_PUNCT': True},
{'LOWER': 'halal'}]
matcher.add('100%', None, pattern3)
for i, doc in grouped_reviews_df['doc'].iteritems():
match = matcher(doc)
grouped_reviews_... | _____no_output_____ | FTL | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter |
3.5. Mention of non-halal terms 4. Examine the term frequency in the labeling notes | import spacy.attrs
halal_dicts = []
non_halal_dicts = []
# for i, note in target_df['note_1'].iteritems():
# if note:
# doc = nlp(str(note))
# counts_dict = doc.count_by(spacy.attrs.IDS['LEMMA'])
# halal_dicts.append(counts_dict)
doc=nlp(target_df['note_1'].iloc[704].lower())
counts_dict... | veggie 17659162195392082590 1
raman 15907565465263018957 1
be 10382539506755952630 1
� 15133719645169837349 2
halal 12288342265014770467 1
and 2283656566040971221 1
make 9614445426764226664 1
with 12510949447758279278 1
vegetable 10226061632043966089 1
broth 2343545011278681547 2
for 16037325823156266367 1
all 13409319... | FTL | src/features/feature_engineering/Feature_engineering_v1.ipynb | WAzaizeh/Halal_o_Meter |
Intra-zonal trips Parameter estimationAssignment of inner-zonal trips is not possible with common methods of transport modelling. A Logit regression based on zonal attributes is required. | input_path = '../input/'
output_path = '../output/'
model_path = '../model/' | _____no_output_____ | Apache-2.0 | quetzal_germany-master/notebooks/cal21_inner-zone_estimation.ipynb | avi-shake/Flensburg_Modeling |
Model formulationThe Logit regression model consists of observable utility functions, one for each mode j:> V_ij = ASC_ij + b_ac_i * AC_j + b_pop_i * POP + b_cars_i * CARSWith explainatory variables* AC: accessibility as average distance to and from PT stops in km or binary for car usage* POP: population density* CARS... | # Load calibration data set
df = pd.read_csv(input_path + 'transport_demand/calibration_intra-cellular_trips_MiD2017.csv')
print(df.shape)
col_dict = {'mode_model': 'MODE', 'purpose_vp': 'PURPOSE', 'pop_density': 'POP',
'car_density': 'CARS', 'accessibility_rail': 'AC_RAIL',
'accessibility_bus':... | _____no_output_____ | Apache-2.0 | quetzal_germany-master/notebooks/cal21_inner-zone_estimation.ipynb | avi-shake/Flensburg_Modeling |
Build the calibration model with Biogeme | database = db.Database('MiD', df.copy())
globals().update(database.variables)
database.getSampleSize()
# Define Betas
asc_rail = Beta('asc_rail', 0, None, None, 0)
asc_bus = Beta('asc_bus', 0, None, None, 0)
asc_car = Beta('asc_car', 0, None, None, 1)
asc_nm = Beta('asc_nm', 0, None, None, 0)
b_ac_rail = Beta('b_ac_rai... | _____no_output_____ | Apache-2.0 | quetzal_germany-master/notebooks/cal21_inner-zone_estimation.ipynb | avi-shake/Flensburg_Modeling |
Import Library and Dataset | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
pd.set_option('display.max_columns', None)
data_train = pd.read_excel('Data_Train.xlsx')
data_test = pd.read_excel('Data_Test.xlsx') | _____no_output_____ | MIT | 10 - Feature Engineering/Feature_Engineering.ipynb | algonacci/Projects |
Combining the Dataset | price_train = data_train.Price
# Concatenate training and test sets
data = pd.concat([data_train.drop(['Price'], axis=1), data_test])
data.columns | _____no_output_____ | MIT | 10 - Feature Engineering/Feature_Engineering.ipynb | algonacci/Projects |
Exploratory Data Analysis | data.head()
data.info()
data.describe()
data = data.drop_duplicates()
data.isnull().sum()
data = data.drop(data.loc[data['Route'].isnull()].index) | _____no_output_____ | MIT | 10 - Feature Engineering/Feature_Engineering.ipynb | algonacci/Projects |
Feature Engineering | data['Airline'].unique()
import seaborn as sns
sns.countplot(x='Airline', data=data)
plt.xticks(rotation=90)
data['Airline'] = np.where(data['Airline']=='Vistara Premium economy', 'Vistara', data['Airline'])
data['Airline'] = np.where(data['Airline']=='Jet Airways Business', 'Jet Airways', data['Airline'])
data['Airli... | _____no_output_____ | MIT | 10 - Feature Engineering/Feature_Engineering.ipynb | algonacci/Projects |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.