markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Apply PCA Finally apply a PCA transformation. This has to be done because the only way to visualise the decision boundary in 2D would be if the KNN algorithm ran in 2D as well. Note that removing the PCA will improve the accuracy (KNeighbours is applied to the entire train data, not just the two principal components)...
from sklearn.decomposition import PCA # # Just like the preprocessing transformation, create a PCA # transformation as well. Fit it against the training data, and then # project the training and testing features into PCA space using the # PCA model's .transform() method. # # pca_reducer = PCA(n_components=2).fit(X_tr...
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
KNN algorithm Now we finally apply the K-neighbours algorithm, using the related module from SKlearn. For K-Neighbours, generally the higher your "K" value, the smoother and less jittery your decision surface becomes. Higher K values also result in your model providing probabilistic information about the ratio of sampl...
from sklearn.neighbors import KNeighborsClassifier # # Create and train a KNeighborsClassifier. Start with K=9 neighbors. # NOTE: Be sure to train the classifier against the pre-processed, PCA- # transformed training data above! # knn = KNeighborsClassifier(n_neighbors=9) knn.fit(X_train_pca, y_train)
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
Decision Boundaries A unique feature of supervised classification algorithms are their decision boundaries, or more generally, their n-dimensional decision surface: a threshold or region where if superseded, will result in your sample being assigned that class. The decision surface isn't always spherical. In fact, it c...
import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') # Look Pretty import numpy as np def plotDecisionBoundary(model, X, y, colors, padding=0.6, resolution = 0.0025): fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111) # Calculate the boundaries x_min, x_max = X[:, ...
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
Just a reminder: these are the wheat labels:
for label in np.unique(y_original): print (label) myColours = ['royalblue','forestgreen','ghostwhite'] plotDecisionBoundary(knn, X_train_pca, y_train, colors = myColours)
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
The KNN (with K=9) algorithm divided the space into three clusters, one for each wheat type. The clusters fit quite well the testing data but not perfectly, some data points are mis-classified.
# # Display the accuracy score of the test data/labels, computed by # the KNeighbors model. # # NOTE: You do NOT have to run .predict before calling .score, since # .score will take care of running the predictions automatically. # print(knn.score(X_test_pca, y_test))
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
K-Neighbours is particularly useful when no other model fits your data well, as it is a parameter free approach to classification. So for example, you don't have to worry about things like your data being linearly separable or not. Some of the caution-points to keep in mind while using K-Neighbours is that your data ne...
# # Load in the dataset, identify nans, and set proper headers. # X = pd.read_csv("../Datasets/breast-cancer-wisconsin.data", header=None, names=['sample', 'thickness', 'size', 'shape', 'adhesion', 'epithelial', 'nuclei', 'chromatin', 'nucleoli', 'mito...
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
Data Pre-processing Extract the target values, remove all NaN values and split into testing and training data
# # Copy out the status column into a slice, then drop it from the main # dataframe. # # y = X.status.copy() X.drop(['status'], axis=1, inplace=True) # # With the labels safely extracted from the dataset, replace any nan values # with the mean feature / column value # if X.isnull().values.any() == True: print("Pre...
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
Define hyper-parameters. We will loop the KNN algorithm with different parameters, specifically: different scalers for normalisation reduced or not reduced (here PCA but can also use isomap for reduction) different weight function and different values of K
# automate the tuning of hyper-parameters using for-loops to traverse the search space. reducers = [False, True] weights = ['uniform', 'distance'] # Experiment with the basic SKLearn preprocessing scalers. We know that # the features consist of different units mixed in together, so it might be # reasonable to assume ...
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
Hyper-parameters tuning Loop through all the parameters: fit the model and print the result every time
# the f print function works from Python 3.6, you can use print otherwise separator = "--------------------------------------" print('*** Starting K-neighbours classifier') print(separator) bestScore = 0.0 # outer loop: the scalers for scaler in scalers: print("* Scaler = ", scaler) scalerTrained = scaler().fit(...
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
Re-apply the best parameters to the model
print("These are the best parameters for the model:") print("PCA? | K | Weight | Scaler | Score") print(f"{bestPCA} | {bestK} | {bestWeight} | {bestScaler} | {bestScore}") BestScalerTrained = bestScaler().fit(X_train) X_train_scaled = BestScalerTrained.transform(X_train) X_test_scaled = BestScalerTrained.transf...
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
Plotting the decision boundaries
# 2 for benign (blue colour), 4 for malignant (red colour) myColours = {2:'royalblue',4:'lightsalmon'} plotDecisionBoundary(bestKnmodel, X_test_reduced, y_test, colors = myColours, padding = 0.1, resolution = 0.1)
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
Another example for KNN with reduction
import scipy.io import math # Same datasets as in the PCA example! # load up the face_data.mat, calculate the # num_pixels value, and rotate the images to being right-side-up # instead of sideways. # mat = scipy.io.loadmat('../datasets/face_data.mat') df = pd.DataFrame(mat['images']).T num_images, num_pixels = df.shap...
02-Classification/knn.ipynb
Mashimo/datascience
apache-2.0
Create some text to use....
text = "Compatibility of systems of linear constraints over the set of natural numbers. Criteria of compatibility of a system of linear Diophantine equations, strict inequations, and nonstrict inequations are considered. Upper bounds for components of a minimal set of solutions and algorithms of construction of minimal...
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
Then add PyTextRank into the spaCy pipeline...
import pytextrank tr = pytextrank.TextRank() nlp.add_pipe(tr.PipelineComponent, name="textrank", last=True) doc = nlp(text)
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
Examine the results: a list of top-ranked phrases in the document
for p in doc._.phrases: print("{:.4f} {:5d} {}".format(p.rank, p.count, p.text)) print(p.chunks)
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
Construct a list of the sentence boundaries with a phrase vector (initialized to empty set) for each...
sent_bounds = [ [s.start, s.end, set([])] for s in doc.sents ] sent_bounds
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
Iterate through the top-ranked phrases, added them to the phrase vector for each sentence...
limit_phrases = 4 phrase_id = 0 unit_vector = [] for p in doc._.phrases: print(phrase_id, p.text, p.rank) unit_vector.append(p.rank) for chunk in p.chunks: print(" ", chunk.start, chunk.end) for sent_start, sent_end, sent_vector in sent_bounds: if chunk.start...
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
Let's take a look at the results...
sent_bounds for sent in doc.sents: print(sent)
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
We also construct a unit_vector for all of the phrases, up to the limit requested...
unit_vector sum_ranks = sum(unit_vector) unit_vector = [ rank/sum_ranks for rank in unit_vector ] unit_vector
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
Iterate through each sentence, calculating its euclidean distance from the unit vector...
from math import sqrt sent_rank = {} sent_id = 0 for sent_start, sent_end, sent_vector in sent_bounds: print(sent_vector) sum_sq = 0.0 for phrase_id in range(len(unit_vector)): print(phrase_id, unit_vector[phrase_id]) if phrase_id not in sent_vector: sum_sq += uni...
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
Sort the sentence indexes in descending order
from operator import itemgetter sorted(sent_rank.items(), key=itemgetter(1))
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
Extract the sentences with the lowest distance, up to the limite requested...
limit_sentences = 2 sent_text = {} sent_id = 0 for sent in doc.sents: sent_text[sent_id] = sent.text sent_id += 1 num_sent = 0 for sent_id, rank in sorted(sent_rank.items(), key=itemgetter(1)): print(sent_id, sent_text[sent_id]) num_sent += 1 if num_sent == limit_sentences: break
explain_summ.ipynb
ceteri/pytextrank
apache-2.0
์ •๊ทœํ™” <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/addons/tutorials/layers_normalizations"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org์—์„œ ๋ณด๊ธฐ</a></td> <td><a target="_blank" href="https://colab.research.google.com/github/tenso...
!pip install -U tensorflow-addons import tensorflow as tf import tensorflow_addons as tfa
site/ko/addons/tutorials/layers_normalizations.ipynb
tensorflow/docs-l10n
apache-2.0
๋ฐ์ดํ„ฐ์„ธํŠธ ์ค€๋น„ํ•˜๊ธฐ
mnist = tf.keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0
site/ko/addons/tutorials/layers_normalizations.ipynb
tensorflow/docs-l10n
apache-2.0
๊ทธ๋ฃน ์ •๊ทœํ™” ํŠœํ† ๋ฆฌ์–ผ ์†Œ๊ฐœ ๊ทธ๋ฃน ์ •๊ทœํ™”(GN)๋Š” ์ž…๋ ฅ ์ฑ„๋„์„ ๋” ์ž‘์€ ํ•˜์œ„ ๊ทธ๋ฃน์œผ๋กœ ๋‚˜๋ˆ„๊ณ  ํ‰๊ท ๊ณผ ๋ถ„์‚ฐ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๊ฐ’์„ ์ •๊ทœํ™”ํ•ฉ๋‹ˆ๋‹ค. GN์€ ๋‹จ์ผ ์˜ˆ์ œ์—์„œ ๋™์ž‘ํ•˜๋ฏ€๋กœ ์ด ๊ธฐ์ˆ ์€ ๋ฐฐ์น˜ ํฌ๊ธฐ์™€ ๋…๋ฆฝ์ ์ž…๋‹ˆ๋‹ค. GN์€ ์‹คํ—˜์ ์œผ๋กœ ์ด๋ฏธ์ง€ ๋ถ„๋ฅ˜ ์ž‘์—…์—์„œ ๋ฐฐ์น˜ ์ •๊ทœํ™”์™€ ๋น„์Šทํ•œ ์ ์ˆ˜๋ฅผ ๊ธฐ๋กํ–ˆ์Šต๋‹ˆ๋‹ค. ์ „์ฒด batch_size๊ฐ€ ๋‚ฎ์€ ๊ฒฝ์šฐ ์ด๋•Œ ๋ฐฐ์น˜ ์ •๊ทœํ™”์˜ ์„ฑ๋Šฅ์ด ์ €ํ•˜๋  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๋ฐฐ์น˜ ์ •๊ทœํ™” ๋Œ€์‹  GN์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์œ ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ‘œ์ค€ "channels last" ์„ค์ •์—์„œ Conv2D ๋ ˆ์ด์–ด ์ดํ›„ 10๊ฐœ์˜ ์ฑ„๋„์„ 5๊ฐœ์˜ ํ•˜์œ„ ๊ทธ๋ฃน์œผ๋กœ ๋ถ„ํ• ํ•˜๋Š” ์˜ˆ์ œ
model = tf.keras.models.Sequential([ # Reshape into "channels last" setup. tf.keras.layers.Reshape((28,28,1), input_shape=(28,28)), tf.keras.layers.Conv2D(filters=10, kernel_size=(3,3),data_format="channels_last"), # Groupnorm Layer tfa.layers.GroupNormalization(groups=5, axis=3), tf.keras.layers.Flatten(),...
site/ko/addons/tutorials/layers_normalizations.ipynb
tensorflow/docs-l10n
apache-2.0
์ธ์Šคํ„ด์Šค ์ •๊ทœํ™” ํŠœํ† ๋ฆฌ์–ผ ์†Œ๊ฐœ ์ธ์Šคํ„ด์Šค ์ •๊ทœํ™”๋Š” ๊ทธ๋ฃน ํฌ๊ธฐ๊ฐ€ ์ฑ„๋„ ํฌ๊ธฐ(๋˜๋Š” ์ถ• ํฌ๊ธฐ)์™€ ๊ฐ™์€ ๊ทธ๋ฃน ์ •๊ทœํ™”์˜ ํŠน์ˆ˜ํ•œ ๊ฒฝ์šฐ์ž…๋‹ˆ๋‹ค. ์‹คํ—˜ ๊ฒฐ๊ณผ๋Š” ๋ฐฐ์น˜ ์ •๊ทœํ™”๋ฅผ ๋Œ€์ฒดํ•  ๋•Œ ์ธ์Šคํ„ด์Šค ์ •๊ทœํ™”๊ฐ€ ์Šคํƒ€์ผ ์ „์†ก์—์„œ ์ž˜ ์ˆ˜ํ–‰๋จ์„ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค. ์ตœ๊ทผ์—๋Š” ์ธ์Šคํ„ด์Šค ์ •๊ทœํ™”๊ฐ€ GAN์—์„œ ๋ฐฐ์น˜ ์ •๊ทœํ™”๋ฅผ ๋Œ€์ฒดํ•˜๋Š” ์šฉ๋„๋กœ๋„ ์‚ฌ์šฉ๋˜์—ˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ์ œ Conv2D ๋ ˆ์ด์–ด ๋‹ค์Œ์— InstanceNormalization์„ ์ ์šฉํ•˜๊ณ  ๊ท ์ผํ•˜๊ฒŒ ์ดˆ๊ธฐํ™”๋œ ์Šค์ผ€์ผ ๋ฐ ์˜คํ”„์…‹ ์ธ์ž๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
model = tf.keras.models.Sequential([ # Reshape into "channels last" setup. tf.keras.layers.Reshape((28,28,1), input_shape=(28,28)), tf.keras.layers.Conv2D(filters=10, kernel_size=(3,3),data_format="channels_last"), # LayerNorm Layer tfa.layers.InstanceNormalization(axis=3, ...
site/ko/addons/tutorials/layers_normalizations.ipynb
tensorflow/docs-l10n
apache-2.0
๋ ˆ์ด์–ด ์ •๊ทœํ™” ํŠœํ† ๋ฆฌ์–ผ ์†Œ๊ฐœ ๋ ˆ์ด์–ด ์ •๊ทœํ™”๋Š” ๊ทธ๋ฃน ํฌ๊ธฐ๊ฐ€ 1์ธ ๊ทธ๋ฃน ์ •๊ทœํ™”์˜ ํŠน์ˆ˜ํ•œ ๊ฒฝ์šฐ์ž…๋‹ˆ๋‹ค. ํ‰๊ท ๊ณผ ํ‘œ์ค€ ํŽธ์ฐจ๋Š” ๋‹จ์ผ ์ƒ˜ํ”Œ์˜ ๋ชจ๋“  ํ™œ์„ฑํ™”์—์„œ ๊ณ„์‚ฐ๋ฉ๋‹ˆ๋‹ค. ์‹คํ—˜ ๊ฒฐ๊ณผ๋Š” ๋ ˆ์ด์–ด ์ •๊ทœํ™”๊ฐ€ ๋ฐฐ์น˜ ํฌ๊ธฐ์™€๋Š” ๋…๋ฆฝ์ ์œผ๋กœ ๋™์ž‘ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ˆœํ™˜ ์‹ ๊ฒฝ๋ง์— ์ ํ•ฉํ•˜๋‹ค๋Š” ๊ฒƒ์„ ๋ณด์—ฌ์ค๋‹ˆ๋‹ค. Example Conv2D ๋ ˆ์ด์–ด ๋‹ค์Œ์— ๋ ˆ์ด์–ด ์ •๊ทœํ™”๋ฅผ ์ ์šฉํ•˜๊ณ  ์Šค์ผ€์ผ ๋ฐ ์˜คํ”„์…‹ ์ธ์ž๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.
model = tf.keras.models.Sequential([ # Reshape into "channels last" setup. tf.keras.layers.Reshape((28,28,1), input_shape=(28,28)), tf.keras.layers.Conv2D(filters=10, kernel_size=(3,3),data_format="channels_last"), # LayerNorm Layer tf.keras.layers.LayerNormalization(axis=3 , center=True , scale=True), tf.k...
site/ko/addons/tutorials/layers_normalizations.ipynb
tensorflow/docs-l10n
apache-2.0
Train SVM on features Using the multiclass SVM code developed earlier in the assignment, train SVMs on top of the features extracted above; this should achieve better results than training SVMs directly on top of raw pixels. |Number of Bins|Validation Accuracy|Learning Rate|Regularization Strength|Test Accuracy| |-----...
# Use the validation set to tune the learning rate and regularization strength from cs231n.classifiers.linear_classifier import LinearSVM learning_rates = [1e-7, 2e-7, 3e-7, 5e-5, 8e-7] regularization_strengths = [1e4, 2e4, 3e4, 4e4, 5e4, 6e4, 7e4, 8e4, 7e5] results = {} best_val = -1 best_svm = None ##############...
assignment1/features.ipynb
Hasil-Sharma/Neural-Networks-CS231n
gpl-3.0
Inline question 1: Describe the misclassification results that you see. Do they make sense? Neural Network on image features Earlier in this assigment we saw that training a two-layer neural network on raw pixels achieved better classification performance than linear classifiers on raw pixels. In this notebook we have ...
print X_train_feats.shape
assignment1/features.ipynb
Hasil-Sharma/Neural-Networks-CS231n
gpl-3.0
| Learning Rate| Regularization Rate | Validation Accuracy | Test Accuracy | | --- | --- | --- | --- | | 0.1 | 0.0001 | 0.544 | 0.534 | | 0.1 | 0.000215443469003 | 0.544 | 0.538 | | 0.1 | 0.000464158883361 | 0.542 | 0.534 | | 0.1 | 0.001 | 0.537 | 0.535 | | 0.1 | 0.00215443469003 | 0.536 | 0.533 | | 0.1 | 0.00464158883...
from cs231n.classifiers.neural_net import TwoLayerNet input_dim = X_train_feats.shape[1] hidden_dim = 500 num_classes = 10 best_net = None best_val_acc = 0.0 best_hidden_size = None best_learning_rate = None best_regularization_strength = None ##########################################################################...
assignment1/features.ipynb
Hasil-Sharma/Neural-Networks-CS231n
gpl-3.0
ไฝฟ็”จไน‹ๅ‰ไธ‹่ผ‰็š„ mnist ่ณ‡ๆ–™๏ผŒ่ผ‰ๅ…ฅ่จ“็ทด่ณ‡ๆ–™ train_set ๅ’Œๆธฌ่ฉฆ่ณ‡ๆ–™ test_set
import gzip import pickle with gzip.open('../Week02/mnist.pkl.gz', 'rb') as f: train_set, validation_set, test_set = pickle.load(f, encoding='latin1') train_X, train_y = train_set validation_X, validation_y = validation_set test_X, test_y = test_set
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
ไน‹ๅ‰็š„็œ‹ๅœ–็‰‡ๅ‡ฝๆ•ธ
from IPython.display import display def showX(X): int_X = (X*255).clip(0,255).astype('uint8') # N*784 -> N*28*28 -> 28*N*28 -> 28 * 28N int_X_reshape = int_X.reshape(-1,28,28).swapaxes(0,1).reshape(28,-1) display(Image.fromarray(int_X_reshape)) # ่จ“็ทด่ณ‡ๆ–™๏ผŒ X ็š„ๅ‰ 20 ็ญ† showX(train_X[:20])
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
train_set ๆ˜ฏ็”จไพ†่จ“็ทดๆˆ‘ๅ€‘็š„ๆจกๅž‹็”จ็š„ ๆˆ‘ๅ€‘็š„ๆจกๅž‹ๆ˜ฏๅพˆ็ฐกๅ–ฎ็š„ logistic regression ๆจกๅž‹๏ผŒ็”จๅˆฐ็š„ๅƒๆ•ธๅชๆœ‰ไธ€ๅ€‹ 784x10 ็š„็Ÿฉ้™ฃ W ๅ’Œไธ€ๅ€‹้•ทๅบฆ 10 ็š„ๅ‘้‡ bใ€‚ ๆˆ‘ๅ€‘ๅ…ˆ็”จๅ‡ๅ‹ป้šจๆฉŸไบ‚ๆ•ธไพ†่จญๅฎš W ๅ’Œ b ใ€‚
W = np.random.uniform(low=-1, high=1, size=(28*28,10)) b = np.random.uniform(low=-1, high=1, size=10)
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
ๅฎŒๆ•ด็š„ๆจกๅž‹ๅฆ‚ไธ‹ ๅฐ‡ๅœ–็‰‡็œ‹ๆˆๆ˜ฏ้•ทๅบฆ 784 ็š„ๅ‘้‡ x ่จˆ็ฎ— $Wx+b$๏ผŒ ็„ถๅพŒๅ†ๅ– $exp$ใ€‚ ๆœ€ๅพŒๅพ—ๅˆฐ็š„ๅๅ€‹ๆ•ธๅ€ผใ€‚ๅฐ‡้€™ไบ›ๆ•ธๅ€ผ้™คไปฅไป–ๅ€‘็š„็ธฝๅ’Œใ€‚ ๆˆ‘ๅ€‘ๅธŒๆœ›ๅ‡บไพ†็š„ๆ•ธๅญ—ๆœƒ็ฌฆๅˆ้€™ๅผตๅœ–็‰‡ๆ˜ฏ้€™ๅ€‹ๆ•ธๅญ—็š„ๆฉŸ็އใ€‚ $ \Pr(Y=i|x, W, b) = \frac {e^{W_i x + b_i}} {\sum_j e^{W_j x + b_j}}$ ๅ…ˆๆ‹ฟ็ฌฌไธ€็ญ†่ณ‡ๆ–™่ฉฆ่ฉฆ็œ‹๏ผŒ x ๆ˜ฏ่ผธๅ…ฅใ€‚ y ๆ˜ฏ้€™ๅผตๅœ–็‰‡ๅฐๆ‡‰ๅˆฐ็š„ๆ•ธๅญ—(ไปฅ้€™ๅ€‹ไพ‹ๅญไพ†่ชช y=5)ใ€‚
x = train_X[0] y = train_y[0] showX(x) y
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
ๅ…ˆ่จˆ็ฎ— $e^{Wx+b} $
Pr = np.exp(x @ W + b) Pr.shape
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
็„ถๅพŒ normalize๏ผŒ่ฎ“็ธฝๅ’Œ่ฎŠๆˆ 1 ๏ผˆ็ฌฆๅˆๆฉŸ็އ็š„ๆ„็พฉ๏ผ‰
Pr = Pr/Pr.sum() Pr
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
็”ฑๆ–ผ $W$ ๅ’Œ $b$ ้ƒฝๆ˜ฏ้šจๆฉŸ่จญๅฎš็š„๏ผŒๆ‰€ไปฅไธŠ้ขๆˆ‘ๅ€‘็ฎ—ๅ‡บ็š„ๆฉŸ็އไนŸๆ˜ฏ้šจๆฉŸ็š„ใ€‚ ๆญฃ็ขบ่งฃๆ˜ฏ $y=5$๏ผŒ ้‹ๆฐฃๅฅฝๆœ‰ๅฏ่ƒฝ็Œœไธญ ็‚บไบ†่ฆ่ฉ•ๆ–ทๆˆ‘ๅ€‘็š„้ ๆธฌ็š„ๅ“่ณช๏ผŒ่ฆ่จญ่จˆไธ€ๅ€‹่ฉ•ๆ–ท่ชคๅทฎ็š„ๆ–นๅผ๏ผŒๆˆ‘ๅ€‘็”จ็š„ๆ–นๆณ•ๅฆ‚ไธ‹๏ผˆไธๆ˜ฏๅธธ่ฆ‹็š„ๆ–นๅทฎ๏ผŒ่€Œๆ˜ฏ็”จ็†ต็š„ๆ–นๅผไพ†็ฎ—๏ผŒๅฅฝ่™•ๆ˜ฏๅฎนๆ˜“ๅพฎๅˆ†๏ผŒๆ•ˆๆžœๅฅฝ๏ผ‰ $ loss = - \log(\Pr(Y=y|x, W,b)) $ ไธŠ่ฟฐ็š„่ชคๅทฎ่ฉ•ๅˆ†ๆ–นๅผ๏ผŒๅธธๅธธ็จฑไฝœ error ๆˆ–่€… loss๏ผŒๆ•ธๅญธๅผๅฏ่ƒฝๆœ‰้ปž่ฒป่งฃใ€‚ๅฏฆ้š›่จˆ็ฎ—ๅ…ถๅฏฆๅพˆ็ฐกๅ–ฎ๏ผŒๅฐฑๆ˜ฏไธ‹้ข็š„ๅผๅญ
loss = -np.log(Pr[y]) loss
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
ๆƒณ่พฆๆณ•ๆ”น้€ฒใ€‚ ๆˆ‘ๅ€‘็”จไธ€็จฎ่ขซ็จฑไฝœๆ˜ฏ gradient descent ็š„ๆ–นๅผไพ†ๆ”นๅ–„ๆˆ‘ๅ€‘็š„่ชคๅทฎใ€‚ ๅ› ็‚บๆˆ‘ๅ€‘็Ÿฅ้“ gradient ๆ˜ฏ่ฎ“ๅ‡ฝๆ•ธไธŠๅ‡ๆœ€ๅฟซ็š„ๆ–นๅ‘ใ€‚ๆ‰€ไปฅๆˆ‘ๅ€‘ๅฆ‚ๆžœๆœ gradient ็š„ๅๆ–นๅ‘่ตฐไธ€้ปž้ปž๏ผˆไนŸๅฐฑๆ˜ฏไธ‹้™ๆœ€ๅฟซ็š„ๆ–นๅ‘๏ผ‰๏ผŒ้‚ฃ้บผๅพ—ๅˆฐ็š„ๅ‡ฝๆ•ธๅ€ผๆ‡‰่ฉฒๆœƒๅฐไธ€้ปžใ€‚ ่จ˜ๅพ—ๆˆ‘ๅ€‘็š„่ฎŠๆ•ธๆ˜ฏ $W$ ๅ’Œ $b$ (่ฃก้ข็ธฝๅ…ฑๆœ‰ 28*20+10 ๅ€‹่ฎŠๆ•ธ)๏ผŒๆ‰€ไปฅๆˆ‘ๅ€‘่ฆๆŠŠ $loss$ ๅฐ $W$ ๅ’Œ $b$ ่ฃก้ข็š„ๆฏไธ€ๅ€‹ๅƒๆ•ธไพ†ๅๅพฎๅˆ†ใ€‚ ้‚„ๅฅฝ้€™ๅ€‹ๅๅพฎๅˆ†ๆ˜ฏๅฏไปฅ็”จๆ‰‹็ฎ—ๅ‡บไป–็š„ๅฝขๅผ๏ผŒ่€Œๆœ€ๅพŒๅๅพฎๅˆ†็š„ๅผๅญไนŸไธๆœƒๅพˆ่ค‡้›œใ€‚ $loss$ ๅฑ•้–‹ๅพŒๅฏไปฅๅฏซๆˆ $loss = \log(\sum_j e^{W_j x + b_j}) - W_i x - b_i$ ๅฐ $k \ne...
gradb = Pr.copy() gradb[y] -= 1 print(gradb)
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
ๅฐ $W$ ็š„ๅๅพฎๅˆ†ไนŸไธ้›ฃ ๅฐ $k \neq i$ ๆ™‚, $loss$ ๅฐ $W_{k,t}$ ็š„ๅๅพฎๅˆ†ๆ˜ฏ $$ \frac{e^{W_k x + b_k} W_{k,t} x_t}{\sum_j e^{W_j x + b_j}} = \Pr(Y=k | x, W, b) x_t$$ ๅฐ $k = i$ ๆ™‚, $loss$ ๅฐ $W_{k,t}$ ็š„ๅๅพฎๅˆ†ๆ˜ฏ $$ \Pr(Y=k | x, W, b) x_t - x_t$$
print(Pr.shape, x.shape, W.shape) gradW = x.reshape(784,1) @ Pr.reshape(1,10) gradW[:, y] -= x
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
็ฎ—ๅฅฝ gradient ๅพŒ๏ผŒ่ฎ“ W ๅ’Œ b ๅˆ†ๅˆฅๅพ€ gradient ๅๆ–นๅ‘่ตฐไธ€้ปž้ปž๏ผŒๅพ—ๅˆฐๆ–ฐ็š„ W ๅ’Œ b
W -= 0.1 * gradW b -= 0.1 * gradb
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
ๅ†ไธ€ๆฌก่จˆ็ฎ— $\Pr$ ไปฅๅŠ $loss$
Pr = np.exp(x @ W + b) Pr = Pr/Pr.sum() loss = -np.log(Pr[y]) loss
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
Q ็œ‹็œ‹ Pr ๏ผŒ ็„ถๅพŒๆ‰พๅ‡บๆฉŸ็އๆœ€ๅคง่€…๏ผŒ predict y ๅ€ผ ๅ†่ท‘ไธ€้ไธŠ้ข็จ‹ๅบ๏ผŒ็œ‹็œ‹่ชคๅทฎๆ˜ฏๅฆ่ฎŠๅฐ๏ผŸ ๆ‹ฟๅ…ถไป–็š„ๆธฌ่ฉฆ่ณ‡ๆ–™ไพ†็œ‹็œ‹๏ผŒๆˆ‘ๅ€‘็š„ W, b ๅญธๅˆฐไบ†ไป€้บผ๏ผŸ ๆˆ‘ๅ€‘ๅฐ‡ๅŒๆจฃ็š„ๆ–นๅผ่ผชๆตๅฐไบ”่ฌ็ญ†่จ“็ทด่ณ‡ๆ–™ไพ†ๅš๏ผŒ็œ‹็œ‹ๆƒ…ๅฝขๆœƒๅฆ‚ไฝ•
W = np.random.uniform(low=-1, high=1, size=(28*28,10)) b = np.random.uniform(low=-1, high=1, size=10) score = 0 N=50000*20 d = 0.001 learning_rate = 1e-2 for i in range(N): if i%50000==0: print(i, "%5.3f%%"%(score*100)) x = train_X[i%50000] y = train_y[i%50000] Pr = np.exp( x @ W +b) Pr = Pr...
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
็ตๆžœ็™ผ็พๆญฃ็ขบ็އๅคง็ด„ๆ˜ฏ 92%๏ผŒ ไฝ†้€™ๆ˜ฏๅฐ่จ“็ทด่ณ‡ๆ–™่€Œไธๆ˜ฏๅฐๆธฌ่ฉฆ่ณ‡ๆ–™ ่€Œไธ”๏ผŒไธ€็ญ†ไธ€็ญ†็š„่จ“็ทด่ณ‡ไนŸๆœ‰้ปžๆ…ข๏ผŒ็ทšๆ€งไปฃๆ•ธ็š„็‰น้ปžๅฐฑๆ˜ฏ่ƒฝๅค ๅ‘้‡้‹็ฎ—ใ€‚ๅฆ‚ๆžœๆŠŠๅพˆๅคš็ญ† $x$ ็•ถๆˆๅˆ—ๅ‘้‡็ต„ๅˆๆˆไธ€ๅ€‹็Ÿฉ้™ฃ๏ผˆ็„ถๅพŒๅซๅš $X$๏ผ‰๏ผŒ็”ฑๆ–ผ็Ÿฉ้™ฃไน˜ๆณ•็š„ๅŽŸ็†๏ผŒๆˆ‘ๅ€‘้‚„ๆ˜ฏไธ€ๆจฃ่จˆ็ฎ— $WX+b$ ๏ผŒ ๅฐฑๅฏไปฅๅŒๆ™‚ๅพ—ๅˆฐๅคš็ญ†็ตๆžœใ€‚ ไธ‹้ข็š„ๅ‡ฝๆ•ธ๏ผŒๅฏไปฅไธ€ๆฌก่ผธๅ…ฅๅคš็ญ† $x$๏ผŒ ๅŒๆ™‚ไธ€ๆฌก่จˆ็ฎ—ๅคš็ญ† $x$ ็š„็ตๆžœๅ’Œๆบ–็ขบ็އใ€‚
def compute_Pr(X): Pr = np.exp(X @ W + b) return Pr/Pr.sum(axis=1, keepdims=True) def compute_accuracy(Pr, y): return (Pr.argmax(axis=1)==y).mean()
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
ไธ‹้ขๆ˜ฏๆ›ดๆ–ฐ้Žๅพ—่จ“็ทด้Ž็จ‹๏ผŒ ็•ถ i%100000 ๆ™‚๏ผŒ้ †ไพฟ่จˆ็ฎ—ไธ€ไธ‹ test accuracy ๅ’Œ valid accuracyใ€‚
%%timeit -r 1 -n 1 def compute_Pr(X): Pr = np.exp(X @ W + b) return Pr/Pr.sum(axis=1, keepdims=True) def compute_accuracy(Pr, y): return (Pr.argmax(axis=1)==y).mean() W = np.random.uniform(low=-1, high=1, size=(28*28,10)) b = np.random.uniform(low=-1, high=1, size=10) score = 0 N=20000 batch_size = 128 lea...
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
ๆœ€ๅพŒๅพ—ๅˆฐ็š„ๆบ–็ขบ็އๆ˜ฏ 92%-93% ไธ็ฎ—ๅฎŒ็พŽ๏ผŒไธ้Ž็•ข็ซŸ้€™ๅชๆœ‰ไธ€ๅ€‹็Ÿฉ้™ฃ่€Œๅทฒใ€‚ ๅ…‰็œ‹ๆ•ธๆ“šๆฒ’ๆ„Ÿ่ฆบ๏ผŒๆˆ‘ๅ€‘ไพ†็œ‹็œ‹ๅ‰ๅ็ญ†ๆธฌ่ฉฆ่ณ‡ๆ–™่ท‘่ตทไพ†็š„ๆƒ…ๅฝข ๅฏไปฅ็œ‹ๅˆฐๅ‰ๅ็ญ†ๅชๆœ‰้Œฏไธ€ๅ€‹
Pr = compute_Pr(test_X[:10]) pred_y =Pr.argmax(axis=1) for i in range(10): print(pred_y[i], test_y[i]) showX(test_X[i])
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
็œ‹็œ‹ๅ‰ไธ€็™พ็ญ†่ณ‡ๆ–™ไธญ๏ผŒๆ˜ฏๅ“ชไบ›ๆƒ…ๆณ็ฎ—้Œฏ
Pr = compute_Pr(test_X[:100]) pred_y = Pr.argmax(axis=1) for i in range(100): if pred_y[i] != test_y[i]: print(pred_y[i], test_y[i]) showX(test_X[i])
Week05/From NumPy to Logistic Regression.ipynb
tjwei/HackNTU_Data_2017
mit
You can definitely begin to make out some of the structure that is occuring in the photovoltaic performance of this device. This image looks great, but there are still many areas of improvement. For example, I will need to extensively prove that this image is not purely a result of topographical cross-talk. If this ima...
fig, axs = plt.subplots(nrows=3) axs[0].imshow(real_sum_img ,'hot') axs[0].set_title('Total Signal Sum') axs[1].imshow(fft_sum_img, cmap='hot') axs[1].set_title('Sum of the FFT Power Spectrum') axs[2].imshow(amp_diff_img, cmap='hot') axs[2].set_title('Difference in Amplitude After Trigger') plt.tight_layout() plt.sho...
Examples/demo.ipynb
jarrison/trEFM-learn
mit
www.topuniversities.com
root_url_1 = 'https://www.topuniversities.com' # we use the link to the API from where the website fetches its data instead of BeautifulSoup # much much cleaner list_url_1 = root_url_1 + '/sites/default/files/qs-rankings-data/357051_indicators.txt' r = requests.get(list_url_1) top_universities = pd.DataFrame() top_uni...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Best universities in term of: We selected the top 10 universities in point (a) and (b). For point (c) and (d), the top 200 universities were used in order to have more data. (a) ratio between faculty members and students
top = 10 top_universities_ratio = select_top_N(top_universities, 'overall_rank', top) top_universities_ratio_sf = top_universities_ratio[['name', 'students_total', 'faculty_total']] top_universities_ratio_sf = top_universities_ratio_sf.set_index(['name']) top_universities_ratio_sf.index.name = None fig, axes = plt.su...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: We see that it is rather difficult to compare the ratios of the different universities. This is due to the different sizes of the population. In order to draw more precise information about it, we need to normalize the data with repect to each university.
# normalize the data to be able to make a good comparison top_universities_ratio_normed = top_universities_ratio_sf.div(top_universities_ratio_sf.sum(1), axis=0).sort_values(by='faculty_total', ascending=False) top_universities_ratio_normed.index.name = None fig, axes = plt.subplots(1, 1, figsize=(10,5), sharey=True) ...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: You noticed that the y-axis ranges from 0.7 to 1. We limited the visualization to this interval because the complete interval does not add meaningful insight about the data. Analyzing the results, we see that the Caltech university is the university in the top 10 offering more faculty members to its students....
top_universities_ratio_s = top_universities_ratio[['name', 'students_international', 'students_national']] top_universities_ratio_s = top_universities_ratio_s.set_index(['name']) top_universities_ratio_s_normed = top_universities_ratio_s.div(top_universities_ratio_s.sum(1), axis=0).sort_values(by='students_internationa...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: The most international university, by its students, among the top 10 universities is the Imperial College London. Notice that ETHZ is in the third position. (c) same comparisons by country
ratio_country_sf = top_universities.groupby(['location'])['students_total', 'faculty_total'].sum() ratio_country_sf_normed = ratio_country_sf.div(ratio_country_sf.sum(1), axis=0).sort_values(by='faculty_total', ascending=False) ratio_country_sf_normed.index.name = None fig, axes = plt.subplots(1, 1, figsize=(15, 5)) r...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: Aggregating the data by country, we see that Russia is the country offering more faculty members for its student, followed by Danemark and Saudi Arabia. The most international university in terms of students is Australia, followed by United Kingdom and Hong Kong. Switzerland is in the fifth position and India...
ratio_region_s = top_universities.groupby(['region'])['students_total', 'faculty_total'].sum() ratio_region_s_normed = ratio_region_s.div(ratio_region_s.sum(1), axis=0).sort_values(by='faculty_total', ascending=False) ratio_region_s_normed.index.name = None fig, axes = plt.subplots(1, 1, figsize=(10,5), sharey=True) r...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: Asia is the region offering more faculty members to its students. It is followed by North America and Europe. The most international university in terms of students is Oceania. Europe is second. Analysis of the two methods We get consistent results comparing the results obtained by region or by country about ...
# we repeat the same procedure as for www.topuniversities.com root_url_2 = 'https://www.timeshighereducation.com' list_url_2 = root_url_2 + '/sites/default/files/the_data_rankings/world_university_rankings_2018_limit0_369a9045a203e176392b9fb8f8c1cb2a.json' r = requests.get(list_url_2) times_higher_education = pd.DataF...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Best universities in term of: We selected the top 10 universities in point (a) and (b). For point (c) and (d), the top 200 universities were used in order to have more data. (a) ratio between faculty members and students
top = 10 times_higher_education_ratio = select_top_N(times_higher_education, 'overall_rank', top) times_higher_education_ratio_sf = times_higher_education_ratio[['name', 'students_total', 'faculty_total']] times_higher_education_ratio_sf = times_higher_education_ratio_sf.set_index(['name']) times_higher_education_rati...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: The university of Chicago is the faculty with the more faculty members by students. It is closely followed by the California Institute of Technology. (b) ratio of international students
times_higher_education_ratio_s = times_higher_education_ratio[['name', 'students_international', 'students_national']] times_higher_education_ratio_s = times_higher_education_ratio_s.set_index(['name']) times_higher_education_ratio_s_normed = times_higher_education_ratio_s.div(times_higher_education_ratio_s.sum(1), axi...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: The Imperial College Longon university has a strong lead in the internationalization of its student. Oxford and ETHZ are following bunched together. (c) same comparisons by country
ratio_country_sf = times_higher_education.groupby(['location'])['students_total', 'faculty_total'].sum() ratio_country_sf_normed = ratio_country_sf.div(ratio_country_sf.sum(1), axis=0).sort_values(by='faculty_total', ascending=False) ratio_country_sf_normed.index.name = None fig, axes = plt.subplots(1, 1, figsize=(15,...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: Denmark is in the first position. We find the Russian Federation in the second place. This is the same result obtained with the top universities website the other way around. This shows that either the universities of each country have different ranking in each website or each website has different informatio...
ratio_country_s = times_higher_education.groupby(['location'])['students_international', 'students_national'].sum() ratio_country_s_normed = ratio_country_s.div(ratio_country_s.sum(1), axis=0).sort_values(by='students_international', ascending=False) ratio_country_s_normed.index.name = None fig, axes = plt.subplots(1,...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: Luxembourg has more international than national students which allows it to be in first position without difficulty. Switzerland is in the sixth position (versus fifth for top university website). (d) same comparisons by region
# Some countries have their field 'region' filled with 'N/A': this is due to the technique we used to write the # correct region for each university. In the sample we are considering, let's see how many universities are concerned: times_higher_education[times_higher_education['region'] == 'N/A'] # As there is only two...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Comments: In the first plot, we see that Africa is the region where there is more faculty members by students. The two following regions are very close to each other. In the second plot, Oceania is the more internationalized school in terms of its students and Europe is second. We had similar results by the other websi...
# Detects same universities with different names in the two dataframes before merging # using Jaccard similarity and same location rule (seems to keep matching entry) def t(x): # Compute Jaccard score (intersection over union) def jaccard(a, b): u = set(a.split(' ')) v = set(b.split(' ')) ...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Insights Here we first proceed by creating the correlation matrix (since it's a symetric matrix we only kept the lower triangle). We then plot it using a heatmap to see correlation between columns of the dataframe. We also made another heatmap with only correlation whose absolute value is greater than 0.5. Finally we a...
merged_num = merged.select_dtypes(include=[np.number]) merged_num.dropna(how='all', axis=1) merged_num.dropna(how='any', axis=0) def avg_feature(x): cols = set([x for x in x.index if 'overall' not in x]) cols_common = set([x[0:-2] for x in cols]) for cc in cols_common: cc_x = '{}_x'.format(cc) ...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Best university First we have to transform ranking in some score. Here we assume a linear relation for the score given the ranking, so we gave a score of 1 for the best ranking and 0 for the worst ranking with linear mapping between these two. We did it for each of the ranking (the two websites). Also we don't really k...
r = merged[['name', 'overall_rank_x', 'overall_rank_y']] r.head() def lin(df): best_rank = df.min() worst_rank = df.max() a = 1 / (best_rank - worst_rank) b = 1 - a*best_rank return df.apply(lambda x: a*x + b) r['stud_staff_ratio'] = merged[['faculty_international_x', 'faculty_international_y']]...
HW02/Homework 2.ipynb
Timonzimm/CS-401
mit
Customizing the atoms involved in the contact ContactFrequency takes the parameters query and haystack, which are lists of atom indices. It will then search for all contacts between atoms in query and atoms in haystack. This allows you to, for example, focus on the contacts between two distinct parts of a protein. By o...
# the default selection is default_selection = topology.select("not water and symbol != 'H'") print(len(default_selection))
examples/changing_defaults.ipynb
dwhswenson/contact_map
lgpl-2.1
Note that the general assumption is that the query is no larger than the haystack. If this isn't obeyed, you'll still get correct answers, but some algorithms may be less efficient, and visualizations have also been designed with this in mind. Changing the query Now let's focus in on contacts involving specific regions...
switch1 = topology.select("resSeq 32 to 38 and symbol != 'H'") %%time sw1_contacts = ContactFrequency(trajectory=traj, query=switch1) sw1_contacts.residue_contacts.plot();
examples/changing_defaults.ipynb
dwhswenson/contact_map
lgpl-2.1
This shows all contacts of switch 1 with anything else in the system. Here, we automatically zoom in to have query on the x axis and the rest on the y axis. The boxes are long rectangles instead of squares as in the default selection. The box represents the residue number (in the resid numbering system) that is to its ...
fig, ax = sw1_contacts.residue_contacts.plot() ax.set_xlim(0, sw1_contacts.residue_contacts.max_size) ax.set_ylim(0, sw1_contacts.residue_contacts.max_size);
examples/changing_defaults.ipynb
dwhswenson/contact_map
lgpl-2.1
Changing query and haystack What if we wanted to zoom in even more, and only look at the contacts between the switch 1 and cations in the system? We make one of the the query and the other the haystack. Since switch1 contains more atoms than cations, we'll use switch1 as the haystack.
cations = topology.select("resname NA or resname MG") %%time cations_switch1 = ContactFrequency(trajectory=traj, query=cations, haystack=switch1) cations_switch1.residue_contacts.plot();
examples/changing_defaults.ipynb
dwhswenson/contact_map
lgpl-2.1
Now we'll plot again, but we'll change the x and y axes so that we now can see switch 1 along x and cations (the query) along y:
fig, ax = cations_switch1.residue_contacts.plot() ax.set_xlim(*cations_switch1.haystack_residue_range) ax.set_ylim(*cations_switch1.query_residue_range);
examples/changing_defaults.ipynb
dwhswenson/contact_map
lgpl-2.1
Here you can see that the most significant contacts here are between residue 36 and the ion listed as residue 167. Let's see just how frequently that contact is made:
print(cations_switch1.residue_contacts.counter[frozenset([36, 167])])
examples/changing_defaults.ipynb
dwhswenson/contact_map
lgpl-2.1
So about half the time. Now, which residue/ion are these? Remember, these indices start at 0, even though the tradition in science (and the PDB) is to count from 1. Furthermore, the PDB residue numbers for the ions skip the section of the protein that has been removed. But we can easily obtain the relevant residues:
print(topology.residue(36)) print(topology.residue(167))
examples/changing_defaults.ipynb
dwhswenson/contact_map
lgpl-2.1
So this is a contact between the Glu37 and the magnesium ion (which is listed as residue 202 in the PDB). Changing the cutoff Depending on the atoms you use to select contacts, you might choose different cutoff distances. The default cutoff of 0.45 nm is reasonable for heavy atom contacts. However, if you use all atoms...
%%time large_cutoff = ContactFrequency(trajectory=traj[0], cutoff=1.5) %%time large_cutoff.residue_contacts.plot();
examples/changing_defaults.ipynb
dwhswenson/contact_map
lgpl-2.1
The larger cutoff leads to a more dense contact matrix. The performance of plotting depends on how dense the contact matrix is -- for tricks to plot dense matrices more quickly, see the documentation on customizing plotting. Changing the number of ignored neighbors By default, Contact Map Explorer ignore atoms from 2 r...
%%time ignore_none = ContactFrequency(trajectory=traj, n_neighbors_ignored=0) ignore_none.residue_contacts.plot();
examples/changing_defaults.ipynb
dwhswenson/contact_map
lgpl-2.1
Rossman Data Preparation Individual Data Source In addition to the data provided by the competition, we will be using external datasets put together by participants in the Kaggle competition. We can download all of them here. Then we should untar them in the directory to which data_dir is pointing to.
data_dir = 'rossmann' print('available files: ', os.listdir(data_dir)) file_names = ['train', 'store', 'store_states', 'state_names', 'googletrend', 'weather', 'test'] path_names = {file_name: os.path.join(data_dir, file_name + '.csv') for file_name in file_names} df_train = pd.read_csv(pa...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
We turn state Holidays to booleans, to make them more convenient for modeling.
df_train['StateHoliday'] = df_train['StateHoliday'] != '0' df_test['StateHoliday'] = df_test['StateHoliday'] != '0'
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
For the weather and state names data, we perform a join on a state name field and create a single dataframe.
df_weather = pd.read_csv(path_names['weather']) print('weather data dimension: ', df_weather.shape) df_weather.head() df_state_names = pd.read_csv(path_names['state_names']) print('state names data dimension: ', df_state_names.shape) df_state_names.head() df_weather = df_weather.rename(columns={'file': 'StateName'}) ...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
For the google trend data. We're going to extract the state and date information from the raw dataset, also replace all instances of state name 'NI' to match the usage in the rest of the data: 'HB,NI'.
df_googletrend = pd.read_csv(path_names['googletrend']) print('google trend data dimension: ', df_googletrend.shape) df_googletrend.head() df_googletrend['Date'] = df_googletrend['week'].str.split(' - ', expand=True)[0] df_googletrend['State'] = df_googletrend['file'].str.split('_', expand=True)[2] df_googletrend.loc[...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
The following code chunks extracts particular date fields from a complete datetime for the purpose of constructing categoricals. We should always consider this feature extraction step when working with date-time. Without expanding our date-time into these additional fields, we can't capture any trend/cyclical behavior ...
DEFAULT_DT_ATTRIBUTES = [ 'Year', 'Month', 'Week', 'Day', 'Dayofweek', 'Dayofyear', 'Is_month_end', 'Is_month_start', 'Is_quarter_end', 'Is_quarter_start', 'Is_year_end', 'Is_year_start' ] def add_datepart(df, colname, drop_original_col=False, dt_attributes=DEFAULT_DT_ATTRIBUTES, ...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
The Google trends data has a special category for the whole of the Germany - we'll pull that out so we can use it explicitly.
df_trend_de = df_googletrend.loc[df_googletrend['file'] == 'Rossmann_DE', ['Year', 'Week', 'trend']] df_trend_de.head()
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
Merging Various Data Source Now we can outer join all of our data into a single dataframe. Recall that in outer joins everytime a value in the joining field on the left table does not have a corresponding value on the right table, the corresponding row in the new table has Null values for all right table fields. One wa...
df_store = pd.read_csv(path_names['store']) print('store data dimension: ', df_store.shape) df_store.head() df_store_states = pd.read_csv(path_names['store_states']) print('store states data dimension: ', df_store_states.shape) df_store_states.head() df_store = df_store.merge(df_store_states, on='Store', how='left') ...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
Final Data After merging all the various data source to create our master dataframe, we'll still perform some additional feature engineering steps including: Some of the rows contain missing values for some columns, we'll impute them here. What values to impute is pretty subjective then we don't really know the root c...
for df in (df_joined_train, df_joined_test): df['CompetitionOpenSinceYear'] = (df['CompetitionOpenSinceYear'] .fillna(1900) .astype(np.int32)) df['CompetitionOpenSinceMonth'] = (df['CompetitionOpenSinceMonth'] ...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
For the CompetitionMonthsOpen field, we limit the maximum to 2 years to limit the number of unique categories.
for df in (df_joined_train, df_joined_test): df['CompetitionMonthsOpen'] = df['CompetitionDaysOpen'] // 30 df.loc[df['CompetitionMonthsOpen'] > 24, 'CompetitionMonthsOpen'] = 24 df.loc[df['CompetitionMonthsOpen'] < -24, 'CompetitionMonthsOpen'] = -24 df_joined_train['CompetitionMonthsOpen'].unique()
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
Repeat the same process for Promo
from isoweek import Week for df in (df_joined_train, df_joined_test): df['Promo2Since'] = pd.to_datetime(df.apply(lambda x: Week( x.Promo2SinceYear, x.Promo2SinceWeek).monday(), axis=1)) df['Promo2Days'] = df['Date'].subtract(df['Promo2Since']).dt.days for df in (df_joined_train, df_joined_test): ...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
Durations It is common when working with time series data to extract features that captures relationships across rows instead of between columns. e.g. time until next event, time since last event. Here, we would like to compute features such as days until next promotion or days before next promotion. And the same proce...
columns = ['Date', 'Store', 'Promo', 'StateHoliday', 'SchoolHoliday'] df = df_joined_train[columns].append(df_joined_test[columns]) df['DateUnixSeconds'] = df['Date'].astype(np.int64) // 10 ** 9 df.head() @numba.njit def compute_duration(store_arr, date_unix_seconds_arr, field_arr): """ For each store, track t...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
If we look at the values in the AfterStateHoliday column, we can see that the first row of the StateHoliday column is True, therefore, the corresponding AfterStateHoliday is therefore 0 indicating it's a state holiday that day, after encountering a state holiday, the AfterStateHoliday column will start incrementing unt...
df = df.sort_values(['Store', 'Date'], ascending=[True, False]) start = time.time() for col in ('SchoolHoliday', 'StateHoliday', 'Promo'): result = compute_duration(df['Store'].values, df['DateUnixSeconds'].values, df[col].values) df['Before' + col] ...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
After creating these new features, we join it back to the original dataframe.
df = df.drop(['Promo', 'StateHoliday', 'SchoolHoliday', 'DateUnixSeconds'], axis=1) df_joined_train = df_joined_train.merge(df, on=['Date', 'Store'], how='inner') df_joined_test = df_joined_test.merge(df, on=['Date', 'Store'], how='inner') print('dimension: ', df_joined_train.shape) df_joined_train.head() df_joined_t...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
We save the cleaned data so we won't have to repeat this data preparation step again.
output_dir = 'cleaned_data' if not os.path.isdir(output_dir): os.makedirs(output_dir, exist_ok=True) engine = 'pyarrow' output_path_train = os.path.join(output_dir, 'train_clean.parquet') output_path_test = os.path.join(output_dir, 'test_clean.parquet') df_joined_train.to_parquet(output_path_train, engine=engine) ...
projects/kaggle_rossman_store_sales/rossman_data_prep.ipynb
ethen8181/machine-learning
mit
Use the lane pixals identified to fit a ploygon and draw it back on the original image
def write_stats(img): """ Write lane stats on image """ font = cv2.FONT_HERSHEY_SIMPLEX size = 1 weight = 2 color = (255,70,0) cv2.putText(img,'Left Curve : '+ '{0:.2f}'.format(left_line.radius_of_curvature)+' m',(10,30), font, size, color, weight) cv2.putText(img,'Right Curve : ...
car-lane-detection.ipynb
neerajdixit/car-lane-detection
apache-2.0
See the distribution of predictions over time
fs.display_model_drift('deployed_models','twimlcon_regression', 5)
twimlcon-workshop-materials/5 - Model Governance.ipynb
splicemachine/splice-community-sample-code
apache-2.0
See the distribution of features at the time a model was trained, and the distribution seen by the deployed model
fs.display_model_feature_drift('deployed_models','twimlcon_regression')
twimlcon-workshop-materials/5 - Model Governance.ipynb
splicemachine/splice-community-sample-code
apache-2.0
Investigate individual predictions
%%sql select * from deployed_models.twimlcon_regression where customerid = 12526 and (eval_time >= '2020-11-01' and eval_time <= '2020-11-07') from splicemachine.notebook import get_mlflow_ui get_mlflow_ui() #tags."Run ID" = {runid} spark.stop()
twimlcon-workshop-materials/5 - Model Governance.ipynb
splicemachine/splice-community-sample-code
apache-2.0
If this tutorial we are going to use estimate the connectivity and subsequently filter them. Load data
import sys import tqdm import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import numpy as np np.set_printoptions(threshold=sys.maxsize) fmri = np.load('data/fmri_autism_ts.npy', allow_pickle=True) labels = np.load('data/fmri_autism_labels.npy') num_subjects = len(fmri) num_samples, num_r...
tutorials/fMRI - 1 - Graph Analysis (Group).ipynb
makism/dyfunconn
bsd-3-clause
Compute the connectivity
conn_mtx = np.zeros((num_subjects, num_rois, num_rois)) for subj in tqdm.tqdm(range(num_subjects)): fmri_ts = fmri[subj] conn_mtx[subj, ...] = np.corrcoef(fmri_ts.T) np.save('data/fmri_autism_conn_mtx.npy', conn_mtx)
tutorials/fMRI - 1 - Graph Analysis (Group).ipynb
makism/dyfunconn
bsd-3-clause
Filter connectivity matrices
thres_conn_mtx = np.zeros_like(conn_mtx) from dyconnmap.graphs import threshold_eco for subj in tqdm.tqdm(range(num_subjects)): subj_conn_mtx = np.abs(conn_mtx[subj]) _, CIJtree, _ = threshold_eco(subj_conn_mtx) thres_conn_mtx[subj] = CIJtree np.save('data/fmri_autism_thres_conn_mtx.npy', thres_con...
tutorials/fMRI - 1 - Graph Analysis (Group).ipynb
makism/dyfunconn
bsd-3-clause
Cada celda la puedes usar para escribir el cรณdigo que tu quieras y si de repente se te olvida alguna funciรณn o tienes duda de si el nombre es correcto IPython es muy amable en ese sentido. Para saber acerca de una funciรณn, es decir cuรกl es su salida o los parรกmetros que necesita puedes usar el signo de interrogaciรณn a...
sum? max? round? mean?
UsoJupyter/CuadernoJupyter.ipynb
PyladiesMx/Empezando-con-Python
mit
Como te pudiste dar cuenta, cuando no encuentra la funciรณn te da un error... En IPython, y por lo tanto en Jupyter, hay una utilidad de completar con Tab. Esto quiere decir que si tu empiezas a escribir el nombre de una variable, funciรณn o atributo, no tienes que escribirlo todo, puedes empezar con unas cuantas letras ...
variable = 50 saludo = 'Hola'
UsoJupyter/CuadernoJupyter.ipynb
PyladiesMx/Empezando-con-Python
mit
Ejercicio 3 Empieza a escribir las primeras tres letras de cada elemento de la celda anterior y presiona tab para ver si se puede autocompletar
vars?
UsoJupyter/CuadernoJupyter.ipynb
PyladiesMx/Empezando-con-Python
mit
Tambiรฉn hay funciones mรกgicas que nos permitirรกn hacer diversas tareas como mostrar las grรกficas que se produzcan en el cรณdigo dentro de una celda, medir el tiempo de ejecuciรณn del cรณdigo y cambiar del directorio de trabajo, entre otras. para ver quรฉ funciones mรกgicas hay en Jupyter sรณlo tienes que escribir python %mag...
%magic
UsoJupyter/CuadernoJupyter.ipynb
PyladiesMx/Empezando-con-Python
mit
Grรกficas Ahora veremos unos ejemplos de grรกficas y cรณmo hacerlas interactivas. Estos ejemplos fueron tomados de la libreta para demostraciรณn de nature
# Importa matplotlib (paquete para graficar) y numpy (paquete para arreglos). # Fรญjate en el la funciรณn mรกgica para que aparezca nuestra grรกfica en la celda. %matplotlib inline import matplotlib.pyplot as plt import numpy as np # Crea un arreglo de 30 valores para x que va de 0 a 5. x = np.linspace(0, 5, 30) y = np....
UsoJupyter/CuadernoJupyter.ipynb
PyladiesMx/Empezando-con-Python
mit
Google Cloud Storage Let's see if we can create a bucket with boto (using credentials, project ID, etc. specified in boto config file)...
import datetime now = datetime.datetime.now() BUCKET_NAME = 'test_' + GPRED_PROJECT_ID + now.strftime("%Y-%m-%d") # lower case letters required, no upper case allowed import boto import gcs_oauth2_boto_plugin project_id = %env GPRED_PROJECT_ID header_values = {"x-goog-project-id": project_id} boto.storage_uri(BUCKET_N...
credentials/Test.ipynb
louisdorard/bml-base
mit
Listing existing buckets...
uri = boto.storage_uri('', 'gs') # If the default project is defined, call get_all_buckets() without arguments. for bucket in uri.get_all_buckets(headers=header_values): print bucket.name
credentials/Test.ipynb
louisdorard/bml-base
mit
Upload a file to the new bucket
import os os.system("echo 'hello!' > newfile") filename = 'newfile' boto.storage_uri(BUCKET_NAME + '/' + filename, 'gs').new_key().set_contents_from_file(open(filename))
credentials/Test.ipynb
louisdorard/bml-base
mit