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 |
|---|---|---|---|---|---|
Read in files | dir_in_res = '../out/20.0216 feat/reg_rf_boruta'
dir_in_anlyz = os.path.join(dir_in_res, 'anlyz_filtered')
df_featSummary = pd.read_csv(os.path.join(dir_in_anlyz, 'feat_summary.csv')) #feature summary
df_featSummary['feat_sources'] = df_featSummary['feat_sources'].apply(literal_eval)
df_featSummary['feat_genes'] = df_f... | _____no_output_____ | MIT | notebooks/10b-anlyz_run02-synthetic_lethal_classes-feat1.ipynb | pritchardlabatpsu/cga |
Breakdown - basic - top most important feature | df_counts = df_featSummary.groupby('feat_source1')['feat_source1'].count()
df_counts = df_counts.to_dict()
df_sl = pd.DataFrame([{'new_syn_lethal':df_counts['CERES'],
'classic_syn_lethal': sum([df_counts[k] for k in ['CN','Mut','RNA-seq']]) }])
df_sl = df_sl.T.squeeze()
df_sl | _____no_output_____ | MIT | notebooks/10b-anlyz_run02-synthetic_lethal_classes-feat1.ipynb | pritchardlabatpsu/cga |
Breakdown of lethality, top most important feature | df_src1 = df_featSummary[['target','feat_source1']].set_index('target')
df = pd.DataFrame({'isNotCERES': df_src1.feat_source1.isin(['RNA-seq', 'CN', 'Mut']),
'sameGene': feat_summary_annot_gene.inSame_1,
'sameParalog': feat_summary_annot_paralog.inSame_1,
'sameGS... | _____no_output_____ | MIT | notebooks/10b-anlyz_run02-synthetic_lethal_classes-feat1.ipynb | pritchardlabatpsu/cga |
Breakdown of lethality, top 10 most important feature | df_src = df_featSummary.set_index('target').feat_sources
df = pd.DataFrame({'hasNoCERES': df_src.apply(lambda x: any([n in x for n in ['CN','Mut','RNA-seq','Lineage']])),
'sameGene': feat_summary_annot_gene.inSame_top10,
'sameParalog': feat_summary_annot_paralog.inSame_top10,
... | _____no_output_____ | MIT | notebooks/10b-anlyz_run02-synthetic_lethal_classes-feat1.ipynb | pritchardlabatpsu/cga |
Module 2: Inversion In the previous module we started with a continuous distribution of a physical property and discretized it into many cells, then we performed a forward simulation that created data from known model parameters. Inversion, of course, is exactly the opposite process. Imagine each model parameter that ... | # Import Packages
import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Here is the model that we had previously: | # Begin by creating a ficticious set of model data
n_cells = 1000 # Set number of model parameters
n_nodes = n_cells + 1
xn = np.linspace(0, 1, n_nodes) # Define 1D domain on nodes
xc = 0.5*(xn[1:] + xn[:-1]) # Define 1D domain on cell centers
# Define Gaussian function:
def gauss(x, amplitude, mean, std):
"""D... | _____no_output_____ | MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Again, we define out kernel functions and averaging and volume matrices as before: | # Make the set of kernel functions
def kernel_functions(x, j, p, q):
return np.exp(-p*j*x) * np.cos(2*np.pi*q*j*x)
p = 0.01 # Set values for p, q
q = 0.15
n_data = 20 # specify number of output data
j_min = 0
j_max = n_data
j_values = np.linspace(j_min, j_max, n_data)
Gn = np.zeros((n_nodes, n_data))
for i... | (1000, 1000)
| MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Last, we produce our data: | G = Gn.T @ Av.T @ V
d = G @ mtrue
# Plot
fig, ax = plt.subplots(1, 1)
ax.plot(d, '-o')
ax.set_title('Synthetic Data $d$') | _____no_output_____ | MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Introducing noise to the data This is where we stood at the end of the last module. Next, to simulate taking data in the field, we are going to add a noise to the data before we perform our inversion. We will do this by defining a lambda function that assigns a floor value and percent scaling factor. Also, we will ass... | # Add noise to our synthetic data
add_noise = False # set to true if you want to add noise to the data
if add_noise is True:
relative_noise = 0.04
noise_floor = 1e-2
noise = (
relative_noise * np.random.randn(n_data) * np.abs(d) + # percent of data
noise_floor * np.random.randn(n_data)
... | _____no_output_____ | MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Setting up the inverse problemNow we will assemble the pieces for constructing an objective function to be minimized in the inversion. Throughout we use L2 norms, so the first thing we will do is define a simple function for computing a weighted L2 norm. | def weighted_l2_norm(W, v):
"""
A function that returns a weighted L2 norm. The parameter W is a weighting matrix
and v is a vector.
"""
Wv = W @ v
return Wv.T @ Wv | _____no_output_____ | MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Calculating $\phi_d$ We are now in a position to build up the data misfit term, $\phi_d$. We will need a function to compute the 2-norm, so constructing a function to do this is useful. Next we will make the matrix $W_d$, which is a diagonal matrix that contains the inverses of the uncertainty in our data. Again, we w... | # Calculate the data misfit, phi_d
noise_floor = 1e-3
relative_error = 0.05
standard_deviation = noise_floor + relative_error * np.abs(dobs)
# construct Wd
Wd = np.diag(1/standard_deviation)
fig, ax = plt.subplots(1, 1)
img = ax.imshow(Wd, "Greys")
plt.colorbar(img, ax=ax)
ax.set_title("Wd") | _____no_output_____ | MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Calculating $\phi_m$As discussed above, we are going to first need to make our $W_m$ matrix, which is a partitioned matrix from two other matrices, $W_s$ and $W_x$, each scaled by a separate parameter $\alpha_s$ and $\alpha_x$. We are going to discuss the manner in which $\alpha_s$ and $\alpha_x$ are selected in more ... | # Start with Ws
sqrt_vol = np.sqrt(delta_x) # in 1D - the "Volume" = length of each cell (delta_x)
Ws = np.diag(sqrt_vol)
# and now Wx
Dx = np.zeros((n_cells-1, n_cells)) # differencing matrix
for i, dx in enumerate(delta_x[:-1]):
Dx[i, i] = -1/dx
Dx[i, i+1] = 1/dx
Wx = Dx @ np.diag(sqrt_vol)
print(Ws.s... | _____no_output_____ | MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Stack Ws, Wx to make a single regularization matrix Wm | alpha_s = 1e-6
alpha_x = 1
Wm = np.vstack([
np.sqrt(alpha_s)*Ws,
np.sqrt(alpha_x)*Wx
])
print(Wm.shape) | (1999, 1000)
| MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Inverting for our recovered model At last we can invert to find our recovered model and see how it compares with the true model. First we will assign a value for $\beta$. As with the $\alpha$ parameters from before, we will assign a value, but the choice of beta will be a topic that we explore more fully in the next ... | beta = 1e-1 # Set beta value
mref = 0.5 * np.ones(n_cells) # choose a reference model
WdG = Wd @ G
mrec = (
np.linalg.inv(WdG.T @ WdG + beta * Wm.T @ Wm) @
(WdG.T @ Wd @ dobs + beta * Wm.T @ Wm @ mref)
)
fig, ax = plt.subplots(1, 1)
ax.plot(xc, mtrue, label="true")
ax.plot(xc, mrec, label="recovered")
ax.l... | _____no_output_____ | MIT | Module 2, Inversion-Doug.ipynb | lheagy/inversion-tutorial |
Speed Test | times = []
valid_mask_t = torch.from_numpy(np.ones([1,80,80,1]).astype(np.float32)).to(DEVICE)
for d_i in range(10):
_target = torch.from_numpy(d_trains[d_i].astype(np.float32)).to(DEVICE)
calibration_map = make_circle_masks(_target.size(0), map_size[0], map_size[1],
rmi... | 0.03891327977180481
0.04005876183509827
0.04132132604718208
0.04402513429522514
0.04346586391329765
0.04147135838866234
0.03921307995915413
0.038483794778585434
0.04098214581608772
0.044003926217556
---------
0.04119386710226536
| MIT | 02_Traffic_info_test_2_hidden_12_pool_multi_location.ipynb | chenmingxiang110/NCA_Prediction |
Fit interpretable models to the training set and test on validation sets. | #%matplotlib inline
#%load_ext autoreload
#%autoreload 2
import os
import pickle as pkl
from os.path import join as oj
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.feature_selection import RFE
from sklearn.linear... | Index(['ArrPtIntub', 'DxCspineInjury', 'FocalNeuroFindings', 'HighriskDiving',
'IntervForCervicalStab', 'PtExtremityWeakness', 'PtSensoryLoss',
'PtTenderExt', 'SubInj_TorsoTrunk', 'outcome'],
dtype='object')
| MIT | rulevetting/projects/csi_pecarn/notebooks/fit_models_ll.ipynb | aashen12/rule-vetting |
fit simple models **decision tree** | # fit decision tree
dt = DecisionTreeClassifier(max_depth=4, class_weight={0: 1, 1: 1e3})
dt.fit(X_train, y_train)
stats, threshes = predict_and_save(dt, model_name='decision_tree')
print(stats,threshes)
plt.show()
plt.savefig("tree-roc.png", dpi='figure', format=None, metadata=None,
bbox_inches=None, pad_inc... | _____no_output_____ | MIT | rulevetting/projects/csi_pecarn/notebooks/fit_models_ll.ipynb | aashen12/rule-vetting |
**bayesian rule list (this one is slow)** | np.random.seed(13)
# train classifier (allow more iterations for better accuracy; use BigDataRuleListClassifier for large datasets)
print('training bayesian_rule_list...')
brl = imodels.BayesianRuleListClassifier(listlengthprior=2, max_iter=10000, class1label="IwI", verbose=False)
brl.fit(X_train, y_train, feature_name... | Trained RuleListClassifier for detecting IwI
=============================================
IF IntervForCervicalStab > 0.5 THEN probability of IwI: 59.3% (54.8%-63.8%)
ELSE IF FocalNeuroFindings > 0.5 THEN probability of IwI: 15.8% (9.7%-23.0%)
ELSE IF DxCspineInjury > 0.5 THEN probability of IwI: 10.0% (5.1%-16.2%)
ELS... | MIT | rulevetting/projects/csi_pecarn/notebooks/fit_models_ll.ipynb | aashen12/rule-vetting |
**rulefit** | # fit a rulefit model
np.random.seed(13)
rulefit = imodels.RuleFitRegressor(max_rules=4)
rulefit.fit(X_train, y_train, feature_names=feature_names)
# preds = rulefit.predict(X_test)
stats, threshes = predict_and_save(rulefit, model_name='rulefit')
'''
def print_best(sens, spec):
idxs = np.array(sens) > 0.9
pri... | _____no_output_____ | MIT | rulevetting/projects/csi_pecarn/notebooks/fit_models_ll.ipynb | aashen12/rule-vetting |
**greedy (CART) rule list** | class_weight = {0: 1, 1: 100}
d = imodels.GreedyRuleListClassifier(max_depth=9, class_weight=class_weight, criterion='neg_corr')
d.fit(X_train, y_train, feature_names=feature_names, verbose=False)
stats, threshes = predict_and_save(d, model_name='grl')
# d.print_list()
print(d) | /Users/seunghoonpaik/Desktop/SH/Berkeley/Coursework/215A/Lab/final-proj/andy-github/rule-env/lib/python3.8/site-packages/numpy/lib/function_base.py:2691: RuntimeWarning: invalid value encountered in true_divide
c /= stddev[:, None]
/Users/seunghoonpaik/Desktop/SH/Berkeley/Coursework/215A/Lab/final-proj/andy-github/ru... | MIT | rulevetting/projects/csi_pecarn/notebooks/fit_models_ll.ipynb | aashen12/rule-vetting |
**rf** look at all the results | def plot_metrics(suffix, title=None, fs=15):
for fname in sorted(os.listdir(MODELS_DIR)):
if 'pkl' in fname:
if not fname[:-4] == 'rf':
r = pkl.load(open(oj(MODELS_DIR, fname), 'rb'))
# print(r)
# print(r.keys())
... | _____no_output_____ | MIT | rulevetting/projects/csi_pecarn/notebooks/fit_models_ll.ipynb | aashen12/rule-vetting |
**This notebook is an exercise in the [Introduction to Machine Learning](https://www.kaggle.com/learn/intro-to-machine-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/dansbecker/underfitting-and-overfitting).**--- RecapYou've built your first model, and now it's time to optimize... | # Code you have previously used to load data
import pandas as pd
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeRegressor
# Path of the file to read
iowa_file_path = '../input/home-data-for-ml-course/train.csv'
home_data = pd.... | _____no_output_____ | MIT | exercise-underfitting-and-overfitting.ipynb | gabboraron/Intro_to_Machine_Learning-Kaggle |
ExercisesYou could write the function `get_mae` yourself. For now, we'll supply it. This is the same function you read about in the previous lesson. Just run the cell below. | def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):
model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)
model.fit(train_X, train_y)
preds_val = model.predict(val_X)
mae = mean_absolute_error(val_y, preds_val)
return(mae) | _____no_output_____ | MIT | exercise-underfitting-and-overfitting.ipynb | gabboraron/Intro_to_Machine_Learning-Kaggle |
Step 1: Compare Different Tree SizesWrite a loop that tries the following values for *max_leaf_nodes* from a set of possible values.Call the *get_mae* function on each value of max_leaf_nodes. Store the output in some way that allows you to select the value of `max_leaf_nodes` that gives the most accurate model on you... | candidate_max_leaf_nodes = [5, 25, 50, 100, 250, 500]
# Write loop to find the ideal tree size from candidate_max_leaf_nodes
results = []
for max_leaf_nodes in candidate_max_leaf_nodes:
my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
print("Max leaf nodes: %d \t\t Mean Absolute Error: %d" %(m... | _____no_output_____ | MIT | exercise-underfitting-and-overfitting.ipynb | gabboraron/Intro_to_Machine_Learning-Kaggle |
Step 2: Fit Model Using All DataYou know the best tree size. If you were going to deploy this model in practice, you would make it even more accurate by using all of the data and keeping that tree size. That is, you don't need to hold out the validation data now that you've made all your modeling decisions. | # Fill in argument to make optimal size and uncomment
final_model = DecisionTreeRegressor(max_leaf_nodes=best_tree_size, random_state=1)
# fit the final model and uncomment the next two lines
final_model.fit(X, y)
# Check your answer
step_2.check()
step_2.hint()
step_2.solution() | _____no_output_____ | MIT | exercise-underfitting-and-overfitting.ipynb | gabboraron/Intro_to_Machine_Learning-Kaggle |
Differentiable SVGTensor optimization Load a target SVG and apply the standard pre-processing. | svg = SVG.load_svg("docs/imgs/dolphin.svg").normalize().zoom(0.9).canonicalize().simplify_heuristic() | simplify
| MIT | notebooks/svgtensor.ipynb | GeorgeProjects/deepsvg |
Convert the SVG to the differentiable SVGTensor data-structure. | svg_target = SVGTensor.from_data(svg.to_tensor())
p_target = svg_target.sample_points()
plot_points(p_target, show_color=True) | _____no_output_____ | MIT | notebooks/svgtensor.ipynb | GeorgeProjects/deepsvg |
Create an arbitrary SVG whose BΓ©zier parameters will be optimized to match the target shape. | circle = SVG.unit_circle().normalize().zoom(0.9).split(8) # split: 1/2/4/8
svg_pred = SVGTensor.from_data(circle.to_tensor()) | _____no_output_____ | MIT | notebooks/svgtensor.ipynb | GeorgeProjects/deepsvg |
SVGTensor enables to sample points in a differentiable way, so that the loss that will be backpropagated down to the SVG BΓ©zier parameters. | p_pred = svg_pred.sample_points()
plot_points(p_pred, show_color=True)
svg_pred.control1.requires_grad_(True)
svg_pred.control2.requires_grad_(True)
svg_pred.end_pos.requires_grad_(True);
optimizer = optim.Adam([svg_pred.control1, svg_pred.control2, svg_pred.end_pos], lr=0.1) | _____no_output_____ | MIT | notebooks/svgtensor.ipynb | GeorgeProjects/deepsvg |
Write a standard gradient descent algorithm and observe the step-by-step optimization! | img_list = []
for i in range(150):
optimizer.zero_grad()
p_pred = svg_pred.sample_points()
l = svg_emd_loss(p_pred, p_target)
l.backward()
optimizer.step()
if i % 4 == 0:
img = svg_pred.draw(with_points=True, do_display=False, return_png=True)
img_list.append(img)
... | SVG[Bbox(0.0 0.0 294.8680114746094 294.8680114746094)](
SVGPathGroup(SVGPath(M[P(0.0, 0.0), P(284.3949890136719, 115.12999725341797)] C[P(284.3949890136719, 115.12999725341797), P(280.5419921875, 119.21499633789062), P(274.864990234375, 119.21499633789062), P(272.9989929199219, 119.21499633789062)] C[P(272.99899291992... | MIT | notebooks/svgtensor.ipynb | GeorgeProjects/deepsvg |
Table of Contents1 Intro2 Load Data3 Cyclical Feeding3.1 TODOs4 Image Sharpening5 Source Data FaceSwap and Upscaling6 Celeba Test IntroNotebook exploring random experiments around the use of the trained Faceswap generators. | import numpy as np
import pandas as pd
import seaborn as sns
from PIL import Image
import matplotlib.pyplot as plt
from pathlib import Path
import sys
import pickle
import yaml
from numpy.random import shuffle
from ast import literal_eval
import tensorflow as tf
import cv2
from tqdm import tqdm
# Plotting
%matplotl... | _____no_output_____ | Apache-2.0 | notebooks/Creative Experiments.ipynb | 5agado/face-swap |
Load Data | # Load two random celeba faces
from_face_img = cv2.cvtColor(cv2.imread(str(data_folder / "img_align_celeba" /
"000{}{}{}.jpg".format(*np.random.randint(0, 9, 3)))),
cv2.COLOR_BGR2RGB)
to_face_img = cv2.cvtColor(cv2.imread(str(data_folder / "img_align_celeba" /
... | _____no_output_____ | Apache-2.0 | notebooks/Creative Experiments.ipynb | 5agado/face-swap |
Cyclical FeedingCycling feeding own output to generator. Can start with actual face or random noise. TODOs* Try apply text on image before feeding to generator | def crop(img, crop_factor=0.2):
h, w = img.shape[:2]
h_crop = int((h * crop_factor)//2)
w_crop = int((w * crop_factor)//2)
return img[h_crop:h-h_crop, w_crop:w-w_crop]
def zoom(img, zoom_factor=1.5):
h, w = img.shape[:2]
mat = cv2.getRotationMatrix2D((w//2, h//2), 0, zoom_factor)
#mat[:, 2] ... | _____no_output_____ | Apache-2.0 | notebooks/Creative Experiments.ipynb | 5agado/face-swap |
Image Sharpening | # adapted from https://github.com/AdityaPokharel/Sharpen-Image
regular_kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
edge_enhance_kernel = np.array([[-1,-1,-1,-1,-1],
[-1,2,2,2,-1],
[-1,2,8,2,-1],
[-2,2,2,2,-1],
... | _____no_output_____ | Apache-2.0 | notebooks/Creative Experiments.ipynb | 5agado/face-swap |
Source Data FaceSwap and UpscalingTry to cherry pick some results of face-swapping on the training data, apply upscaling to a reasonable size (e.g. 128x128) and any possible post-processing that might help in improving image quality. | input_path = data_folder / "facesets" / "cage"
out_path = data_folder / "faceswap_experiments" / "source_faceswap" / "cage_trump"
out_size = (64, 64)
# collected all image paths
img_paths = image_processing.get_imgs_paths(input_path, as_str=False)
# iterate over all collected image paths
for i, img_path in enumerate(... | _____no_output_____ | Apache-2.0 | notebooks/Creative Experiments.ipynb | 5agado/face-swap |
Celeba TestTest Celeba training and generation of artworks | def plot_sample(images: list, predict_fun,
tanh_fix=False, save_to: str=None,
nb_test_imgs=14, nb_columns=3, white_border=3):
# need number of images divisible by number of columns
nb_rows = nb_test_imgs//nb_columns
assert nb_test_imgs % nb_columns == 0
images = images[0... | _____no_output_____ | Apache-2.0 | notebooks/Creative Experiments.ipynb | 5agado/face-swap |
In this notebook, we show the dynamical relaxation time. Init | from __future__ import division
%load_ext autoreload
%autoreload 2
import sys,os
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from matplotlib import rcParams, rc
import spc
import model
import chi2
import margin
import tools as tl
import numpy as np
import matplotlib
%matplotlib notebook
import matplotlib.pyplo... | _____no_output_____ | MIT | notebooks/3_demo_dynamical_relaxation_time.ipynb | ChenSun-Phys/ULDM_x_SPARC |
Functions moved to the corresponding .py file | # def model.tau(f, m, v=57., rho=0.003):
# """ relaxation time computation [Gyr]
# :param f: fraction
# :param m: scalar mass [eV]
# :param v: dispersion [km/s]
# :param rho: DM density [Msun/pc**3]
# """
# return 0.6 * 1./f**2 * (m/(1.e-22))**3 * (v/100)**6 * (rho/0.1)**(-2)
# mod... | _____no_output_____ | MIT | notebooks/3_demo_dynamical_relaxation_time.ipynb | ChenSun-Phys/ULDM_x_SPARC |
Check the data | #gal = data2['UGC01281']
gal = data2['UGC04325']
print(gal.Vobs[-1])
model.reconstruct_density_DM(gal)
plt.subplots()
plt.plot(gal.R, gal.Vobs, '.')
plt.xlabel('R [kpc]')
plt.ylabel(r'$v$ km/s')
fn, _, _ = model.reconstruct_density_DM(gal)
plt.subplots()
r_arr = np.logspace(gal.R[0], gal.R[-1])
plt.plot(r_arr, fn(r_arr... | _____no_output_____ | MIT | notebooks/3_demo_dynamical_relaxation_time.ipynb | ChenSun-Phys/ULDM_x_SPARC |
Relaxatin time at last data point | f1 = 0.85
f2 = 0.15
m1_arr = np.logspace(-25, -19, 100)
m2_arr = np.logspace(-25, -19, 100)
m1_mesh, m2_mesh = np.meshgrid(m1_arr, m2_arr, indexing='ij')
m1_flat, m2_flat = m1_mesh.reshape(-1), m2_mesh.reshape(-1)
gal = data2['UGC04325']
tau1_flat = []
tau1_self_flat = []
for i in range(len(m1_flat)):
m1 = m1_fla... | _____no_output_____ | MIT | notebooks/3_demo_dynamical_relaxation_time.ipynb | ChenSun-Phys/ULDM_x_SPARC |
This is the result with coulomb log > 1. | plt.subplots()
plt.plot(m1_target_arr, 'k.')
plt.yscale('log')
plt.ylim(1e-25, 1e-19)
plt.xlabel('Galaxy ID')
plt.ylabel('m [eV]')
plt.title('Dynamical relaxation time set to 10 Gyr')
_, ax = plt.subplots()
plt.fill_betweenx(np.logspace(-25, -19), 1e-25, 2.66e-21, color='salmon', alpha=0.5, zorder=0)
f1 = 0.85
f2 = 0.... | _____no_output_____ | MIT | notebooks/3_demo_dynamical_relaxation_time.ipynb | ChenSun-Phys/ULDM_x_SPARC |
change the fraction | #gal = data2['NGC0100']
gal = data2['UGC04325']
#gal = data2['UGC01281']
#gal = data2['NGC3769']
#gal = data2['NGC3877']
#gal = data2['NGC6503']
m2 = 1.e-23 # [eV]
#f2 = 0.15
m1_arr = np.logspace(-25.2, -18.8, 50)
f1_arr = np.linspace(0., 1., 50)
m1_mesh, f1_mesh = np.meshgrid(m1_arr, f1_arr, indexing='ij')
m1_flat, ... | _____no_output_____ | MIT | notebooks/3_demo_dynamical_relaxation_time.ipynb | ChenSun-Phys/ULDM_x_SPARC |
velocity dispersion | gal = data2['NGC0100']
R = np.logspace(-1, 3)
#y = model.sigma_disp(gal, R, get_array=False)
# debug interp
#y_npinterp = model.sigma_disp_over_vcirc(gal, R)
# no interp
ratio_arr = model.sigma_disp_over_vcirc(gal, R)
plt.subplots()
#plt.plot(R, y)
#plt.plot(R, y_npinterp)
plt.plot(R, ratio_arr, '--')
plt.xscale('l... | _____no_output_____ | MIT | notebooks/3_demo_dynamical_relaxation_time.ipynb | ChenSun-Phys/ULDM_x_SPARC |
The Comloub Log | # plot out to check
gal = spc.findGalaxyByName('UGC04325', data)
interpol_method = 'linear' #nearest
f_arr = np.linspace(0.01, 1, 200)
#m = 2e-23
#m = 1.3e-23
m = 1e-23
#m = 3e-24
#m = 1e-21
r_supply_arr = np.array([model.supply_radius(f, m, gal) for f in f_arr])
r_relax_arr = np.array([model.relax_radius(f, m, gal,... | _____no_output_____ | MIT | notebooks/3_demo_dynamical_relaxation_time.ipynb | ChenSun-Phys/ULDM_x_SPARC |
Although Basenji is unaware of the locations of known genes in the genome, we can go in afterwards and ask what a model predicts for those locations to interpret it as a gene expression prediction.To do this, you'll need * Trained model * Gene Transfer Format (GTF) gene annotations * BigWig coverage tracks * Gene seque... | import os, subprocess
if not os.path.isfile('data/hg19.ml.fa'):
subprocess.call('curl -o data/hg19.ml.fa https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa', shell=True)
subprocess.call('curl -o data/hg19.ml.fa.fai https://storage.googleapis.com/basenji_tutorial_data/hg19.ml.fa.fai', shell=True) ... | _____no_output_____ | Apache-2.0 | tutorials/genes.ipynb | JasperSnoek/basenji |
Next, let's grab a few CAGE datasets from FANTOM5 related to heart biology.These data were processed by1. Aligning with Bowtie2 with very sensitive alignment parameters.2. Distributing multi-mapping reads and estimating genomic coverage with bam_cov.py | if not os.path.isfile('data/CNhs11760.bw'):
subprocess.call('curl -o data/CNhs11760.bw https://storage.googleapis.com/basenji_tutorial_data/CNhs11760.bw', shell=True)
subprocess.call('curl -o data/CNhs12843.bw https://storage.googleapis.com/basenji_tutorial_data/CNhs12843.bw', shell=True)
subprocess.call('c... | _____no_output_____ | Apache-2.0 | tutorials/genes.ipynb | JasperSnoek/basenji |
Then we'll write out these BigWig files and labels to a samples table. | samples_out = open('data/heart_wigs.txt', 'w')
print('aorta\tdata/CNhs11760.bw', file=samples_out)
print('artery\tdata/CNhs12843.bw', file=samples_out)
print('pulmonic_valve\tdata/CNhs12856.bw', file=samples_out)
samples_out.close() | _____no_output_____ | Apache-2.0 | tutorials/genes.ipynb | JasperSnoek/basenji |
Predictions in the portion of the genome that we trained might inflate our accuracy, so we'll focus on chr9 genes, which have formed my typical test set. Then we use [basenji_hdf5_genes.py](https://github.com/calico/basenji/blob/master/bin/basenji_hdf5_genes.py) to create the file.The most relevant options are:| Option... | ! basenji_hdf5_genes.py -g data/human.hg19.genome -l 262144 -c 0.333 -p 3 -t data/heart_wigs.txt -w 128 data/hg19.ml.fa data/gencode_chr9.gtf data/gencode_chr9_l262k_w128.h5 | _____no_output_____ | Apache-2.0 | tutorials/genes.ipynb | JasperSnoek/basenji |
Now, you can either train your own model in the [Train/test tutorial](https://github.com/calico/basenji/blob/master/tutorials/train_test.ipynb) or download one that I pre-trained. | if not os.path.isfile('models/gm12878_d10.tf.meta'):
subprocess.call('curl -o models/gm12878_d10.tf.index https://storage.googleapis.com/basenji_tutorial_data/model_gm12878_d10.tf.index', shell=True)
subprocess.call('curl -o models/gm12878_d10.tf.meta https://storage.googleapis.com/basenji_tutorial_data/model_g... | _____no_output_____ | Apache-2.0 | tutorials/genes.ipynb | JasperSnoek/basenji |
Finally, you can offer data/gencode_chr9_l262k_w128.h5 and the model to [basenji_test_genes.py](https://github.com/calico/basenji/blob/master/bin/basenji_test_genes.py) to make gene expression predictions and benchmark them.The most relevant options are:| Option/Argument | Value | Note ||:---|:---|:---|| -o | data/genc... | ! basenji_test_genes.py -o data/gencode_chr9_test --rc -s --table models/params_small.txt models/gm12878_best.tf data/gencode_chr9_l262k_w128.h5 | _____no_output_____ | Apache-2.0 | tutorials/genes.ipynb | JasperSnoek/basenji |
Day 1: Chronal Calibration "We've detected some temporal anomalies," one of Santa's Elves at the Temporal Anomaly Research and Detection Instrument Station tells you. She sounded pretty worried when she called you down here. "At 500-year intervals into the past, someone has been changing Santa's history!""The good new... | day1_input = read_input('day_01.txt')
day1_freq_changes = map(int, day1_input.split())
# Part 1 - total frequency change
sum(day1_freq_changes) | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 1 Part Two You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice.For example, using the same list of changes above, the device would loop as follows: Current frequency 0, change of +1; resulting frequency ... | def first_freq_seen_twice(changes):
# Keep looping through input and tracking what how many times we've seen current frequency
i = 0
loop_count = 0
N = len(changes)
seen_twice = None
current_freq = 0
freq_seen = defaultdict(int)
freq_seen[0] = 1
while seen_twice is None:
if ... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Feels like there should be a smarter way to do this e.g. use cumsum input list somehow.We see from the naive solution that it takes 142 loops to see a frequency again.The plot below shows that the frequency changes are usually small with a few large jumps, and from part 1 we know that each loop has a net offset of +402... | _ = plt.plot(np.cumsum(day1_freq_changes))
_ = plt.show() | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 2: Inventory Management System You stop falling through time, catch your breath, and check the screen on the device. "Destination reached. Current Year: 1518. Current Location: North Pole Utility Closet 83N10." You made it! Now, to find those anomalies.Outside the utility closet, you hear footsteps and a voice. ".... | box_ids = read_input('day_02.txt').split('\n')
len(box_ids)
def count_letters(box_id):
res = defaultdict(int)
for letter in box_id:
res[letter] += 1
count_2 = 1 if 2 in res.values() else 0
count_3 = 1 if 3 in res.values() else 0
return count_2, count_3
# checksum =
np.prod(np.array([sum(lst... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part TwoConfident that your list of box IDs is complete, you're ready to find the boxes full of prototype fabric.The boxes will have IDs which differ by exactly one character at the same position in both strings. For example, given the following box IDs: abcde fghij klmno pqrst fguij axcye wvxyzTh... | box_ids_ints = np.array([[ord(c) for c in box_id] for box_id in box_ids])
def find_diff_1_boxes(box_ids):
X = np.array([[ord(c) for c in box_id] for box_id in box_ids])
res = []
n_boxes = len(box_ids)
for i in range(n_boxes):
for j in range(i, n_boxes):
char_diff = np.not_equal(X[i, ... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 3: No Matter How You Slice It The Elves managed to locate the chimney-squeeze prototype fabric for Santa's suit (thanks to someone who helpfully wrote its box IDs on the wall of the warehouse in the middle of the night). Unfortunately, anomalies are still affecting them - nobody can even agree on how to cut the fa... | def parse_day_03():
lines = [line.split() for line in read_input('day_03.txt').split('\n')]
def parse_rec(rec):
id = int(rec[0].lstrip('#'))
x0, y0 = map(int, rec[2].rstrip(':').split(','))
w, h = map(int, rec[3].split('x'))
return {'id': id, 'x0': x0, 'y0': y0, 'w': w, 'h': h}
... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part Two Amidst the chaos, you notice that exactly one claim doesn't overlap by even a single square inch of fabric with any other claim. If you can somehow draw attention to it, maybe the Elves will be able to make Santa's suit after all!For example, in the claims above, only claim 3 is intact after all claims are ma... | events = sorted(read_input('day_04.txt').split('\n'))
def parse_sleep_events(events):
res = []
rec = None
for event in events:
if 'Guard' in event:
# Start new record
if rec is not None:
res.append(rec)
rec = {
'guard_id': int(re.fi... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part Two Strategy 2: Of all guards, which guard is most frequently asleep on the same minute?In the example above, Guard 99 spent minute 45 asleep more than any other guard or minute - three times in total. (In all other cases, any guard spent any minute asleep at most twice.)What is the ID of the guard you chose mult... | def find_most_often_asleep(guard_sleeps):
often_asleep = {k: np.sum(v, axis=0) for k, v in guard_sleeps.iteritems()}
most_sleeps = 0
sleep_time = None
sleep_guard = None
for guard, sleep in often_asleep.iteritems():
if np.max(sleep) > most_sleeps:
most_sleeps = np.max(sleep)
... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 5: Alchemical Reduction You've managed to sneak in to the prototype suit manufacturing lab. The Elves are making decent progress, but are still struggling with the suit's size reduction capabilities.While the very latest in 1518 alchemical technology might have solved their problem eventually, you can do better. Y... | polymer = read_input('day_05.txt')
def reduce_polymer(polymer, remove_unit=None):
lower_letters = [chr(x) for x in range(ord('a'), ord('z') + 1)]
upper_letters = [chr(x) for x in range(ord('A'), ord('Z') + 1)]
lower_upper = [low + upp for low, upp in zip(lower_letters, upper_letters)]
upper_lower = [upp... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part Two Time to improve the polymer.One of the unit types is causing problems; it's preventing the polymer from collapsing as much as it should. Your goal is to figure out which unit type is causing the most problems, remove all instances of it (regardless of polarity), fully react the remaining polymer, and measure ... | min([len(reduce_polymer(polymer, chr(x))) for x in range(ord('a'), ord('z')+1)]) | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 6: Chronal Coordinates The device on your wrist beeps several times, and once again you feel like you're falling."Situation critical," the device announces. "Destination indeterminate. Chronal interference detected. Please specify new target coordinates."The device then produces a list of coordinates (your puzzle ... | coords = np.array([[int(x), int(y)] for x, y in [c.split(',') for c in read_input('day_06.txt').split('\n') ]])
coords[:10]
def label_closest(coords):
x_max, y_max = coords.max(axis=0) + 1
region = np.nan*np.zeros((x_max, y_max))
for x in range(x_max):
for y in range(y_max):
dist = np.... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part Two On the other hand, if the coordinates are safe, maybe the best you can do is try to find a region near as many coordinates as possible.For example, suppose you want the sum of the Manhattan distance to all of the coordinates to be less than 32. For each location, add up the distances to all of the given coord... | def label_total_dist(coords):
x_max, y_max = coords.max(axis=0) + 1
region = np.nan*np.zeros((x_max, y_max))
for x in range(x_max):
for y in range(y_max):
region[x, y] = np.sum(np.abs(coords - np.array([x, y])))
return region
total_dist = label_total_dist(coords)
np.sum(total_dist < ... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 7: The Sum of Its Parts You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed ashore. It's quite cold out, so you decide to risk c... | step_dep = [[c[5], c[-12]] for c in read_input('day_07.txt').split('\n')]
def parse_dep(step_dep):
pre_cond, step = zip(*step_dep)
all_steps = list(set(pre_cond) | set(step))
deps = defaultdict(list)
for d in step_dep:
deps[d[1]].append(d[0])
for d in list(set(all_steps) - set(deps.keys())):... | {0: ('S', 79), 1: [], 2: [], 3: [], 4: []}
{0: ('C', 63), 1: [], 2: [], 3: [], 4: []}
{0: ('L', 72), 1: ('P', 76), 2: [], 3: [], 4: []}
{0: ('V', 82), 1: ('P', 4), 2: ('W', 83), 3: [], 4: []}
{0: ('V', 78), 1: ('A', 61), 2: ('W', 79), 3: ('M', 73), 4: ('Q', 77)}
{0: ('V', 17), 1: ('Y', 85), 2: ('W', 18), 3: ('M', 12), ... | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part Two As you're about to begin construction, four of the Elves offer to help. "The sun will set soon; it'll go faster if we work together." Now, you need to account for multiple people working on steps simultaneously. If multiple steps are available, workers should still begin them in alphabetical order.Each step t... | license = map(int, read_input('day_08.txt').split())
license[:10]
def parse_license(license):
nodes = {}
node = 0
n_node = 0
meta_sum = 0
n_meta = 0
parent = None
mode = 'read_n_child'
for x in license:
if mode == 'read_n_child':
if node not in nodes.keys():
... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part Two The second check is slightly more complicated: you need to find the value of the root node (A in the example above).The value of a node depends on whether it has child nodes.If a node has no child nodes, its value is the sum of its metadata entries. So, the value of node B is 10+11+12=33, and the value of nod... | license_nodes[0]['value'] | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 9: Marble Mania You talk to the Elves while you wait for your navigation system to initialize. To pass the time, they introduce you to their favorite marble game.The Elves play this game by taking turns arranging the marbles in a circle according to very particular rules. The marbles are numbered starting with 0 a... | n_players, n_marbles = [int(el) for i, el in enumerate(read_input('day_09.txt').split()) if i in [0, 6]]
def play_marbles(n_players, n_marbles, display=False):
players = defaultdict(int)
current_player = 1
current_pos = 0
marbles = deque()
marbles.append(0)
for m in range(1, n_marbles + 1):
... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part Two Amused by the speed of your answer, the Elves are curious:What would the new winning Elf's score be if the number of the last marble were 100 times larger?Your puzzle answer was 3150377341. Confession:My original solution using Python lists was obviously going to be far to slow for this (took about 20s for P... | play_marbles(n_players, n_marbles * 100) | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 10: The Stars Align It's no use; your navigation system simply isn't capable of providing walking directions in the arctic circle, and certainly not in 1018.The Elves suggest an alternative. In times like these, North Pole rescue operations will arrange points of light in the sky to guide missing Elves back to bas... | stars = np.array(map(lambda s: map(int,
s.lstrip(
'position=<'
).replace(
'> velocity=<', ','
).rstrip(
'>'
).split(
... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part TwoGood thing you didn't have to wait, because that would have taken a long time - much longer than the 3 seconds in the example above.Impressed by your sub-hour communication capabilities, the Elves are curious: exactly how many seconds would they have needed to wait for that message to appear?Your puzzle answer... | def grid_power(serial):
X, Y = np.meshgrid(np.arange(300, dtype=np.int)+1, np.arange(300, dtype=np.int)+1)
P = (np.floor((((((X + 10) * Y) + serial) * (X + 10)) % 1000) / 100) - 5).astype(np.int)
return P
def find_max_grid_power(power, size=3):
p_max = 0
x_m = 0
y_m = 0
y_max, x_max = power.... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part TwoYou discover a dial on the side of the device; it seems to let you select a square of any size, not just 3x3. Sizes from 1x1 to 300x300 are supported.Realizing this, you now must find the square of any size with the largest total power. Identify this square by including its size as a third parameter after the ... | find_max_grid_power(grid_power(42), 12)
def find_max_grid_power_and_size(serial):
power = grid_power(serial)
p_max = 0
x_m = 0
y_m = 0
s_m = 0
for size in range(1, 301):
p, x, y, s = find_max_grid_power(power, size)
if p > p_max:
p_max = p
x_m = x
... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 12: Subterranean Sustainability The year 518 is significantly more underground than your history books implied. Either that, or you've arrived in a vast cavern network under the North Pole.After exploring a little, you discover a long tunnel that contains a row of small pots as far as you can see to your left and ... | pots_input = read_input('day_12.txt')
def parse_pots_rule(pots_input):
lines = pots_input.split('\n')
initial_state = lines[0].lstrip('initial state: ')
update_rules = defaultdict(lambda: '.')
for rule in lines[2:]:
r, t = rule.split(' => ')
update_rules[r] = t
return initial_state, ... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part TwoYou realize that 20 generations aren't enough. After all, these plants will need to last another 1500 years to even reach your timeline, not to mention your future.After fifty billion (50000000000) generations, what is the sum of the numbers of all pots which contain a plant?Your puzzle answer was 115000000045... | # See if things settle down after a while
iterate_pots_update(pots_initial, pots_rule, 120, display_count=True) | (111, 23, 3010)
(112, 23, 3033)
(113, 23, 3056)
(114, 23, 3079)
(115, 23, 3102)
(116, 23, 3125)
(117, 23, 3148)
(118, 23, 3171)
(119, 23, 3194)
| Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Looks like by generation 120 the population stops changing and pot sum keeps increasing by 23 each generation. | # Final pot count after 50,000,000,000 generations
3217 + (23 * (50000000000 - 120)) | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 13: Mine Cart Madness A crop of this size requires significant logistics to transport produce, soil, fertilizer, and so on. The Elves are very busy pushing things around in carts on some kind of rudimentary system of tracks they've come up with.Seeing as how cart-and-track systems don't appear in recorded history ... | tracks_input = read_input('day_13.txt')
tracks_test_input = r"""/->-\
| | /----\
| /-+--+-\ |
| | | | v |
\-+-/ \-+--/
\------/ """
def parse_tracks(tracks):
mine = np.array(map(list, tracks.split('\n')))
return mine
print(parse_tracks(tracks_test_input))
def update_tracks(mine):
new_mine... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Day 14: Chocolate Charts You finally have a chance to look at all of the produce moving around. Chocolate, cinnamon, mint, chili peppers, nutmeg, vanilla... the Elves must be growing these plants to make hot chocolate! As you realize this, you hear a conversation in the distance. When you go to investigate, you discov... | def make_recipes(n_recipes=0, find_recipe=None, initial='37'):
recipes = initial
pos_1 = 0
pos_2 = 1
new_recipes = []
if not find_recipe:
loop_cond = (lambda r: len(r) < n_recipes + 10)
else:
loop_cond = (lambda r: not(find_recipe in r[-len(find_recipe)-1:]))
while loop_... | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
Part TwoAs it turns out, you got the Elves' plan backwards. They actually want to know how many recipes appear on the scoreboard to the left of the first recipes whose scores are the digits from your puzzle input.- 51589 first appears after 9 recipes.- 01245 first appears after 5 recipes.- 92510 first appears after 18... | make_recipes(None, '59414')
make_recipes(None, '260321') | _____no_output_____ | Apache-2.0 | Advent Of Code 2018 mattmcd.ipynb | mattmcd/AdventOfCode2018 |
PART IISentiment Analysis Classifications - Review and ComparisonFirst, we needed to create vector words. For simplicity, we used a pre-trained model.Google was able to teach the Word2Vec model on a massive Google News dataset that contained over 100 billion different words! Google has created [3 million vector words](... | import numpy as np
import pandas as pd
import pickle
import gensim, logging
import gensim.models.keyedvectors as word2vec
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Also let's write a style for alignment in the middle of all graphs, images, etc: | from IPython.core.display import HTML
HTML("""
<style>
.output_png {
display: table-cell;
text-align: center;
vertical-align: middle;
}
</style>
""") | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Next, we will load the sample data we processed in the previous part: | with open('documents.pql', 'rb') as f:
docs = pickle.load(f)
print("Number of documents:", len(docs)) | Number of documents: 38544
| MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Now we will load our glove model in word2vec format. Because the GloVe dump from Stanford's site is slightly different from the word2vec format. You can convert a GloVe file to word2vec format using the following command in your console:`python -m gensim.scripts.glove2word2vec --input model/glove.6B.50d.txt --output m... | model = word2vec.KeyedVectors.load_word2vec_format('model/glove.6B.50d.w2vformat.txt', binary=False) | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Now let's get a list of all the words from our dictionary: | words = list(model.vocab) | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Just to make sure everything is loaded correctly, we can look at the dimensions of the dictionary list and the embedding matrix: | print(words[:50], "\n\nTotal words:", len(words), "\n\nWord-Vectors shape:", model.vectors.shape) | ['the', ',', '.', 'of', 'to', 'and', 'in', 'a', '"', "'s", 'for', '-', 'that', 'on', 'is', 'was', 'said', 'with', 'he', 'as', 'it', 'by', 'at', '(', ')', 'from', 'his', "''", '``', 'an', 'be', 'has', 'are', 'have', 'but', 'were', 'not', 'this', 'who', 'they', 'had', 'i', 'which', 'will', 'their', ':', 'or', 'its', 'one... | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
We can also find a word like "football" in our word list and then access the corresponding vector through the embedding matrix: | print(model['football']) | [-1.8209 0.70094 -1.1403 0.34363 -0.42266 -0.92479 -1.3942
0.28512 -0.78416 -0.52579 0.89627 0.35899 -0.80087 -0.34636
1.0854 -0.087046 0.63411 1.1429 -1.6264 0.41326 -1.1283
-0.16645 0.17424 0.99585 -0.81838 -1.7724 0.078281 0.13382
-0.59779 -0.45068 2.5474 1.0693 -... | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Word Average Embedding ModelWell, let's start analyzing our vectors. Our first approach will be the **word average embedding model**. The essence of this naive approach is to take the average of all word vectors from a sentence to get one 50-dimensional vector that represents the tone of the whole sentence that we feed... | def sent_embed(words, docs):
x_sent_embed, y_sent_embed = [], []
count_words, count_non_words = 0, 0
# recover the embedding of each sentence with the average of the vector that composes it
# sent - sentence, state - state of the sentence (pos/neg)
for sent, state in docs:
# average e... | 30709 out of 1802696 words were not found in the vocabulary.
| MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Cosine SimilarityTo measure the similarity of 2 words, we need a way to measure the degree of similarity between 2 embedding vectors for these 2 words. Given 2 vectors $u$ and $v$, cosine similarity is determined as follows:$$\text{cosine_similarity(u, v)} = \frac {u . v} {||u||_2 ||v||_2} = cos(\theta)$$where: * $u.v$... | def cosine_similarity(u, v):
"""
Cosine similarity reflects the degree of similariy between u and v
Arguments:
u -- a word vector of shape (n,)
v -- a word vector of shape (n,)
Returns:
cosine_similarity -- the cosine similarity between u and v defined by the ... | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Let's check the cosine similarity on 2 negative sentences: | print("Sentence #5: ", docs[5], "\n\nSentence #7: ", docs[7])
print("\nSentence Embedding #5: ", x[5], "\n\nSentence Embedding #7: ", x[7])
print("cosine_similarity = ", cosine_similarity(np.array(x[5]), np.array(x[7]))) | cosine_similarity = 0.8968743967161681
| MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
A value of 0.89 indicates that the sentences are close to each other, and so it is.Let's check on two positive sentences: | print("Sentence #1: ", docs[1], "\n\nSentence #4: ", docs[4])
print("\nSentence Embedding #1: ", x[1], "\n\nSentence Embedding #4: ", x[4])
print("cosine_similarity = ", cosine_similarity(np.array(x[1]), np.array(x[4]))) | cosine_similarity = 0.9481159093219256
| MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
These sentences are also close to each other. So now let's check sentences with different states: | print("Sentence #1: ", docs[0], "\n\nSentence #5: ", docs[6])
print("cosine_similarity = ", cosine_similarity(np.array(x[0]), np.array(x[6]))) | cosine_similarity = 0.7410293614966914
| MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
As we see, our average embedding still has some problems with separating different classes with cosine similarity. Split Corpus Now, for further work, we will divide our corpus for training, testing and development sets: | from sklearn.model_selection import train_test_split
# train test
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
# train dev
x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=42)
print('Length of x_train:', len(x_train), '| Lengt... | Shape of x_train set: (24668, 50)
| MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Visualization of Classification ReportWe will need these methods when we start to visualize our data, so we will write them now.The following function takes the conclusion of the `classification_report` function as an argument and plots the results ( function is based on [this](https://stackoverflow.com/a/31689645/1446... | def plot_classification_report(classification_report, title='Classification Report', cmap='RdBu'):
lines = classification_report.split('\n')
classes, plotMat, support, class_names = [], [], [], []
for line in lines[2 : (len(lines) - 5)]:
t = line.strip().split()
if len(t) < 2: con... | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
This function is designed to create a heatmap with text in each cell using the matplotlib library (code based on idea from [here](https://stackoverflow.com/a/16124677/14467732)): | def heatmap(AUC, title, xlabel, ylabel, xticklabels, yticklabels, figure_width=40, figure_height=20, correct_orientation=False, cmap='RdBu'):
fig, ax = plt.subplots()
c = ax.pcolor(AUC, edgecolors='k', linestyle='dashed', linewidths=0.2, cmap=cmap)
# put the major ticks at the middle of each cell
ax.se... | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
This function just inserts the text into the cells of the heatmap (idea is taken from [here](https://stackoverflow.com/a/25074150/14467732)): | def show_val(pc, fmt="%.2f", **kw):
pc.update_scalarmappable()
ax = pc.axes
for p, color, value in zip(pc.get_paths(), pc.get_facecolors(), pc.get_array()):
x, y = p.vertices[:-2, :].mean(0)
if np.all(color[:3] > 0.5):
color = (0.0, 0.0, 0.0)
else:
color = (1.... | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
The last auxiliary function is intended to specify the size of the figure in centimeters in matplotlib, because by default there is only the method `set_size_inches`, therefore, we will convert inches to centimeters and use this method: | def cm_to_inch(*dim):
inch = 2.54
return tuple(i/inch for i in dim[0]) if type(dim[0]) == tuple else tuple(i/inch for i in dim) | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
**Note:** To better understand the following classifiers, I advise you to read [this article](https://towardsdatascience.com/comparative-study-on-classic-machine-learning-algorithms-24f9ff6ab222) or other similar ones that you will find on the Internet. KNN ModelThe K-nearest neighbors (KNN) algorithm is a type of supe... | from sklearn.neighbors import KNeighborsClassifier
error = []
# calculating error for neighbor values between 1 and 25
for i in range(1, 25):
knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(x_train, y_train)
pred_i = knn.predict(x_test)
error.append(np.mean(pred_i != y_test)) | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
The next step is to plot the error values against neighbor values: | plt.figure(figsize=(10, 5))
plt.plot(range(1, 25), error, color='black', linestyle='dashed', marker='o', markerfacecolor='green', markersize=10)
plt.title('Error Rate Neighbor Value')
plt.xlabel('Neighbor Value')
plt.ylabel('Mean Error') | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
As we can see, it is best to take k=5, but still mean error a little higher than normal. | # create KNN Classifier
knn = KNeighborsClassifier(n_neighbors=5, weights='distance')
# train the classifier using the training sets
knn.fit(x_train, y_train)
# predict the response for test dataset
y_pred = knn.predict(x_test)
print("Nearest Neighbors Result (k=5):\n" + '-' * 35)
print("Accuracy Score (k=5):", str(... | Nearest Neighbors Result (k=5):
-----------------------------------
Accuracy Score (k=5): 71.46%
Accuracy (x_train, y_train): 100.0%
| MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
The accuracy of the model is good, we can work with it.Now let's explore our KNN Classification results with help of `classification_report` function from sklearn.metrics: | from sklearn.metrics import classification_report
print('\nClassification KNN:\n', classification_report(y_test, knn.predict(x_test))) |
Classification KNN:
precision recall f1-score support
0 0.67 0.65 0.66 3292
1 0.74 0.77 0.75 4417
accuracy 0.71 7709
macro avg 0.71 0.71 0.71 7709
weighted avg 0.71 ... | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Now finally let's visualize our classification report: | plot_classification_report(classification_report(y_test, knn.predict(x_test)), title='KNN Classification Report') | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Logistic RegressionLogistic Regression is a Machine Learning classification algorithm that is used to predict the probability of a categorical dependent variable. In logistic regression, the dependent variable is a binary variable that contains data coded as 1 (yes, success, etc.) or 0 (no, failure, etc.). In other wor... | from sklearn.linear_model import LogisticRegression
logit = LogisticRegression(solver='liblinear', multi_class='ovr', n_jobs=1)
logit.fit(x_train, y_train)
print("Accuracy Score:", str(round(logit.score(x_test, y_test) * 100, 2)) + '%')
print('\nClassification Logistic Regression:\n', classification_report(y_test, log... |
Classification Logistic Regression:
precision recall f1-score support
0 0.70 0.64 0.67 3292
1 0.75 0.79 0.77 4417
accuracy 0.73 7709
macro avg 0.72 0.72 0.72 7709
weighted a... | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Now let's visualize our classification report: | plot_classification_report(classification_report(y_test, logit.predict(x_test)), title='Logistic Regression Classification Report') | _____no_output_____ | MIT | Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb | JackShen1/sentimento |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.