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 |
|---|---|---|---|---|---|
SummaryIn this tutorial, we have investigated the dynamics of a rate-based single excitatory population of neurons.We learned about:- The effect of the input parameters and the time constant of the network on the dynamics of the population.- How to find the fixed point(s) of the system.Next, we have two Bonus, but imp... | #@title Video: Stability of fixed points
from IPython.display import YouTubeVideo
video = YouTubeVideo(id="nvxxf59w2EA", width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video | Video available at https://youtube.com/watch?v=nvxxf59w2EA
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Initial values and trajectoriesHere, let us first set $w_{EE}=5.0$ and $I^{\text{ext}}_E=0.5$, and investigate the dynamics of $E(t)$ starting with different initial values $E(0) \equiv E_{\text{init}}$. We will plot the trajectories of $E(t)$ with $E_{\text{init}} = 0.0, 0.1, 0.2,..., 0.9$. | #@title Initial values
pars = default_parsE()
pars['wEE'] = 5.0
pars['I_ext_E'] = 0.5
plt.figure(figsize=(10,6))
for ie in range(10):
pars['E_init'] = 0.1*ie # set the initial value
E = simulate_E(pars) # run the simulation
# plot the activity with given initial
plt.plot(pars['range_t'], E, 'b', a... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Interactive Demo: dynamics as a function of the initial value.Let's now set $E_{init}$ to a value of your choice in this demo. How does the solution change? What do you observe? | #@title Initial value Explorer
pars = default_parsE()
pars['wEE'] = 5.0
pars['I_ext_E'] = 0.5
def plot_E_diffEinit(E_init):
pars['E_init'] = E_init
E = simulate_E(pars)
plt.figure()
plt.plot(pars['range_t'], E, 'b', label='E(t)')
plt.xlabel('t (ms)', fontsize=16.)
plt.ylabel('E activity', fontsize=16.)... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Stability analysis via linearization of the dynamicsJust like Equation $1$ in the case ($w_{EE}=0$) discussed above, a generic linear system $$\frac{dx}{dt} = \lambda (x - b),$$ has a fixed point for $x=b$. The analytical solution of such a system can be found to be:$$x(t) = b + \big{(} x(0) - b \big{)} \text{e}^{\lam... | # Exercise 4
def dF(x,a,theta):
"""
Population activation function.
Args:
x : the population input
a : the gain of the function
theta : the threshold of the function
Returns:
dFdx : the population activation response F(x) for input x
"""
################... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Exercise 5: Compute eigenvalues As discussed above, for the case with $w_{EE}=5.0$ and $I^{\text{ext}}_E=0.5$, the system displays **3** fixed points. However, when we simulated the dynamics and varied the initial conditions $E_{\rm init}$, we could only obtain **two** steady states. In this exercise, we will now chec... | # Exercise 5
pars = default_parsE()
pars['wEE'] = 5.0
pars['I_ext_E'] = 0.5
def eig_E(pars, fp):
"""
Args:
pars : Parameter dictionary
fp : fixed point E
Returns:
eig : eigevalue of the linearized system
"""
#get the parameters
tau_E, a_E, theta_E = pars['tau_E'], pars['a_E'], pars['the... | Fixed point1=0.042, Eigenvalue=-0.583
Fixed point2=0.447, Eigenvalue=0.498
Fixed point3=0.900, Eigenvalue=-0.626
| CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Think! Throughout the tutorial, we have assumed $w_{\rm EE}> 0 $, i.e., we considered a single population of **excitatory** neurons. What do you think will be the behavior of a population of inhibitory neurons, i.e., where $w_{\rm EE}> 0$ is replaced by $w_{\rm II}< 0$? Bonus 2: Noisy input drives transition between... | #@title OU process `my_OU(pars, sig, myseed=False)`
def my_OU(pars, sig, myseed=False):
"""
A functions that generates Ornstein-Uhlenback process
Args:
pars : parameter dictionary
sig : noise amplitute
myseed : random seed. int or boolean
Returns:
I : Ornstein-Uhlen... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
Bonus Example: Up-Down transitionIn the presence of two or more fixed points, noisy inputs can drive a transition between the fixed points! Here, we stimulate an E population for 1,000 ms applying OU inputs. | #@title Simulation of an E population with OU inputs
pars = default_parsE(T = 1000)
pars['wEE'] = 5.0
sig_ou = 0.7
pars['tau_ou'] = 1. #[ms]
pars['I_ext_E'] = 0.56 + my_OU(pars, sig=sig_ou, myseed=2020)
E = simulate_E(pars)
plt.figure(figsize=(10, 4))
plt.plot(pars['range_t'], E, 'r', alpha=0.8)
plt.xlabel('t (ms)')
... | _____no_output_____ | CC-BY-4.0 | tutorials/W3D2_DynamicNetworks/W3D2_Tutorial1.ipynb | sanchobarriga/course-content |
. Machine Learning models for text classification: | yelp_class = yelp[(yelp.stars==1) | (yelp.stars==5)]
X = yelp_class['text']
y = yelp_class['stars']
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
# count vectorization converts the text into integerized count vectors corresponding to the occurence of a particular word in the senten... | [[159 69]
[ 22 976]]
precision recall f1-score support
1 0.88 0.70 0.78 228
5 0.93 0.98 0.96 998
avg / total 0.92 0.93 0.92 1226
| MIT | ADS_Project1.ipynb | shrikumarp/ADSSpring18 |
. Support Vector Classifier | from sklearn.model_selection import GridSearchCV
parameters = [{'C': [1, 10, 100], 'kernel': ['linear']},
{'C': [1, 10, 100], 'kernel': ['rbf']}]
from sklearn.svm import SVC
svmmodel = SVC()
svmmodel.fit(X_train,y_train)
predsvm= svmmodel.predict(X_test)
print(confusion_matrix(y_test,predsvm))
print('\n')... | [[ 0 228]
[ 0 998]]
precision recall f1-score support
1 0.00 0.00 0.00 228
5 0.81 1.00 0.90 998
avg / total 0.66 0.81 0.73 1226
| MIT | ADS_Project1.ipynb | shrikumarp/ADSSpring18 |
Now we use the parameters list defined above to try to tune the parameter 'C' to see if we can squeeze out more accuracy out of this classifier. | grid_search_svm = GridSearchCV(estimator = svmmodel,
param_grid = parameters,
scoring = 'accuracy',
cv = 10,
n_jobs = -1)
#GridSearchCV(estimator, param_grid, scoring=None, fit_params=None, n_jobs=1, iid=True, r... | _____no_output_____ | MIT | ADS_Project1.ipynb | shrikumarp/ADSSpring18 |
As we can wee, the best selected parameters from the Girid search of better parameters turned out to be C= 1 and kernel ='Linear', and this model performed with the accuracy of 91.57%. . Using Random Forest Classifier Algorithm | from sklearn.ensemble import RandomForestClassifier
rforest = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)
rforest.fit(X_train, y_train)
rfpred= rforest.predict(X_test)
print(confusion_matrix(y_test,rfpred))
print('\n')
print(classification_report(y_test,rfpred)) | [[ 81 147]
[ 19 979]]
precision recall f1-score support
1 0.81 0.36 0.49 228
5 0.87 0.98 0.92 998
avg / total 0.86 0.86 0.84 1226
| MIT | ADS_Project1.ipynb | shrikumarp/ADSSpring18 |
. Using Logistic Regression | from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV | _____no_output_____ | MIT | ADS_Project1.ipynb | shrikumarp/ADSSpring18 |
We set the parameter grid again with a random space of values for parameter C, and we try to get the maximum accuracy by tuning the hyperparameters. | c_space = np.logspace(-5, 8, 15)
param_grid = {'C': c_space}
logreg = LogisticRegression()
logreg_cv = GridSearchCV(logreg, param_grid, cv= 10)
# here we pass the parameters of the Logistic regression model, the parameter values array and the number of Cross validations as 10 to the GridSearchCV function.
logreg_cv.fit... | precision recall f1-score support
1 0.86 0.79 0.83 228
5 0.95 0.97 0.96 998
avg / total 0.94 0.94 0.94 1226
| MIT | ADS_Project1.ipynb | shrikumarp/ADSSpring18 |
Copyright 2018 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
Distributed Training in TensorFlow Run in Google Colab View source on GitHub > Note: This is an archived TF1 notebook. These are configuredto run in TF2's [compatbility mode](https://www.tensorflow.org/guide/migrate)but will run in TF1 as well. To use TF1 in Colab, use the[%tensorflow_version 1.x](https... | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior() | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data ... | mirrored_strategy = tf.distribute.MirroredStrategy() | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this: | mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"]) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.Ncc... | mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce()) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create a `Ce... | central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy() | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/r1/guide/version_compatwhat_is_not_covered) as we are currently improving... | multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implem... | multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) f... | mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd') | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that... | dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays: | import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add ... | # Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
What's supported now?In [TF nightly release](https://pypi.org/project/tf-nightly-gpu/), we now support training with Keras using all strategies.Note: When using `TPUStrategy` with TPU pods with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in... | mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.N... | def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers... | with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.train.GradientDescentOptimizer(0.1) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy. | dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset) | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put it in a function `step_fn` and pass it to `tf.distribute.Strategy.run` along with the inputs from the iterator: | def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
train_op = optimizer.minimize(loss)
... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the l... | with mirrored_strategy.scope():
input_iterator = dist_dataset.make_initializable_iterator()
iterator_init = input_iterator.initializer
var_init = tf.global_variables_initializer()
loss = train_step(input_iterator.get_next())
with tf.Session() as sess:
sess.run([var_init, iterator_init])
for _ in range... | _____no_output_____ | Apache-2.0 | site/en/r1/guide/distribute_strategy.ipynb | DorianKodelja/docs |
Setting target or labelfor each input | label_oneDimension=data['is_duplicate']
label_oneDimension.head(2)
import numpy as np
from keras.utils.np_utils import to_categorical
label_twoDimension = to_categorical(data['is_duplicate'], num_classes=2)
label_twoDimension[0:1]
question_one=data['question1'].astype(str)
print(question_one.head())
question_two=data['... | 0 What is the step by step guide to invest in share market?
1 What would happen if the Indian government stole the Kohinoor (Koh-i-Noor) d...
2 How can Internet speed be increased by hacking through DNS?
3 Find the remainder when [math]23^{24}[/math] i... | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Reading test data and preprocessing | #Data reading
'''
data_test = pd.read_csv('drive/My Drive/Summer Internship 2020 July/My Test File/Sunil/test.csv')
data_test_sample=data_test.dropna()
#data_test_sample=data_test_sample.head(100)
data_test_sample.head()
'''
'''
question_one_test=data_test_sample['question1'].astype(str)
print(question_one_test.head())... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Fitting text on a single tokenized object | from keras.preprocessing.text import Tokenizer
tok_all = Tokenizer(filters='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~', char_level = False)
tok_all.fit_on_texts(question_one+question_two)
#tok_all.fit_on_texts(question_one+question_two+question_one_test+question_two_test)
vocabulary_all=len(tok_all.word_counts)
print(vocabula... | 89983
| Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Train data Sequencing and Encoding | #Encoding question 1
encoded_q1=tok_all.texts_to_sequences(question_one)
print(question_one[0])
encoded_q1[0]
#Encoding question 2
encoded_q2=tok_all.texts_to_sequences(question_two)
print(question_two[0])
encoded_q2[0] | What is the step by step guide to invest in share market?
| Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Pre-Padding on Train data | #####Padding encoded sequence of words
from keras.preprocessing import sequence
max_length=100
padded_docs_q1 = sequence.pad_sequences(encoded_q1, maxlen=max_length, padding='pre')
#####Padding encoded sequence of words
from keras.preprocessing import sequence
max_length=100
padded_docs_q2 = sequence.pad_sequences(enco... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Encoding on Test data | '''
#Encoding question 1
encoded_q1_test=tok_all.texts_to_sequences(question_one_test)
print(question_one_test[0])
encoded_q1_test[0]
'''
'''#Encoding question 1
encoded_q2_test=tok_all.texts_to_sequences(question_two_test)
print(question_two_test[0])
encoded_q2_test[0]''' | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Pre-Padding on test data | '''#####Padding encoded sequence of words
padded_docs_q1_test = sequence.pad_sequences(encoded_q1_test, maxlen=max_length, padding='pre')
padded_docs_q2_test = sequence.pad_sequences(encoded_q2_test, maxlen=max_length, padding='pre')''' | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Reading Embedding Vector from Glove | import os
import numpy as np
embeddings_index = {}
f = open('drive/My Drive/ML Internship IIIT Dharwad/Copy of glove.6B.300d.txt')
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
print('Loaded %s word vectors.... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Defining Input Shape for Model | Question1_shape= Input(shape=[max_length])
Question1_shape.shape
Question2_shape= Input(shape=[max_length])
Question2_shape.shape | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Embedding Layer | Embedding_Layer = Embedding(vocabulary_all+1,300,weights=[embedding_matrix], input_length=max_length, trainable=False) | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
CNN Network | CNN2_network=Sequential([Embedding_Layer,
Conv1D(32,3,activation="relu",padding='same'),
Dropout(0.2),
MaxPool1D(2),
Conv1D(64,5,activation="relu",padding='same'),
Dropout(0.2),
Max... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Printing Model summary | CNN2_network.summary()
from keras.utils.vis_utils import plot_model
plot_model(CNN2_network, to_file='CNN2_network.png', show_shapes=True, show_layer_names=True) | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
create siamese network from CNN model and store output feature vectors | Question1_CNN_feature=CNN2_network(Question1_shape)
Question2_CNN_feature=CNN2_network(Question2_shape) | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Adding and multiplying features obtained from Siamese CNN network | from keras import backend as K
from keras.optimizers import Adam
lamda_function=Lambda(lambda tensor:K.abs(tensor[0]-tensor[1]),name="Absolute_distance")
abs_distance_vector=lamda_function([Question1_CNN_feature,Question2_CNN_feature])
lamda_function2=Lambda(lambda tensor:K.abs(tensor[0]*tensor[1]),name="Hamadard_mult... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Adding abs_distance_vector and hamadard_vector | from keras.layers import Add
added_vecotr = Add()([abs_distance_vector, hamadard_vector]) | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Final Model prediction | predict=Dense(2,activation="sigmoid")(added_vecotr) | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Creating sequential model using Model() class and compilation | from sklearn.metrics import roc_auc_score, roc_curve, accuracy_score
Siamese2_Network=Model(inputs=[Question1_shape,Question2_shape],outputs=predict)
Siamese2_Network.compile(loss = "binary_crossentropy", optimizer=Adam(lr=0.00003), metrics=["accuracy"])
Siamese2_Network.summary() | Model: "functional_5"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
i... | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Plot model | from keras.utils import plot_model
plot_model(Siamese2_Network, to_file='Siamese2_Network.png',show_shapes=True, show_layer_names=True) | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Setting hyperparameter for training | from keras.callbacks import EarlyStopping, ReduceLROnPlateau,ModelCheckpoint
earlystopper = EarlyStopping(patience=8, verbose=1)
#checkpointer = ModelCheckpoint(filepath = 'cnn_model_one_.{epoch:02d}-{val_loss:.6f}.hdf5',
# verbose=1,
# save_best_only=True, sa... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Data split into train and validation set | # Splitting data into train and test
from sklearn.model_selection import train_test_split
q1_train, q1_val,q2_train, q2_val, label_train, label_val, label_oneD_train, label_oneD_val = train_test_split(padded_docs_q1,padded_docs_q2, label_twoDimension, label_oneDimension, test_size=0.30,
random_state=42) | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Model fitting or training | history = Siamese2_Network.fit([q1_train,q2_train],label_train,
batch_size=32,epochs=100,validation_data=([q1_val,q2_val],label_val),callbacks=[earlystopper, reduce_lr]) | Epoch 1/100
8844/8844 [==============================] - 64s 7ms/step - loss: 0.5987 - accuracy: 0.6722 - val_loss: 0.5843 - val_accuracy: 0.6917
Epoch 2/100
8844/8844 [==============================] - 64s 7ms/step - loss: 0.5591 - accuracy: 0.7142 - val_loss: 0.5705 - val_accuracy: 0.7091
Epoch 3/100
8844/8844 [=====... | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Model Prediction | Siamese2_Network_predictions = Siamese2_Network.predict([q1_val,q2_val])
#Siamese2_Network_predictions = Siamese2_Network.predict([padded_docs_q1_test,padded_docs_q2_test])
#Siamese2_Network_predictions_testData = Siamese2_Network.predict([padded_docs_q1_test,padded_docs_q1_test]) | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Log loss | from sklearn.metrics import log_loss
log_loss_val= log_loss(label_val,Siamese2_Network_predictions)
log_loss_val | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Classification report | predictions = np.zeros_like(Siamese2_Network_predictions)
predictions[np.arange(len(Siamese2_Network_predictions)), Siamese2_Network_predictions.argmax(1)] = 1
predictionInteger=(np.argmax(predictions, axis=1))
#print('np.argmax(a, axis=1): {0}'.format(np.argmax(predictions, axis=1)))
predictionInteger
from sklearn.met... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Final train and val loss | min_val_loss = min(history.history["val_loss"])
min_train_loss = min(history.history["loss"])
max_val_acc = max(history.history["val_accuracy"])
max_train_acc = max(history.history["accuracy"])
print("min_train_loss=%g, min_val_loss=%g, max_train_acc=%g, max_val_acc=%g" % (min_train_loss,min_val_loss,max_train_acc,max_... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Plot epoch Vs loss | from matplotlib import pyplot as plt
plt.plot(history.history["loss"],color = 'red', label = 'train_loss')
plt.plot(history.history["val_loss"],color = 'blue', label = 'val_loss')
plt.title('Loss Visualisation')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.savefig('2Layer_CNN_lossPlot_siamese.pdf',dpi=1000)... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Plot Epoch Vs Accuracy | plt.plot(history.history["accuracy"],color = 'red', label = 'train_accuracy')
plt.plot(history.history["val_accuracy"],color = 'blue', label = 'val_accuracy')
plt.title('Accuracy Visualisation')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.savefig('2Layer_CNN_accuracyPlot_siamese.pdf',dpi=1000)
files.do... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Area Under Curve- ROC | #pred_test = Siamese2_Network.predict([padded_docs_q1_test,padded_docs_q2_test])
pred_train = Siamese2_Network.predict([q1_train,q2_train])
pred_val = Siamese2_Network.predict([q1_val,q2_val])
import numpy as np
import matplotlib.pyplot as plt
from itertools import cycle
from sklearn import svm, datasets
from sklearn.... | _____no_output_____ | Apache-2.0 | CNN Models/Models/Duplicate_Question_2CNN_Layer.ipynb | roushan-raj/Duplicate-Question-Pair-Detection |
Hierarchical Clustering **Hierarchical clustering** refers to a class of clustering methods that seek to build a **hierarchy** of clusters, in which some clusters contain others. In this assignment, we will explore a top-down approach, recursively bipartitioning the data using k-means. **Note to Amazon EC2 users**: To... | import graphlab
import matplotlib.pyplot as plt
import numpy as np
import sys
import os
import time
from scipy.sparse import csr_matrix
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances
%matplotlib inline
'''Check GraphLab Create version'''
from distutils.version import StrictVersion
as... | This non-commercial license of GraphLab Create for academic use is assigned to sudhanshu.shekhar.iitd@gmail.com and will expire on September 18, 2017.
| MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Load the Wikipedia dataset | wiki = graphlab.SFrame('people_wiki.gl/') | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
As we did in previous assignments, let's extract the TF-IDF features: | wiki['tf_idf'] = graphlab.text_analytics.tf_idf(wiki['text']) | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
To run k-means on this dataset, we should convert the data matrix into a sparse matrix. | from em_utilities import sframe_to_scipy # converter
# This will take about a minute or two.
tf_idf, map_index_to_word = sframe_to_scipy(wiki, 'tf_idf') | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
To be consistent with the k-means assignment, let's normalize all vectors to have unit norm. | from sklearn.preprocessing import normalize
tf_idf = normalize(tf_idf) | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Bipartition the Wikipedia dataset using k-means Recall our workflow for clustering text data with k-means:1. Load the dataframe containing a dataset, such as the Wikipedia text dataset.2. Extract the data matrix from the dataframe.3. Run k-means on the data matrix with some value of k.4. Visualize the clustering resul... | def bipartition(cluster, maxiter=400, num_runs=4, seed=None):
'''cluster: should be a dictionary containing the following keys
* dataframe: original dataframe
* matrix: same data, in matrix format
* centroid: centroid for this particular cluster'''
data_m... | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
The following cell performs bipartitioning of the Wikipedia dataset. Allow 20-60 seconds to finish.Note. For the purpose of the assignment, we set an explicit seed (`seed=1`) to produce identical outputs for every run. In pratical applications, you might want to use different random seeds for all runs. | wiki_data = {'matrix': tf_idf, 'dataframe': wiki} # no 'centroid' for the root cluster
left_child, right_child = bipartition(wiki_data, maxiter=100, num_runs=6, seed=1) | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Let's examine the contents of one of the two clusters, which we call the `left_child`, referring to the tree visualization above. | left_child | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
And here is the content of the other cluster we named `right_child`. | right_child | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Visualize the bipartition We provide you with a modified version of the visualization function from the k-means assignment. For each cluster, we print the top 5 words with highest TF-IDF weights in the centroid and display excerpts for the 8 nearest neighbors of the centroid. | def display_single_tf_idf_cluster(cluster, map_index_to_word):
'''map_index_to_word: SFrame specifying the mapping betweeen words and column indices'''
wiki_subset = cluster['dataframe']
tf_idf_subset = cluster['matrix']
centroid = cluster['centroid']
# Print top 5 words with larges... | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Let's visualize the two child clusters: | display_single_tf_idf_cluster(left_child, map_index_to_word)
display_single_tf_idf_cluster(right_child, map_index_to_word) | she:0.025 her:0.017 music:0.012 he:0.011 university:0.011
* Anita Kunz 0.97401
anita e kunz oc born 1956 is a canadianborn artist and illustratorkunz has lived in london
new york and toronto contributing to magazines and working
* Janet Jackson ... | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
The left cluster consists of athletes, whereas the right cluster consists of non-athletes. So far, we have a single-level hierarchy consisting of two clusters, as follows: ``` Wikipedia + ... | athletes = left_child
non_athletes = right_child | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Using the bipartition function, we produce two child clusters of the athlete cluster: | # Bipartition the cluster of athletes
left_child_athletes, right_child_athletes = bipartition(athletes, maxiter=100, num_runs=6, seed=1) | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
The left child cluster mainly consists of baseball players: | display_single_tf_idf_cluster(left_child_athletes, map_index_to_word) | baseball:0.111 league:0.103 major:0.051 games:0.046 season:0.045
* Steve Springer 0.89344
steven michael springer born february 11 1961 is an american former professional baseball
player who appeared in major league baseball as a third baseman and
* Dave Ford ... | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
On the other hand, the right child cluster is a mix of players in association football, Austrailian rules football and ice hockey: | display_single_tf_idf_cluster(right_child_athletes, map_index_to_word) | season:0.034 football:0.033 team:0.031 league:0.029 played:0.027
* Gord Sherven 0.95562
gordon r sherven born august 21 1963 in gravelbourg saskatchewan and raised in mankota sas
katchewan is a retired canadian professional ice hockey forward who played
* Ashley Prescott ... | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Our hierarchy of clusters now looks like this:``` Wikipedia + | +--------------------------+--------------------+ | ... | baseball = left_child_athletes
ice_hockey_football = right_child_athletes | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Cluster of ice hockey players and football players In answering the following quiz question, take a look at the topics represented in the top documents (those closest to the centroid), as well as the list of words with highest TF-IDF weights.Let us bipartition the cluster of ice hockey and football players. | left_child_ihs, right_child_ihs = bipartition(ice_hockey_football, maxiter=100, num_runs=6, seed=1)
display_single_tf_idf_cluster(left_child_ihs, map_index_to_word)
display_single_tf_idf_cluster(right_child_ihs, map_index_to_word) | football:0.048 season:0.043 league:0.041 played:0.036 coach:0.034
* Todd Curley 0.94578
todd curley born 14 january 1973 is a former australian rules footballer who played for co
llingwood and the western bulldogs in the australian football league
* Tony Smith (footballer, bo... | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
**Quiz Question**. Which diagram best describes the hierarchy right after splitting the `ice_hockey_football` cluster? Refer to the quiz form for the diagrams. **Caution**. The granularity criteria is an imperfect heuristic and must be taken with a grain of salt. It takes a lot of manual intervention to obtain a good h... | # Bipartition the cluster of non-athletes
left_child_non_athletes, right_child_non_athletes = bipartition(non_athletes, maxiter=100, num_runs=6, seed=1)
display_single_tf_idf_cluster(left_child_non_athletes, map_index_to_word)
display_single_tf_idf_cluster(right_child_non_athletes, map_index_to_word) | she:0.126 her:0.082 film:0.013 actress:0.012 music:0.012
* Janet Jackson 0.93808
janet damita jo jackson born may 16 1966 is an american singer songwriter and actress know
n for a series of sonically innovative socially conscious and
* Lauren Royal ... | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Neither of the clusters show clear topics, apart from the genders. Let us divide them further. | male_non_athletes = left_child_non_athletes
female_non_athletes = right_child_non_athletes | _____no_output_____ | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
**Quiz Question**. Let us bipartition the clusters `male_non_athletes` and `female_non_athletes`. Which diagram best describes the resulting hierarchy of clusters for the non-athletes? Refer to the quiz for the diagrams.**Note**. Use `maxiter=100, num_runs=6, seed=1` for consistency of output. | # Bipartition the cluster of males
left_child_males, right_child_males = bipartition(male_non_athletes, maxiter=100, num_runs=6, seed=1)
display_single_tf_idf_cluster(left_child_males, map_index_to_word)
display_single_tf_idf_cluster(right_child_males, map_index_to_word)
# Bipartition the cluster of females
left_child_... | she:0.121 her:0.100 actress:0.031 film:0.030 music:0.028
* Janet Jackson 0.92374
janet damita jo jackson born may 16 1966 is an american singer songwriter and actress know
n for a series of sonically innovative socially conscious and
* Barbara Hershey ... | MIT | ml-clustering-and-retrieval/week-6/6_hierarchical_clustering_blank.ipynb | zomansud/coursera |
Choropleth Maps ExerciseWelcome to the Choropleth Maps Exercise! In this exercise we will give you some simple datasets and ask you to create Choropleth Maps from them. Due to the Nature of Plotly we can't show you examples embedded inside the notebook.[Full Documentation Reference](https://plot.ly/python/reference/ch... | import plotly.graph_objs as go
from plotly.offline import init_notebook_mode,iplot,plot
init_notebook_mode(connected=True) | _____no_output_____ | MIT | data-visualization/plotly/3_exercises.ipynb | pbgnz/ds-ml |
** Import pandas and read the csv file: 2014_World_Power_Consumption** | import pandas as pd
df = pd.read_csv('2014_World_Power_Consumption') | _____no_output_____ | MIT | data-visualization/plotly/3_exercises.ipynb | pbgnz/ds-ml |
** Check the head of the DataFrame. ** | df.head() | _____no_output_____ | MIT | data-visualization/plotly/3_exercises.ipynb | pbgnz/ds-ml |
** Referencing the lecture notes, create a Choropleth Plot of the Power Consumption for Countries using the data and layout dictionary. ** | data = dict(
type = 'choropleth',
colorscale = 'Viridis',
reversescale = True,
locations = df['Country'],
locationmode = "country names",
z = df['Power Consumption KWH'],
text = df['Country'],
colorbar = {'title' : 'Power Consumption KWH'},
)
layou... | _____no_output_____ | MIT | data-visualization/plotly/3_exercises.ipynb | pbgnz/ds-ml |
USA Choropleth** Import the 2012_Election_Data csv file using pandas. ** | usdf = pd.read_csv('2012_Election_Data') | _____no_output_____ | MIT | data-visualization/plotly/3_exercises.ipynb | pbgnz/ds-ml |
** Check the head of the DataFrame. ** | usdf.head() | _____no_output_____ | MIT | data-visualization/plotly/3_exercises.ipynb | pbgnz/ds-ml |
** Now create a plot that displays the Voting-Age Population (VAP) per state. If you later want to play around with other columns, make sure you consider their data type. VAP has already been transformed to a float for you. ** | data = dict(type='choropleth',
colorscale = 'Viridis',
reversescale = True,
locations = usdf['State Abv'],
z = usdf['Voting-Age Population (VAP)'],
locationmode = 'USA-states',
text = usdf['State'],
marker = dict(line = dict(color = 'rg... | _____no_output_____ | MIT | data-visualization/plotly/3_exercises.ipynb | pbgnz/ds-ml |
COMPSCI-589 HW3: Random Forestname: Harry (Haochen) Wang | from evaluationmatrix import *
from utils import *
from decisiontree import *
from randomforest import *
from run import *
housedata, housecategory = importhousedata()
winedata, winecategory = importwinedata()
cancerdata, cancercategory = importcancerdata()
cmcdata,cmccategory = importcmcdata()
parameterofn = [1, 5, 1... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
I. Wine Dataset | wineaccuracy, wineprecision, winerecall, winef1 = [], [], [], []
wineprecisionstd, winerecallstd, winef1std = [], [] ,[]
for n in parameterofn:
lists = kfoldcrossvalid(winedata, winecategory, 10, n, 10, 5, 0.01, 'id3', 0.1)[0]
beta = 1
a,p0,r0,f0,all = evaluate(lists, 1, beta)
a,p1,r1,f1,all = evaluate... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
Result/Stat of 1 trees random forest of Wine with information gain:| **Accuracy** | **Precision** | **Recall** | **F-Score, Beta=1** || :---: | :---: | :---: | :---: ||0.927 | 0.92 | 0.891 | 0.894 |Result/Stat of 5 trees random forest of Wine with information gain:| **Accuracy** | **Precision** | **Recall** | **F-Score... | ploter(wineaccuracy, '# of n in ntree V.S. accuracy of Wine with info gain', '# of n in ntree', 'Accuracy')
ploter(wineprecision, '# of n in ntree V.S. precision of Wine with info gain', '# of n in ntree', 'Precision', wineprecisionstd)
ploter(winerecall, '# of n in ntree V.S. recall of Wine with info gain', '# of n in... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
For this algorithm, here are the parameters I have:| **k (Fold)** | **max_depth** | **min_size_for_split** | **min_gain** |**bootstrap_ratio** || :---: | :---: | :---: | :---: | :---: || 10 | 10 | 5 | 0.01 | 0.1 |The K is the fold value, I just use the recommend k = 10The max_depth is the maximum depth for the tree, (t... | ploter(wineprecisionstd, '# of n in ntree V.S. std of precision of Wine with info gain', '# of n in ntree', 'Precision')
ploter(winerecallstd, '# of n in ntree V.S. std of recall of Wine with info gain', '# of n in ntree', 'Recall')
ploter(winef1std, '# of n in ntree V.S. std of F-1 Score of Wine with info gain', '# of... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
For the F score and so, we can find out that it's almost the same shape of curve as accuracy, since they have similar calculation process the (the harmonic mean of recall and precision; the accuracy is kind of similar to arithmetic mean of those two.)So F1 score is not a harder matrix to optimize. Notice that the st-de... | houseaccuracy, houseprecision, houserecall, housef1 = [], [], [], []
houseprecisionstd, houserecallstd, housef1std = [], [] ,[]
for n in parameterofn:
lists = kfoldcrossvalid(housedata, housecategory, 10, n, 10, 5, 0.01, 'id3', 0.1)[0]
beta = 1
a,p0,r0,f0,all = evaluate(lists, 0, beta)
a,p1,r1,f1,all =... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
Result/Stat of 1 trees random forest of House with information gain:| **Accuracy** | **Precision** | **Recall** | **F-Score, Beta=1** || :---: | :---: | :---: | :---: ||0.904 | 0.905 | 0.896 | 0.898 |Result/Stat of 5 trees random forest of House with information gain:| **Accuracy** | **Precision** | **Recall** | **F-Sc... | ploter(houseaccuracy, '# of n in ntree V.S. accuracy of HouseVote with info gain', '# of n in ntree', 'Accuracy')
ploter(houseprecision, '# of n in ntree V.S. precision of HouseVote with info gain', '# of n in ntree', 'Precision', houseprecisionstd)
ploter(houserecall, '# of n in ntree V.S. recall of HouseVote with inf... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
For this algorithm, here are the parameters I have:| **k (Fold)** | **max_depth** | **min_size_for_split** | **min_gain** |**bootstrap_ratio** || :---: | :---: | :---: | :---: | :---: || 10 | 10 | 5 | 0.01 | 0.1 |I use the same setup as the first dataset. (4) ANSWER: I would also pick 10 to 20, for this model and 20 i... | ploter(houseprecisionstd, '# of n in ntree V.S. std of precision of HouseVote with info gain', '# of n in ntree', 'Precision')
ploter(houserecallstd, '# of n in ntree V.S. std of recall of HouseVote with info gain', '# of n in ntree', 'Recall')
ploter(housef1std, '# of n in ntree V.S. std of F-1 Score of HouseVote with... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
We can see the drop in st_dev as the n growth, but it is slight increase when the n get larger (anyway the growth is less than 0.005 so I guess it's just random error/fluctuation.) III. Extra Points (Extra Points 1: 6 Points) Reconstruct the same graphs as above, but now using the Gini criterion. You should present t... | wineaccuracygini, wineprecisiongini, winerecallgini, winef1gini = [], [], [], []
wineprecisionginistd, winerecallginistd, winef1ginistd = [], [] ,[]
for n in parameterofn:
lists = kfoldcrossvalid(winedata, winecategory, 10, n, 10, 5, 0.01, 'gini', 0.1)[0]
beta = 1
a,p0,r0,f0,all = evaluate(lists, 1, beta)
... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
Result/Stat of 1 trees random forest of Wine with Gini index:| **Accuracy** | **Precision** | **Recall** | **F-Score, Beta=1** || :---: | :---: | :---: | :---: ||0.93 | 0.917 | 0.89 | 0.893 |Result/Stat of 5 trees random forest of Wine with Gini index:| **Accuracy** | **Precision** | **Recall** | **F-Score, Beta=1** ||... | ploter(wineaccuracygini, '# of n in ntree V.S. accuracy of Wine with Gini index', '# of n in ntree', 'Accuracy')
ploter(wineprecisiongini, '# of n in ntree V.S. precision of Wine with Gini index', '# of n in ntree', 'Precision', wineprecisionginistd)
ploter(winerecallgini, '# of n in ntree V.S. recall of Wine with Gini... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
Result/Stat of 1 trees random forest of House with Gini index:| **Accuracy** | **Precision** | **Recall** | **F-Score, Beta=1** || :---: | :---: | :---: | :---: ||0.947 | 0.948 | 0.946 | 0.944 |Result/Stat of 5 trees random forest of House with Gini index:| **Accuracy** | **Precision** | **Recall** | **F-Score, Beta=1*... | ploter(houseaccuracygini, '# of n in ntree V.S. accuracy of HouseVote with Gini index', '# of n in ntree', 'Accuracy')
ploter(houseprecisiongini, '# of n in ntree V.S. precision of HouseVote with Gini index', '# of n in ntree', 'Precision', houseprecisionginistd)
ploter(houserecallgini, '# of n in ntree V.S. recall of ... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
ANALYSIS for extra I:for those two, we are getting similar result on how the performance improves as n changes. For the house data, our performance is slightly better (around 96%) but the rate of increase is slower.For the wine data, the difference between info gain and gini are neglectable. (Extra Points 2: 6 Points)... | # canceraccuracy, cancerprecision, cancerrecall, cancerf1 = [], [], [], []
# cancerprecisionstd, cancerrecallstd, cancerf1std = [], [], []
# for n in parameterofn:
# lists = kfoldcrossvalid(cancerdata, cancercategory, 10, n, 7, 10, 0.01, 'id3', 0.1)[0]
# beta = 1
# a,p,r,f,all = evaluate(lists, 1, beta)
# ... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
Result/Stat of 1 trees random forest of Cancer with information gain:| **Accuracy** | **Precision** | **Recall** | **F-Score, Beta=1** || :---: | :---: | :---: | :---: ||0.937 | 0.896 | 0.929 | 0.911 |Result/Stat of 5 trees random forest of Cancer with information gain:| **Accuracy** | **Precision** | **Recall** | **F-... | # ploter(canceraccuracy, '# of n in ntree V.S. accuracy of CancerData with information gain', '# of n in ntree', 'Accuracy')
# ploter(cancerprecision, '# of n in ntree V.S. precision of CancerData with information gain', '# of n in ntree', 'Precision', cancerprecisionstd)
# ploter(cancerrecall, '# of n in ntree V.S. re... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
For this algorithm, here are the parameters I have:| **k (Fold)** | **max_depth** | **min_size_for_split** | **min_gain** |**bootstrap_ratio** || :---: | :---: | :---: | :---: | :---: || 10 | 7 | 10 | 0.01 | 0.1 |I changed the max_depth to 7 because there are more instances in this data. and I also increased the min_si... | # ploter(cancerprecisionstd, '# of n in ntree V.S. std of precision of CancerData with information gain', '# of n in ntree', 'Precision')
# ploter(cancerrecallstd, '# of n in ntree V.S. std of recall of CancerData with information gain', '# of n in ntree', 'Recall')
# ploter(cancerf1std, '# of n in ntree V.S. std of F-... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
ANALYSIS for extra II:In this question, we finally have one fixed positive class. Since it's for detecting cancer, hence we should focus on the recall. For optizmating recall, since it's not a probability classfier, so what we can do is to resample more positive training data, and when analyzing, we could change the be... | cmcaccuracy, cmcprecision, cmcrecall, cmcf1 = [], [], [], []
cmcprecisionstd, cmcrecallstd, cmcf1std = [], [], []
for n in parameterofn:
lists,accu = kfoldcrossvalid(cmcdata, cmccategory, 10, n, 10, 10, 0.01, 'id3', 0.1)
beta = 1
a,p0,r0,f0,all = evaluate(lists, 1, beta)
a,p1,r1,f1,all = evaluate(lists... | _____no_output_____ | MIT | hw3.ipynb | HarryWang0619/COMPSCI589-HW3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.