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 |
|---|---|---|---|---|---|
[3] Preprocessing [3.1]. Preprocessing Review TextNow that we have finished deduplication our data requires some preprocessing before we go on further with analysis and making the prediction model.Hence in the Preprocessing phase we do the following in the order below:-1. Begin by removing the html tags2. Remove an... | # printing some random reviews
sent_0 = final['Text'].values[0]
print(sent_0)
print("="*50)
sent_1000 = final['Text'].values[1000]
print(sent_1000)
print("="*50)
sent_1500 = final['Text'].values[1500]
print(sent_1500)
print("="*50)
sent_4900 = final['Text'].values[4900]
print(sent_4900)
print("="*50)
# remove urls f... | _____no_output_____ | MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[4] Featurization [4.1] BAG OF WORDS | #BoW
count_vect = CountVectorizer() #in scikit-learn
count_vect.fit(preprocessed_reviews)
print("some feature names ", count_vect.get_feature_names()[:10])
print('='*50)
final_counts = count_vect.transform(preprocessed_reviews)
print("the type of count vectorizer ",type(final_counts))
print("the shape of out text BOW ... | some feature names ['aa', 'aahhhs', 'aback', 'abandon', 'abates', 'abbott', 'abby', 'abdominal', 'abiding', 'ability']
==================================================
the type of count vectorizer <class 'scipy.sparse.csr.csr_matrix'>
the shape of out text BOW vectorizer (4986, 12997)
the number of unique words 1... | MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[4.2] Bi-Grams and n-Grams. | #bi-gram, tri-gram and n-gram
#removing stop words like "not" should be avoided before building n-grams
# count_vect = CountVectorizer(ngram_range=(1,2))
# please do read the CountVectorizer documentation http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html
# you can c... | the type of count vectorizer <class 'scipy.sparse.csr.csr_matrix'>
the shape of out text BOW vectorizer (4986, 3144)
the number of unique words including both unigrams and bigrams 3144
| MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[4.3] TF-IDF | tf_idf_vect = TfidfVectorizer(ngram_range=(1,2), min_df=10)
tf_idf_vect.fit(preprocessed_reviews)
print("some sample features(unique words in the corpus)",tf_idf_vect.get_feature_names()[0:10])
print('='*50)
final_tf_idf = tf_idf_vect.transform(preprocessed_reviews)
print("the type of count vectorizer ",type(final_tf_... | some sample features(unique words in the corpus) ['ability', 'able', 'able find', 'able get', 'absolute', 'absolutely', 'absolutely delicious', 'absolutely love', 'absolutely no', 'according']
==================================================
the type of count vectorizer <class 'scipy.sparse.csr.csr_matrix'>
the shap... | MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[4.4] Word2Vec | # Train your own Word2Vec model using your own text corpus
i=0
list_of_sentance=[]
for sentance in preprocessed_reviews:
list_of_sentance.append(sentance.split())
# Using Google News Word2Vectors
# in this project we are using a pretrained model by google
# its 3.3G file, once you load this into your memory
# it ... | number of words that occured minimum 5 times 3817
sample words ['product', 'available', 'course', 'total', 'pretty', 'stinky', 'right', 'nearby', 'used', 'ca', 'not', 'beat', 'great', 'received', 'shipment', 'could', 'hardly', 'wait', 'try', 'love', 'call', 'instead', 'removed', 'easily', 'daughter', 'designed', 'pri... | MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[4.4.1] Converting text into vectors using Avg W2V, TFIDF-W2V [4.4.1.1] Avg W2v | # average Word2Vec
# compute average word2vec for each review.
sent_vectors = []; # the avg-w2v for each sentence/review is stored in this list
for sent in tqdm(list_of_sentance): # for each review/sentence
sent_vec = np.zeros(50) # as word vectors are of zero length 50, you might need to change this to 300 if you ... | 100%|████████████████████████████████████████████████████████████████████████████| 4986/4986 [00:03<00:00, 1330.47it/s]
| MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[4.4.1.2] TFIDF weighted W2v | # S = ["abc def pqr", "def def def abc", "pqr pqr def"]
model = TfidfVectorizer()
tf_idf_matrix = model.fit_transform(preprocessed_reviews)
# we are converting a dictionary with word as a key, and the idf as a value
dictionary = dict(zip(model.get_feature_names(), list(model.idf_)))
# TF-IDF weighted Word2Vec
tfidf_fea... | 100%|█████████████████████████████████████████████████████████████████████████████| 4986/4986 [00:20<00:00, 245.63it/s]
| MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
Truncated-SVD [5.1] Taking top features from TFIDF, SET 2 | # Please write all the code with proper documentation
X = preprocessed_reviews[:]
y = final['Score'][:]
tf_idf = TfidfVectorizer()
tfidf_data = tf_idf.fit_transform(X)
tfidf_feat = tf_idf.get_feature_names()
| _____no_output_____ | MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[5.2] Calulation of Co-occurrence matrix | # Please write all the code with proper documentation
#Ref:https://datascience.stackexchange.com/questions/40038/how-to-implement-word-to-word-co-occurence-matrix-in-python
#Ref:# https://github.com/PushpendraSinghChauhan/Amazon-Fine-Food-Reviews/blob/master/Computing%20Word%20Vectors%20using%20TruncatedSVD.ipynb
def ... | _____no_output_____ | MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[5.3] Finding optimal value for number of components (n) to be retained. | # Please write all the code with proper documentation
k = np.arange(2,100,3)
variance =[]
for i in k:
svd = TruncatedSVD(n_components=i)
svd.fit_transform(X_new)
score = svd.explained_variance_ratio_.sum()
variance.append(score)
plt.plot(k, variance)
plt.xlabel('Number of Components')
plt.ylabel('... | _____no_output_____ | MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[5.4] Applying k-means clustering | # Please write all the code with proper documentation
errors = []
k = [2, 5, 10, 15, 25, 30, 50, 100]
for i in k:
kmeans = KMeans(n_clusters=i, random_state=0)
kmeans.fit(X_new)
errors.append(kmeans.inertia_)
plt.plot(k, errors)
plt.xlabel('K')
plt.ylabel('Error')
plt.title('K VS Error Plot')
plt.sho... | _____no_output_____ | MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[5.5] Wordclouds of clusters obtained in the above section | # Please write all the code with proper documentation
indices = np.argsort(tf_idf.idf_[::-1])
top_feat = [tfidf_feat[i] for i in indices[0:3000]]
top_indices = indices[0:3000]
top_n = np.argsort(top_feat[::-1])
feature_importances = pd.DataFrame(top_n, index = top_feat, columns=['importance']).sort_values('importance... | _____no_output_____ | MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[5.6] Function that returns most similar words for a given word. | # Please write all the code with proper documentation
def similarity(word):
similarity = cosine_similarity(X_new)
word_vect = similarity[top_feat.index(word)]
index = word_vect.argsort()[::-1][1:5]
for i in range(len(index)):
print((i+1),top_feat[index[i]] ,"\n")
similarity('sugary')
similari... | 1 maytag
2 slip
3 gibbles
4 farriage
| MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
[6] Conclusions | # Please write down few lines about what you observed from this assignment.
# Also please do mention the optimal values that you obtained for number of components & number of clusters.
from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["Algorithm","Best Hyperparameter"]
x.add_row(["T-SVD", ... | +-----------+---------------------+
| Algorithm | Best Hyperparameter |
+-----------+---------------------+
| T-SVD | 20 |
| K-Means | 20 |
+-----------+---------------------+
| MIT | #11_Amazon_Fine_Food_Reviews_Analysis_Truncated_SVD.ipynb | wizard-kv/Truncated-SVD-algorithm-on-Amazon-reviews-dataset |
Conditional statements - part 1 MotivationAll the previous programs are based on a pure sequence of statements. After the start of the program the statements areexecuted step by step and the program ends afterwards. However, it is often necessary that parts of a program areonly executed under certain conditions. For ... | 1 == True | _____no_output_____ | CC0-1.0 | week_1/week_1_unit_5_ifstatement_notebook.ipynb | ceedee666/opensap_python_intro |
Conditional statementsUsing the conditional operators it is now possible to formulate conditional statements in Python.The syntax for conditional statements in Python is:```pythonif condition: statement_a1 ... statement_anelse: statement_b1 ... statement_bm```The result of the condition can be either `True... | number = int(input("Please type a number: "))
if number > 100:
print(number, "is greater than 100!")
number = int(input("Please type a number: "))
if number > 100:
print(number, "is greater than 100!")
else:
print(number, "is smaller or equals 100!") | _____no_output_____ | CC0-1.0 | week_1/week_1_unit_5_ifstatement_notebook.ipynb | ceedee666/opensap_python_intro |
Indentations mark the boundaries of code blocksStatements that belong together are called *code blocks*.As can be seen in the previous examples, Python does not use special characters or keywords to mark thebeginning and the end of code blocks. Instead, indentation is used in Python. So indentation and spaces have a m... | a = 3
b = 4
print(a + b)
number = 100
if number > 0:
print("Number is greater than 0") | _____no_output_____ | CC0-1.0 | week_1/week_1_unit_5_ifstatement_notebook.ipynb | ceedee666/opensap_python_intro |
Let us challenge your understanding of code blocks in Python. Take a look at the following program. The last statement `print("Done")` is not indented. What does this mean for the execution of theprogram? Change the program and indent the `print("Done")`. How does the execution of theprogram change? | number = int(input("Please insert a number: "))
if number > 100:
print(number, "is greater than 100!")
else:
print(number, "is smaller oder equals 100!")
print("Done") | _____no_output_____ | CC0-1.0 | week_1/week_1_unit_5_ifstatement_notebook.ipynb | ceedee666/opensap_python_intro |
ExerciseWrite a conditional statement that asks for the user's name. Use the `input()` function. If his name is Harry or Harry Potter, then output "Welcome to Gryffindor, Mr. Potter!". Otherwise output "Sorry, Hogwarts is full.". | name = | _____no_output_____ | CC0-1.0 | week_1/week_1_unit_5_ifstatement_notebook.ipynb | ceedee666/opensap_python_intro |
Greetings! You might be here because you think* Betting markets are far more efficient then Nate Silver or G. Elliott Morris. I really can't help you if you insist otherwise - perhaps G. Elliott will offer you 19/1 on Trump LOL. * Betting markets still requires some interpretation, because many punters are so la... | import numpy as np
from pprint import pprint
import math
from scipy.stats import norm
# Current prices for Biden, expressed as inverse probabilities, and electoral votes
states = [ ('arizona',1.23,11), ('michigan',1.01,16), ('pennsylvania',1.03,20),
('georgia',1.12,16),('nevada',1.035,6), ('north caroli... | {'biden_270_299': '+290.0',
'biden_270_or_more': '-4019.0',
'biden_300_329': '-257.0',
'trump_270_299': '+5407.0',
'trump_270_or_more': '+5169.0',
'trump_300_329': '+121851.0'}
| MIT | Election_in_the_run_with_correlation.ipynb | microprediction/microblog |
Using a random forest for demographic model selectionIn Schrider and Kern (2017) we give a toy example of demographic model selection via supervised machine learning in Figure Box 1. Following a discussion on twitter, Vince Buffalo had the great idea of our providing a simple example of supervised ML in population gen... | #untar and compile ms and sample_stats
!tar zxf ms.tar.gz; cd msdir; gcc -o ms ms.c streec.c rand1.c -lm; gcc -o sample_stats sample_stats.c tajd.c -lm
#I get three compiler warnings from ms, but everything should be fine
#now I'll just move the programs into the current working dir
!mv msdir/ms . ; mv msdir/sample_sta... | _____no_output_____ | MIT | demographicModelSelectionExample.ipynb | kern-lab/popGenMachineLearningExamples |
Install `scikit-learn`If you use anaconda, you may already have these modules installed, but if not you can install with either of the following | !conda install scikit-learn --yes | _____no_output_____ | MIT | demographicModelSelectionExample.ipynb | kern-lab/popGenMachineLearningExamples |
or if you don't use `conda`, you can use `pip` to install scikit-learn with | !pip install -U scikit-learn | _____no_output_____ | MIT | demographicModelSelectionExample.ipynb | kern-lab/popGenMachineLearningExamples |
Step 1: create a training set and a testing setWe will create a training set using simulations from three different demographic models: equilibrium population size, instantaneous population growth, and instantaneous population contraction. As you'll see this is really just a toy example because we will perform classif... | #simulate under the equilibrium model
!./ms 20 2000 -t 100 -r 100 10000 | ./sample_stats > equilibrium.msOut.stats
#simulate under the contraction model
!./ms 20 2000 -t 100 -r 100 10000 -en 0 1 0.5 -en 0.2 1 1 | ./sample_stats > contraction.msOut.stats
#simulate under the growth model
!./ms 20 2000 -t 100 -r 100 10000... | _____no_output_____ | MIT | demographicModelSelectionExample.ipynb | kern-lab/popGenMachineLearningExamples |
Step 2: train our classifier and visualize decision surfaceNow that we have a training and testing set ready to go, we can move on to training our classifier. For this example we will use a random forest classifier (Breiman 2001). This is all implemented in `scikit-learn` and so the code is very brief. | from sklearn.ensemble import RandomForestClassifier
rfClf = RandomForestClassifier(n_estimators=100,n_jobs=10)
clf = rfClf.fit(X_train, Y_train)
| _____no_output_____ | MIT | demographicModelSelectionExample.ipynb | kern-lab/popGenMachineLearningExamples |
That's it! The classifier is trained. This Random Forest classifer used 100 decision trees in its ensemble, a pretty large number considering that we are only using two summary stats to represent our data. Nevertheless it trains on the data very, very quickly.Confession: the real reason we are using only two summary st... | from sklearn.preprocessing import normalize
#These two functions (taken from scikit-learn.org) plot the decision boundaries for a classifier.
def plot_contours(ax, clf, xx, yy, **params):
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
out = ax.contourf(xx, yy, Z, **params)
retur... | _____no_output_____ | MIT | demographicModelSelectionExample.ipynb | kern-lab/popGenMachineLearningExamples |
Above we can see which regions of our feature space are assigned to each class: dark blue shaded areas will be classified as Equilibrium, faint blue as Contraction, and red as Growth. Note the non-linear decision surface. Looks pretty cool! And also illustrates how this type of classifier might be useful for discrimina... | #here's the confusion matrix function
def makeConfusionMatrixHeatmap(data, title, trueClassOrderLs, predictedClassOrderLs, ax):
data = np.array(data)
data = normalize(data, axis=1, norm='l1')
heatmap = ax.pcolor(data, cmap=plt.cm.Blues, vmin=0.0, vmax=1.0)
for i in range(len(predictedClassOrderLs)):
... | _____no_output_____ | MIT | demographicModelSelectionExample.ipynb | kern-lab/popGenMachineLearningExamples |
Looks pretty good. But can we make it better? Well a simple way might be to increase the number of features (i.e. summary statistics) we use as input. Let's give that a whirl using all of the output from Hudson's `sample_stats` | X1 = np.loadtxt("equilibrium.msOut.stats",usecols=(1,3,5,7,9))
X2 = np.loadtxt("contraction.msOut.stats",usecols=(1,3,5,7,9))
X3 = np.loadtxt("growth.msOut.stats",usecols=(1,3,5,7,9))
X = np.concatenate((X1,X2,X3))
#create associated 'labels' -- these will be the targets for training
y = [0]*len(X1) + [1]*len(X2) + [2]... | _____no_output_____ | MIT | demographicModelSelectionExample.ipynb | kern-lab/popGenMachineLearningExamples |
1 A partir del fichero "US_Crime_Rates_1960_2014", se pide:1. Tratar el dataset como una serie temporal a partir de la columna Year. Siempre el eje X será el nuevo índice Year.2. Dibujar todas las columnas numéricas.3. Como se puede ver en el punto 2, la columna "Population" tiene una magnitud diferente a la de las de... | import pandas as pd
df = pd.read_csv("../data/US_Crime_Rates_1960_2014.csv")
df.set_index("Year", inplace=True)
df.plot() | _____no_output_____ | Apache-2.0 | 2_Ejercicios/Modulo2/5.DeciTrees_Kgboost_gridserarch/exercises/4.crime.ipynb | JaunIgciona/DataBootcamp_Nov2020 |
This notebook will help you train a vanilla Point-Cloud AE with the basic architecture we used in our paper. (it assumes latent_3d_points is in the PYTHONPATH and the structural losses have been compiled) | import os.path as osp
from latent_3d_points.src.ae_templates import mlp_architecture_ala_iclr_18, default_train_params
from latent_3d_points.src.autoencoder import Configuration as Conf
from latent_3d_points.src.point_net_ae import PointNetAutoEncoder
from latent_3d_points.src.in_out import snc_category_to_synth_id, ... | _____no_output_____ | MIT | notebooks/train_single_class_ae.ipynb | sinanbayraktar/latent_3d_points |
Define Basic Parameters | top_out_dir = '../data/' # Use to save Neural-Net check-points etc.
top_in_dir = '../data/shape_net_core_uniform_samples_2048/' # Top-dir of where point-clouds are stored.
experiment_name = 'single_class_ae'
n_pc_points = 2048 # Number of points per model.
bneck_size = 128 # Bo... | Give me the class name (e.g. "chair"): chair
| MIT | notebooks/train_single_class_ae.ipynb | sinanbayraktar/latent_3d_points |
Load Point-Clouds | syn_id = snc_category_to_synth_id()[class_name]
class_dir = osp.join(top_in_dir , syn_id)
all_pc_data = load_all_point_clouds_under_folder(class_dir, n_threads=8, file_ending='.ply', verbose=True) | 6778 pclouds were loaded. They belong in 1 shape-classes.
| MIT | notebooks/train_single_class_ae.ipynb | sinanbayraktar/latent_3d_points |
Load default training parameters (some of which are listed beloq). For more details please print the configuration object. 'batch_size': 50 'denoising': False ( by default AE is not denoising) 'learning_rate': 0.0005 'z_rotate': False ( randomly rotate models of each batch) 'loss_disp... | train_params = default_train_params()
encoder, decoder, enc_args, dec_args = mlp_architecture_ala_iclr_18(n_pc_points, bneck_size)
train_dir = create_dir(osp.join(top_out_dir, experiment_name))
conf = Conf(n_input = [n_pc_points, 3],
loss = ae_loss,
training_epochs = train_params['training_epoch... | _____no_output_____ | MIT | notebooks/train_single_class_ae.ipynb | sinanbayraktar/latent_3d_points |
If you ran the above lines, you can reload a saved model like this: | load_pre_trained_ae = False
restore_epoch = 500
if load_pre_trained_ae:
conf = Conf.load(train_dir + '/configuration')
reset_tf_graph()
ae = PointNetAutoEncoder(conf.experiment_name, conf)
ae.restore_model(conf.train_dir, epoch=restore_epoch) | _____no_output_____ | MIT | notebooks/train_single_class_ae.ipynb | sinanbayraktar/latent_3d_points |
Build AE Model. | reset_tf_graph()
ae = PointNetAutoEncoder(conf.experiment_name, conf) | _____no_output_____ | MIT | notebooks/train_single_class_ae.ipynb | sinanbayraktar/latent_3d_points |
Train the AE (save output to train_stats.txt) | buf_size = 1 # Make 'training_stats' file to flush each output line regarding training.
fout = open(osp.join(conf.train_dir, 'train_stats.txt'), 'a', buf_size)
train_stats = ae.train(all_pc_data, conf, log_file=fout)
fout.close() | _____no_output_____ | MIT | notebooks/train_single_class_ae.ipynb | sinanbayraktar/latent_3d_points |
Evaluation Get a batch of reconstuctions and their latent-codes. | feed_pc, feed_model_names, _ = all_pc_data.next_batch(10)
reconstructions = ae.reconstruct(feed_pc)[0]
latent_codes = ae.transform(feed_pc) | _____no_output_____ | MIT | notebooks/train_single_class_ae.ipynb | sinanbayraktar/latent_3d_points |
Use any plotting mechanism such as matplotlib to visualize the results. | i = 2
plot_3d_point_cloud(reconstructions[i][:, 0],
reconstructions[i][:, 1],
reconstructions[i][:, 2], in_u_sphere=True);
i = 4
plot_3d_point_cloud(reconstructions[i][:, 0],
reconstructions[i][:, 1],
reconstructions[i][:, 2], in_u_sph... | _____no_output_____ | MIT | notebooks/train_single_class_ae.ipynb | sinanbayraktar/latent_3d_points |
Figs for the measurement force paper | from scipy.io import loadmat
from scipy.optimize import curve_fit
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from numpy import trapz
def cm2inch(value):
return value/2.54
#axes.xaxis.set_tick_params(direction='in', which='both')
#axes.yaxis.s... | _____no_output_____ | MIT | 02_body/chapter3/images/trajctory analysis/.ipynb_checkpoints/graph_ploting-checkpoint.ipynb | eXpensia/Confined-Brownian-Motion |
Deviations from Normality | import ashmodule as ash
%load_ext autoreload
%autoreload 2
hfi = ash.get_hfi_returns()
hfi.head()
import pandas as pd
pd.concat([hfi.mean(),hfi.median(), hfi.mean()>hfi.median()],axis='columns') | _____no_output_____ | Unlicense | Introduction to Portfolio Construction and Analysis with Python/W1/Deviation From Normality.ipynb | Alashmony/InvestmentManagementML |
Skewness Function:$$ S(R)= \frac{ E [(R-E(R))^3]}{\sigma_R^3} $$ | %autoreload 2
ash.skewness(hfi)
import scipy.stats
scipy.stats.skew(hfi)
ash.skewness(hfi) | _____no_output_____ | Unlicense | Introduction to Portfolio Construction and Analysis with Python/W1/Deviation From Normality.ipynb | Alashmony/InvestmentManagementML |
Kurtosis Function:$$ S(R)= \frac{ E [(R-E(R))^4]}{\sigma_R^4} $$ | %autoreload 2
ash.kurt(hfi)
scipy.stats.kurtosis(hfi)+3
scipy.stats.jarque_bera(hfi)
ash.is_normal(hfi)
hfi.aggregate(ash.is_normal)
ffme= ash.get_ffme_returns()
ash.skewness(ffme)
ash.kurt(ffme)
ffme.aggregate(ash.is_normal) | _____no_output_____ | Unlicense | Introduction to Portfolio Construction and Analysis with Python/W1/Deviation From Normality.ipynb | Alashmony/InvestmentManagementML |
Copyright 2017 Google LLC. | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the L... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Mejora del rendimiento de las redes neuronales **Objetivo de aprendizaje:** mejorar el rendimiento de una red neuronal al normalizar los atributos y aplicar diversos algoritmos de optimización**NOTA:** Los métodos de optimización que se describen en este ejercicio no son específicos para las redes neuronales; son med... | from __future__ import print_function
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Entrenamiento de la red neuronalA continuación, entrenaremos la red neuronal. | def construct_feature_columns(input_features):
"""Construct the TensorFlow Feature Columns.
Args:
input_features: The names of the numerical input features to use.
Returns:
A set of feature columns
"""
return set([tf.feature_column.numeric_column(my_feature)
for my_feature in input_fea... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Ajuste linealUna buena práctica estándar puede ser normalizar las entradas para que estén dentro del rango -1, 1. Esto ayuda al SGD a no bloquearse al realizar pasos que son demasiado grandes en una dimensión o demasiado pequeños en otra. Los apasionados de la optimización numérica pueden observar aquí una relación c... | def linear_scale(series):
min_val = series.min()
max_val = series.max()
scale = (max_val - min_val) / 2.0
return series.apply(lambda x:((x - min_val) / scale) - 1.0) | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Tarea 1: Normalizar los atributos con ajuste lineal**Normaliza las entradas a la escala -1, 1.****Dedica alrededor de 5 minutos a entrenar y evaluar los datos recientemente normalizados. ¿Qué nivel de eficacia puedes tener?**Como regla general, las redes neuronales se entrenan mejor cuando los atributos de entrada es... | def normalize_linear_scale(examples_dataframe):
"""Returns a version of the input `DataFrame` that has all its features normalized linearly."""
#
# Your code here: normalize the inputs.
#
pass
normalized_dataframe = normalize_linear_scale(preprocess_features(california_housing_dataframe))
normalized_training... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
SoluciónHaz clic más abajo para conocer una solución posible. Dado que la normalización usa mín. y máx., debemos asegurarnos de que esta se realice en todo el conjunto de datos a la vez.En este caso podemos hacerlo, porque todos nuestros datos están en un mismo DataFrame. Si tuviéramos varios conjuntos de datos, una... | def normalize_linear_scale(examples_dataframe):
"""Returns a version of the input `DataFrame` that has all its features normalized linearly."""
processed_features = pd.DataFrame()
processed_features["latitude"] = linear_scale(examples_dataframe["latitude"])
processed_features["longitude"] = linear_scale(example... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Tarea 2: Probar un optimizador diferente** Usa los optmizadores AdaGrad y Adam, y compara el rendimiento.**El optimizador AdaGrad es una alternativa. La idea clave de AdaGrad es que modifica la tasa de aprendizaje de forma adaptativa para cada coeficiente de un modelo, lo cual disminuye la tasa de aprendizaje efectiv... | #
# YOUR CODE HERE: Retrain the network using Adagrad and then Adam.
# | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
SoluciónHaz clic más abajo para conocer la solución. Primero, probemos AdaGrad. | _, adagrad_training_losses, adagrad_validation_losses = train_nn_regression_model(
my_optimizer=tf.train.AdagradOptimizer(learning_rate=0.5),
steps=500,
batch_size=100,
hidden_units=[10, 10],
training_examples=normalized_training_examples,
training_targets=training_targets,
validation_exampl... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Ahora, probemos Adam. | _, adam_training_losses, adam_validation_losses = train_nn_regression_model(
my_optimizer=tf.train.AdamOptimizer(learning_rate=0.009),
steps=500,
batch_size=100,
hidden_units=[10, 10],
training_examples=normalized_training_examples,
training_targets=training_targets,
validation_examples=norm... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Imprimamos un gráfico de métricas de pérdida en paralelo. | plt.ylabel("RMSE")
plt.xlabel("Periods")
plt.title("Root Mean Squared Error vs. Periods")
plt.plot(adagrad_training_losses, label='Adagrad training')
plt.plot(adagrad_validation_losses, label='Adagrad validation')
plt.plot(adam_training_losses, label='Adam training')
plt.plot(adam_validation_losses, label='Adam validat... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Tarea 3: Explorar métodos de normalización alternativos**Prueba alternar las normalizaciones para distintos atributos a fin de mejorar aún más el rendimiento.**Si observas detenidamente las estadísticas de resumen de los datos transformados, es posible que observes que, al realizar un ajuste lineal en algunos atribut... | _ = training_examples.hist(bins=20, figsize=(18, 12), xlabelsize=2) | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Es posible que obtengamos mejores resultados al elegir formas adicionales para transformar estos atributos.Por ejemplo, un ajuste logarítmico podría ayudar a algunos atributos. O bien, el recorte de los valores extremos podría hacer que el resto del ajuste sea más informativo. | def log_normalize(series):
return series.apply(lambda x:math.log(x+1.0))
def clip(series, clip_to_min, clip_to_max):
return series.apply(lambda x:(
min(max(x, clip_to_min), clip_to_max)))
def z_score_normalize(series):
mean = series.mean()
std_dv = series.std()
return series.apply(lambda x:(x - mean) / ... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
El bloque anterior contiene algunas funciones de normalización adicionales posibles. Prueba algunas de estas o agrega otras propias.Ten en cuenta que, si normalizas el objetivo, deberás anular la normalización de las predicciones para que las métricas de pérdida sean comparables. | def normalize(examples_dataframe):
"""Returns a version of the input `DataFrame` that has all its features normalized."""
#
# YOUR CODE HERE: Normalize the inputs.
#
pass
normalized_dataframe = normalize(preprocess_features(california_housing_dataframe))
normalized_training_examples = normalized_dataframe.he... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
SoluciónHaz clic más abajo para conocer una solución posible. Estas son solo algunas formas en las que podemos pensar acerca de los datos. Otras transformaciones podrían funcionar incluso mejor.Las funciones `households`, `median_income` y `total_bedrooms` aparecen todas distribuidas normalmente en un espacio logarí... | def normalize(examples_dataframe):
"""Returns a version of the input `DataFrame` that has all its features normalized."""
processed_features = pd.DataFrame()
processed_features["households"] = log_normalize(examples_dataframe["households"])
processed_features["median_income"] = log_normalize(examples_dataframe... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Desafío opcional: Usar solo los atributos de latitud y longitud**Entrena un modelo de red neuronal que use solo latitud y longitud como atributos.**A los agentes de bienes raíces les gusta decir que la ubicación es el único atributo importante en el precio de la vivienda.Veamos si podemos confirmar esto al entrenar u... | #
# YOUR CODE HERE: Train the network using only latitude and longitude
# | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
SoluciónHaz clic más abajo para conocer una solución posible. Una buena idea es mantener latitud y longitud normalizadas: | def location_location_location(examples_dataframe):
"""Returns a version of the input `DataFrame` that keeps only the latitude and longitude."""
processed_features = pd.DataFrame()
processed_features["latitude"] = linear_scale(examples_dataframe["latitude"])
processed_features["longitude"] = linear_scale(exampl... | _____no_output_____ | Apache-2.0 | ml/cc/exercises/estimators/es-419/improving_neural_net_performance.ipynb | plgod/eng-edu |
Optimization terminated successfully (Exit mode 0) Current function value: 1213.8140260451162 Iterations: 12 Function evaluations: 65 Gradient evaluations: 12[5.6 0.5 0.23812683 2.4052193 ] | recons = utils.reconstruct(res.x,allMeans,allFieldFeatures,allFieldPCAModels)
plt.rcParams.update({'font.size': 18})
fig, (axs1,axs2) = plt.subplots(1, 2,figsize = (20,10))
for n in [0,3]:
if n==0:
axs1.plot(np.arange(0.3,30.05,0.1),clinicalProfiles[n][config.allRanges[n][0]:config.allRanges[n][1]],'r--',... | _____no_output_____ | MIT | TestClinicalDataMethod3.ipynb | taborzbislaw/DeepBeam |
  | import torch
import random
import numpy as np
random.seed(0)
np.random.seed(0)
torch.manual_seed(0)
torch.cuda.manual_seed(0)
torch.backends.cudnn.deterministic = True
import torchvision.datasets
CIFAR_train = torchvision.datasets.CIFAR10('./', download=True, train=True)
CIFAR_test = torchvision.datasets.CIFAR10('./',... | _____no_output_____ | MIT | module06_cifar.ipynb | Teradater/Neural_Networks_and_CV |
ВыводыХаки начинают работать в отличие от мниста- Здорово помогает макспулинг- Батчнорм - пушка, но и переобучение намного раньше. Как сделать еще лучше? ЛеНет хорошо работал для 1 канала, а для 3х каналов маловато фильтров в свертках. Исправим это | class CIFARNet(torch.nn.Module):
def __init__(self):
super(CIFARNet, self).__init__()
self.batch_norm0 = torch.nn.BatchNorm2d(3)
self.conv1 = torch.nn.Conv2d(3, 16, 3, padding=1)
self.act1 = torch.nn.ReLU()
self.batch_norm1 = torch.nn.BatchNorm2d(16)
self.pool1 = to... | _____no_output_____ | MIT | module06_cifar.ipynb | Teradater/Neural_Networks_and_CV |
News Headlines SentimentUse the news api to pull the latest news articles for bitcoin and ethereum and create a DataFrame of sentiment scores for each coin. Use descriptive statistics to answer the following questions:1. Which coin had the highest mean positive score?2. Which coin had the highest negative score?3. Whi... | # Read your api key environment variable
api_key = os.getenv("news_api")
# Create a newsapi client
newsapi = NewsApiClient(api_key=api_key)
# Fetch the Bitcoin news articles
bitcoin_news_en = newsapi.get_everything(
q="Bitcoin",
language="en",
sort_by="relevancy"
)
# Show the total number of news
bitcoin_... | _____no_output_____ | ADSL | Starter_Code/.ipynb_checkpoints/crypto_sentiment-checkpoint.ipynb | Aljjohara/NLP |
Questions:Q: Which coin had the highest mean positive score?A: Bitcoin with 0.067400Q: Which coin had the highest compound score?A: Bitcoin with 0.310145Q. Which coin had the highest positive score?A: Ethereum with 0.335000 --- TokenizerIn this section, you will use NLTK and Python to tokenize the text for each coin.... | from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer, PorterStemmer
from string import punctuation
import re
import nltk
# Expand the default stopwords list if necessary
nltk.download("punkt")
nltk.download('stopwords')
print(stopwords.words('... | _____no_output_____ | ADSL | Starter_Code/.ipynb_checkpoints/crypto_sentiment-checkpoint.ipynb | Aljjohara/NLP |
--- NGrams and Frequency AnalysisIn this section you will look at the ngrams and word frequency for each coin. 1. Use NLTK to produce the n-grams for N = 2. 2. List the top 10 words for each coin. | from collections import Counter
from nltk import ngrams
# Generate the Bitcoin N-grams where N=2
all_bigrams_bitcoin = []
for tokens in bitcoin_df['tokens']:
bigrams = list(ngrams(tokens,n=2))
all_bigrams_bitcoin += bigrams
Counter(all_bigrams_bitcoin).most_common()[:10]
# Generate the Ethereum N-grams where N=... | _____no_output_____ | ADSL | Starter_Code/.ipynb_checkpoints/crypto_sentiment-checkpoint.ipynb | Aljjohara/NLP |
Word CloudsIn this section, you will generate word clouds for each coin to summarize the news for each coin | from wordcloud import WordCloud
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = [20.0, 10.0]
# Generate the Bitcoin word cloud
wc = WordCloud().generate(' '.join(all_tokens_bitcoin))
plt.imshow(wc)
# Generate the Ethereum word cloud
wc = WordC... | _____no_output_____ | ADSL | Starter_Code/.ipynb_checkpoints/crypto_sentiment-checkpoint.ipynb | Aljjohara/NLP |
Named Entity RecognitionIn this section, you will build a named entity recognition model for both coins and visualize the tags using SpaCy. | import spacy
from spacy import displacy
# Optional - download a language model for SpaCy
!python -m spacy download en_core_web_sm
# Load the spaCy model
nlp = spacy.load('en_core_web_sm') | _____no_output_____ | ADSL | Starter_Code/.ipynb_checkpoints/crypto_sentiment-checkpoint.ipynb | Aljjohara/NLP |
Bitcoin NER | # Concatenate all of the bitcoin text together
btc_all_text = ' '.join(list(bitcoin_df['text']))
# Run the NER processor on all of the text
btc_doc = nlp(btc_all_text)
# Add a title to the document
btc_doc.user_data['title'] = 'Bitcoin NER'
# Render the visualization
displacy.render(btc_doc, style='ent')
# List all En... | Mark Zuckerberg PERSON
Facebook ORG
Deadline PERSON
this week DATE
+2657 ORG
Reuters
ORG
Goldman Sachs ORG
five CARDINAL
bitcoin GPE
Wednesday DATE
Goldman ORG
Michael Novogratz PERSON
Monday DATE
bitcoin GPE
$10,000 resistance MONEY
Novogratz PERSON
Satoshi Nakaboto PERSON
Bitcoin GPE
Bitcoin GPE
Today DATE
Satoshi N... | ADSL | Starter_Code/.ipynb_checkpoints/crypto_sentiment-checkpoint.ipynb | Aljjohara/NLP |
--- Ethereum NER | # Concatenate all of the bitcoin text together
eth_all_text = ' '.join(list(ethereum_df['text']))
# Run the NER processor on all of the text
eth_doc = nlp(eth_all_text)
# Add a title to the document
eth_doc.user_data['title'] = 'Ethereum NER'
# Render the visualization
displacy.render(eth_doc, style='ent')
# List all... | Andreessen HorowitzsCrypto Startup School ORG
45 CARDINAL
U.S. GPE
seven-week DATE
Andreessen Ho PERSON
+3009 ORG
Satoshi Nakaboto PERSON
Bitcoin GPE
Bitcoin GPE
Today DATE
Satoshi Nakaboto PERSON
Bitcoin GPE
Andreessen Horowitzs ORG
Crypto Startup School ORG
45 CARDINAL
U.S. GPE
seven-week DATE
Andreessen Ho PERSON
Ak... | ADSL | Starter_Code/.ipynb_checkpoints/crypto_sentiment-checkpoint.ipynb | Aljjohara/NLP |
Test | dataiter = iter(testloader)
images, labels = dataiter.next()
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%5s' % classes[labels[j]] for j in range(4)))
outputs = net(images)
outputs
_, predicted = torch.max(outputs, 1)
print('Predicted: ', ' '.join('%5s' % classes[predicted[j]]
... | _____no_output_____ | MIT | scripts/tutorials/biginner/04_cifar10_tutorial_gpu.ipynb | tayutaedomo/pytorch-sandbox |
Boxplot with matplotlib=======================An example of doing box plots with matplotlib | import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 5))
axes = plt.subplot(111)
n = 5
Z = np.zeros((n, 4))
X = np.linspace(0, 2, n)
Y = np.random.random((n, 4))
plt.boxplot(Y)
plt.xticks([])
plt.yticks([])
# Add a title and a box around it
from matplotlib.patches import FancyBboxPatch
... | _____no_output_____ | CC-BY-4.0 | _downloads/plot_boxplot_ext.ipynb | scipy-lectures/scipy-lectures.github.com |
AgendaВ предыдущем семинаре вы создали (или ещё создаёте - тогда марш доделывать!) {вставьте имя монстра}, который не по наслышке понял, что люди - негодяи и подлецы, которым неведом закон и справедливость. __Мы не будем этого терпеть!__ Наши законспирированные биореакторы, известные среди примитивной органической жиз... |
#тут будет текст
corpora = ""
for fname in os.listdir("codex"):
import sys
if sys.version_info >= (3,0):
with open("codex/"+fname, encoding='cp1251') as fin:
text = fin.read() #If you are using your own corpora, make sure it's read correctly
corpora += text
else:
... | _____no_output_____ | MIT | week4/week4-ru - RNN - homework part.ipynb | LatatyeS/HSE_deeplearning |
Константы | #длина последоватеьности при обучении (как далеко распространяются градиенты в BPTT)
seq_length = длина последовательности. От балды - 10, но это не идеально
#лучше начать с малого (скажем, 5) и увеличивать по мере того, как сетка выучивает базовые вещи. 10 - далеко не предел.
# Максимальный модуль градиента
grad_clip... | _____no_output_____ | MIT | week4/week4-ru - RNN - homework part.ipynb | LatatyeS/HSE_deeplearning |
Входные переменные | input_sequence = T.matrix('input sequence','int32')
target_values = T.ivector('target y')
| _____no_output_____ | MIT | week4/week4-ru - RNN - homework part.ipynb | LatatyeS/HSE_deeplearning |
Соберём нейросетьВам нужно создать нейросеть, которая принимает на вход последовательность из seq_length токенов, обрабатывает их и выдаёт вероятности для seq_len+1-ого токена.Общий шаблон архитектуры такой сети -* Вход* Обработка входа* Рекуррентная нейросеть* Вырезание последнего состояния* Обычная нейросеть* Выходн... |
l_in = lasagne.layers.InputLayer(shape=(None, None),input_var=input_sequence)
Ваша нейронка (см выше)
l_out = последний слой, возвращающий веростности для всех len(tokens) вариантов для y
# Веса модели
weights = lasagne.layers.get_all_params(l_out,trainable=True)
print weights
network_output = Выход нейросети
#е... | _____no_output_____ | MIT | week4/week4-ru - RNN - homework part.ipynb | LatatyeS/HSE_deeplearning |
Компилируем всякое-разное |
#обучение
train = theano.function([input_sequence, target_values], loss, updates=updates, allow_input_downcast=True)
#функция потерь без обучения
compute_cost = theano.function([input_sequence, target_values], loss, allow_input_downcast=True)
# Вероятности с выхода сети
probs = theano.function([input_sequence],netwo... | _____no_output_____ | MIT | week4/week4-ru - RNN - homework part.ipynb | LatatyeS/HSE_deeplearning |
Генерируем свои законы* Для этого последовательно применяем нейронку к своему же выводу.* Генерировать можно по разному - * случайно пропорционально вероятности, * только слова максимальной вероятностью * случайно, пропорционально softmax(probas*alpha), где alpha - "жадность" | def max_sample_fun(probs):
return np.argmax(probs)
def proportional_sample_fun(probs)
"""Сгенерировать следующий токен (int32) по предсказанным вероятностям.
probs - массив вероятностей для каждого токена
Нужно вернуть одно целове число - выбранный токен - пропорционально вероятностям
""... | _____no_output_____ | MIT | week4/week4-ru - RNN - homework part.ipynb | LatatyeS/HSE_deeplearning |
Обучение моделиВ котором вы можете подёргать параметры или вставить свою генерирующую функцию. |
print("Training ...")
#сколько всего эпох
n_epochs=100
# раз в сколько эпох печатать примеры
batches_per_epoch = 1000
#сколько цепочек обрабатывать за 1 вызов функции обучения
batch_size=100
for epoch in xrange(n_epochs):
print "Генерируем текст в пропорциональном режиме"
generate_sample(proportional_s... | _____no_output_____ | MIT | week4/week4-ru - RNN - homework part.ipynb | LatatyeS/HSE_deeplearning |
A chance to speed up training and get bonus score* Try predicting next token probas at ALL ticks (like in the seminar part)* much more objectives, much better gradients* You may want to zero-out loss for first several iterations Конституция нового мирового правительства | seed = u"Каждый человек должен"
sampling_fun = proportional_sample_fun
result_length = 300
generate_sample(sampling_fun,seed,result_length)
seed = u"В случае неповиновения"
sampling_fun = proportional_sample_fun
result_length = 300
generate_sample(sampling_fun,seed,result_length)
И далее по списку | _____no_output_____ | MIT | week4/week4-ru - RNN - homework part.ipynb | LatatyeS/HSE_deeplearning |
*Accompanying code examples of the book "Introduction to Artificial Neural Networks and Deep Learning: A Practical Guide with Applications in Python" by [Sebastian Raschka](https://sebastianraschka.com). All code examples are released under the [MIT license](https://github.com/rasbt/deep-learning-book/blob/master/LICEN... | %load_ext watermark
%watermark -a 'Sebastian Raschka' -v -p tensorflow | Sebastian Raschka
CPython 3.6.1
IPython 6.0.0
tensorflow 1.2.0
| MIT | tensorflow1_ipynb/gan/gan.ipynb | tranhoangkhuongvn/deeplearning-models |
Model Zoo -- General Adversarial Networks Implementation of General Adversarial Nets (GAN) where both the discriminator and generator are multi-layer perceptrons with one hidden layer only. In this example, the GAN generator was trained to generate MNIST images.Uses- samples from a random normal distribution (range [-... | import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import pickle as pkl
tf.test.gpu_device_name()
### Abbreviatiuons
# dis_*: discriminator network
# gen_*: generator network
########################
### Helper functions
########################
def leaky_relu(x, al... | _____no_output_____ | MIT | tensorflow1_ipynb/gan/gan.ipynb | tranhoangkhuongvn/deeplearning-models |
Functions used: 1. importing csv files2. Changing directory3. Reading only specific columns into the dataframe4. Using del [ to delete a column ]5. Using .drop() [ to delete multiple columns ]6. Using .set_index() 1. Import The csv files: | import pandas as pd
import numpy as np
link = "C:\\Users\\MAHE\\Desktop\\Data Science\\Projects\\data\\banknifty" | _____no_output_____ | MIT | Data-Science-HYD-2k19/Projects/codes/PROJECT 1 (Jupiter ) ( Bank Nifty )/Merge BankNift and Data/BankNifty-Trial1-Copy1.ipynb | Sanjay9921/Python |
2. Get the current working directory to the location of the data: | import os
os.getcwd()
os.chdir(link) | _____no_output_____ | MIT | Data-Science-HYD-2k19/Projects/codes/PROJECT 1 (Jupiter ) ( Bank Nifty )/Merge BankNift and Data/BankNifty-Trial1-Copy1.ipynb | Sanjay9921/Python |
3. Read the csv file df = data frame | df = pd.read_csv("all_here.csv", sep = ",")
df.head()
df.tail() | _____no_output_____ | MIT | Data-Science-HYD-2k19/Projects/codes/PROJECT 1 (Jupiter ) ( Bank Nifty )/Merge BankNift and Data/BankNifty-Trial1-Copy1.ipynb | Sanjay9921/Python |
4. Reading the "CE" and "PE" from the columns to their resp. df: a. Reading "CE" into df_ce: | df_ce = df[df["Option Type"]=="CE"]
df_ce.head()
df_ce.tail() | _____no_output_____ | MIT | Data-Science-HYD-2k19/Projects/codes/PROJECT 1 (Jupiter ) ( Bank Nifty )/Merge BankNift and Data/BankNifty-Trial1-Copy1.ipynb | Sanjay9921/Python |
b. Reading "PE" into df_pe: | df_pe = df[df["Option Type"]=="PE"]
df_pe.head()
df_pe.tail() | _____no_output_____ | MIT | Data-Science-HYD-2k19/Projects/codes/PROJECT 1 (Jupiter ) ( Bank Nifty )/Merge BankNift and Data/BankNifty-Trial1-Copy1.ipynb | Sanjay9921/Python |
5. Discarding irrelevant columns: [ keep ,Expiry Date, Strike Price, Open, High, Low, Close ] Deleting only 1 column at a time: [ del ] | del df_ce["Symbol"] | _____no_output_____ | MIT | Data-Science-HYD-2k19/Projects/codes/PROJECT 1 (Jupiter ) ( Bank Nifty )/Merge BankNift and Data/BankNifty-Trial1-Copy1.ipynb | Sanjay9921/Python |
Deleting multiple columns at a time: [ .drop([".."],axis = 1) ] | df_ce = df_ce.drop(["Date","LTP","Settle Price","No. of contracts","Turnover in Lacs","Premium Turnover in Lacs","Open Int","Change in OI","Underlying Value"],axis = 1)
df_pe = df_pe.drop(["Date","LTP","Settle Price","No. of contracts","Turnover in Lacs","Premium Turnover in Lacs","Open Int","Change in OI","Underlying ... | _____no_output_____ | MIT | Data-Science-HYD-2k19/Projects/codes/PROJECT 1 (Jupiter ) ( Bank Nifty )/Merge BankNift and Data/BankNifty-Trial1-Copy1.ipynb | Sanjay9921/Python |
6. Set Expiry date as the index: [ set_index() ] | df_ce.set_index("Expiry",inplace = True)
df_ce.head()
df_pe.set_index("Expiry",inplace = True)
df_pe.head() | _____no_output_____ | MIT | Data-Science-HYD-2k19/Projects/codes/PROJECT 1 (Jupiter ) ( Bank Nifty )/Merge BankNift and Data/BankNifty-Trial1-Copy1.ipynb | Sanjay9921/Python |
Clean data | # Remove rows with zero cases
max_cases = [max(v) for v in df['cases']]
df['max_cases'] = max_cases
df_with_cases = df[df['max_cases'] > 0]
# Shuffle data
shuffled_df = df_with_cases.sample(frac=1)
# Break into train test (random k-fold cross val on the training set is done to pick hyperparams)
train_ratio, val_ratio,... | [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.625, 0.625, 3.375, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.625]
[... | MIT | modeling/04_prediction_time_series.ipynb | zheng-da/covid19-severity-prediction |
Predict deaths from cases | def create_case_to_death_data(df):
_cases = []
_deaths = []
_y_deaths = []
for i in range(len(df)):
row = df.iloc[i]
deaths = row['deaths']
cases = row['cases']
for j in range(len(deaths)):
if cases[j] > 0:
_cases.append(cases[j])
... | _____no_output_____ | MIT | modeling/04_prediction_time_series.ipynb | zheng-da/covid19-severity-prediction |
Binary Classification Fairness Assessment TemplateUse this template as a skeleton for comparing fairness and performance measures across a set of trained binary classification models. | # Recommended list of libraries (optional unless otherwise specified)
from fairmlhealth import report, measure # Required
import os
import pandas as pd | _____no_output_____ | MIT | templates/Template-BinaryClassificationAssessment.ipynb | masino-lab/fairMLHealth |
-------- Load (or Generate) Data and ModelsHere you should load (or generate) your test dataset and models. | # < Optional Loading/Cleaning/Training Code Here > | _____no_output_____ | MIT | templates/Template-BinaryClassificationAssessment.ipynb | masino-lab/fairMLHealth |
-------- Evaluate a Single (Baseline) Model Set the Required Variables * X (NumPy array or similar pandas object): test data to be passed to the models to generate predictions. It's recommended that these be separate data from those used to train the model.* y (NumPy array or similar pandas object): target data array... | # Set Pointers to be Passed to the Comparison Tools
X = None # <- add your test data
y = None # <- add your test labels
PA = None # if the protected attribute(s) is not present in the data,
model = None # add a dict or a list of trained, scikit-compatible models | _____no_output_____ | MIT | templates/Template-BinaryClassificationAssessment.ipynb | masino-lab/fairMLHealth |
---- | report.compare(X, y, PA, model, pred_type = "classificationmeasure.data(X, y)")
measure.data(X, y)
measure.performance(X, y, y_pred=model.predict(X), y_prob=model_1.predict_proba(X_test), pred_type="classification")
measure.bias(X, y, model.predict(X), pred_type="classification") | _____no_output_____ | MIT | templates/Template-BinaryClassificationAssessment.ipynb | masino-lab/fairMLHealth |
Apply to a test image to check performance | # sdir = '/Users/Tyler-SFG/Desktop/Box Sync/SFG Centralized Resources/Projects/Aquaculture/Waitt Aquaculture/aqua-mapping/aqua-mapping-data/aqua-images/planet/planet_order_242451/20180830_154418_0f3c'
# planet2chips(tiff_directory = sdir, chip_directory = sdir, chip_size = 512) | _____no_output_____ | MIT | notebooks/process_planet_scenes.ipynb | tclavelle/aqua_python |
Now we need a function to copy the VGG project templates and via.html files into each chip directory so that the chips can be labeled. | def process_planet_orders(source_dir, target_dir):
"""Find unique PlanetScope scenes in a directory of Planet order folders
and process newly added scenes into image chips"""
# Get list of all planet orders in source directory
orders = np.array(next(os.walk(source_dir))[1])
# Add full path... | _____no_output_____ | MIT | notebooks/process_planet_scenes.ipynb | tclavelle/aqua_python |
Apply the function to process all Planet orders presently in Box | # Run function
sdir = '/Users/Tyler-SFG/Desktop/Box Sync/SFG Centralized Resources/Projects/Aquaculture/Waitt Aquaculture/aqua-mapping/aqua-mapping-data/aqua-images/planet'
tdir = '/Users/Tyler-SFG/Desktop/Box Sync/SFG Centralized Resources/Projects/Aquaculture/Waitt Aquaculture/aqua-mapping/aqua-mapping-data/aqua-imag... | 141
/Users/Tyler-SFG/Desktop/Box Sync/SFG Centralized Resources/Projects/Aquaculture/Waitt Aquaculture/aqua-mapping/aqua-mapping-data/aqua-images/planet/planet_order_236949/20180825_231532_1_0f3c
filename: 20180825_231532_1_0f3c_3B_AnalyticMS_SR.tif
image name: 20180825_231532_1
(4, 4510, 8605)
| MIT | notebooks/process_planet_scenes.ipynb | tclavelle/aqua_python |
Move tiff files for labeled chipsAfter a Planet scene is processed into tiff and png chips, the pngs containing objects are added to a VGG project and labeled. Labels are then saved in a `[batchname]_labels.json` file. The last step prior to uploading the chips to Tana is to create a new directory for the chip contain... | # Function to copy the tiffs of PNGs selected for labeling and make directories for each chip
def copy_chip_tiffs(label_dir, chips_dir, prepped_dir):
""" Take a VGG labeling project with PNGs and create a directory
for each chip in the prepped directory
"""
# Read annotations
pngs = os.listdir(... | _____no_output_____ | MIT | notebooks/process_planet_scenes.ipynb | tclavelle/aqua_python |
Run function to copy tifs for selected PNGs | # Copy tiffs for chile cages
labels = '/Users/Tyler-SFG/Desktop/Box Sync/SFG Centralized Resources/Projects/Aquaculture/Waitt Aquaculture/aqua-mapping/aqua-mapping-data/aqua-images/vgg/labeled/label_china/pngs'
prepped_dir = '/Users/Tyler-SFG/Desktop/Box Sync/SFG Centralized Resources/Projects/Aquaculture/Waitt Aquacul... | _____no_output_____ | MIT | notebooks/process_planet_scenes.ipynb | tclavelle/aqua_python |
Now we need a function to create the class masks for each image | def masks_from_labels(labels, prepped_dir):
# Read annotations
annotations = json.load(open(labels))
annotations = list(annotations.values()) # don't need the dict keys
# The VIA tool saves images in the JSON even if they don't have any
# annotations. Skip unannotated images.
annotati... | _____no_output_____ | MIT | notebooks/process_planet_scenes.ipynb | tclavelle/aqua_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.