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
LSTM with Word2Vec Embedding
2v = Word2Vec.load("w2v_300features_10minwordcounts_10context") embedding_matrix = w2v.wv.syn0 print("Shape of embedding matrix : ", embedding_matrix.shape) top_words = embedding_matrix.shape[0] #4016 maxlen = 300 batch_size = 62 nb_classes = 4 nb_epoch = 7 # Vectorize X_train and X_test to 2D tensor t...
_____no_output_____
MIT
IMDB Reviews NLP.ipynb
gsingh1629/SentAnalysis
Implementing TF-IDF------------------------------------Here we implement TF-IDF, (Text Frequency - Inverse Document Frequency) for the spam-ham text data.We will use a hybrid approach of encoding the texts with sci-kit learn's TFIDF vectorizer. Then we will use the regular TensorFlow logistic algorithm outline.Creati...
import tensorflow as tf import matplotlib.pyplot as plt import csv import numpy as np import os import string import requests import io import nltk from zipfile import ZipFile from sklearn.feature_extraction.text import TfidfVectorizer from tensorflow.python.framework import ops ops.reset_default_graph()
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Start a computational graph session.
sess = tf.Session()
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
We set two parameters, `batch_size` and `max_features`. `batch_size` is the size of the batch we will train our logistic model on, and `max_features` is the maximum number of tf-idf textual words we will use in our logistic regression.
batch_size = 200 max_features = 1000
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Check if data was downloaded, otherwise download it and save for future use
save_file_name = 'temp_spam_data.csv' if os.path.isfile(save_file_name): text_data = [] with open(save_file_name, 'r') as temp_output_file: reader = csv.reader(temp_output_file) for row in reader: text_data.append(row) else: zip_url = 'http://archive.ics.uci.edu/ml/machine-learni...
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
We now clean our texts. This will decrease our vocabulary size by converting everything to lower case, removing punctuation and getting rid of numbers.
texts = [x[1] for x in text_data] target = [x[0] for x in text_data] # Relabel 'spam' as 1, 'ham' as 0 target = [1. if x=='spam' else 0. for x in target] # Normalize text # Lower case texts = [x.lower() for x in texts] # Remove punctuation texts = [''.join(c for c in x if c not in string.punctuation) for x in texts]...
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Define tokenizer function and create the TF-IDF vectors with SciKit-Learn.
import nltk nltk.download('punkt') def tokenizer(text): words = nltk.word_tokenize(text) return words # Create TF-IDF of texts tfidf = TfidfVectorizer(tokenizer=tokenizer, stop_words='english', max_features=max_features) sparse_tfidf_texts = tfidf.fit_transform(texts)
/srv/venv/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:1089: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. if hasattr(X, 'dtype') and np.issubdtype(X.dtype, np.float):...
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Split up data set into train/test.
train_indices = np.random.choice(sparse_tfidf_texts.shape[0], round(0.8*sparse_tfidf_texts.shape[0]), replace=False) test_indices = np.array(list(set(range(sparse_tfidf_texts.shape[0])) - set(train_indices))) texts_train = sparse_tfidf_texts[train_indices] texts_test = sparse_tfidf_texts[test_indices] target_train = np...
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Now we create the variables and placeholders necessary for logistic regression. After which, we declare our logistic regression operation. Remember that the sigmoid part of the logistic regression will be in the loss function.
# Create variables for logistic regression A = tf.Variable(tf.random_normal(shape=[max_features,1])) b = tf.Variable(tf.random_normal(shape=[1,1])) # Initialize placeholders x_data = tf.placeholder(shape=[None, max_features], dtype=tf.float32) y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32) # Declare log...
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Next, we declare the loss function (which has the sigmoid in it), and the prediction function. The prediction function will have to have a sigmoid inside of it because it is not in the model output.
# Declare loss function (Cross Entropy loss) loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=model_output, labels=y_target)) # Prediction prediction = tf.round(tf.sigmoid(model_output)) predictions_correct = tf.cast(tf.equal(prediction, y_target), tf.float32) accuracy = tf.reduce_mean(predictions_...
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Now we create the optimization function and initialize the model variables.
# Declare optimizer my_opt = tf.train.GradientDescentOptimizer(0.0025) train_step = my_opt.minimize(loss) # Intitialize Variables init = tf.global_variables_initializer() sess.run(init)
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Finally, we perform our logisitic regression on the 1000 TF-IDF features.
train_loss = [] test_loss = [] train_acc = [] test_acc = [] i_data = [] for i in range(10000): rand_index = np.random.choice(texts_train.shape[0], size=batch_size) rand_x = texts_train[rand_index].todense() rand_y = np.transpose([target_train[rand_index]]) sess.run(train_step, feed_dict={x_data: rand_x,...
Generation # 500. Train Loss (Test Loss): 0.92 (0.93). Train Acc (Test Acc): 0.39 (0.40) Generation # 1000. Train Loss (Test Loss): 0.71 (0.74). Train Acc (Test Acc): 0.56 (0.56) Generation # 1500. Train Loss (Test Loss): 0.58 (0.62). Train Acc (Test Acc): 0.66 (0.66) Generation # 2000. Train Loss (Test Loss): 0.59 (0....
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Here is matplotlib code to plot the loss and accuracies.
# Plot loss over time plt.plot(i_data, train_loss, 'k-', label='Train Loss') plt.plot(i_data, test_loss, 'r--', label='Test Loss', linewidth=4) plt.title('Cross Entropy Loss per Generation') plt.xlabel('Generation') plt.ylabel('Cross Entropy Loss') plt.legend(loc='upper right') plt.show() # Plot train and test accurac...
_____no_output_____
MIT
tests/tf/03_implementing_tf_idf.ipynb
gopala-kr/ds-notebooks
Table of Contents 1  Texte d'oral de modélisation - Agrégation Option Informatique1.1  Préparation à l'agrégation - ENS de Rennes, 2016-171.2  À propos de ce document1.3  Implémentation1.3.1  Une bonne structure de donnée pour des intervalles et des graphes d'intervale...
Sys.command "ocaml -version";;
The OCaml toplevel, version 4.04.2
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
---- ImplémentationLa question d'implémentation était la question 2) en page 7.> « Proposer une structure de donnée adaptée pour représenter un graphe d'intervalles dont une représentation sous forme de famille d’intervalles est connue.> Implémenter de manière efficace l’algorithme de coloriage de graphes d'intervalles...
type intervalle = (int * int);; type intervalles = intervalle list;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
- Pour des **graphes d'intervalles**, on utilise une simple représentation sous forme de liste d'adjacence, plus facile à mettre en place en OCaml qu'une représentation sous forme de matrice. Ici, tous nos graphes ont pour sommets $0 \dots n - 1$.
type sommet = int;; type voisins = sommet list;; type graphe_intervalle = voisins list;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
> *Note:* j'ai préféré garder une structure très simple, pour les intervalles, les graphes d'intervalles et les coloriages, mais on perd un peu en lisibilité dans la fonction coloriage.> > Implicitement, dès qu'une liste d'intervalles est fixée, de taille $n$, ils sont numérotés de $0$ à $n-1$. Le graphe `g` aura pour ...
let graphe_depuis_intervalles (intvls : intervalles) : graphe_intervalle = let n = List.length intvls in (* Nomber de sommet *) let array_intvls = Array.of_list intvls in (* Tableau des intervalles *) let index_intvls = Array.to_list ( Array.init n (fun i -> ( arra...
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Algorithme de coloriage de graphe d'intervalles> Étant donné un graphe $G = (V, E)$, on cherche un entier $n$ minimal et une fonction $c : V \to \{1, \cdots, n\}$ telle que si $(v_1 , v_2) \in E$, alors $c(v_1) \neq c(v_2)$.On suit les indications de l'énoncé pour implémenter facilement cet algorithme.> Une *heuristiq...
type couleur = int;; type coloriage = (intervalle * couleur) list;; let coloriage_depuis_couleurs (intvl : intervalles) (c : couleur array) : coloriage = Array.to_list (Array.init (Array.length c) (fun i -> (List.nth intvl i), c.(i)));; let quelle_couleur (intvl : intervalle) (colors : coloriage) = List.asso...
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Ensuite, l'ordre partiel $\prec_i$ sur les intervalles est défini comme ça :$$ I = (a,b) \prec_i J=(x, y) \Longleftrightarrow a < x $$
let ordre_partiel ((a, _) : intervalle) ((x, _) : intervalle) = a < x ;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
On a ensuite besoin d'une fonction qui va calculer l'inf de $\mathbb{N} \setminus \{x : x \in \mathrm{valeurs} \}$:
let inf_N_minus valeurs = let res = ref 0 in (* Très important d'utiliser une référence ! *) while List.mem !res valeurs do incr res; done; !res ;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
On vérifie rapidement sur deux exemples :
inf_N_minus [0; 1; 3];; (* 2 *) inf_N_minus [0; 1; 2; 3; 4; 5; 6; 10];; (* 7 *)
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Enfin, on a besoin d'une fonction pour trouver l'intervalle $I \in V$, minimal pour $\prec_i$, tel que $c(I) = +\infty$.
let trouve_min_interval intvl (c : coloriage) (inf : couleur) = let colorie inter = quelle_couleur inter c in (* D'abord on extraie {I : c(I) = +oo} *) let intvl2 = List.filter (fun i -> (colorie i) = inf) intvl in (* Puis on parcourt la liste et on garde le plus petit pour l'ordre *) let i0 = ref 0...
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Et donc tout cela permet de finir l'algorithme, tel que décrit dans le texte :
let coloriage_intervalles (intvl : intervalles) : coloriage = let n = List.length intvl in (* Nombre d'intervalles *) let array_intvls = Array.of_list intvl in (* Tableau des intervalles *) let index_intvls = Array.to_list ( Array.init n (fun i -> ( array_intvls.(i), i) ...
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Une fois qu'on a un coloriage, à valeurs dans $0,\dots,k$ on récupère le nombre de couleurs comme $1 + \max c$, i.e., $k+1$.
let max_valeurs = List.fold_left max 0;; let nombre_chromatique (colorg : coloriage) : int = 1 + max_valeurs (List.map snd colorg) ;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Algorithme pour calculer le *stable maximum* d'un graphe d'intervallesOn répond ici à la question 7.> « Proposer un algorithme efficace pour construire un stable maximum (i.e., un ensemble de sommets indépendants) d'un graphe d’intervalles dont on connaı̂t une représentation sous forme d'intervalles.> On pourra cherch...
(* On définit des entiers, c'est plus simple *) let ann = 0 and betty = 1 and cynthia = 2 and diana = 3 and emily = 4 and felicia = 5 and georgia = 6 and helen = 7;; let graphe_densmore = [ [betty; cynthia; emily; felicia; georgia]; (* Ann *) [ann; cynthia; helen]; (* Betty *) [ann; betty; diana; emily; h...
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
![images/densmore.png](images/densmore.png)> Figure 1. Graphe d'intervalle pour le problème de l'assassinat du duc de Densmore. Avec les prénoms plutôt que des numéros, cela donne : ![images/densmore2.png](images/densmore2.png)> Figure 2. Graphe d'intervalle pour le problème de l'assassinat du duc de Densmore. Comment...
let vaccins : intervalles = [ (4, 12); (8, 15); (0, 20); (2, 3); (-3, 6); (-10, 10); (6, 20); (-5, 2); (-2, 8) ]
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Qu'on peut visualiser sous forme de graphe facilement :
let graphe_vaccins = graphe_depuis_intervalles vaccins;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
![images/vaccins.png](images/vaccins.png)> Figure 3. Graphe d'intervalle pour le problème des frigos et des vaccins. Avec des intervalles au lieu de numéro : ![images/vaccins2.png](images/vaccins2.png)> Figure 4. Graphe d'intervalle pour le problème des frigos et des vaccins. On peut récupérer une coloriage minimal pou...
coloriage_intervalles vaccins;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
La couleur la plus grande est `5`, donc le nombre chromatique de ce graphe est `6`.
nombre_chromatique (coloriage_intervalles vaccins);;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Par contre, la solution au problème des frigos et des vaccins réside dans le nombre de couverture de cliques, $k(G)$, pas dans le nombre chromatique $\chi(G)$.On peut le résoudre en répondant à la question 7, qui demandait de mettre au point un algorithme pour construire un *stable maximum* pour un graphe d'intervalle....
let csa : intervalles = [ (32, 36); (24, 30); (28, 33); (22, 26); (20, 25); (30, 33); (31, 34); (27, 31) ];; let graphe_csa = graphe_depuis_intervalles csa;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
![images/csa.png](images/csa.png)> Figure 5. Graphe d'intervalle pour le problème du CSA. Avec des intervalles au lieu de numéro : ![images/csa2.png](images/csa2.png)> Figure 6. Graphe d'intervalle pour le problème du CSA. On peut récupérer une coloriage minimal pour ce graphe :
coloriage_intervalles csa;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
La couleur la plus grande est `3`, donc le nombre chromatique de ce graphe est `4`.
nombre_chromatique (coloriage_intervalles csa);;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Par contre, la solution au problème CSA réside dans le nombre de couverture de cliques, $k(G)$, pas dans le nombre chromatique $\chi(G)$.On peut le résoudre en répondant à la question 7, qui demandait de mettre au point un algorithme pour construire un *stable maximum* pour un graphe d'intervalle. Le problème du wagon...
let restaurant = [ (1170, 1214); (1230, 1319); (1140, 1199); (1215, 1259); (1260, 1319); (1155, 1229); (1200, 1259) ];; let graphe_restaurant = graphe_depuis_intervalles restaurant;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
![images/restaurant.png](images/restaurant.png)> Figure 7. Graphe d'intervalle pour le problème du wagon restaurant. Avec des intervalles au lieu de numéro : ![images/restaurant2.png](images/restaurant2.png)> Figure 8. Graphe d'intervalle pour le problème du wagon restaurant.
coloriage_intervalles restaurant;;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
La couleur la plus grande est `2`, donc le nombre chromatique de ce graphe est `3`.
nombre_chromatique (coloriage_intervalles restaurant);;
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Solution via l'algorithme de coloriage de graphe d'intervallesPour ce problème là, la solution est effectivement donnée par le nombre chromatique.La couleur sera le numéro de table pour chaque passagers (ou couple de passagers), et donc le nombre minimal de table à installer dans le wagon restaurant est exactement le ...
(** Transforme un [graph] en une chaîne représentant un graphe décrit par le langage DOT, voir http://en.wikipedia.org/wiki/DOT_language pour plus de détails sur ce langage. @param graphname Donne le nom du graphe tel que précisé pour DOT @param directed Vrai si le graphe doit être dirigé (c'est le cas ici...
_____no_output_____
MIT
agreg/Crime_parfait.ipynb
doc22940/notebooks-2
Produit matriciel avec une matrice creuseLes dictionnaires sont une façon assez de représenter les matrices creuses en ne conservant que les coefficients non nuls. Comment écrire alors le produit matriciel ?
from jyquickhelper import add_notebook_menu add_notebook_menu()
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Matrice creuse et dictionnaireUne [matrice creuse](https://fr.wikipedia.org/wiki/Matrice_creuse) ou [sparse matrix](https://en.wikipedia.org/wiki/Sparse_matrix) est constituée majoritairement de 0. On utilise un dictionnaire avec les coefficients non nuls. La fonction suivante pour créer une matrice aléatoire.
import random def random_matrix(n, m, ratio=0.1): mat = {} nb = min(n * m, int(ratio * n * m + 0.5)) while len(mat) < nb: i = random.randint(0, n-1) j = random.randint(0, m-1) mat[i, j] = 1 return mat mat = random_matrix(3, 3, ratio=0.5) mat
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Calcul de la dimensionPour obtenir la dimension de la matrice, il faut parcourir toutes les clés du dictionnaire.
def dimension(mat): maxi, maxj = 0, 0 for k in mat: maxi = max(maxi, k[0]) maxj = max(maxj, k[1]) return maxi + 1, maxj + 1 dimension(mat)
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Cette fonction possède l'inconvénient de retourner une valeur fausse si la matrice ne possède aucun coefficient non nul sur la dernière ligne ou la dernière colonne. Cela peut être embarrassant, tout dépend de l'usage. Produit matriciel classiqueOn implémente le produit matriciel classique, à trois boucles.
def produit_classique(m1, m2): dim1 = dimension(m1) dim2 = dimension(m2) if dim1[1] != dim2[0]: raise Exception("Impossible de multiplier {0}, {1}".format( dim1, dim2)) res = {} for i in range(dim1[0]): for j in range(dim2[1]): s = 0 ...
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Sur la matrice aléatoire...
produit_classique(mat, mat)
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Produit matriciel plus élégantA-t-on vraiment besoin de s'enquérir des dimensions de la matrice pour faire le produit matriciel ? Ne peut-on pas tout simplement faire une boucle sur les coefficients non nul ?
def produit_elegant(m1, m2): res = {} for (i, k1), v1 in m1.items(): if v1 == 0: continue for (k2, j), v2 in m2.items(): if v2 == 0: continue if k1 == k2: if (i, j) in res: res[i, j] += v1 * v2 ...
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Mesure du tempsA priori, la seconde méthode est plus rapide puisque son coût est proportionnel au produit du nombre de coefficients non nuls dans les deux matrices. Vérifions.
bigmat = random_matrix(100, 100) %timeit produit_classique(bigmat, bigmat) %timeit produit_elegant(bigmat, bigmat)
157 ms ± 9.33 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
C'est beaucoup mieux. Mais peut-on encore faire mieux ? Dictionnaires de dictionnairesCa sonne un peu comme [mille millions de mille sabords](https://fr.wikipedia.org/wiki/Vocabulaire_du_capitaine_Haddock) mais le dictionnaire que nous avons créé a pour clé un couple de coordonnées et valeur des coefficients. La fonct...
def matrice_dicodico(mat): res = {} for (i, j), v in mat.items(): if i not in res: res[i] = {j: v} else: res[i][j] = v return res matrice_dicodico(simple)
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Peut-on adapter le calcul matriciel élégant ? Il reste à associer les indices de colonnes de la première avec les indices de lignes de la seconde. Cela pose problème en l'état quand les indices de colonnes sont inaccessibles sans connaître les indices de lignes d'abord à moins d'échanger l'ordre pour la seconde matrice...
def matrice_dicodico_lc(mat, ligne=True): res = {} if ligne: for (i, j), v in mat.items(): if i not in res: res[i] = {j: v} else: res[i][j] = v else: for (j, i), v in mat.items(): if i not in res: res[i] = {j...
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Maintenant qu'on a fait ça, on peut songer au produit matriciel.
def produit_elegant_rapide(m1, m2): res = {} for k, vs in m1.items(): if k in m2: for i, v1 in vs.items(): for j, v2 in m2[k].items(): if (i, j) in res: res[i, j] += v1 * v2 else : res[i, ...
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
On mesure le temps avec une grande matrice.
m1 = matrice_dicodico_lc(bigmat, ligne=False) m2 = matrice_dicodico_lc(bigmat) %timeit produit_elegant_rapide(m1, m2)
6.46 ms ± 348 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Beaucoup plus rapide, il n'y a plus besoin de tester les coefficients non nuls. La comparaison n'est pas très juste néanmoins car il faut transformer les deux matrices avant de faire le calcul. Et si on l'incluait ?
def produit_elegant_rapide_transformation(mat1, mat2): m1 = matrice_dicodico_lc(mat1, ligne=False) m2 = matrice_dicodico_lc(mat2) return produit_elegant_rapide(m1, m2) produit_elegant_rapide_transformation(simple, simple) %timeit produit_elegant_rapide_transformation(bigmat, bigmat)
7.17 ms ± 635 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
Finalement ça vaut le coup... mais est-ce le cas pour toutes les matrices.
%matplotlib inline import time mesures = [] for ratio in [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.99]: big = random_matrix(100, 100, ratio=ratio) t1 = time.perf_counter() produit_elegant_rapide_transformation(big, big) t2 = time.perf_counter() dt = (t2 - t1) obs = {"dicodico": dt, "...
_____no_output_____
MIT
_doc/notebooks/td1a/matrix_dictionary.ipynb
Jerome-maker/ensae_teaching_cs
__Callbacks API__A __callback__ is an object that can perform actions at various stages of training (e.g. at the start or end of an epoch, before or after a single batch, etc)._You can use callbacks to:_- Write TensorBoard logs after every batch of training to monitor your metrics.- Periodically save your model to di...
import tensorflow as tf # Defining the callback class class myCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs={}): if(logs.get('accuracy')>0.6): print("\nReached 60% accuracy so cancelling training!") self.model.stop_training = True mnist = tf.keras.datasets.fashion_mnist ...
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz 32768/29515 [=================================] - 0s 0us/step Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz 26427392/26421880 [=====================...
MIT
03_callbacks.ipynb
mohd-faizy/03_TensorFlow_In_Practice
Loan predictions Problem StatementWe want to automate the loan eligibility process based on customer details that are provided as online application forms are being filled. You can find the dataset [here](https://drive.google.com/file/d/1h_jl9xqqqHflI5PsuiQd_soNYxzFfjKw/view?usp=sharing). These details concern the cus...
import pandas as pd import numpy as np from matplotlib import pyplot as plt df = pd.read_csv('data.csv') df.head(10) df.shape
_____no_output_____
MIT
clf.ipynb
Ruslion/Predicting-loan-eligibility
2. Data ExplorationLet's do some basic data exploration here and come up with some inferences about the data. Go ahead and try to figure out some irregularities and address them in the next section. One of the key challenges in any data set are missing values. Lets start by checking which columns contain missing valu...
df.isnull().sum()
_____no_output_____
MIT
clf.ipynb
Ruslion/Predicting-loan-eligibility
Look at some basic statistics for numerical variables.
df.dtypes df.nunique()
_____no_output_____
MIT
clf.ipynb
Ruslion/Predicting-loan-eligibility
1. How many applicants have a `Credit_History`? (`Credit_History` has value 1 for those who have a credit history and 0 otherwise)2. Is the `ApplicantIncome` distribution in line with your expectation? Similarly, what about `CoapplicantIncome`?3. Tip: Can you see a possible skewness in the data by comparing the mean to...
from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.preprocessing import FunctionTransformer from sklearn.metrics import accuracy_score from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder f...
_____no_output_____
MIT
clf.ipynb
Ruslion/Predicting-loan-eligibility
Looking at the randomness (or otherwise) of mouse behaviour Also, the randomness (or otherwise) of trial types to know when best to start looking at 'full task' behaviour
# Import libraries import matplotlib.pyplot as plt %matplotlib inline import pandas as pd import seaborn as sns import random import copy import numpy as np from scipy.signal import resample from scipy.stats import zscore from scipy import interp from sklearn.linear_model import LogisticRegression from sklearn.metrics...
_____no_output_____
MIT
tf/.ipynb_checkpoints/Totally Random-checkpoint.ipynb
mathewzilla/whiskfree
Repeat the trick for ON policy trials
# P_ijk_ON P_ij_ON = np.zeros([3,3]) P_ijk_ON = np.zeros([3,3,3]) for i in range(len(tt[AB_pol]) - 2): # p_i = tt[ON_pol][i] # p_j = tt[ON_pol][i+1] # p_k = tt[ON_pol][i+2] p_i = ch[AB_pol][i] p_j = ch[AB_pol][i+1] p_k = ch[AB_pol][i+2] P_ij_ON[p_i-1,p_j-1] += 1 P_ijk_ON[p_i-1,p_j-1,[p_k...
_____no_output_____
MIT
tf/.ipynb_checkpoints/Totally Random-checkpoint.ipynb
mathewzilla/whiskfree
Finally, transition probabilities for choices - do they follow the trial types? (Actually, let's just re-run the code from above changing tt to ch) Now, let's use graphs to visualise confusion matrices
cm_AB = confusion_matrix(tt[AB_pol],ch[AB_pol]) cm_ON = confusion_matrix(tt[ON_pol],ch[ON_pol]) print(cm_AB) print(cm_ON) print(accuracy_score(tt[AB_pol],ch[AB_pol])) print(accuracy_score(tt[ON_pol],ch[ON_pol])) cmap = sns.diverging_palette(220,10, l=70, as_cmap=True, center="dark") # blue to red via black with sns.axe...
_____no_output_____
MIT
tf/.ipynb_checkpoints/Totally Random-checkpoint.ipynb
mathewzilla/whiskfree
Should also look at patterns in licking wrt correct/incorrect
for v in g.vertices(): print(v) for e in g.edges(): print(e) 19.19 - 9.92 # gt.graph_draw(g,output_size=(400,400),fit_view=True,output='simple_graph.pdf') gt.graph_draw(g2,output_size=(400,400),fit_view=True) deg. # Stats... len(tt[tt[AB_pol]]) gt.graph_draw?
_____no_output_____
MIT
tf/.ipynb_checkpoints/Totally Random-checkpoint.ipynb
mathewzilla/whiskfree
Load and plot protraction/retraction trial data for one mouse
# quick load and classification of pro/ret data tt = pd.read_csv('~/work/whiskfree/data/tt_36_subset_sorted.csv',header=None) ch = pd.read_csv('~/work/whiskfree/data/ch_36_subset_sorted.csv',header=None) proret = pd.read_csv('~/work/whiskfree/data/proret_36_subset_sorted.csv',header=None) tt = tt.values.reshape(-1,1) ...
[[164 54 77] [ 86 241 25] [ 21 114 133]] [[189 15 62] [ 80 236 25] [ 2 158 148]]
MIT
tf/.ipynb_checkpoints/Totally Random-checkpoint.ipynb
mathewzilla/whiskfree
bibliotecas utilizadas Aperte Play para inicializar as bibliotecas
import networkx as nx import matplotlib.pyplot as plt import numpy as np
_____no_output_____
MIT
TRABALHO1GRAFOS.ipynb
haroldosfilho/Python
Entre com o número de vértces do seu grafo e digite enter.
n = input("entre com o numero de vertices:" )
entre com o numero de vertices:5
MIT
TRABALHO1GRAFOS.ipynb
haroldosfilho/Python
aperte o play para tranformar num número inteiro a sua entrada.
num=int(str(n)) print(num)
5
MIT
TRABALHO1GRAFOS.ipynb
haroldosfilho/Python
aperte o play para gerar a lista dos vértices do seu Grafo
G = nx.path_graph(num) list(G.nodes) m = int(input("Entre com o número de arestas : "))
Entre com o número de arestas : 7
MIT
TRABALHO1GRAFOS.ipynb
haroldosfilho/Python
Digite as suas arestas, quais vértices estão conectados, aperte enter após cada aresta informada.
# creating an empty list lst = [] # iterating till the range for i in range(0, m): ele = str(input()) lst.append(ele) # adding the element print(lst)
01 12 13 23 24 34 02 ['01', '12', '13', '23', '24', '34', '02']
MIT
TRABALHO1GRAFOS.ipynb
haroldosfilho/Python
aperte play para gerar uma representação no plano do seu Grafo.
G = nx.Graph(lst) opts = { "with_labels": True, "node_color": 'y' } nx.draw(G, **opts)
_____no_output_____
MIT
TRABALHO1GRAFOS.ipynb
haroldosfilho/Python
aperte o play para gerar os elementos da sua matriz de adjacência do seu Grafo
A = nx.adjacency_matrix(G) print(A)
(0, 1) 1 (0, 2) 1 (1, 0) 1 (1, 2) 1 (1, 3) 1 (2, 0) 1 (2, 1) 1 (2, 3) 1 (2, 4) 1 (3, 1) 1 (3, 2) 1 (3, 4) 1 (4, 2) 1 (4, 3) 1
MIT
TRABALHO1GRAFOS.ipynb
haroldosfilho/Python
Agora basta apertar o play e a sua matriz de adjacência está pronta!
A = nx.adjacency_matrix(G).toarray() print(A)
[[0 1 1 0 0] [1 0 1 1 0] [1 1 0 1 1] [0 1 1 0 1] [0 0 1 1 0]]
MIT
TRABALHO1GRAFOS.ipynb
haroldosfilho/Python
ClarityViz Pipeline: .img -> histogram .nii -> graph represented as csv -> graph as graphml -> plotly To run: Step 1:First, run the following. This takes the .img, generates the localeq histogram as an nii file, gets the nodes and edges as a csv and converts the csv into a graphml
python runclarityviz.py --token Fear199Coronal --file-type img --source-directory /cis/project/clarity/data/clarity/isoCoronal
_____no_output_____
Apache-2.0
examples/Jupyter/ClarityViz Pipeline.ipynb
jonl1096/seelvizorg
Step 2: Then run this. This just converts the graphml into a plotly
python runclarityviz.py --token Fear199Coronal --plotly yes
_____no_output_____
Apache-2.0
examples/Jupyter/ClarityViz Pipeline.ipynb
jonl1096/seelvizorg
Results
Starting pipeline for Fear199.img Generating Histogram... FINISHED GENERATING HISTOGRAM Loading: Fear199/Fear199localeq.nii Image Loaded: Fear199/Fear199localeq.nii FINISHED LOADING NII Coverting to points... token=Fear199 total=600735744 max=255.000000 threshold=0.300000 sample=0.500000 (This will take couple minutes)...
_____no_output_____
Apache-2.0
examples/Jupyter/ClarityViz Pipeline.ipynb
jonl1096/seelvizorg
Code runclarityviz.py:
from clarityviz import clarityviz import ... def get_args(): parser = argparse.ArgumentParser(description="Description") parser.add_argument("--token", type=str, required=True, help="The token.") parser.add_argument("--file-type", type=str, required=False, help="The file type.") parser.add_argument("-...
_____no_output_____
Apache-2.0
examples/Jupyter/ClarityViz Pipeline.ipynb
jonl1096/seelvizorg
clarityviz.py
def generateHistogram(self): print('Generating Histogram...') if self._source_directory == None: path = self._token + '.img' else: path = self._source_directory + "/" + self._token + ".img" im = nib.load(path) im = im.get_data() img = im[:,:,:] ...
_____no_output_____
Apache-2.0
examples/Jupyter/ClarityViz Pipeline.ipynb
jonl1096/seelvizorg
Mixture Density Networks with Edward, Keras and TensorFlowThis notebook explains how to implement Mixture Density Networks (MDN) with Edward, Keras and TensorFlow.Keep in mind that if you want to use Keras and TensorFlow, like we do in this notebook, you need to set the backend of Keras to TensorFlow, [here](http://ke...
# imports %matplotlib inline import matplotlib.pyplot as plt import seaborn as sns import edward as ed import numpy as np import tensorflow as tf from edward.stats import norm # Normal distribution from Edward. from keras import backend as K from keras.layers import Dense from sklearn.cross_validation import train_...
_____no_output_____
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
We will need some functions to plot the results later on, these are defined in the next code block.
from scipy.stats import norm as normal def plot_normal_mix(pis, mus, sigmas, ax, label='', comp=True): """ Plots the mixture of Normal models to axis=ax comp=True plots all components of mixture model """ x = np.linspace(-10.5, 10.5, 250) final = np.zeros_like(x) for i, (weight_mix, mu_mix, ...
_____no_output_____
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
Making some toy-data to play with.This is the same toy-data problem set as used in the [blog post](http://blog.otoro.net/2015/11/24/mixture-density-networks-with-tensorflow/) by Otoro where he explains MDNs. This is an inverse problem as you can see, for every ```X``` there are multiple ```y``` solutions.
def build_toy_dataset(nsample=40000): y_data = np.float32(np.random.uniform(-10.5, 10.5, (1, nsample))).T r_data = np.float32(np.random.normal(size=(nsample, 1))) # random noise x_data = np.float32(np.sin(0.75 * y_data) * 7.0 + y_data * 0.5 + r_data * 1.0) return train_test_split(x_data, y_data, random_...
Size of features in training data: (4000, 1) Size of output in training data: (4000, 1) Size of features in test data: (36000, 1) Size of output in test data: (36000, 1)
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
Building a MDN using Edward, Keras and TFWe will define a class that can be used to construct MDNs. In this notebook we will be using a mixture of Normal Distributions. The advantage of defining a class is that we can easily reuse this to build other MDNs with different amount of mixture components. Furthermore, this ...
class MixtureDensityNetwork: """ Mixture density network for outputs y on inputs x. p((x,y), (z,theta)) = sum_{k=1}^K pi_k(x; theta) Normal(y; mu_k(x; theta), sigma_k(x; theta)) where pi, mu, sigma are the output of a neural network taking x as input and with parameters theta. There are no laten...
_____no_output_____
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
We can set a seed in Edward so we can reproduce all the random components. The following line:```ed.set_seed(42)```sets the seed in Numpy and TensorFlow under the [hood](https://github.com/blei-lab/edward/blob/master/edward/util.pyL191). We use the class we defined above to initiate the MDN with 20 mixtures, this now c...
ed.set_seed(42) model = MixtureDensityNetwork(20)
_____no_output_____
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
In the following code cell we define the TensorFlow placeholders that are then used to define the Edward data model.The following line passes the ```model``` and ```data``` to ```MAP``` from Edward which is then used to initialise the TensorFlow variables. ```inference = ed.MAP(model, data)``` MAP is a Bayesian concept...
X = tf.placeholder(tf.float32, shape=(None, 1)) y = tf.placeholder(tf.float32, shape=(None, 1)) data = ed.Data([X, y]) # Make Edward Data model inference = ed.MAP(model, data) # Make the inference model sess = tf.Session() # Start TF session K.set_session(sess) # Pass session info to Keras inference.initialize(sess=s...
_____no_output_____
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
Having done that we can train the MDN in TensorFlow just like we normally would, and we can get out the predictions we are interested in from ```model```, in this case: * ```model.pi``` the mixture components, * ```model.mus``` the means,* ```model.sigmas``` the standard deviations. This is done in the last line of ...
NEPOCH = 1000 train_loss = np.zeros(NEPOCH) test_loss = np.zeros(NEPOCH) for i in range(NEPOCH): _, train_loss[i] = sess.run([inference.train, inference.loss], feed_dict={X: X_train, y: y_train}) test_loss[i] = sess.run(inference.loss, feed_dict={X: X_test, y: y_test}) pred_...
_____no_output_____
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
We can plot the log-likelihood of the training and test sample as function of training epoch.Keep in mind that ```inference.loss``` returns the total log-likelihood, so not the loss per data point, so in the plotting routine we divide by the size of the train and test data respectively. We see that it converges after 4...
fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(16, 3.5)) plt.plot(np.arange(NEPOCH), test_loss/len(X_test), label='Test') plt.plot(np.arange(NEPOCH), train_loss/len(X_train), label='Train') plt.legend(fontsize=20) plt.xlabel('Epoch', fontsize=15) plt.ylabel('Log-likelihood', fontsize=15)
_____no_output_____
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
Next we can have a look at how some individual examples perform. Keep in mind this is an inverse problemso we can't get the answer correct, we can hope that the truth lies in area where the model has high probability.In the next plot the truth is the vertical grey line while the blue line is the prediction of the mixtu...
obj = [0, 4, 6] fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(16, 6)) plot_normal_mix(pred_weights[obj][0], pred_means[obj][0], pred_std[obj][0], axes[0], comp=False) axes[0].axvline(x=y_test[obj][0], color='black', alpha=0.5) plot_normal_mix(pred_weights[obj][2], pred_means[obj][2], pred_std[obj][2], axes[1], ...
_____no_output_____
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
We can check the ensemble by drawing samples of the prediction and plotting the density of those. Seems the MDN learned what it needed too.
a = sample_from_mixture(X_test, pred_weights, pred_means, pred_std, amount=len(X_test)) sns.jointplot(a[:,0], a[:,1], kind="hex", color="#4CB391", ylim=(-10,10), xlim=(-14,14))
_____no_output_____
Apache-2.0
docs/source/notebooks/MDN_Edward_Keras_TF.ipynb
caosenqi/Edward1
Importing Required Libraries
from pyspark.sql import SparkSession from pyspark.sql import functions as F
_____no_output_____
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
Getting Spark Session
spark = SparkSession.builder.getOrCreate()
_____no_output_____
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
Reading CSV
df = spark.read.csv("Big_Cities_Health_Data_Inventory.csv", header=True) df.show(10)
+------------------+--------------------+----+------+---------------+-----+--------------------+--------------------------+--------------------+-------+-----+ |Indicator Category| Indicator|Year|Gender|Race/ Ethnicity|Value| Place|BCHC Requested Methodology| Source|Methods|Notes| +-...
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
Printing Schema
df.printSchema()
root |-- Indicator Category: string (nullable = true) |-- Indicator: string (nullable = true) |-- Year: string (nullable = true) |-- Gender: string (nullable = true) |-- Race/ Ethnicity: string (nullable = true) |-- Value: string (nullable = true) |-- Place: string (nullable = true) |-- BCHC Requested Methodolo...
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
Dropping Unwanted Columns
df = df.drop("Notes", "Methods", "Source", "BCHC Requested Methodology") df.printSchema()
root |-- Indicator Category: string (nullable = true) |-- Indicator: string (nullable = true) |-- Year: string (nullable = true) |-- Gender: string (nullable = true) |-- Race/ Ethnicity: string (nullable = true) |-- Value: string (nullable = true) |-- Place: string (nullable = true)
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
Counting Null Values
df.select([F.count(F.when(F.isnan(c) | F.col(c).isNull(), c)).alias(c) for c in df.columns]).show()
+------------------+---------+----+------+---------------+-----+-----+ |Indicator Category|Indicator|Year|Gender|Race/ Ethnicity|Value|Place| +------------------+---------+----+------+---------------+-----+-----+ | 0| 28| 28| 218| 212| 231| 218| +------------------+---------+----+-...
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
Since there are several null values in the columns as shown in the table above, first steps would be to remove / replace null values in each column Working with Null Values
df.filter(df["Indicator"].isNull()).show(28)
+--------------------+---------+----+------+---------------+-----+-----+ | Indicator Category|Indicator|Year|Gender|Race/ Ethnicity|Value|Place| +--------------------+---------+----+------+---------------+-----+-----+ | FOR THE POPULATI...| null|null| null| null| null| null| | 12 MONTHS (S1701)"| n...
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
Since all the rows that have null values in Indicator have null values for other columns like Year, Gender, Race and etc, it would be better to remove these observations
# Counting total number of rows in the dataset to compare with the rows after null value rows are removed. rows_count_pre = df.count() print("Total number of rows before deleting: ",rows_count_pre) # deleting all the rows where there are null values in the columns mentioned below df = df.na.drop(subset=["Indicator", "Y...
+------------------+---------+----+------+---------------+-----+-----+ |Indicator Category|Indicator|Year|Gender|Race/ Ethnicity|Value|Place| +------------------+---------+----+------+---------------+-----+-----+ | 0| 0| 0| 0| 0| 0| 0| +------------------+---------+----+-...
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
The results above show that all the rows with null values have been deleted from the dataset. This completes the step of removing all the null values from the dataset Splitting the Place Column into City and State Columns
split_col = F.split(df["Place"], ',') df = df.withColumn("City_County", split_col.getItem(0)) df = df.withColumn("State", split_col.getItem(1)) df.select("City_County", "State").show(truncate=False) Creating a User Defined Function to take care of the City_County column to extract the city. Same can be done using impor...
+--------+-----+ |City |State| +--------+-----+ |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA | |Atlanta | GA ...
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
This sums up the cleaning process of data using PySpark. Below is the final state of the dataset
df.show()
+--------------------+--------------------+----+------+---------------+-----+--------------------+--------------------+-----+--------+ | Indicator Category| Indicator|Year|Gender|Race/ Ethnicity|Value| Place| City_County|State| City| +--------------------+--------------------+----+--...
MIT
Data Cleaning with PySpark.ipynb
raziiq/python-pyspark-data-cleaning
Exploratory Data Analysis* Dataset taken from https://github.com/Tariq60/LIAR-PLUS 1. Import Libraries
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt TRAIN_PATH = "../data/raw/dataset/tsv/train2.tsv" VAL_PATH = "../data/raw/dataset/tsv/val2.tsv" TEST_PATH = "../data/raw/dataset/tsv/test2.tsv" columns = ["id", "statement_json", "label", "statement", "subject", "speaker", "speaker_title...
_____no_output_____
MIT
notebooks/eda-notebook.ipynb
archity/fake-news
2. Read the dataset
train_df = pd.read_csv(TRAIN_PATH, sep="\t", names=columns) val_df = pd.read_csv(VAL_PATH, sep="\t", names=columns) test_df = pd.read_csv(TEST_PATH, sep="\t", names=columns) print(f"Length of train set: {len(train_df)}") print(f"Length of validation set: {len(val_df)}") print(f"Length of test set: {len(test_df)}") trai...
_____no_output_____
MIT
notebooks/eda-notebook.ipynb
archity/fake-news
3. Data Cleaning * Some of the most important coloumns are "label", "statement".* Now we should check if any of them have null values.
print("Do we have empty strings in `label`?") pd.isna(train_df["label"]).value_counts()
Do we have empty strings in `label`?
MIT
notebooks/eda-notebook.ipynb
archity/fake-news
* 2 entries without any label* What exactly are those 2 entries?
train_df.loc[pd.isna(train_df["label"]), :].index train_df.loc[[2143]] train_df.loc[[9377]]
_____no_output_____
MIT
notebooks/eda-notebook.ipynb
archity/fake-news
* All the coloumns of those 2 entries are blank* Drop those 2 entries
train_df.dropna(subset=["label"], inplace=True) len(train_df)
_____no_output_____
MIT
notebooks/eda-notebook.ipynb
archity/fake-news
4. Some Feature Analysis 4.1 Party Affiliation
print(train_df["party_affiliation"].value_counts()) if not os.path.exists("./img"): os.makedirs("./img") fig = plt.figure(figsize=(10, 6)) party_affil_plot = train_df["party_affiliation"].value_counts().plot.bar() plt.tight_layout(pad=1) plt.savefig("img/party_affil_plot.png", dpi=200)
republican 4497 democrat 3336 none 1744 organization 219 independent 147 newsmaker 56 libertarian 40 activist 39 journalist ...
MIT
notebooks/eda-notebook.ipynb
archity/fake-news
4.2 States Stats
print(train_df["state_info"].value_counts()) fig = plt.figure(figsize=(10, 6)) state_info_plot = train_df["state_info"].value_counts().plot.bar() plt.tight_layout(pad=1) plt.savefig("img/state_info_plot.png", dpi=200)
Texas 1009 Florida 997 Wisconsin 713 New York 657 Illinois 556 ... Qatar 1 Virginia 1 United Kingdom 1 China 1 Rhode Island 1 Name: state_info, Length: 84, dtype: int64
MIT
notebooks/eda-notebook.ipynb
archity/fake-news
* Apparently, we have a state_info entry with value as "Virginia director, Coalition to Stop Gun Violence".It should be replaced with "Virginia" only
train_df[train_df["state_info"]=="Virginia director, Coalition to Stop Gun Violence"] indx = train_df[train_df["state_info"]=="Virginia director, Coalition to Stop Gun Violence"].index[0] train_df.loc[indx, "state_info"] = "Virginia" fig = plt.figure(figsize=(10, 6)) state_info_plot = train_df["state_info"].value_coun...
_____no_output_____
MIT
notebooks/eda-notebook.ipynb
archity/fake-news