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
The following loop runs a simulation for each value of `p1` in `p1_array`; after each simulation, it prints the number of unhappy customers at the Olin station:
for p1 in p1_array: state = run_simulation(p1, p2, num_steps) print(p1, state.olin_empty)
0.0 0 0.1 0 0.2 0 0.30000000000000004 5 0.4 2 0.5 4 0.6000000000000001 14 0.7000000000000001 17 0.8 30 0.9 34 1.0 41
MIT
code/chap04-Mine.ipynb
dlrow-olleh/ModSimPy
Now we can do the same thing, but storing the results in a `SweepSeries` instead of printing them.
sweep = SweepSeries() for p1 in p1_array: state = run_simulation(p1, p2, num_steps) sweep[p1] = state.olin_empty sweep plot(sweep)
_____no_output_____
MIT
code/chap04-Mine.ipynb
dlrow-olleh/ModSimPy
And then we can plot the results.
plot(sweep, label='Olin') decorate(title='Olin-Wellesley Bikeshare', xlabel='Arrival rate at Olin (p1 in customers/min)', ylabel='Number of unhappy customers') savefig('figs/chap02-fig02.pdf')
Saving figure to file figs/chap02-fig02.pdf
MIT
code/chap04-Mine.ipynb
dlrow-olleh/ModSimPy
Exercises**Exercise:** Wrap this code in a function named `sweep_p1` that takes an array called `p1_array` as a parameter. It should create a new `SweepSeries`, run a simulation for each value of `p1` in `p1_array`, store the results in the `SweepSeries`, and return the `SweepSeries`.Use your function to plot the num...
def sweep_p1(p1_array): results = SweepSeries() for p1 in p1_array: state = run_simulation(p1, p2, num_steps) results[p1] = state.olin_empty return results unhappy_olin= sweep_p1(p1_array) plot(unhappy_olin, label='Olin') decorate(title='unhappy Olin', xlabel='Arrival rate...
_____no_output_____
MIT
code/chap04-Mine.ipynb
dlrow-olleh/ModSimPy
**Exercise:** Write a function called `sweep_p2` that runs simulations with `p1=0.5` and a range of values for `p2`. It should store the results in a `SweepSeries` and return the `SweepSeries`.
def sweep_p2(p2_array): results = SweepSeries() for p2 in p2_array: state = run_simulation(0.5, p2, num_steps) results[p2] = state.olin_empty return results p2_array = linspace(0, 1, 11) unhappy_olin_again = sweep_p2(p2_array) plot(unhappy_olin_again, label='Olin') decorate(title='Unhappy O...
_____no_output_____
MIT
code/chap04-Mine.ipynb
dlrow-olleh/ModSimPy
Optional exercisesThe following two exercises are a little more challenging. If you are comfortable with what you have learned so far, you should give them a try. If you feel like you have your hands full, you might want to skip them for now.**Exercise:** Because our simulations are random, the results vary from one...
def run_multiple_simulations(p1, p2, num_steps, num_runs): for i in range(num_runs): results = TimeSeries() state = run_simulation(p1, p2, num_steps) results[i] = state.olin_empty return results olin_sad = run_multiple_simulations(0.3, 0.3, 60, 10) plot(olin_sad,...
_____no_output_____
MIT
code/chap04-Mine.ipynb
dlrow-olleh/ModSimPy
**Exercise:** Continuting the previous exercise, use `run_multiple_simulations` to run simulations with a range of values for `p1` and```p2 = 0.3num_steps = 60num_runs = 20```Store the results in a `SweepSeries`, then plot the average number of unhappy customers as a function of `p1`. Label the axes.What value of `p1...
# Solution goes here # Solution goes here
_____no_output_____
MIT
code/chap04-Mine.ipynb
dlrow-olleh/ModSimPy
SINGLE EXECUTION Applying in baseScaled
Y = basePre['target'] x_train, x_test, y_train, y_test = train_test_split(baseScaled, Y, test_size=0.30, random_state=0) clf = ad(criterion=c,min_samples_leaf=msl,min_samples_split=mss,max_depth=md,random_state=rs) clf.fit(x_train, y_train) sc = cross_val_score(clf, baseScaled, Y, cv=cv) accArray = np.array([[sc.mea...
_____no_output_____
MIT
alg-AD.ipynb
rodolfomedeiros/heart-disease-prediction
Applying in basePCAInversa
x_train, x_test, y_train, y_test = train_test_split(basePCAInversa, Y, test_size=0.30, random_state=0) clf = ad(criterion=c,min_samples_leaf=msl,min_samples_split=mss,max_depth=md,random_state=rs) clf.fit(x_train, y_train) sc = cross_val_score(clf, basePCAInversa, Y, cv=cv) accArray = np.append(accArray, [[sc.mean(),...
_____no_output_____
MIT
alg-AD.ipynb
rodolfomedeiros/heart-disease-prediction
Applying in basePCAProporcional
x_train, x_test, y_train, y_test = train_test_split(basePCAProporcional, Y, test_size=0.30, random_state=0) clf = ad(criterion=c,min_samples_leaf=msl,min_samples_split=mss,max_depth=md,random_state=rs) clf.fit(x_train, y_train) sc = cross_val_score(clf, basePCAProporcional, Y, cv=cv) accArray = np.append(accArray, [[...
_____no_output_____
MIT
alg-AD.ipynb
rodolfomedeiros/heart-disease-prediction
PCA com 70%
x_train, x_test, y_train, y_test = train_test_split(basePca70, Y, test_size=0.30, random_state=0) clf = ad(criterion=c,min_samples_leaf=msl,min_samples_split=mss,max_depth=md,random_state=rs) clf.fit(x_train, y_train) sc = cross_val_score(clf, basePca70, Y, cv=cv) accArray = np.append(accArray, [[sc.mean(), sc.std()*...
_____no_output_____
MIT
alg-AD.ipynb
rodolfomedeiros/heart-disease-prediction
PCA com 50%
x_train, x_test, y_train, y_test = train_test_split(basePca50, Y, test_size=0.30, random_state=0) clf = ad(criterion=c,min_samples_leaf=msl,min_samples_split=mss,max_depth=md,random_state=rs) clf.fit(x_train, y_train) sc = cross_val_score(clf, basePca50, Y, cv=cv) accArray = np.append(accArray, [[sc.mean(), sc.std()*...
_____no_output_____
MIT
alg-AD.ipynb
rodolfomedeiros/heart-disease-prediction
BAGGING com a melhor single
clf = ad(criterion=c,min_samples_leaf=msl,min_samples_split=mss,max_depth=md,random_state=rs) model = BaggingClassifier(clf, n_estimators=5, random_state=0) sc = cross_val_score(model, basePca50, Y, cv=cv) accArray = np.array([[sc.mean(), sc.std()*2]]) clf = ad(criterion=c,min_samples_leaf=msl,min_samples_split=mss,m...
_____no_output_____
MIT
alg-AD.ipynb
rodolfomedeiros/heart-disease-prediction
Batch Scheduler to train
## !sbatch --gres=gpu:titanxp:1 --mem=32G run.sh
_____no_output_____
MIT
main.ipynb
isrugeek/climate_extreme_values
Test for latest data points
df = pd.read_csv('data/weatherstats_montreal_daily_inter.csv',index_col=0) df = pre_process(df[:360], save_plots=True) max_v = create_dataset(df[df['Year'] >= 2018], look_back=28, forecast_horizon=15, batch_size=1) max_y_plot = [] for input_x, max_y, no_z in max_v: max_y_plot.append(max_y[0][0]) print (len(max_y_pl...
_____no_output_____
MIT
main.ipynb
isrugeek/climate_extreme_values
LSTM Forecaster
ep_loss, mean, rms, lower, upper, mae, acc, test_true_y, test_pred_y = forecaster.LSTMForecaster(df) print (rms,mae) forecast_fi = {} fn = 0 for i in range(0, len(ep_loss), 15): sp = i ep = i + 15 forecast_fi[fn] = ep_loss[sp:ep] fn+=1 fig, axs = plt.subplots(nrows=5, ncols=6, figsize=(20,10 )) f...
_____no_output_____
MIT
main.ipynb
isrugeek/climate_extreme_values
GU-LSTM Forecaster
ep_loss, mean, rms, lower, upper, mae, acc, test_true_y, test_pred_y = forecaster.LSTMGUForecaster(df) print (rms,mae) forecast_fi = {} fn = 0 for i in range(0, len(ep_loss), 15): sp = i ep = i + 15 forecast_fi[fn] = ep_loss[sp:ep] fn+=1 fig, axs = plt.subplots(nrows=5, ncols=6, figsize=(20,10 )) ...
_____no_output_____
MIT
main.ipynb
isrugeek/climate_extreme_values
ENCDEC Forecaster
ep_loss, mean, rms, lower, upper, mae, acc, test_true_y, test_pred_y = forecaster.ENCDECForecaster(df) print (mae,rms) fig, ax = plt.subplots(figsize=(7,4)) ax.plot(np.array(test_true_y[:100]).reshape(-1),c='blue', label='GT', alpha=5) ax.plot(mean[:100], label='Prediction', c='green', linestyle='--', alpha=5) ax.set(t...
_____no_output_____
MIT
main.ipynb
isrugeek/climate_extreme_values
Deep Deterministic Policy Gradients (DDPG)---In this notebook, we train DDPG with OpenAI Gym's Pendulum-v0 environment. 1. Import the Necessary Packages
import gym import random import torch import numpy as np from collections import deque import matplotlib.pyplot as plt %matplotlib inline %load_ext autoreload %autoreload 2 from MyAgent import Agent
_____no_output_____
MIT
ddpg-pendulum/DDPG.ipynb
xlnwel/deep-reinforcement-learning
2. Instantiate the Environment and Agent
env = gym.make('Pendulum-v0') env.seed(2) agent = Agent(state_size=3, action_size=1) print(env.action_space.shape) print(env.action_space.low) print(env.action_space.high)
(1,) [-2.] [2.]
MIT
ddpg-pendulum/DDPG.ipynb
xlnwel/deep-reinforcement-learning
3. Train the Agent with DDPG
def ddpg(n_episodes=300, max_t=300, print_every=100): scores_deque = deque(maxlen=print_every) scores = [] for i_episode in range(1, n_episodes+1): state = env.reset() # agent.reset() # old implementation score = 0 for t in range(max_t): action = agent.act(state) ...
Episode 100 Average Score: -642.86 Episode 200 Average Score: -198.31 Episode 300 Average Score: -155.96
MIT
ddpg-pendulum/DDPG.ipynb
xlnwel/deep-reinforcement-learning
4. Watch a Smart Agent!
agent.actor_local.load_state_dict(torch.load('checkpoint_actor.pth')) agent.critic_local.load_state_dict(torch.load('checkpoint_critic.pth')) state = env.reset() for t in range(200): action = agent.act(state, add_noise=False) env.render() state, reward, done, _ = env.step(action) if done: break...
_____no_output_____
MIT
ddpg-pendulum/DDPG.ipynb
xlnwel/deep-reinforcement-learning
Python Basics with Numpy (optional assignment)Welcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help familiarize you with functions we'll need. **Instructions:**- You will be using Python 3.- Avoid using for-loops and while-loops, un...
### START CODE HERE ### (≈ 1 line of code) test = "Hello World" ### END CODE HERE ### print ("test: " + test)
test: Hello World
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
**Expected output**:test: Hello World **What you need to remember**:- Run your cells using SHIFT+ENTER (or "Run cell")- Write code in the designated areas using Python 3 only- Do not modify the code outside of the designated areas 1 - Building basic functions with numpy Numpy is the main package for scientific computi...
# GRADED FUNCTION: basic_sigmoid import math def basic_sigmoid(x): """ Compute sigmoid of x. Arguments: x -- A scalar Return: s -- sigmoid(x) """ ### START CODE HERE ### (≈ 1 line of code) s = 1/(1+math.exp(-1*x)) ### END CODE HERE ### return s basic_sigmoid(3)
_____no_output_____
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
**Expected Output**: ** basic_sigmoid(3) ** 0.9525741268224334 Actually, we rarely use the "math" library in deep learning because the inputs of the functions are real numbers. In deep learning we mostly use matrices and vectors. This is why numpy is more useful.
### One reason why we use "numpy" instead of "math" in Deep Learning ### x = [1, 2, 3] basic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.
_____no_output_____
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
In fact, if $ x = (x_1, x_2, ..., x_n)$ is a row vector then $np.exp(x)$ will apply the exponential function to every element of x. The output will thus be: $np.exp(x) = (e^{x_1}, e^{x_2}, ..., e^{x_n})$
import numpy as np # example of np.exp x = np.array([1, 2, 3]) print(np.exp(x)) # result is (exp(1), exp(2), exp(3))
[ 2.71828183 7.3890561 20.08553692]
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
Furthermore, if x is a vector, then a Python operation such as $s = x + 3$ or $s = \frac{1}{x}$ will output s as a vector of the same size as x.
# example of vector operation x = np.array([1, 2, 3]) print (x + 3)
[4 5 6]
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
Any time you need more info on a numpy function, we encourage you to look at [the official documentation](https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.exp.html). You can also create a new cell in the notebook and write `np.exp?` (for example) to get quick access to the documentation.**Exercise**: I...
# GRADED FUNCTION: sigmoid import numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function() def sigmoid(x): """ Compute the sigmoid of x Arguments: x -- A scalar or numpy array of any size Return: s -- sigmoid(x) """ ### START C...
_____no_output_____
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
**Expected Output**: **sigmoid([1,2,3])** array([ 0.73105858, 0.88079708, 0.95257413]) 1.2 - Sigmoid gradientAs you've seen in lecture, you will need to compute gradients to optimize loss functions using backpropagation. Let's code your first gradient function.**Exercise**: Implement th...
# GRADED FUNCTION: sigmoid_derivative def sigmoid_derivative(x): """ Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x. You can store the output of the sigmoid function into variables and then use it to calculate the gradient. Arguments:...
sigmoid_derivative(x) = [ 0.19661193 0.10499359 0.04517666]
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
**Expected Output**: **sigmoid_derivative([1,2,3])** [ 0.19661193 0.10499359 0.04517666] 1.3 - Reshaping arrays Two common numpy functions used in deep learning are [np.shape](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html) and [np.reshape()](https://docs....
# GRADED FUNCTION: image2vector def image2vector(image): """ Argument: image -- a numpy array of shape (length, height, depth) Returns: v -- a vector of shape (length*height*depth, 1) """ ### START CODE HERE ### (≈ 1 line of code) v = image.reshape(image.shape[0]*image.shape[1]...
image2vector(image) = [[ 0.67826139] [ 0.29380381] [ 0.90714982] [ 0.52835647] [ 0.4215251 ] [ 0.45017551] [ 0.92814219] [ 0.96677647] [ 0.85304703] [ 0.52351845] [ 0.19981397] [ 0.27417313] [ 0.60659855] [ 0.00533165] [ 0.10820313] [ 0.49978937] [ 0.34144279] [ 0.94630077]]
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
**Expected Output**: **image2vector(image)** [[ 0.67826139] [ 0.29380381] [ 0.90714982] [ 0.52835647] [ 0.4215251 ] [ 0.45017551] [ 0.92814219] [ 0.96677647] [ 0.85304703] [ 0.52351845] [ 0.19981397] [ 0.27417313] [ 0.60659855] [ 0.00533165] [ 0.10820313] [ 0.49978937] [ 0.34144279] [ 0.94630077]...
# GRADED FUNCTION: normalizeRows def normalizeRows(x): """ Implement a function that normalizes each row of the matrix x (to have unit length). Argument: x -- A numpy matrix of shape (n, m) Returns: x -- The normalized (by row) numpy matrix. You are allowed to modify x. """ ...
normalizeRows(x) = [[ 0. 0.6 0.8 ] [ 0.13736056 0.82416338 0.54944226]]
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
**Expected Output**: **normalizeRows(x)** [[ 0. 0.6 0.8 ] [ 0.13736056 0.82416338 0.54944226]] **Note**:In normalizeRows(), you can try to print the shapes of x_norm and x, and then rerun the assessment. You'll find out that they have different shapes. This i...
# GRADED FUNCTION: softmax def softmax(x): """Calculates the softmax for each row of the input x. Your code should work for a row vector and also for matrices of shape (n, m). Argument: x -- A numpy matrix of shape (n,m) Returns: s -- A numpy matrix equal to the softmax of x, of shape (n,m) ...
softmax(x) = [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04 1.21052389e-04] [ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04 8.01252314e-04]]
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
**Expected Output**: **softmax(x)** [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04 1.21052389e-04] [ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04 8.01252314e-04]] **Note**:- If you print the shapes of x_exp, x_sum and s above and rerun the a...
import time x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0] x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0] ### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ### tic = time.process_time() dot = 0 for i in range(len(x1)): dot+= x1[i]*x2[i] toc = time.process_time() print ("dot = " + str(dot) + "\n ----- Comp...
dot = 278 ----- Computation time = 0.09656799999979704ms outer = [[81 18 18 81 0 81 18 45 0 0 81 18 45 0 0] [18 4 4 18 0 18 4 10 0 0 18 4 10 0 0] [45 10 10 45 0 45 10 25 0 0 45 10 25 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [63 14 14 63 ...
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
As you may have noticed, the vectorized implementation is much cleaner and more efficient. For bigger vectors/matrices, the differences in running time become even bigger. **Note** that `np.dot()` performs a matrix-matrix or matrix-vector multiplication. This is different from `np.multiply()` and the `*` operator (whic...
# GRADED FUNCTION: L1 def L1(yhat, y): """ Arguments: yhat -- vector of size m (predicted labels) y -- vector of size m (true labels) Returns: loss -- the value of the L1 loss function defined above """ ### START CODE HERE ### (≈ 1 line of code) loss = np.sum(np.abs(y-yhat...
L1 = 1.1
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
**Expected Output**: **L1** 1.1 **Exercise**: Implement the numpy vectorized version of the L2 loss. There are several way of implementing the L2 loss but you may find the function np.dot() useful. As a reminder, if $x = [x_1, x_2, ..., x_n]$, then `np.dot(x,x)` = $\sum_{j=0}^n x_j^{2}$. - ...
# GRADED FUNCTION: L2 def L2(yhat, y): """ Arguments: yhat -- vector of size m (predicted labels) y -- vector of size m (true labels) Returns: loss -- the value of the L2 loss function defined above """ ### START CODE HERE ### (≈ 1 line of code) loss = np.sum(np.dot(y-yhat...
L2 = 0.43
MIT
Python+Basics+With+Numpy+v3.ipynb
sudharshan-chakra/DeepLearning.ai-Implementation
**GLOBAL TERRORISM ANALYSIS** PART 4 : REPORT Author : Samarpan Das ------ **Introduction**1. The **Global Terrorism Database** [GTD](https://gtd.terrorismdata.com/files/gtd-1970-2019-4/) is an open-source database including information on terrorist attacks around the world from 1970 through 2019. The GTD includes s...
import time import matplotlib.pyplot as plt import matplotlib.ticker as ticker from matplotlib import animation import numpy as np import pandas as pd import seaborn as sns
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Connecting colab to google drive
from google.colab import drive drive.mount('/content/drive')
Mounted at /content/drive
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Importing data from google drive
# BaseForAnalysis.csv was uploaded into google drve before hand primary_df = pd.read_csv('/content/drive/My Drive/BaseForAnalysis.csv', sep=',', encoding="ISO-8859-1")
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Initial layout of the data
primary_df.head(10) print ('dataframe shape: ', primary_df.shape)
dataframe shape: (201183, 29)
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Changing the content and features of the dataRenaming certain columns to better identifiable names
primary_df.rename(columns = {'iyear':'year', 'imonth':'month', 'iday':'day', 'country_txt' : 'country', 'region_txt' : 'region', 'crit1' : 'crit', 'attacktype1_txt' : 'attacktype', ...
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Glimpse of the final preprocessed data
primary_df.head(10) ''' # Converting the dataframe to a csv file and uploading it to google drive with the name BaseForAnalysis_Version2.csv primary_df.to_csv("/content/drive/My Drive/BaseForAnalysis_Version2.csv", sep = ",") '''
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
End of data processing------ .. 3. Data Analysis & VisualizationHere is a glimpse of the analysis and vizualisation using Python, for viewing some more advanced analysis and visualizations refer to Global Terrorism Analysis Workbook @ my Tableau Public Profile¶Detailed code and explaination of the analysis and visuali...
import time import matplotlib.pyplot as plt import matplotlib.ticker as ticker from matplotlib import animation import numpy as np import pandas as pd pd.options.mode.chained_assignment = None import seaborn as sns import plotly.express as px
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Connecting drive to google colab
from google.colab import drive drive.mount('/content/drive') terror_df = pd.read_csv('/content/drive/My Drive/BaseForAnalysis_Version2.csv', sep=',', encoding="ISO-8859-1")
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Glimpse of the final dataset that will be used to draw the analysis
terror_df.head(10)
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Cols involved
terror_df.columns
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Analysis of the numerical figures in the data frame
terror_df[['nkilled', 'nkillonlyter', 'nwounded', 'propdamageextent', 'ncasualties']].describe().transpose() terror_df.info(verbose = True)
<class 'pandas.core.frame.DataFrame'> RangeIndex: 201183 entries, 0 to 201182 Data columns (total 31 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Unnamed: 0 201183 non-null int64 1 eventid 201183 non-null int64 2 year ...
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Analysis of the number of attacks per yea
f = plt.figure(figsize=(20, 7)) sns.set(font_scale = 1.1) sns.set_theme(style = "darkgrid") xaxis = sns.countplot(x = 'year', data = terror_df) xaxis.set_xticklabels(xaxis.get_xticklabels(), rotation=60) plt.ylabel('Count', fontsize=12) plt.xlabel('Year', fontsize=12) plt.title('Number of Terrorist Attack by Year', fo...
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Number of Attacks per Region (The globe has been divided into 12 distinct regions as per global standards
f = plt.figure(figsize=(16, 8)) sns.set(font_scale=0.7) sns.countplot(y='region', data=terror_df) plt.ylabel('Region', fontsize=12) plt.xlabel('Count', fontsize=12) plt.title('Number of Terrorist Attack by Region', fontsize=12)
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Number of Attacks per Attack Method
f = plt.figure(figsize=(20, 8)) sns.set(font_scale=0.8) sns.countplot(x='attacktype', data=terror_df,) plt.xlabel('Methods of Attack', fontsize=12) plt.ylabel('Counts', fontsize=12) plt.title('Types of Terrorist Attack ', fontsize=12)
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Number of Attacks per Type of Targets
f = plt.figure(figsize=(20, 8)) sns.set(font_scale=0.8) xaxis = sns.countplot(x='targettype', data=terror_df,) xaxis.set_xticklabels(xaxis.get_xticklabels(), rotation=60) plt.xlabel('Target Types', fontsize=12) plt.ylabel('Count', fontsize=12) plt.title('Types of Target', fontsize=12)
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Top 15 Contries with most number of Attacks by terror groups
fig= plt.figure(figsize=(16, 10)) sns.set(font_scale=0.9) terror_country = sns.barplot(x=terror_df['country'].value_counts()[0:15].index, y=terror_df['country'].value_counts()[0:15], palette='RdYlGn') terror_country.set_xticklabels(terror_country.get_xticklabels(), rotation=70) terror_country.set_xlabel('Country', font...
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
... Analysis of number of attacks in a region on a particular calender yearThis helps us compare the rise / fall of attacks on a region
region_year = pd.crosstab(terror_df.year, terror_df.region) region_year.head(20) fig = plt.figure(figsize=(16, 10)) color_list_reg_yr = ['palegreen', 'lime', 'green', 'Aqua', 'skyblue', 'darkred', 'darkgray', 'tan', 'orangered', 'plum', 'salmon', 'mistyrose'] region_year.plot(figsize=(14, 10), fo...
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Analysis of number of attacks of a particular type on a particular calender yearThis helps us compare the rise / fall of attack types over the years
attacktype_year = pd.crosstab(terror_df.year, terror_df.attacktype) attacktype_year.head(20)
_____no_output_____
Apache-2.0
project/Report/Report.ipynb
SamarpanDas/Global-Terrorism-Analysis
Example: Masked statistics==========================Plot a masked statistics
import numpy as np import matplotlib.pyplot as plt data = np.loadtxt('../../../../data/populations.txt') populations = np.ma.masked_array(data[:,1:]) year = data[:, 0] bad_years = (((year >= 1903) & (year <= 1910)) | ((year >= 1917) & (year <= 1918))) populations[bad_years, 0] = np.ma.masked populations[b...
_____no_output_____
CC-BY-4.0
_downloads/plot_maskedstats.ipynb
scipy-lectures/scipy-lectures.github.com
Fine-tune a 🤗 Transformers model This notebook is based on [an official 🤗 notebook - "How to fine-tune a model on text classification"](https://github.com/huggingface/notebooks/blob/6ca682955173cc9d36ffa431ddda505a048cbe80/examples/text_classification.ipynb). The main aim of this notebook is to show the process of c...
#! pip install "datasets" "transformers>=4.19.0" "torch>=1.10.0" "mlflow" "ray[air]>=1.13"
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Set up Ray We will use `ray.init()` to initialize a local cluster. By default, this cluster will be compromised of only the machine you are running this notebook on. You can also run this notebook on an Anyscale cluster.This notebook *will not* run in [Ray Client](https://docs.ray.io/en/latest/cluster/ray-client.html...
from pprint import pprint import ray ray.init()
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
We can check the resources our cluster is composed of. If you are running this notebook on your local machine or Google Colab, you should see the number of CPU cores and GPUs available on the said machine.
pprint(ray.cluster_resources())
{'CPU': 2.0, 'GPU': 1.0, 'accelerator_type:T4': 1.0, 'memory': 7855477556.0, 'node:172.28.0.2': 1.0, 'object_store_memory': 3927738777.0}
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
In this notebook, we will see how to fine-tune one of the [🤗 Transformers](https://github.com/huggingface/transformers) model to a text classification task of the [GLUE Benchmark](https://gluebenchmark.com/). We will be running the training using [Ray AIR](https://docs.ray.io/en/latest/ray-air/getting-started.html).Yo...
use_gpu = True # set this to False to run on CPUs num_workers = 1 # set this to number of GPUs/CPUs you want to use
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Fine-tuning a model on a text classification task The GLUE Benchmark is a group of nine classification tasks on sentences or pairs of sentences. If you would like to learn more, refer to the [original notebook](https://github.com/huggingface/notebooks/blob/6ca682955173cc9d36ffa431ddda505a048cbe80/examples/text_classif...
GLUE_TASKS = ["cola", "mnli", "mnli-mm", "mrpc", "qnli", "qqp", "rte", "sst2", "stsb", "wnli"]
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
This notebook is built to run on any of the tasks in the list above, with any model checkpoint from the [Model Hub](https://huggingface.co/models) as long as that model has a version with a classification head. Depending on you model and the GPU you are using, you might need to adjust the batch size to avoid out-of-mem...
task = "cola" model_checkpoint = "distilbert-base-uncased" batch_size = 16
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Loading the dataset We will use the [🤗 Datasets](https://github.com/huggingface/datasets) library to download the data and get the metric we need to use for evaluation (to compare our model to the benchmark). This can be easily done with the functions `load_dataset` and `load_metric`.Apart from `mnli-mm` being a spe...
from datasets import load_dataset actual_task = "mnli" if task == "mnli-mm" else task datasets = load_dataset("glue", actual_task)
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
The `dataset` object itself is [`DatasetDict`](https://huggingface.co/docs/datasets/package_reference/main_classes.htmldatasetdict), which contains one key for the training, validation and test set (with more keys for the mismatched validation and test set in the special case of `mnli`). We will also need the metric. I...
from datasets import load_metric def load_metric_fn(): return load_metric('glue', actual_task)
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
The metric is an instance of [`datasets.Metric`](https://huggingface.co/docs/datasets/package_reference/main_classes.htmldatasets.Metric). Preprocessing the data Before we can feed those texts to our model, we need to preprocess them. This is done by a 🤗 Transformers `Tokenizer` which will (as the name indicates) to...
from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, use_fast=True)
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
We pass along `use_fast=True` to the call above to use one of the fast tokenizers (backed by Rust) from the 🤗 Tokenizers library. Those fast tokenizers are available for almost all models, but if you got an error with the previous call, remove that argument. To preprocess our dataset, we will thus need the names of th...
task_to_keys = { "cola": ("sentence", None), "mnli": ("premise", "hypothesis"), "mnli-mm": ("premise", "hypothesis"), "mrpc": ("sentence1", "sentence2"), "qnli": ("question", "sentence"), "qqp": ("question1", "question2"), "rte": ("sentence1", "sentence2"), "sst2": ("sentence", None), ...
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
We can them write the function that will preprocess our samples. We just feed them to the `tokenizer` with the argument `truncation=True`. This will ensure that an input longer that what the model selected can handle will be truncated to the maximum length accepted by the model.
def preprocess_function(examples, *, tokenizer): sentence1_key, sentence2_key = task_to_keys[task] if sentence2_key is None: return tokenizer(examples[sentence1_key], truncation=True) return tokenizer(examples[sentence1_key], examples[sentence2_key], truncation=True)
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
To apply this function on all the sentences (or pairs of sentences) in our dataset, we just use the `map` method of our `dataset` object we created earlier. This will apply the function on all the elements of all the splits in `dataset`, so our training, validation and testing data will be preprocessed in one single co...
encoded_datasets = datasets.map(preprocess_function, batched=True, fn_kwargs=dict(tokenizer=tokenizer))
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
For Ray AIR, instead of using 🤗 Dataset objects directly, we will convert them to [Ray Datasets](https://docs.ray.io/en/latest/data/dataset.html). Both are backed by Arrow tables, so the conversion is straightforward. We will use the built-in `ray.data.from_huggingface` function.
import ray.data ray_datasets = ray.data.from_huggingface(encoded_datasets)
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Fine-tuning the model with Ray AIR Now that our data is ready, we can download the pretrained model and fine-tune it.Since all our tasks are about sentence classification, we use the `AutoModelForSequenceClassification` class.We will not go into details about each specific component of the training (see the [original...
from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer import numpy as np import torch num_labels = 3 if task.startswith("mnli") else 1 if task=="stsb" else 2 metric_name = "pearson" if task == "stsb" else "matthews_correlation" if task == "cola" else "accuracy" model_name = model_chec...
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
With our `trainer_init_per_worker` complete, we can now instantiate the `HuggingFaceTrainer`. Aside from the function, we set the `scaling_config`, controlling the amount of workers and resources used, and the `datasets` we will use for training and evaluation.We specify the `MlflowLoggerCallback` inside the `run_confi...
from ray.train.huggingface import HuggingFaceTrainer from ray.air import RunConfig from ray.tune.integration.mlflow import MLflowLoggerCallback trainer = HuggingFaceTrainer( trainer_init_per_worker=trainer_init_per_worker, scaling_config={"num_workers": num_workers, "use_gpu": use_gpu}, datasets={"train": ...
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Finally, we call the `fit` method to being training with Ray AIR. We will save the `Result` object to a variable so we can access metrics and checkpoints.
result = trainer.fit()
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
You can use the returned `Result` object to access metrics and the Ray AIR `Checkpoint` associated with the last iteration.
result
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Predict on test data with Ray AIR You can now use the checkpoint to run prediction with `HuggingFacePredictor`, which wraps around [🤗 Pipelines](https://huggingface.co/docs/transformers/main_classes/pipelines). In order to distribute prediction, we use `BatchPredictor`. While this is not necessary for the very small...
from ray.train.huggingface import HuggingFacePredictor from ray.train.batch_predictor import BatchPredictor import pandas as pd sentences = ['Bill whistled past the house.', 'The car honked its way down the road.', 'Bill pushed Harry off the sofa.', 'the kittens yawned awake and played.', 'I demand that the mo...
Map Progress (2 actors 1 pending): 0%| | 0/1 [00:12<?, ?it/s](BlockWorker pid=735) 2022-05-12 18:36:08.491769: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected Map Progress (2 actors 1 pending): 100%|██████████|...
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Share the model To be able to share your model with the community, there are a few more steps to follow.We have conducted the training on the Ray cluster, but share the model from the local enviroment - this will allow us to easily authenticate.First you have to store your authentication token from the Hugging Face w...
from huggingface_hub import notebook_login notebook_login()
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Then you need to install Git-LFS. Uncomment the following instructions:
# !apt install git-lfs
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Now, load the model and tokenizer locally, and recreate the 🤗 Transformers `Trainer`:
from ray.train.huggingface import load_checkpoint hf_trainer = load_checkpoint( checkpoint=result.checkpoint, model=AutoModelForSequenceClassification, tokenizer=AutoTokenizer )
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
You can now upload the result of the training to the Hub, just execute this instruction:
hf_trainer.push_to_hub()
_____no_output_____
Apache-2.0
doc/source/ray-air/examples/huggingface_text_classification.ipynb
jianoaix/ray
Image recon
# Import required libraries from image_util import * import skimage.filters from matplotlib import pyplot as plt import cairocffi as cairo import math, random import numpy as np import pandas as pd from IPython.display import Image from scipy.interpolate import interp1d import astra %matplotlib inline def r8_to_sino(...
_____no_output_____
MIT
Misc Notebooks/r8_small-Copy1.ipynb
johnowhitaker/CIRTS
import tensorflow as tf tf.__version__
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Tensor constantTensor: Multi dim array
const = tf.constant(43) const const.numpy()
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
JAX: Built on Numpy but it supports CUDA
# for specific datatype const = tf.constant(43, dtype=tf.float32) const const.numpy() const_mat = tf.constant([[1,3],[4,5]], dtype=tf.float32) print(const_mat) const_mat.numpy() const_mat.shape const_mat.dtype ## We can't perform assignment like below const_mat[0][0] = 32
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Commonly used method
tf.ones(shape=(2,3)) -1*tf.ones(shape=(2,3)) 6*tf.ones(shape=(2,3)) tf.zeros(shape=(2,4))
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
add operations
const1 = tf.constant([[1,2,3],[4,5,6]]) const2 = tf.constant([[2,5,3],[3,5,8]]) const1 + const2 ## Adding from tensorflow object tf.add(const1, const2)
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Random const
tf.random.normal(shape=(2,2), mean=0, stddev=1.0) tf.random.uniform(shape=(2,2), minval=0, maxval=20)
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Variables
var1 = tf.Variable([[1,2,3],[4,5,6]]) var2 = tf.Variable(43) var2.assign(32) var2 type(var2) var2 = 33 type(var2) var1.assign([[22,2,3],[4,5,6]]) var1[1,1].assign(34) var1 var1[1][1].assign(34) var1.assign([[22,2,3],[4,5,6],[3,4,5]])
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
reshaping operation
tensor = tf.Variable([[22,2,3],[4,5,6]]) tensor.shape tf.reshape(tensor, [3,2]) tf.reshape(tensor, [1,6]) tf.reshape(tensor, [6,1])
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
other mathematical ops
var1 tf.square(var1)
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
[detailed link of the demo of all the funcitons in tensorflow ](https://colab.research.google.com/drive/12sBvm2ON-gAWNisJD1dpoNTdFri3dEjE?usp=sharing) Broadcasting in TF
tensor scaler = 4 scaler * tensor scaler + tensor
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Matrix Multiplication
mat_u = tf.constant([[6,7,7]]) mat_v = tf.constant([[3,4,3]]) mat_u.shape mat_v.shape
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Rule: column of mat A = row of matrix B. If you are multiplying AB
tf.matmul(mat_u, mat_v) tf.matmul(mat_u, tf.transpose(mat_v)) ## alternative to above mat_u @ tf.transpose(mat_v) tf.matmul(tf.transpose(mat_u), mat_v) mat_u * mat_v # element wise multiplication # shape of both should be same
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Casting method in tf to change the data type
mat_u.dtype tf.cast(mat_u, dtype=tf.int16) ## can be used in quantizing a model to save the space in the memory allocation 34.34343434 ## <<< THis will be more precise 34.34
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Ragged tensorsnested variable length arrays
ragged = tf.ragged.constant([[1,2,4,5,6], [1], [135,1]]) ragged.shape ragged[0].shape ragged[1].shape
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Checkpointing to restore the matrix vals
var1 = tf.Variable(5*tf.ones((5,5))) var1 ckpt = tf.train.Checkpoint(var=var1) savepath = ckpt.save("./vars.ckpt") var1.assign(tf.zeros((5,5))) var1 ckpt.restore(savepath) var1
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
tf.function $z = x^3 * 6 + y^3$
def f1(x, y): input_var = tf.multiply(x ** 3, 6) + y ** 3 return tf.reduce_mean(input_tensor=input_var) func = tf.function(f1) x = tf.constant([3.,-4.]) y = tf.constant([1.,4.]) f1(x,y) ## using a simple python function func(x, y) @tf.function ## tf decorator function def f2(x, y): input_var = tf.multiply(x ** 3,...
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Example of decorator
def print_me(): print("Hi FSDS") print_me() print("**"*20) print_me() print("**"*20) def decorate_it(input_func): def decorated_func(): print("**"*20) input_func() print("**"*20) return decorated_func decorated_func = decorate_it(print_me) decorated_func() @decorate_it def print_me2(): print("Hi F...
**************************************** Sunny ****************************************
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Calculation of Gradients in tf
x = tf.random.normal(shape=(2,2)) ## this creates a const by default y = tf.random.normal(shape=(2,2))
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
$f(x,y) = \sqrt{(x^2 + y^2)}$$\nabla f(x,y) = \frac{\partial f}{\partial x} \hat{\imath} + \frac{\partial f}{\partial y} \hat{\jmath}$
with tf.GradientTape() as tape: tape.watch(x) ### <<< I want to calculate grad wrt x f = tf.sqrt(tf.square(x) + tf.square(y)) df_dx = tape.gradient(f, x) print(df_dx) with tf.GradientTape() as tape: tape.watch(y) ### <<< I want to calculate grad wrt y f = tf.sqrt(tf.square(x) + tf.square(y)) df_dy = ta...
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Simple linear regression example $f(x) = W.x + b$
TRUE_W = 3.0 TRUE_B = 2.0 NUM_EXAMPLES = 1000 x = tf.random.normal(shape=[NUM_EXAMPLES]) noise = tf.random.normal(shape=[NUM_EXAMPLES]) y = x * TRUE_W + TRUE_B + noise import matplotlib.pyplot as plt plt.scatter(x, y, c="b") plt.show()
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Lets define a model
class MyModel(tf.Module): def __init__(self, **kwargs): super().__init__(**kwargs) # initial weights self.w = tf.Variable(5.0) self.b = tf.Variable(0.0) def __call__(self, x): return self.w*x + self.b class Test: def __init__(self, x): self.x = x def __call__(self): return self.x ...
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
Define loss function
def MSE_loss(target_y, predicted_y): error = target_y - predicted_y squared_error = tf.square(error) mse = tf.reduce_mean(squared_error) return mse plt.scatter(x, y, c="b") pred_y = model(x) ## without training plt.scatter(x, pred_y, c="r") plt.show() current_loss = MSE_loss(y, model(x)) current_loss.numpy(...
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer
training function def
def train(model, x, y, learning_rate): with tf.GradientTape() as tape: current_loss = MSE_loss(y, model(x)) dc_dw, dc_db = tape.gradient(current_loss, [model.w, model.b]) model.w.assign_sub(learning_rate * dc_dw) model.b.assign_sub(learning_rate * dc_db) model = MyModel() Ws, bs = [], [] epochs = 10*2 ...
_____no_output_____
MIT
Tensorflow.ipynb
iamatul1214/CatDealer