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
Run the following cell on the "test.jpg" image to verify that your function is correct.
out_scores, out_boxes, out_classes = predict(sess, "test.jpg")
Found 7 boxes for test.jpg car 0.60 (925, 285) (1045, 374) car 0.66 (706, 279) (786, 350) bus 0.67 (5, 266) (220, 407) car 0.70 (947, 324) (1280, 705) car 0.74 (159, 303) (346, 440) car 0.80 (761, 282) (942, 412) car 0.89 (367, 300) (745, 648)
MIT
Convolutional_Neural_Networks/Autonomous driving application Car detection/Autonomous+driving+application+-+Car+detection+-+v3.ipynb
mnrmja007/my_dl_projects
Summary and Observations 1) AString Integrals provide smooth curly connections between two straight lines2) Further integrals provide smooth curly connections between parabolas!!3) In general, AString integrals can provide smooth connections between any similar shapes!!!
AString1(0) v=[0,0.1,0.25,0.5,0.9,1] for i in v: print(AString1(i))
_____no_output_____
MIT
AString Solutions.ipynb
SolitonScientific/AtomicString
Your first neural networkIn this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and th...
%matplotlib inline %load_ext autoreload %autoreload 2 %config InlineBackend.figure_format = 'retina' import numpy as np import pandas as pd import matplotlib.pyplot as plt
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Load and prepare the dataA critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon!
data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) rides.head()
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Checking out the dataThis dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the `cnt` column. You can see the first few rows of the data above.Below is a plot showing the number of bike riders ov...
rides[:24*10].plot(x='dteday', y='cnt')
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Dummy variablesHere we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to `get_dummies()`.
dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday'] for each in dummy_fields: dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False) rides = pd.concat([rides, dummies], axis=1) fields_to_drop = ['instant', 'dteday', 'season', 'weathersit', 'weekday', 'atemp', 'mnth...
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Scaling target variablesTo make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.The scaling factors are saved so we can go backwards when we use the network for predictions.
quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed'] # Store scalings in a dictionary so we can convert back later scaled_features = {} for each in quant_features: mean, std = data[each].mean(), data[each].std() scaled_features[each] = [mean, std] data.loc[:, each] = (data[each] - me...
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Splitting the data into training, testing, and validation setsWe'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders.
# Save data for approximately the last 21 days test_data = data[-21*24:] # Now remove the test data from the data set data = data[:-21*24] # Separate the data into features and targets target_fields = ['cnt', 'casual', 'registered'] features, targets = data.drop(target_fields, axis=1), data[target_fields] test_feat...
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set).
# Hold out the last 60 days or so of the remaining data as a validation set train_features, train_targets = features[:-60*24], targets[:-60*24] val_features, val_targets = features[-60*24:], targets[-60*24:]
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Time to build the networkBelow you'll build your network. We've built out the structure. You'll implement both the forward pass and backwards pass through the network. You'll also set the hyperparameters: the learning rate, the number of hidden units, and the number of training passes.The network has two layers, a hid...
############# # In the my_answers.py file, fill out the TODO sections as specified ############# from my_answers import NeuralNetwork def MSE(y, Y): return np.mean((y-Y)**2)
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Unit testsRun these unit tests to check the correctness of your network implementation. This will help you be sure your network was implemented correctly befor you starting trying to train it. These tests must all be successful to pass the project.
import unittest inputs = np.array([[0.5, -0.2, 0.1]]) targets = np.array([[0.4]]) test_w_i_h = np.array([[0.1, -0.2], [0.4, 0.5], [-0.3, 0.2]]) test_w_h_o = np.array([[0.3], [-0.1]]) class TestMethods(unittest.TestCase): ########## # Un...
..... ---------------------------------------------------------------------- Ran 5 tests in 0.008s OK
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Training the networkHere you'll set the hyperparameters for the network. The strategy here is to find hyperparameters such that the error on the training set is low, but you're not overfitting to the data. If you train the network too long or have too many hidden nodes, it can become overly specific to the training se...
import sys #################### ### Set the hyperparameters in you myanswers.py file ### #################### from my_answers import iterations, learning_rate, hidden_nodes, output_nodes N_i = train_features.shape[1] network = NeuralNetwork(N_i, hidden_nodes, output_nodes, learning_rate) losses = {'train':[], 'val...
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Check out your predictionsHere, use the test data to view how well your network is modeling the data. If something is completely wrong here, make sure each step in your network is implemented correctly.
fig, ax = plt.subplots(figsize=(8,4)) mean, std = scaled_features['cnt'] predictions = network.run(test_features).T*std + mean ax.plot(predictions[0], label='Prediction') ax.plot((test_targets['cnt']*std + mean).values, label='Data') ax.set_xlim(right=len(predictions)) ax.legend() dates = pd.to_datetime(rides.ix[test...
_____no_output_____
MIT
project-bikesharing/Predicting_bike_sharing_data.ipynb
hailla/deep-learning-v2-pytorch
Matplotlib interactive functionsFrom https://matplotlib.org/gallery/event_handling/ginput_manual_clabel_sgskip.htmlsphx-glr-gallery-event-handling-ginput-manual-clabel-sgskip-py
import time import numpy as np import matplotlib.pyplot as plt %matplotlib qt def tellme(s): print(s) plt.title(s, fontsize=16) plt.draw() plt.clf() plt.axis([-1., 1., -1., 1.]) plt.setp(plt.gca(), autoscale_on=False) tellme('You will define a triangle, click to begin') plt.waitforbuttonpress() while ...
_____no_output_____
MIT
Matplotlib_interactive_functions.ipynb
furnstahl/binder_test
HRNet for MARS TutorialThis notebook will walk through using the [HRNet pose estimator](https://github.com/leoxiaobin/deep-high-resolution-net.pytorch) with the [data](https://data.caltech.edu/records/2011) used in the [Mouse Action Recognition System](https://www.biorxiv.org/content/10.1101/2020.07.26.222299v1). 0. ...
import data_utils.process_keypoints as process_data project = '/home/ubuntu/Desktop/ericykma/hrnet_notebook/HRNet_for_MARS' process_data.process_all_keypoints(project)
_____no_output_____
MIT
HRNet_MARS_tutorial.ipynb
404ic/HRNet_for_MARS
3. Train the model. Place your config files in `experiments/mars`. See `example_config.yaml` for an example.Then, run `python tools/train.py experiments/mars/example_config.yaml` in the root of your project directory, replacing `example_config.yaml` with your config file to train your model. You can view training and ...
import data_utils.visualize as visualize visualize.plot_frame(project='/home/ubuntu/Desktop/ericykma/hrnet_notebook/HRNet_for_MARS', config_file='experiments/mars/w48_256x192_adam_lr1e-3_imagenet_pretrain.yaml', frame_num=13999, save=True ...
_____no_output_____
MIT
HRNet_MARS_tutorial.ipynb
404ic/HRNet_for_MARS
Numpy Exercise 1 Imports
import numpy as np %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import antipackage import github.ellisonbg.misc.vizarray as va
_____no_output_____
MIT
assignments/assignment03/NumpyEx01.ipynb
CalPolyPat/phys202-2015-work
Checkerboard Write a Python function that creates a square `(size,size)` 2d Numpy array with the values `0.0` and `1.0`:* Your function should work for both odd and even `size`.* The `0,0` element should be `1.0`.* The `dtype` should be `float`.
def checkerboard(size): """Return a 2d checkboard of 0.0 and 1.0 as a NumPy array""" board = np.ones((size,size), dtype=float) for i in range(size): if i%2==0: board[i,1:size:2]=0 else: board[i,0:size:2]=0 va.enable() return board checkerboard(10) a = checkerb...
_____no_output_____
MIT
assignments/assignment03/NumpyEx01.ipynb
CalPolyPat/phys202-2015-work
Use `vizarray` to visualize a checkerboard of `size=20` with a block size of `10px`.
va.set_block_size(10) checkerboard(20) assert True
_____no_output_____
MIT
assignments/assignment03/NumpyEx01.ipynb
CalPolyPat/phys202-2015-work
Use `vizarray` to visualize a checkerboard of `size=27` with a block size of `5px`.
va.set_block_size(5) checkerboard(27) assert True
_____no_output_____
MIT
assignments/assignment03/NumpyEx01.ipynb
CalPolyPat/phys202-2015-work
stack gen
%%time log_pos = np.log1p(np.arange(1,11)) best_sellers = [1587422, 1803710, 10243, 548905, 1906937, 716822, 1361154, 1716388, 725371, 859574] best_sellers_domain = [item_domain_map[e] for e in best_sellers] def pad(lst): if len(lst) == 0: return best_sellers if len(lst) < 10: lst +=...
_____no_output_____
MIT
3_stack.ipynb
nagahamaVH/meli2020
test
groups = train.groupby('seq_index').size().values learning_rate, max_depth, min_child_weight, subsample, colsample_bytree = params mdl = xgboost.XGBRanker(seed=0, tree_method='gpu_hist', gpu_id=0, n_estimators=100, learning_rate=learning_rate, max_depth=max_depth, min_child_weight=min_child_w...
_____no_output_____
MIT
3_stack.ipynb
nagahamaVH/meli2020
PCE vs MC$$ \frac{dy(t)}{dt} = -\lambda y, \ \ y(0)=1 $$$$ y(t) = e^{-\lambda t} $$$$QoI = y(T)$$where $T$ is a fixed time point. $\Lambda = (-\infty, \infty)$, $\mathcal{D}=(0,\infty)$ Polynomial Chaos
start_def = time.time() def Phi(n): #define H_n coeffs = [0]*(n+1) coeffs[n] = 1 return coeffs def inner2_herm(n): ###return the denominator when computing $k_i$ return factorial(n) def product3_herm(i,j,l): #compute \Phi_i*\Phi_j*\Phi_l return lambda x: H.hermeval(x, H.hermemul(H.h...
_____no_output_____
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
Monte Carlo
start_ode_mc = time.time() def ode(y,t,nsample,k): ''' Build the ode system ''' dydt = np.zeros(nsample) for i in range(nsample): dydt[i] = -k[i]*y[i] return dydt time_def_mc = time.time() - start_ode_mc nsample = np.array([10, 100, 1000, 10000, 100000]) time_solveode_mc = np.zeros(len...
_____no_output_____
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
Comparison Computing time
#### Table 7.2, row 1 #### ### PCE print(time_solveode) ### MC print(time_solveode_mc)
0.016252994537353516 [8.58545303e-04 7.44271278e-03 7.87193775e-02 7.58476496e-01 8.74571085e+00]
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
Mean value at $t=1$, $t=0.5$ Sample size = 1000 for MC
## t = 0.5 mean_pc_05 = sol_herm[:,0][50] #mean value using pc at t=0.5 mean_exact_05 = np.e**(1/8) ## t = 1 mean_pc_1 = sol_herm[:,0][100] #mean value using pc at t=1 mean_exact_1 = np.e**(1/2) #### Table 7.2, row 2 #### print(mean_pc_05) print(mean_mc_05) print(mean_exact_05) print() #### Table 7.2, row 3 ###...
1.1331484337155744 [0.84243543 1.12379462 1.12573071 1.13969688 1.13387003] 1.1331484530668263 1.6486794979185284 [0.80759128 1.64191001 1.58804937 1.67483542 1.65016842] 1.6487212707001282
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
NN vs PolyFinite difference:$$\frac{y_{i+1} - y_i}{\Delta t} = -\lambda y_i$$so$$y_{i+1} = -\lambda\Delta t y_i + y_i = (1-\lambda\Delta t)y_i$$Define $n := \frac{0.5}{\Delta t}$, then$$\hat{Q}(\lambda)=y(0.5) = y_n = (1-\lambda\Delta t)^n y_0 = (1-\lambda\Delta t)^n$$ NN
####################################### #define the activation function def rbf(x): return tf.math.exp(-x**2) ####################################### #define the derivative of the activation function def d_rbf(x): return tf.gradients(rbf,x) #######################a################ #we couldn't use “tf_d_leaky...
_____no_output_____
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
Polynomial Regression`np.polyfit`
######## With feature scaling ############ mymodel1 = np.poly1d(np.polyfit(data_trans[:,0], y_out, 1)) preds_fd_pr1 = mymodel1(data_trans[:,0]) mse_fd_pr1 = tf.keras.losses.MSE(y_exact,preds_fd_pr1).numpy() fig = plt.figure() plt.xlabel("$\lambda$") plt.ylabel("$q$") plt.title("MSE=%.5f"%(mse_fd_pr1)) plt.scatter(lam_...
_____no_output_____
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
Stochastic collocation method\begin{align*}- \nabla\cdot(A\nabla u) &= (e^{\lambda_1}\lambda_1^2\pi^2 + e^{\lambda_2}\lambda_2^2\pi^2)u \\u &= 0 \, \text{ on } \Gamma_0 \,\text{( Left edge)}\\(A\nabla u)\cdot n &= -e^{\lambda_2}\lambda_2\pi \sin\lambda_1\pi x\sin \lambda_2\pi y \, \text{ on } \Gamma_1 \, \text{( ...
def QoI_FEM(x0,y0,lam1,lam2,gridx,gridy,p): mesh = fn.UnitSquareMesh(gridx, gridy) V = fn.FunctionSpace(mesh, "Lagrange", p) # Define diffusion tensor (here, just a scalar function) and parameters A = fn.Expression((('exp(lam1)','a'), ('a','exp(lam2)')), a = fn.Constant(0.0), lam1 = lam...
[[0.2609293 0.2609164 ] [0.19351774 0.19350624] [0.07109627 0.07108757] [0.40917364 0.40915816] [0.59556611 0.59555097] [0.40529523 0.40528473]]
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
Further Discussion Scaling, number of layers, print out the MSE every step, how to piecewise - x_train, x_plt should have similar property. For StandardScaler(), var \& mean need to be similar
def model(x): if x<=1: return 15*x+10 elif x<=7: return x**3-12*x**2+36*x elif x<=10: return 15/np.pi*np.sin(np.pi*(x-7))+7 else: return -30*np.sqrt(x-9)+37 np.random.seed(12345) x_syn = np.random.uniform(0,15,100) y_exact = np.array([model(i) for i in x_syn]) y_syn = y_e...
_____no_output_____
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
NN2
scaler_syn = StandardScaler() syndata_trans = scaler_syn.fit_transform(x_syn.reshape(-1,1))
_____no_output_____
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
One step method
############### With Feature Scaling ############### num_neuron = 5 tf.random.set_seed(12345) model_syn_all = tf.keras.Sequential() model_syn_all.add(tf.keras.layers.Dense(num_neuron,activation=rbf)) model_syn_all.add(tf.keras.layers.Dense(num_neuron,activation=rbf)) # model_syn_all.add(tf.keras.layers.Dense(num_neuron...
_____no_output_____
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
Split step method
## Step 1 num_neuron = 5 tf.random.set_seed(12345) model_nn1 = tf.keras.Sequential() model_nn1.add(tf.keras.layers.Dense(num_neuron,activation=rbf)) model_nn1.add(tf.keras.layers.Dense(1)) model_nn1.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.01)) model_nn1.fit(syndata_trans[:,0],y_syn, epo...
_____no_output_____
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
3 "1-5-1" = "1-15-1"
num_neuron = 15 tf.random.set_seed(12345) model_nn11 = tf.keras.Sequential() model_nn11.add(tf.keras.layers.Dense(num_neuron,activation=rbf)) model_nn11.add(tf.keras.layers.Dense(1)) model_nn11.compile(loss='mean_squared_error', optimizer=tf.keras.optimizers.Adam(0.01)) model_nn11.fit(syndata_trans[:,0],y_syn, epochs=...
_____no_output_____
MIT
AppendixB.ipynb
User-zwj/Thesis_Wenjuan_Code
EDA of All Sides Media ratings for 'debiaser' data product Sagar Setru, September 21th, 2020 Brief description using CoNVO framework ContextSome people are eager to get news from outside of their echo chamber. However, they do not know where to go outside of their echo chambers, and may also have some activation ene...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np import os # make sure I'm in the right environment (should be 'debiaser') print('Conda environment:') print(os.environ['CONDA_DEFAULT_ENV']) # get the entire news csv into data frame # get file name fname = '../all_sides_media...
_____no_output_____
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
There are 300 news media organizations represented. That's a lot to choose from.
# confirm all media organizations are only shown once all_sides_df['name'].is_unique # plot histograms of bias across publications plt.figure(figsize=(10,5)); sns.countplot(all_sides_df['bias'],order=['left','left-center','center','right-center','right','allsides']) plt.ylabel('N'); sns.set_context('talk', font_scale=...
/Users/sagarsetru/anaconda3/envs/debiaser/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misint...
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
We see that most vote tallies somewhat disagree with the given rating.
# what are the 'allsides ratings?' all_sides_df_all_sides_rating = all_sides_df.loc[all_sides_df['bias']=='allsides'] all_sides_df_all_sides_rating.head()
_____no_output_____
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
These look like news outlets that cover all sides of a story.
all_sides_df_all_sides_rating.shape # it's not so big, so let's just look at it all all_sides_df_all_sides_rating
_____no_output_____
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
These look like news/media organizations that try to show all sides of an issue. It may be worth looking at what these websites do, for inspiration. These could also be generically recommended to the user.
# let's see what the distribution of total votes is plt.figure(figsize=(10,5)); sns.distplot(all_sides_df['total_votes'],kde=False) plt.ylabel('N'); plt.xlabel('Total votes') sns.set_context('talk', font_scale=1.5); plt.xticks(rotation=90); plt.xscale('log') plt.show(); plt.clf()
/Users/sagarsetru/anaconda3/envs/debiaser/lib/python3.7/site-packages/seaborn/distributions.py:2551: FutureWarning: `distplot` is a deprecated function and will be removed in a future version. Please adapt your code to use either `displot` (a figure-level function with similar flexibility) or `histplot` (an axes-level ...
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
There are lots of websites with very few votes, and a few with thousands. My guess is that the websites with thousands of votes are the most popular news media organizations. Let's take a look at those.
total_votes_threshold = 10000 all_sides_df_high_votes = all_sides_df.loc[all_sides_df['total_votes']>=total_votes_threshold] all_sides_df_high_votes.shape
_____no_output_____
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
There are 35 news organizations with more than the above threshold number of votes votes. What are they? What are their biases?
all_sides_df_high_votes # plt.figure(figsize=(10,5)); sns.countplot(all_sides_df_high_votes['bias'],order=['left','left-center','center','right-center','right']) plt.ylabel('N'); plt.yticks(np.arange(0, 11, step=2)) plt.xlabel('AllSides Media bias rating') sns.set_context('talk', font_scale=1.5); plt.xticks(rotation=90...
/Users/sagarsetru/anaconda3/envs/debiaser/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misint...
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
These look like larger news organizations that will more likely cover lots of topics, though there are more left and center-left news organizations than right and center-right. This is a good list of news organizations to include in the MVP.
# how often does the 'public' agree with these ratings? # plt.figure(figsize=(10,5)); sns.countplot(all_sides_df_high_votes['agreeance_text'],order=['Absolutely Disagrees','Strongly Disagrees','Disagrees','Somewhat Disagrees','Neutral','Somehwat Agrees','Agrees','Strongly Agrees','Absolutely Agrees']) plt.ylabel('N'); ...
/Users/sagarsetru/anaconda3/envs/debiaser/lib/python3.7/site-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variable as a keyword arg: x. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misint...
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
The disagreement is exclusively amongst those news organizations with left-center, center, and right-center ratings. Users tend to agree about those news organizations that are further left or right as rated by AllSides. Among those news organizations where there is disagreement between users and AllSides, we see some ...
all_sides_df_high_votes.to_csv('../all_sides_media_data/allsides_final.csv', index_label='index')
_____no_output_____
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
Separately, I added the domain names for each news organization as a column to the dataframe. Here, I check those domain names below.
all_sides_with_domains = pd.read_csv('../all_sides_media_data/allsides_final_plus_others_with_domains.csv') all_sides_with_domains.head() all_sides_names = all_sides_with_domains['name'] all_sides_domains = all_sides_with_domains['domain'] all_sides_names_domains = pd.concat([all_sides_names,all_sides_domains],axis=1)...
name domain 0 ABC News (Online) abcnews.go.com 1 Al Jazeera aljazeera.com 2 Associated Press apnews.com 3 BBC News bbc.com 4 Bloomberg bloomberg.com 5 ...
MIT
notebooks/3 eda_all_sides_media.ipynb
sagarsetru/debiaser
Task 1: Word Embeddings (10 points)This notebook will guide you through all steps necessary to train a word2vec model (Detailed description in the PDF). ImportsThis code block is reserved for your imports. You are free to use the following packages: (List of packages)
# Imports from pandas import DataFrame import pandas as pd import numpy as np import os import re from sklearn.preprocessing import OneHotEncoder import nltk from nltk.tokenize import word_tokenize nltk.download('punkt') nltk.download('stopwords') import math import io
[nltk_data] Downloading package punkt to [nltk_data] C:\Users\piyab\AppData\Roaming\nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package stopwords to [nltk_data] C:\Users\piyab\AppData\Roaming\nltk_data... [nltk_data] Package stopwords is already up-to-date!
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.1 Get the data (0.5 points)The Hindi portion HASOC corpus from [github.io](https://hasocfire.github.io/hasoc/2019/dataset.html) is already available in the repo, at data/hindi_hatespeech.tsv . Load it into a data structure of your choice. Then, split off a small part of the corpus as a development set (~100 data poi...
#TODO: implement! #from google.colab import files #uploaded = files.upload() #Get the data #os.chdir("D:/Saarland/NN TI/NNTI_WS2021_Project") df = DataFrame.from_csv("hindi_.tsv", sep="\t") def split_data (df): df = df[:20] return df
C:\Users\piyab\Anaconda3\lib\site-packages\ipykernel_launcher.py:9: FutureWarning: from_csv is deprecated. Please use read_csv(...) instead. Note that some of the default arguments are different, so please refer to the documentation for from_csv when changing your function calls if __name__ == '__main__':
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.2 Data preparation (0.5 + 0.5 points)* Prepare the data by removing everything that does not contain information. User names (starting with '@') and punctuation symbols clearly do not convey information, but we also want to get rid of so-called [stopwords](https://en.wikipedia.org/wiki/Stop_word), i. e. words that h...
#TODO: implement! def clean_data(sentence): hindi_stopword_file = open('stopwords.txt', encoding="utf8") hindi_stopwords = [] for x in hindi_stopword_file: hindi_stopwords.append(x.rstrip()) text_tokens = word_tokenize(sentence) special_words_list = ['#', '?', '!', ';', ',','&' ,'+'...
_____no_output_____
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.3 Build the vocabulary (0.5 + 0.5 points)The input to the first layer of word2vec is an one-hot encoding of the current word. The output od the model is then compared to a numeric class label of the words within the size of the skip-gram window. Now* Compile a list of all words in the development section of your cor...
#TODO: implement! def building_vocabulary(df): sentences = [] v = [] #unique_words frequency_of_words = {} for line in df['text']: words = [x for x in line.split()] for word in words: if word != ':': if word not in v: ...
_____no_output_____
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
* Then, write a function ```word_to_one_hot``` that returns a one-hot encoding of an arbitrary word in the vocabulary. The size of the one-hot encoding should be ```len(v)```.
#TODO: implement! def word_to_one_hot(word): try: ohe = OneHotEncoder(sparse=False) ohe.fit(word) ohe_word = ohe.transform(word) return ohe_word except ValueError: #Array_With_zero_sample pass
_____no_output_____
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.4 Subsampling (0.5 points)The probability to keep a word in a context is given by:$P_{keep}(w_i) = \Big(\sqrt{\frac{z(w_i)}{0.001}}+1\Big) \cdot \frac{0.001}{z(w_i)}$Where $z(w_i)$ is the relative frequency of the word $w_i$ in the corpus. Now,* Calculate word frequencies* Define a function ```sampling_prob``` that ...
#TODO: implement! def sampling_prob(word): probability = (math.sqrt(word/0.001) + 1 ) * (0.001/word) return probability
_____no_output_____
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.5 Skip-Grams (1 point)Now that you have the vocabulary and one-hot encodings at hand, you can start to do the actual work. The skip gram model requires training data of the shape ```(current_word, context)```, with ```context``` being the words before and/or after ```current_word``` within ```window_size```. * Have ...
#TODO: implement! def get_target_context(sentences,w2v_model,vocab_one_hot,vocab_index,subsampling_probability): center_word_list = [] context_word_list = [] for sentence in sentences: for i in range(len(sentence)): center_word = vocab_one_hot[sentence[i]] #vocab_one_hot co...
_____no_output_____
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.6 Hyperparameters (0.5 points)According to the word2vec paper, what would be a good choice for the following hyperparameters? * Embedding dimension* Window sizeInitialize them in a dictionary or as independent variables in the code block below.
# Set hyperparameters window_size = 2 embedding_size = 100 # More hyperparameters learning_rate = 0.05 epochs = 100
_____no_output_____
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.7 Pytorch Module (0.5 + 0.5 + 0.5 points)Pytorch provides a wrapper for your fancy and super-complex models: [torch.nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html). The code block below contains a skeleton for such a wrapper. Now,* Initialize the two weight matrices of word2vec as fields o...
# Create model def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0) class Word2Vec(object): def __init__(self): self.embedding_size = 100 self.window_size = 2 # sentences weren't too long, so self.learning_rate = 0.05 self.epochs = 100 def ...
Word2Vec( (input): Linear(in_features=534, out_features=300, bias=False) (output): Linear(in_features=300, out_features=534, bias=False) )
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.8 Loss function and optimizer (0.5 points)Initialize variables with [optimizer](https://pytorch.org/docs/stable/optim.htmlmodule-torch.optim) and loss function. You can take what is used in the word2vec paper, but you can use alternative optimizers/loss functions if you explain your choice in the report.
# Define optimizer and loss #optimizer = torch.optim.Adam(w2v_model.parameters(), lr=0.01) #criterion = nn.CrossEntropyLoss()
_____no_output_____
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.9 Training the model (3 points)As everything is prepared, implement a training loop that performs several passes of the data set through the model. You are free to do this as you please, but your code should:* Load the weights saved in 1.6 at the start of every execution of the code block* Print the accumulated loss...
# Define train procedure # load initial weights def train(w2v_model,X_train,Y_train, Vocab_len): #loss_list = [] print("Training started") for x in range(1, w2v_model.epochs): loss = 0 for j in range(len(X_train)): u = w2v_model.feed_forward(X_train[j]) ...
_____no_output_____
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
1.10 Train on the full dataset (0.5 points)Now, go back to 1.1 and remove the restriction on the number of sentences in your corpus. Then, reexecute code blocks 1.2, 1.3 and 1.6 (or those relevant if you created additional ones). * Then, retrain your model on the complete dataset.* Now, the input weights of the model ...
#df = split_data(df) # converting upper case letters to lowercase df['text'] = df['text'].str.lower() # data preprocessing df['text'] = df['text'].map(lambda x: clean_data(x)) # drop empty values df = drop_empty_values(df) #building vocabulary and Calculating word frequencies sentences, frequency_of_words , v...
_____no_output_____
MIT
Task1_Word_Embeddings.ipynb
priya00priya/NNTI-WS2021-NLP-Project
dMRI Data Reconstruction In this notebook, we will reconstruct MRI imgaes from raw data by using Python.This includes: 1. Data processing; 2. DTI reconstruction and 3. DKI reocnstruction. Data Preprocessing Data preprocessing is quit important for dMRI reconstruction. Different data preprocessing may lead to differen...
import os #TO control directories import numpy as np import nibabel as nib # read and save medical images from dipy.denoise.localpca import mppca #denoising import nipype.interfaces.fsl as fsl #topup from nipype.interfaces.fsl import TOPUP from nipype.testing import anatfile import timeit #compute time, useage: timei...
_____no_output_____
CC0-1.0
dMRI Reconstruction Project.ipynb
zhangerjun/project_template
Set data path
data_path = "/home/erjun/githubEZ/dMRI_BHS/dMRI_data/dwi" ap_file = 'sub-032213_ses-001_dir-AP_run-1_dwi.nii.gz' # dMRI data pa_file = 'sub-032213_ses-001_dir-PA_run-1_dwi.nii.gz' bvals_file = 'sub-032216_ses-001_dir-AP_run-1_dwi.bvals' # bval file bvecs_file = 'sub-032216_ses-001_dir-AP_run-1_dwi.bvecs' # bvec file d...
_____no_output_____
CC0-1.0
dMRI Reconstruction Project.ipynb
zhangerjun/project_template
__Denoising__
# Load data file img = nib.load(os.path.join(data_path,ap_file)) data = img.get_data() # Use dipy to denoise denoised = mppca(data, patch_radius=50) # Save data nib.save(nib.Nifti1Image(data, img.affine), os.path.join(data_path,denoised_file)) print('DONE')
_____no_output_____
CC0-1.0
dMRI Reconstruction Project.ipynb
zhangerjun/project_template
TOPUP
# Set default output type and test ExtractROI tool for Define b_0 image extraction function fsl.FSLCommand.set_default_output_type('NIFTI_GZ') fslroi = fsl.ExtractROI(in_file=anatfile, roi_file='bar.nii.gz', t_min=0,t_size=1) fslroi.cmdline == 'fslroi %s bar.nii.gz 0 1' % anatfile # Define b_0 image extraction functio...
_____no_output_____
CC0-1.0
dMRI Reconstruction Project.ipynb
zhangerjun/project_template
EDDY
btr = fsl.BET(in_file= 'epi_b0.nii.gz',#'epi_b0_corrected.nii.gz', frac=0.2, out_file='brain.nii.gz', mask=True) btr.run() # total nuber of volumes in dwi data img = nib.load(denoised_file).get_data() nvolumes = img.shape[-1] file = open('index.txt','w') for i in range(0, nvolumes): file.write('1 ')...
_____no_output_____
CC0-1.0
dMRI Reconstruction Project.ipynb
zhangerjun/project_template
DTI Reconstruction
import math from skimage import io #用于读取保存或显示图片或者视频 import time from dipy.io import read_bvals_bvecs from dipy.core.gradients import gradient_table from dipy.reconst.dti import TensorModel from dipy.reconst.dti import fractional_anisotropy from dipy.reconst.dti import color_fa import dipy.reconst.dki as dki # Set new ...
_____no_output_____
CC0-1.0
dMRI Reconstruction Project.ipynb
zhangerjun/project_template
Show basical output maps
# set plot background plt.style.use('seaborn-dark') # plot paramter maps fig, [ax0, ax2, ax3, ax4] = plt.subplots(1,4,figsize=(10,8),subplot_kw={'xticks': [], 'yticks': []}) ax0.imshow(DTI_RGB[:,:,30,:]); ax0.set_title('Color coded FA',fontweight='bold',size=10) #ax1.imshow(DTI_FA[:,30,:]); ax1.set_title('Fr...
_____no_output_____
CC0-1.0
dMRI Reconstruction Project.ipynb
zhangerjun/project_template
Introduction![](http://www.gpb.org/sites/www.gpb.org/files/styles/hero_image/public/blogs/images/2018/08/07/maxresdefault.jpg?itok=gN6ErLyU) In this dataset, we are provided with game analytics for the PBS KIDS Measure Up! app. In this app, children navigate a map and complete various levels, which may be activities, v...
import pandas as pd import os import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import StratifiedKFold from sklearn.metrics import cohen_kappa_score from scipy.stats import mode from sklearn.feature_selection import Selec...
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Reading and understanding our data
os.listdir('../input/data-science-bowl-2019') %%time keep_cols = ['event_id', 'game_session', 'installation_id', 'event_count', 'event_code','title' ,'game_time', 'type', 'world','timestamp'] train=pd.read_csv('train.csv',usecols=keep_cols) train_labels=pd.read_csv('train_labels.csv', ...
CPU times: user 33.8 s, sys: 3.23 s, total: 37 s Wall time: 1min 7s
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
We can see that this data contains full history of the installation,ie each time a child has played the game a unique game_session identifier is generated and the attributes related to the game is stored.The atttributes are:The data provided in these files are as follows:- `event_id` - Randomly generated unique identif...
train.shape,train_labels.shape x=train_labels['accuracy_group'].value_counts() sns.barplot(x.index,x)
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Data Preparation In this we will prepare the data and make it in a trainable form.For that we will do the following steps :- first,we will find the installation ids which are in `train.csv` and which are not in `train_labels.csv`.These installations won't be of much use to us because `train_labels.csv` contains the ...
not_req=(set(train.installation_id.unique()) - set(train_labels.installation_id.unique())) train_new=~train['installation_id'].isin(not_req) train.where(train_new,inplace=True) train.dropna(inplace=True) train['event_code']=train.event_code.astype(int)
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Extracting time features
def extract_time_features(df): df['timestamp'] = pd.to_datetime(df['timestamp']) df['month'] = df['timestamp'].dt.month df['hour'] = df['timestamp'].dt.hour df['year'] = df['timestamp'].dt.year df['dayofweek'] = df['timestamp'].dt.dayofweek df['weekofyear'] = df['timestamp'].dt.weekofyear re...
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Next,we will define a `prepare_data` funtion to prepare our train and test data.For the we will do the following steps:- extract `hour_of_day` from timestamp and drop timestamp column,this indicated the hour of day in which is child playes the game.- We will do an on_hot encoding on `event_code` and group the dataf...
time_features=['month','hour','year','dayofweek','weekofyear'] def prepare_data(df): df=extract_time_features(df) df=df.drop('timestamp',axis=1) #df['timestamp']=pd.to_datetime(df['timestamp']) #df['hour_of_day']=df['timestamp'].map(lambda x : int(x.hour)) join_one=pd.get_dummies(df[['eve...
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
In this step,we will - prepare train by merging our train to train_labels.This will be our `final_train`.- prepare the test by selecting last row of each installation_id ,game_session as we have only 1000 rows in `sample_submission`.The last accuracy group for each installation id is taken as the accuracy group of t...
cols=join_test.columns[2:-12].to_list() cols.append('event_id count') cols.append('installation_id')
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
- It seems that we have to group dafaframe by `installation_id` to form a proper trainable dataframe.- We will apply the same to form out test set.
df=join_test[['event_count sum','game_time mean','game_time sum', 'installation_id']].groupby('installation_id',as_index=False,sort=False).agg('mean') df_two=join_test[cols].groupby('installation_id',as_index=False, sort=False).agg('sum').drop('installation_id',axis=1) df_three=join...
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Just making sure that all the columns in our `final_train` and `final_test` is the same,except accuracy_group.The instersection should return `54`.
len(set(final_train.columns) & set(final_test.columns))
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
YES ! It's done.. Label Encoding- We will concat out final_train and final_test to form `final`.- We will label encode the categorical variables.- We will split them back to final_train and final_test.
final=pd.concat([final_train,final_test]) encoding=['type','world','title'] for col in encoding: lb=LabelEncoder() lb.fit(final[col]) final[col]=lb.transform(final[col]) final_train=final[:len(final_train)] final_test=final[len(final_train):] X_train=final_train.drop('accuracy_group',axis=1) y_...
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
EvaluationSubmissions are scored based on the quadratic weighted kappa, which measures the agreement between two outcomes. This metric typically varies from 0 (random agreement) to 1 (complete agreement). In the event that there is less agreement than expected by chance, the metric may go below 0.$$w_{i,j} = \frac{\lef...
def model(X_train,y_train,final_test,n_splits=3): scores=[] pars = { 'colsample_bytree': 0.8, 'learning_rate': 0.08, 'max_depth': 10, 'subsample': 1, 'objective':'multi:softprob', 'num_class':4, 'eval_metric':'mlogloss', 'min_child...
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Making our submission After making our prediction we will make our submission to `submission.csv`.
sub=pd.DataFrame({'installation_id':submission.installation_id,'accuracy_group':pred}) sub.to_csv('submission.csv',index=False)
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Feature SelectionWe will use module of xgboost to plot the feature importances and see what features our model think are important for making prediction.
fig, ax = plt.subplots(figsize=(10,10)) xgb.plot_importance(xgb_model, max_num_features=50, height=0.5, ax=ax,importance_type='gain') plt.show()
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
There are three methods to measure feature_importances in xgboost.They are :- `weight` : The total number of times this feature was used to split the data across all trees.- `Cover` :The number of times a feature is used to split the data across all trees weighted by the number of training data points that go through t...
fig, ax = plt.subplots(figsize=(10,10)) xgb.plot_importance(xgb_model, max_num_features=50, height=0.5, ax=ax,importance_type='weight') plt.show()
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
When we considered weight,the model says that is used `game_time mean` 1035 times to split the data across the trees.hmmm...so how what can we conclude from above figures?We will find out.... Interpreting our model with Confidence`SHAP` is a powerful tool for interpreting our model with more confidence,It makes the pr...
shap_values = shap.TreeExplainer(xgb_model).shap_values(X_train) shap.summary_plot(shap_values, X_train, plot_type="bar")
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
For example,this figure expains the feature importance and it's influence on different class.- for feature `event_code_3020` its SHAP value is high for `class 3` means it influences predicting class 3 is more than any other class. Summary plot for `class 3`
shap.summary_plot(shap_values[3], X_train)
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Here we can see that the variables are ranked in the descending order.- The most important variable `event_code_3020`.- Lower value of `event_code_3020` has a high and positive impact on the model predicting `class 3` .- Lower value of `event_code_3020` the model tends to classify it to `class 3` Similarly for `class0`
shap.summary_plot(shap_values[0], X_train)
_____no_output_____
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Hope you can see the differnce between them. Select from FeaturesWe will use sklearn `SelectFromFeatures` to select relevent features.
X_train,X_test,y_train,y_test=train_test_split(X_train,y_train,test_size=.1) model = XGBClassifier() model.fit(X_train, y_train) threshold = np.sort(model.feature_importances_)[40:] for thresh in threshold: # select features using threshold selection = SelectFromModel(model, threshold=thresh, prefit=True) s...
Thresh=0.000, n=14, cohen kappa score: 99.83% Thresh=0.001, n=13, cohen kappa score: 99.83% Thresh=0.003, n=12, cohen kappa score: 99.83% Thresh=0.006, n=11, cohen kappa score: 99.83% Thresh=0.010, n=10, cohen kappa score: 99.83% Thresh=0.011, n=9, cohen kappa score: 99.83% Thresh=0.013, n=8, cohen kappa score: 98.10% ...
MIT
model_src/xgboost-feature-selection-dsbowl.ipynb
kurianbenoy/Data-Science-Bowl
Batch Normalization – Practice Batch normalization is most useful when building deep neural networks. To demonstrate this, we'll create a convolutional neural network with 20 convolutional layers, followed by a fully connected layer. We'll use it to classify handwritten digits in the MNIST dataset, which should be fam...
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True, reshape=False)
Extracting MNIST_data/train-images-idx3-ubyte.gz Extracting MNIST_data/train-labels-idx1-ubyte.gz Extracting MNIST_data/t10k-images-idx3-ubyte.gz Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
Batch Normalization using `tf.layers.batch_normalization`This version of the network uses `tf.layers` for almost everything, and expects you to implement batch normalization using [`tf.layers.batch_normalization`](https://www.tensorflow.org/api_docs/python/tf/layers/batch_normalization) We'll use the following functi...
""" DO NOT MODIFY THIS CELL """ def fully_connected(prev_layer, num_units): """ Create a fully connectd layer with the given layer as input and the given number of neurons. :param prev_layer: Tensor The Tensor that acts as input into this layer :param num_units: int The size of the ...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
We'll use the following function to create convolutional layers in our network. They are very basic: we're always using a 3x3 kernel, ReLU activation functions, strides of 1x1 on layers with odd depths, and strides of 2x2 on layers with even depths. We aren't bothering with pooling layers at all in this network.This ve...
""" DO NOT MODIFY THIS CELL """ def conv_layer(prev_layer, layer_depth): """ Create a convolutional layer with the given layer as input. :param prev_layer: Tensor The Tensor that acts as input into this layer :param layer_depth: int We'll set the strides and number of feature maps b...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
**Run the following cell**, along with the earlier cells (to load the dataset and define the necessary functions). This cell builds the network **without** batch normalization, then trains it on the MNIST dataset. It displays loss and accuracy data periodically while training.
""" DO NOT MODIFY THIS CELL """ def train(num_batches, batch_size, learning_rate): # Build placeholders for the input samples and labels inputs = tf.placeholder(tf.float32, [None, 28, 28, 1]) labels = tf.placeholder(tf.float32, [None, 10]) # Feed the inputs into a series of 20 convolutional layers...
Batch: 0: Validation loss: 0.69148, Validation accuracy: 0.10020 Batch: 25: Training loss: 0.36335, Training accuracy: 0.09375 Batch: 50: Training loss: 0.32443, Training accuracy: 0.14062 Batch: 75: Training loss: 0.32804, Training accuracy: 0.06250 Batch: 100: Validation loss: 0.32516, Validation accuracy: 0.11260 B...
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
With this many layers, it's going to take a lot of iterations for this network to learn. By the time you're done training these 800 batches, your final test and validation accuracies probably won't be much better than 10%. (It will be different each time, but will most likely be less than 15%.)Using batch normalization...
def fully_connected(prev_layer, num_units, is_training): """ Create a fully connectd layer with the given layer as input and the given number of neurons. :param prev_layer: Tensor The Tensor that acts as input into this layer :param num_units: int The size of the layer. That is, the...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
**TODO:** Modify `conv_layer` to add batch normalization to the convolutional layers it creates. Feel free to change the function's parameters if it helps.
def conv_layer(prev_layer, layer_depth, is_training): """ Create a convolutional layer with the given layer as input. :param prev_layer: Tensor The Tensor that acts as input into this layer :param layer_depth: int We'll set the strides and number of feature maps based on the layer's...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
**TODO:** Edit the `train` function to support batch normalization. You'll need to make sure the network knows whether or not it is training, and you'll need to make sure it updates and uses its population statistics correctly.
def train(num_batches, batch_size, learning_rate): # Build placeholders for the input samples and labels inputs = tf.placeholder(tf.float32, [None, 28, 28, 1]) labels = tf.placeholder(tf.float32, [None, 10]) is_training = tf.placeholder(tf.bool) # Feed the inputs into a series of 20 convolutio...
Batch: 0: Validation loss: 0.69141, Validation accuracy: 0.09900 Batch: 25: Training loss: 0.59129, Training accuracy: 0.12500 Batch: 50: Training loss: 0.47563, Training accuracy: 0.10938 Batch: 75: Training loss: 0.40750, Training accuracy: 0.09375 Batch: 100: Validation loss: 0.36580, Validation accuracy: 0.08680 B...
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
With batch normalization, you should now get an accuracy over 90%. Notice also the last line of the output: `Accuracy on 100 samples`. If this value is low while everything else looks good, that means you did not implement batch normalization correctly. Specifically, it means you either did not calculate the population...
def fully_connected(prev_layer, num_units): """ Create a fully connectd layer with the given layer as input and the given number of neurons. :param prev_layer: Tensor The Tensor that acts as input into this layer :param num_units: int The size of the layer. That is, the number of un...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
**TODO:** Modify `conv_layer` to add batch normalization to the fully connected layers it creates. Feel free to change the function's parameters if it helps.**Note:** Unlike in the previous example that used `tf.layers`, adding batch normalization to these convolutional layers _does_ require some slight differences to ...
def conv_layer(prev_layer, layer_depth): """ Create a convolutional layer with the given layer as input. :param prev_layer: Tensor The Tensor that acts as input into this layer :param layer_depth: int We'll set the strides and number of feature maps based on the layer's depth in the...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
**TODO:** Edit the `train` function to support batch normalization. You'll need to make sure the network knows whether or not it is training.
def train(num_batches, batch_size, learning_rate): # Build placeholders for the input samples and labels inputs = tf.placeholder(tf.float32, [None, 28, 28, 1]) labels = tf.placeholder(tf.float32, [None, 10]) # Feed the inputs into a series of 20 convolutional layers layer = inputs for lay...
_____no_output_____
MIT
batch-norm/Batch_Normalization_Exercises.ipynb
AlphaGit/deep-learning
1. Load model
def get_model(num_classes): model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True) in_features = model.roi_heads.box_predictor.cls_score.in_features #model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) # replace the pre-trained head with a new one model.roi...
_____no_output_____
MIT
draft.ipynb
JiqianDong/BDD-100-CV
2. Show sample plot
def get_preds(idx,img_datalist,threshold): im0 = Image.open(img_datalist[idx]) im0_tensor = torchvision.transforms.ToTensor()(im0) pred = model([im0_tensor]) total_preds = [] for n,confidence in enumerate(pred[0]['scores']): if confidence>threshold: pred_update = {} p...
_____no_output_____
MIT
draft.ipynb
JiqianDong/BDD-100-CV
3. Test
im0 = Image.open(val_img_paths[100]) im0_tensor = torchvision.transforms.ToTensor()(im0) model.backbone.out_channels images, targets = model.transform([im0_tensor,im0_tensor]) images.tensors.shape features = model.backbone(images.tensors) proposals, _ = model.rpn(images, features, targets) box_features1 = model.roi_hea...
_____no_output_____
MIT
draft.ipynb
JiqianDong/BDD-100-CV
Test Multihead attention in pytorch
box_features2 = box_features2.view(2,1000,1024) box_features2.shape class MHSA(nn.Module): def __init__(self, emb_dim, kqv_dim, num_heads=1): super(MHSA, self).__init__() self.emb_dim = emb_dim self.kqv_dim = kqv_dim self.num_heads = num_heads self.w_k = nn.Linear(emb_d...
_____no_output_____
MIT
draft.ipynb
JiqianDong/BDD-100-CV
Test hard attention
box_features2.shape box_features2 = box_features2.view(2,1000,1024) box_features2.shape attention = nn.Sequential(nn.Linear(1024,1),nn.Softmax(dim=1)) attention(box_features2) score = attention(box_features2) score.shape box_features2.shape _,ind = torch.topk(score,k=10,dim=1) torch.index_select(box_features2,) ind tor...
_____no_output_____
MIT
draft.ipynb
JiqianDong/BDD-100-CV
Write custom inference script and requirements to local folder
! mkdir inference_code %%writefile inference_code/inference.py # This is the script that will be used in the inference container import os import json import torch from transformers import AutoModelForSeq2SeqLM, AutoTokenizer def model_fn(model_dir): """ Load the model and tokenizer for inference """ ...
_____no_output_____
MIT
3_deploy.ipynb
samraj1980/pegasus_text_summary
Deploy an endpoint with PyTorchModel Once you .deploy(), this will upload your model package to S3, create a model in SageMaker, create an endpoint configuration, and deploy an endpoint from that configuration.
! pip install -U sagemaker import sagemaker session = sagemaker.Session() session_bucket = session.default_bucket() role = sagemaker.get_execution_role() pytorch_version = '1.7.1' python_version = 'py36' from sagemaker.huggingface import HuggingFaceModel model_name = 'summarization-model' endpoint_name = 'summariza...
_____no_output_____
MIT
3_deploy.ipynb
samraj1980/pegasus_text_summary
(Optional) If you haven't fine-tuned a model, but want to deploy directly from HuggingFace Hub to experiment
# We will pass these as env variables, defining the model and task we want hub = { 'HF_MODEL_ID':'google/pegasus-xsum', 'HF_TASK':'summarization' } hub_model = HuggingFaceModel(env=hub, role=role, pytorch_version='1.7', py_ver...
_____no_output_____
MIT
3_deploy.ipynb
samraj1980/pegasus_text_summary
Clean up Use this code to delete the resources created in SageMaker Inference (endpoint configuration, endpoint and model).
predictor.delete_endpoint() predictor.delete_model()
_____no_output_____
MIT
3_deploy.ipynb
samraj1980/pegasus_text_summary