markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
We now use the plotting library <tt>matplotlib</tt> available in Python to visualize the measurements.
import matplotlib.pyplot as plt plt.ion() fig1 = plt.figure(num=None, figsize=(10, 6), dpi=80, facecolor='w', edgecolor='k') fig1.set_tight_layout(False) plt.plot(r, avg_rdf, '-', color="#A60628", linewidth=2, alpha=1) plt.xlabel('r $[\sigma]$', fontsize=20) plt.ylabel('$g(r)$', fontsize=20) plt.show() fig2 = plt.fig...
doc/tutorials/01-lennard_jones/01-lennard_jones.ipynb
psci2195/espresso-ffans
gpl-3.0
The first column of this array contains the lag time in units of the time step. The second column contains the number of values used to perform the averaging of the correlation. The next three columns contain the x, y and z mean squared displacement of the msd of the first particle. The next three columns then contain ...
fig3 = plt.figure(num=None, figsize=(10, 6), dpi=80, facecolor='w', edgecolor='k') fig3.set_tight_layout(False) lag_time = msd[:, 0] for i in range(0, N_PART, 30): msd_particle_i = msd[:, 2+i*3] + msd[:, 3+i*3] + msd[:, 4+i*3] plt.plot(lag_time, msd_particle_i, 'o-', linewidth=2, label="particle id...
doc/tutorials/01-lennard_jones/01-lennard_jones.ipynb
psci2195/espresso-ffans
gpl-3.0
如下图分别是训练数据"train.csv"和“store.csv”的大致结构,显示头5行的数据内容。从中我们大致了解了有哪些数据特征
for name in names[:2]: display(Image('C:/Users/Administrator/Desktop/report/' + name, width=800))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
先探索一下销售额是否和处于一周的第几天有关,填补缺失值,默认周天以外的时间商店都是处于“open”状态,有如下图的情况,由此可以看出销售额与周几的一些关系
for name in names[2:3]: display(Image('C:/Users/Administrator/Desktop/report/' + name, width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
通过将时间数据进行清理,再探索一下销售额与时间(月)的关系,如下图所示展示了平均销售额与月份的关系以及百分比改变状况。
display(Image('C:/Users/Administrator/Desktop/report/' + "4.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
这个图就比较清晰地表明了销售额与月份有着密切地关系,月份对于销售额比较大地影响。这个特征需要重视。 再比较年份的销售和每年到访的用户数量,如下图所示
display(Image('C:/Users/Administrator/Desktop/report/' + "5.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
从图中可以得知年份用户数量有一定关系,但关系不是很大 接下来用box-plot和折线图分析下月份和用户数量的关系
display(Image('C:/Users/Administrator/Desktop/report/' + "6.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
由此可知用户数量和月份是紧密相关的,这个趋势图和月份与销售额的很像,这样就容易推理出,用户数量基本上决定了销售额。为了验证我们的想法,我们在更细小的时间段进行验证,下面我以星期为验证,看看用户和销售额的关系
display(Image('C:/Users/Administrator/Desktop/report/' + "7.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
由上图能非常明显的看出,我们的推理得到了验证:“销售额的变化基本是和用户数量的变化是一致的,百分比变化几乎完全一样” 现在来看看促销对销售额与顾客数量是否明显的影响
display(Image('C:/Users/Administrator/Desktop/report/' + "8.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
如图可知,促销对于顾客数量以及销售额都有着显著的影响,程度上来说,对于销售额的影响大于对用户数量的影响,因此可以推断出促销一定程度上能提升客单价。 接下来可以看看a、b、c三种state假日在总天数中的占比情况,以及有无state对于销售额和用户的影响
display(Image('C:/Users/Administrator/Desktop/report/' + "9.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
接下来看看学校放假对于销售额和用户量的影响
display(Image('C:/Users/Administrator/Desktop/report/' + "11.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
然后可以再分析下客户量和销售额的关系,下图基本能大致说清楚客户数量与客单价的联系了
display(Image('C:/Users/Administrator/Desktop/report/' + "12.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
由此其实可以推断过度的促销可能使得客单价偏低,有点得不偿失,因此应该控制好平衡。 之后看看将“store”的各种特征合并到“train”后的一些情况,比如店铺不同类型的占比数量,以及不同类型店铺对于销售额和用户量的影响
display(Image('C:/Users/Administrator/Desktop/report/' + "13.png", width=1000)) display(Image('C:/Users/Administrator/Desktop/report/' + "14.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
长期促销销售额对于用户数量的影响,如下图
display(Image('C:/Users/Administrator/Desktop/report/' + "15.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
然后再看一个比较关键的特征,一般竞争者们之间的距离和销售额的关系。形状比较像正态分布
display(Image('C:/Users/Administrator/Desktop/report/' + "16.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
竞争开始时,商店的平均销售额在一段时间内发生了什么事? 我通过一个店铺进行了演示:store_id = 6的平均销售额自竞争开始以来急剧下降。
display(Image('C:/Users/Administrator/Desktop/report/' + "17.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
2.2算法与方法 先从特征开始讲起把: 从上述部分可以看出,仅通过使用客户数量数据或仅仅是促销是不能能预测销售的。销售受到每个属性的影响。为了对销售进行预测,首先我们将摆脱“客户”功能和“销售”功能中的异常值,因为数字过高或过低可能会出现异常情况。 这样的数据会影响模型的精度。处理异常值后,我们可以开始预处理数据。这包括摆脱Null值,encoding一些特征,如StoreType,StateHoliday等。 处理Missing Data是根据特征的现实意义进行填补和丢弃的,比如除每个星期天外,我都默认商店是处于“open”状态的,这比较符合我们的生活常识 如前所述,日期的转换对于预测而言是非常重要的,这也是视觉化中证明的,因为日...
display(Image('C:/Users/Administrator/Desktop/report/' + "19.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
如图所见,商店,DayOfWeek和Date是最重要的feature,似乎在销售上有最大的差异。 这个预测是正确的。 另一方面,假期和促销也似乎有很大的差异,但这些特征已经被降低了 这里有我后来用xgboost实现了低于0.1的error的时候进行的特征的分析,和上面的结果有较显著的区别,如下图所示。尤其是排名3-10的特征,在xgboost运算后明显有了更大的权重,也就是说,xgboost更具有发现特征对于预测结果的能力,不像单模型那样过于简单,靠常识也能知道过于依赖某个特征可信度会有比较大风险。所以最后结果也自然有了区别
display(Image('C:/Users/Administrator/Desktop/report/' + "20.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
5.2思考 项目的分析最初是项目的一个有意义的部分,因为它能够告诉我们哪个功能会影响销售,几乎和DecisionTree回归函数的feature_importance属性一样。 由于数据未进行预处理,因此在数据可视化方面存在困难。 数据中有很多NaN值在几乎每个阶段都在降低产出的质量。 我预计最终的模型要花费更少的时间,但训练时间不是以小时计算的话根本不重要。 优化模型是一个挑战,因为处理的索引错误(如代码中所述)。 现在这个模型可以用于预测销售,即使有更多的商店或不同的业务来了,如果有类似的功能,那么这个模型可以用于适当的预测 如何将模型应用在商业上 理想的方法是(需要检查与业务,看看我们是否需要包括他们的任何一个实施以下...
display(Image('C:/Users/Administrator/Desktop/report/' + "21.png", width=1000)) display(Image('C:/Users/Administrator/Desktop/report/' + "22.png", width=1000))
CapstonePoject/capstone_report.ipynb
littlewizardLI/Udacity-ML-nanodegrees
apache-2.0
Preprocess To do anything useful with it, we'll need to turn the each string into a list of characters: <img src="images/source_and_target_arrays.png"/> Then convert the characters to their int values as declared in our vocabulary:
def extract_character_vocab(data): special_words = ['<PAD>', '<UNK>', '<GO>', '<EOS>'] set_words = set([character for line in data.split('\n') for character in line]) int_to_vocab = {word_i: word for word_i, word in enumerate(special_words + list(set_words))} vocab_to_int = {word: word_i for word_i, w...
seq2seq/sequence_to_sequence_implementation.ipynb
abhi1509/deep-learning
mit
Set up the decoder components - Embedding - Decoder cell - Dense output layer - Training decoder - Inference decoder 1- Embedding Now that we have prepared the inputs to the training decoder, we need to embed them so they can be ready to be passed to the decoder. We'll create an embedding matrix l...
def decoding_layer(target_letter_to_int, decoding_embedding_size, num_layers, rnn_size, target_sequence_length, max_target_sequence_length, enc_state, dec_input): target_vocab_size = len(target_letter_to_int) # 1. Decoder Embedding dec_embeddings = tf.Variable(tf.random_uniform([tar...
seq2seq/sequence_to_sequence_implementation.ipynb
abhi1509/deep-learning
mit
Model outputs training_decoder_output and inference_decoder_output both contain a 'rnn_output' logits tensor that looks like this: <img src="images/logits.png"/> The logits we get from the training tensor we'll pass to tf.contrib.seq2seq.sequence_loss() to calculate the loss and ultimately the gradient.
# Build the graph train_graph = tf.Graph() # Set the graph to default to ensure that it is ready for training with train_graph.as_default(): # Load the model inputs input_data, targets, lr, target_sequence_length, max_target_sequence_length, source_sequence_length = get_model_inputs() # Create...
seq2seq/sequence_to_sequence_implementation.ipynb
abhi1509/deep-learning
mit
Preprocessing tweets Next step is to look at tweets and see if we can preprocess them so they work better for our model. We want to convert each to tweet a list of words. As an input we have tweets which are unicode strings. I simply convert them to list of words by splitting on whitespaces. Then, I do these conversion...
from src.data.dataset import run_interactive_processed_data_generation # When prompt for folder name, insert 'gathered_dataset' run_interactive_processed_data_generation() # data will be saved in data/gathered_dataset/processed/training_set.txt (script shows a relative path)
Notebook.ipynb
mikolajsacha/tweetsclassification
mit
Embedding tweets We have aquired a Word Embedding which allows us to get a vector of numbers for each word. However, our training set consists of lists of words, so we need to specify how to represent a sentence (tweet) based on representations of its words. I test two different approaches:<br> <br> First is to simply ...
# 3D visualization of sentence embeddings, similar to visualization of word embeddings. # It transforms sentence vectors to 3 dimensions using PCA trained on them. # Colors of sentences align with their category from src.visualization.visualize_sentence_embeddings import visualize_sentence_embeddings from src.features...
Notebook.ipynb
mikolajsacha/tweetsclassification
mit
Finding the best model hyperparameters I chose four standard classifiers from sklearn package to test: SVC (SVM Classifier) RandomForestClassifier MLPClassifier (Multi-Layer Perceptron classifier - neural network) KNeighborsClassifier (classification by k-nearest neighbors). For all these methods, I defined a se...
# run grid search on chosen models # consider doing a backup of text summary files from /summary folder before running this script from src.common import DATA_FOLDER, FOLDS_COUNT, CLASSIFIERS_PARAMS, \ SENTENCE_EMBEDDINGS, CLASSIFIERS_WRAPPERS, WORD_EMBEDDINGS from src.models.model_testing.grid_...
Notebook.ipynb
mikolajsacha/tweetsclassification
mit
Applying PCA Until now, I applied PCA several times to make plotting 2D or 3D figures possible. Maybe there is a chance that applying a well fit Principal Component Analysis to our data set will increase model accuracy. The possible option is to fit PCA to our sentece vectors. Then we can train model on sentence vector...
# training for PCA visualization may take a while, so I also use a summary file for storing the results from src.visualization.visualize_pca import visualize_pca from src.common import choose_classifier classifier_class = choose_classifier() visualize_pca(classifier_class, n_jobs=-1)
Notebook.ipynb
mikolajsacha/tweetsclassification
mit
Expanding training set After having a way to choose the best parameters for a model I modified the script for mining tweets. In the beginning I used keywords to search for tweets possibly fit for the training set. This gave me quite clear tweets, but may seem my models not general, because they fit mostly to those keyw...
from src.data.data_gathering.tweet_miner import mine_tweets # At first, we train the best possible model we have so far (searching in grid search results files) # Then, we run as many threads as CPU cores, or two if there is only one core. # First thread reads stream from Twitter API and puts all tweets in a synchrono...
Notebook.ipynb
mikolajsacha/tweetsclassification
mit
Some analysis Having performed grid search on several models, we can analyse how various hyperparameters perform. Use script below to see some plots showing cross-validation performance for different parameters.
# compare how different sentence embedding perform for all tested models from src.common import SENTENCE_EMBEDDINGS from src.visualization.compare_sentence_embeddings import get_grid_search_results_by_sentence_embeddings from src.visualization.compare_sentence_embeddings import compare_sentence_embeddings_bar_chart se...
Notebook.ipynb
mikolajsacha/tweetsclassification
mit
Luego de hacer la importación de las librerías que se van a utilizar, en la función main_eos() definida por un usuario se realiza la especificación de la sustancia pura junto con el modelo de ecuación de estado y parámetros que se requieren en la función "pt.function_elv(components, Vc, Tc, Pc, omega, k, d1)" que reali...
def main_eos(): print("-" * 79) components = ["METHANE"] MODEL = "PR" specification = "constants" component_eos = pt.parameters_eos_constans(components, MODEL, specification) #print(component_eos) #print('-' * 79) methane = component_eos[component_eos.index==components] #print(m...
Envolvente.ipynb
pysg/pyther
mit
9.4 Resultados Se obtiene el diagrama de fases líquido-vapor de una sustancia pura utilizando el método function_elv(components, Vc, Tc, Pc, omega, k, d1) de la librería pyther. Se observa que la función anterior main_eos() puede ser reemplazada por un bloque de widgets que simplifiquen la interfaz gráfica con los usua...
volumen = envolvente[0][0] presion = envolvente[0][1] Vc, Pc = envolvente[1], envolvente[2] plt.plot(volumen,presion) plt.scatter(Vc, Pc) plt.xlabel('Volumen [=] $mol/cm^3$') plt.ylabel('Presión [=] bar') plt.grid(True) plt.text(Vc * 1.4, Pc * 1.01, "Punto critico")
Envolvente.ipynb
pysg/pyther
mit
If we specify the carbon source, we can also get the carbon and mass yield. For example, temporarily setting the objective to produce acetate instead we could get production envelope as follows and pandas to quickly plot the results.
prod_env = production_envelope( model, ["EX_o2_e"], objective="EX_ac_e", c_source="EX_glc__D_e") prod_env.head() %matplotlib inline prod_env[prod_env.direction == 'maximum'].plot( kind='line', x='EX_o2_e', y='carbon_yield')
documentation_builder/phenotype_phase_plane.ipynb
zakandrewking/cobrapy
lgpl-2.1
That layer when called with a list of sentences will create a sentence vector for each sentence by averaging the word vectors of the sentence.
outputs = med_embed(tf.constant(["ilium", "I have a fracture", "aneurism"])) outputs
notebooks/text_models/solutions/custom_tf_hub_word_embedding.ipynb
GoogleCloudPlatform/asl-ml-immersion
apache-2.0
Loading files and dealing with local I/O
import os print os.getcwd() print os.path.abspath("./") # find out "where you are" and "where Data folder is" with these commands
LogReg-sklearn.ipynb
ernestyalumni/MLgrabbag
mit
Let's load the data for Exercise 2 of Machine Learning, taught by Andrew Ng, of Coursera.
ex2data1 = np.loadtxt("./Data/ex2data1.txt",delimiter=',') # you, the user, may have to change this, if the directory that you're running this from is somewhere else ex2data2 = np.loadtxt("./Data/ex2data2.txt",delimiter=',') X_ex2data1 = ex2data1[:,0:2] Y_ex2data1 = ex2data1[:,2] X_ex2data2 = ex2data2[:,:2] Y_ex2data...
LogReg-sklearn.ipynb
ernestyalumni/MLgrabbag
mit
Get the probability estimates; say a student has an Exam 1 score of 45 and an Exam 2 score of 85.
logreg.predict_proba(np.array([[45,85]])).flatten() print "The student has a probability of no admission of %s and probability of admission of %s" % tuple( logreg.predict_proba(np.array([[45,85]])).flatten() )
LogReg-sklearn.ipynb
ernestyalumni/MLgrabbag
mit
Let's change the "regularization" with the C parameter/option for LogisticRegression. Call this logreg2
logreg2 = linear_model.LogisticRegression() logreg2.fit(X_ex2data2,Y_ex2data2) xx_ex2data2, yy_ex2data2 = trainingdat2mesh(X_ex2data2,h=0.02) Z_ex2data2 = logreg.predict(np.c_[xx_ex2data2.ravel(),yy_ex2data2.ravel()]) Z_ex2data2 = Z_ex2data2.reshape(xx_ex2data2.shape) plt.figure(3) plt.pcolormesh(xx_ex2data2,yy_ex2d...
LogReg-sklearn.ipynb
ernestyalumni/MLgrabbag
mit
As one can see, the "dataset cannot be separated into positive and negative examples by a straight-line through the plot." cf. ex2.pdf We're going to need polynomial terms to map onto. Use this code: cf. Underfitting vs. Overfitting¶
from sklearn.pipeline import Pipeline from sklearn.preprocessing import PolynomialFeatures polynomial_features = PolynomialFeatures(degree=6,include_bias=False) pipeline = Pipeline([("polynomial_features", polynomial_features),("logistic_regression",logreg2)]) pipeline.fit(X_ex2data2,Y_ex2data2) Z_ex2data2 = pipeli...
LogReg-sklearn.ipynb
ernestyalumni/MLgrabbag
mit
The principal component score Vector of Hydrophobic, Steric, and Electronic properties (VHSE) is a set of amino acid descriptors that come from A new set of amino acid descriptors and its application in peptide QSARs VHSE1 and VHSE2 are related to hydrophobic (H) properties, VHSE3 and VHSE4 to steric (S) properties,...
# (3-letter, VHSE1, VHSE2, VHSE3, VHSE4, VHSE5, VHSE6, VHSE7, VHSE8) vhse = { "A": ("Ala", 0.15, -1.11, -1.35, -0.92, 0.02, -0.91, 0.36, -0.48), "R": ("Arg", -1.47, 1.45, 1.24, 1.27, 1.55, 1.47, 1.30, 0.83), "N": ("Asn", -0.99, 0.00, -0.37, 0.69, -0.55, 0.85, 0.73, -0.80), "D": ("Asp", -1.15, 0.67, -0.41, -0.01, -2.68,...
VHSE-Based Prediction of Proteasomal Cleavage Sites.ipynb
massie/notebooks
apache-2.0
There were eight dataset used in this study. The reference datasets (s1, s3, s5, s7) were converted into the actual datasets used in the analysis (s2, s4, s6, s8) using the vhse vector. The s2 and s4 datasets were used for training the SVM model and the s6 and s8 were used for testing.
%ls data/proteasomal_cleavage from aa_props import seq_to_aa_props # Converts the raw input into our X matrix and y vector. The 'peptide_key' # and 'activity_key' parameters are the names of the column in the dataframe # for the peptide amino acid string and activity (not cleaved/cleaved) # respectively. The 'sequenc...
VHSE-Based Prediction of Proteasomal Cleavage Sites.ipynb
massie/notebooks
apache-2.0
Creating the In Vivo Data To create the in vivo training set, the authors Queried the AntiJen database (7,324 MHC-I ligands) Removed ligands with unknown source protein in ExPASy/SWISS-PROT (6036 MHC-I ligands) Removed duplicate ligands (3,148 ligands) Removed the 231 ligands used for test samples by Saxova et al, (2,...
training_set = pd.DataFrame.from_csv("data/proteasomal_cleavage/s2_in_vivo_mhc_1_antijen_swiss_prot_dataset.csv") print training_set.head(3)
VHSE-Based Prediction of Proteasomal Cleavage Sites.ipynb
massie/notebooks
apache-2.0
Creating the Linear SVM Model The authors measured linear, polynomial, radial basis, and sigmoid kernel and found no significant difference in performance. The linear kernel was chosen for its simplicity and interpretability. The authors did not provide the C value used in their linear model, so I used GridSearchCV to ...
from sklearn.model_selection import GridSearchCV from sklearn.feature_selection import RFECV def create_linear_svc_model(parameters, sequence_len = 28, use_vhse = True): scaler = MinMaxScaler() (X_train_unscaled, y_train) = dataset_to_X_y(training_set, \ "Sequence",...
VHSE-Based Prediction of Proteasomal Cleavage Sites.ipynb
massie/notebooks
apache-2.0
Testing In Vivo SVM Model
def test_linear_svc_model(scaler, model, sequence_len = 28, use_vhse = True): testing_set = pd.DataFrame.from_csv("data/proteasomal_cleavage/s6_in_vivo_mhc_1_ligands_dataset.csv") (X_test_prescaled, y_test) = dataset_to_X_y(testing_set, \ "Sequences", "Activity", ...
VHSE-Based Prediction of Proteasomal Cleavage Sites.ipynb
massie/notebooks
apache-2.0
Comparing Linear SVM to PAProC, FragPredict, and NetChop Interpreting Model Weights <img src="images/journal.pone.0074506.g002.png" align="left" border="0"/> The VHSE1 variable at the P1 position has the largest positive weight coefficient (10.49) in line with research showing that C-terminal residues are usually hydr...
#h = svr.coef_[:, 0::3] #s = svr.coef_[:, 1::3] #e = svr.coef_[:, 2::3] #%matplotlib notebook #n_groups = h.shape[1] #fig, ax = plt.subplots(figsize=(12,9)) #index = np.arange(n_groups) #bar_width = 0.25 #ax1 = ax.bar(index + bar_width, h.T, bar_width, label="Hydrophobic", color='b') #ax2 = ax.bar(index, s.T, bar_...
VHSE-Based Prediction of Proteasomal Cleavage Sites.ipynb
massie/notebooks
apache-2.0
PCA vs. full matrices Principal component analysis (PCA) is a statistical procedure that uses an orthogonal transformation to convert a set of observations of possibly correlated variables into a set of values of linearly uncorrelated variables called principal components Source. Mei et al, creators of the VHSE, appli...
# Performance with no VHSE (no_vhse_scaler, no_vhse_model) = create_linear_svc_model( parameters = {'C': [0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1]}, use_vhse = False) test_linear_svc_model(no_vhse_scaler, no_vhse_model, use_vhse = False) # Performance with more flanking residues and no VHSE (full_flank_scaler, f...
VHSE-Based Prediction of Proteasomal Cleavage Sites.ipynb
massie/notebooks
apache-2.0
Importing Libraries
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np import nltk nltk.download('stopwords') nltk.download('punkt') from nltk.corpus import stopwords from nltk.util import ngrams from sklearn.feature_extraction.text import CountVectorizer from collections import defaultdict from c...
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Load data
tweet= pd.read_csv('./data/train.csv') test=pd.read_csv('./data/test.csv') tweet.head(3) print('There are {} rows and {} columns in train'.format(tweet.shape[0],tweet.shape[1])) print('There are {} rows and {} columns in train'.format(test.shape[0],test.shape[1]))
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Removing urls
def remove_URL(text): url = re.compile(r'https?://\S+|www\.\S+') return url.sub(r'',text) df['text']=df['text'].apply(lambda x : remove_URL(x))
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Removing HTML tags
def remove_html(text): html=re.compile(r'<.*?>') return html.sub(r'',text) df['text']=df['text'].apply(lambda x : remove_html(x))
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Removing Emojis
# Reference : https://gist.github.com/slowkow/7a7f61f495e3dbb7e3d767f97bd7304b def remove_emoji(text): emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols & pictographs u"\U0001F680-...
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Removing punctuations
def remove_punct(text): table=str.maketrans('','',string.punctuation) return text.translate(table) df['text']=df['text'].apply(lambda x : remove_punct(x))
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Spelling Correction Even if I'm not good at spelling I can correct it with python :) I will use pyspellcheker to do that. Corpus Creation
def create_corpus(df): corpus=[] for tweet in tqdm(df['text']): words=[word.lower() for word in word_tokenize(tweet) if((word.isalpha()==1) & (word not in stop))] corpus.append(words) return corpus corpus=create_corpus(df)
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Download Glove
# download files import wget import zipfile wget.download("http://nlp.stanford.edu/data/glove.6B.zip", './glove.6B.zip') with zipfile.ZipFile("glove.6B.zip", 'r') as zip_ref: zip_ref.extractall("./")
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Embedding Step
embedding_dict={} with open("./glove.6B.100d.txt",'r') as f: for line in f: values=line.split() word=values[0] vectors=np.asarray(values[1:],'float32') embedding_dict[word]=vectors f.close() MAX_LEN=50 tokenizer_obj=Tokenizer() tokenizer_obj.fit_on_texts(corpus) sequences=tokenizer_...
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Baseline Model
model=Sequential() embedding=Embedding(num_words,100,embeddings_initializer=Constant(embedding_matrix), input_length=MAX_LEN,trainable=False) model.add(embedding) model.add(SpatialDropout1D(0.2)) model.add(LSTM(64, dropout=0.2, recurrent_dropout=0.2)) model.add(Dense(1, activation='sigmoid')) opt...
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Training Model
history=model.fit(X_train,y_train,batch_size=4,epochs=5,validation_data=(X_test,y_test),verbose=2)
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
Making our submission
sample_sub=pd.read_csv('./data/sample_submission.csv') y_pre=model.predict(final_test) y_pre=np.round(y_pre).astype(int).reshape(3263) sub=pd.DataFrame({'id':sample_sub['id'].values.tolist(),'target':y_pre}) sub.to_csv('submission.csv',index=False) sub.head()
natural-language-processing-with-disaster-tweets-kaggle-competition/natural-language-processing-with-disaster-tweets-kale.ipynb
kubeflow/examples
apache-2.0
so that is the benchmark to beat, we will export our expressions as Cython code. We then subclass ODEsys to have it render, compile and import the code:
# %load ../scipy2017codegen/odesys_cython.py import uuid import numpy as np import sympy as sym import setuptools import pyximport from scipy2017codegen import templates from scipy2017codegen.odesys import ODEsys pyximport.install() cython_template = """ cimport numpy as cnp import numpy as np def f(cnp.ndarray[cnp....
notebooks/40-chemical-kinetics-cython.ipynb
sympy/scipy-2017-codegen-tutorial
bsd-3-clause
That is a considerable speed up from before. But the solver still has to allocate memory for creating new arrays at each call, and each evaluation has to pass the python layer which is now the bottleneck for the integration. In order to speed up integration further we need to make sure the solver can evaluate the funct...
import matplotlib.pyplot as plt %matplotlib inline
notebooks/40-chemical-kinetics-cython.ipynb
sympy/scipy-2017-codegen-tutorial
bsd-3-clause
Just to see that everything looks alright:
fig, ax = plt.subplots(1, 1, figsize=(14, 6)) cython_sys.plot_result(tout, *cython_sys.integrate_odeint(tout, y0), ax=ax) ax.set_xscale('log') ax.set_yscale('log')
notebooks/40-chemical-kinetics-cython.ipynb
sympy/scipy-2017-codegen-tutorial
bsd-3-clause
Kets are column vectors, i.e. with shape (d, 1):
qu(data, qtype='ket')
docs/basics.ipynb
jcmgray/quijy
mit
The normalized=True option can be used to ensure a normalized output. Bras are row vectors, i.e. with shape (1, d):
qu(data, qtype='bra') # also conjugates the data
docs/basics.ipynb
jcmgray/quijy
mit
And operators are square matrices, i.e. have shape (d, d):
qu(data, qtype='dop')
docs/basics.ipynb
jcmgray/quijy
mit
Which can also be sparse:
qu(data, qtype='dop', sparse=True) psi = 1.0j * bell_state('psi-') psi psi.H psi = up() psi psi.H @ psi # inner product X = pauli('X') X @ psi # act as gate psi.H @ X @ psi # operator expectation expec(psi, psi) expec(psi, X)
docs/basics.ipynb
jcmgray/quijy
mit
Here's an example for a much larger (20 qubit), sparse operator expecation, which will be automatically parallelized:
psi = rand_ket(2**20) A = rand_herm(2**20, sparse=True) + speye(2**20) A expec(A, psi) # should be ~ 1 %%timeit expec(A, psi) dims = [2] * 10 # overall space of 10 qubits X = pauli('X') IIIXXIIIII = ikron(X, dims, inds=[3, 4]) # act on 4th and 5th spin only IIIXXIIIII.shape dims = [2] * 3 XZ = pauli('X') & pauli...
docs/basics.ipynb
jcmgray/quijy
mit
Column expression A Spark column instance is NOT a column of values from the DataFrame: when you crate a column instance, it does not give you the actual values of that column in the DataFrame. I found it makes more sense to me if I consider a column instance as a column of expressions. These expressions are evaluated ...
mtcars = spark.read.csv('../../data/mtcars.csv', inferSchema=True, header=True) mtcars = mtcars.withColumnRenamed('_c0', 'model') mtcars.show(5)
notebooks/02-data-manipulation/2.7.1-column-expression.ipynb
MingChen0919/learning-apache-spark
mit
Part 1: Featurize categorical data using one-hot-encoding (1a) One-hot-encoding We would like to develop code to convert categorical features to numerical ones, and to build intuition, we will work with a sample unlabeled dataset with three data points, with each data point representing an animal. The first feature ...
# Data for manual OHE # Note: the first data point does not include any value for the optional third feature sampleOne = [(0, 'mouse'), (1, 'black')] sampleTwo = [(0, 'cat'), (1, 'tabby'), (2, 'mouse')] sampleThree = [(0, 'bear'), (1, 'black'), (2, 'salmon')] sampleDataRDD = sc.parallelize([sampleOne, sampleTwo, sampl...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
WARNING: If test_helper, required in the cell below, is not installed, follow the instructions here.
# TEST One-hot-encoding (1a) from test_helper import Test Test.assertEqualsHashed(sampleOHEDictManual[(0,'bear')], 'b6589fc6ab0dc82cf12099d1c2d40ab994e8410c', "incorrect value for sampleOHEDictManual[(0,'bear')]") Test.assertEqualsHashed(sampleOHEDictManual[(0,'cat')], ...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(1b) Sparse vectors Data points can typically be represented with a small number of non-zero OHE features relative to the total number of features that occur in the dataset. By leveraging this sparsity and using sparse vector representations of OHE data, we can reduce storage and computational burdens. Below are a f...
import numpy as np from pyspark.mllib.linalg import SparseVector # TODO: Replace <FILL IN> with appropriate code aDense = np.array([0., 3., 0., 4.]) aSparse = SparseVector(len(aDense), range(0,len(aDense)), aDense) bDense = np.array([0., 0., 0., 1.]) bSparse = SparseVector(len(bDense), range(0,len(bDense)), bDense) ...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(1c) OHE features as sparse vectors Now let's see how we can represent the OHE features for points in our sample dataset. Using the mapping defined by the OHE dictionary from Part (1a), manually define OHE features for the three sample data points using SparseVector format. Any feature that occurs in a point should ...
# Reminder of the sample features # sampleOne = [(0, 'mouse'), (1, 'black')] # sampleTwo = [(0, 'cat'), (1, 'tabby'), (2, 'mouse')] # sampleThree = [(0, 'bear'), (1, 'black'), (2, 'salmon')] # TODO: Replace <FILL IN> with appropriate code sampleOneOHEFeatManual = SparseVector(7, [2,3], np.array([1.0,1.0])) sampleTwoO...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(1d) Define a OHE function Next we will use the OHE dictionary from Part (1a) to programatically generate OHE features from the original categorical data. First write a function called oneHotEncoding that creates OHE feature vectors in SparseVector format. Then use this function to create OHE features for the first ...
# TODO: Replace <FILL IN> with appropriate code def oneHotEncoding_old(rawFeats, OHEDict, numOHEFeats): """Produce a one-hot-encoding from a list of features and an OHE dictionary. Note: You should ensure that the indices used to create a SparseVector are sorted. Args: rawFeats (list of ...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(1e) Apply OHE to a dataset Finally, use the function from Part (1d) to create OHE features for all 3 data points in the sample dataset.
# TODO: Replace <FILL IN> with appropriate code def toOHE(row): return oneHotEncoding(row,sampleOHEDictManual,numSampleOHEFeats) sampleOHEData = sampleDataRDD.map(toOHE) print sampleOHEData.collect() # TEST Apply OHE to a dataset (1e) sampleOHEDataValues = sampleOHEData.collect() Test.assertTrue(len(sampleOHEData...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
Part 2: Construct an OHE dictionary (2a) Pair RDD of (featureID, category) To start, create an RDD of distinct (featureID, category) tuples. In our sample dataset, the 7 items in the resulting RDD are (0, 'bear'), (0, 'cat'), (0, 'mouse'), (1, 'black'), (1, 'tabby'), (2, 'mouse'), (2, 'salmon'). Notably 'black' appea...
flat = sampleDataRDD.flatMap(lambda r: r).distinct() print flat.count() for i in flat.take(8): print i # TODO: Replace <FILL IN> with appropriate code sampleDistinctFeats = (sampleDataRDD.flatMap(lambda r: r).distinct()) # TEST Pair RDD of (featureID, category) (2a) Test.assertEquals(sorted(sampleDistinctFeats.co...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(2b) OHE Dictionary from distinct features Next, create an RDD of key-value tuples, where each (featureID, category) tuple in sampleDistinctFeats is a key and the values are distinct integers ranging from 0 to (number of keys - 1). Then convert this RDD into a dictionary, which can be done using the collectAsMap acti...
# TODO: Replace <FILL IN> with appropriate code sampleOHEDict = sampleDistinctFeats.zipWithIndex().collectAsMap() print sampleOHEDict # TEST OHE Dictionary from distinct features (2b) Test.assertEquals(sorted(sampleOHEDict.keys()), [(0, 'bear'), (0, 'cat'), (0, 'mouse'), (1, 'black'), ...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(2c) Automated creation of an OHE dictionary Now use the code from Parts (2a) and (2b) to write a function that takes an input dataset and outputs an OHE dictionary. Then use this function to create an OHE dictionary for the sample dataset, and verify that it matches the dictionary from Part (2b).
# TODO: Replace <FILL IN> with appropriate code def createOneHotDict(inputData): """Creates a one-hot-encoder dictionary based on the input data. Args: inputData (RDD of lists of (int, str)): An RDD of observations where each observation is made up of a list of (featureID, value) tuples. ...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
Part 3: Parse CTR data and generate OHE features Before we can proceed, you'll first need to obtain the data from Criteo. Here is the link to Criteo's data sharing agreement:http://labs.criteo.com/downloads/2014-kaggle-display-advertising-challenge-dataset/. After you accept the agreement, you can obtain the download...
import os.path baseDir = os.path.join('/Users/bill.walrond/Documents/dsprj/data') inputPath = os.path.join('CS190_Mod4', 'dac_sample.txt') fileName = os.path.join(baseDir, inputPath) if os.path.isfile(fileName): rawData = (sc .textFile(fileName, 2) .map(lambda x: x.replace('\t', ','))...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(3a) Loading and splitting the data We are now ready to start working with the actual CTR data, and our first task involves splitting it into training, validation, and test sets. Use the randomSplit method with the specified weights and seed to create RDDs storing each of these datasets, and then cache each of these ...
# TODO: Replace <FILL IN> with appropriate code weights = [.8, .1, .1] seed = 42 # Use randomSplit with weights and seed rawTrainData, rawValidationData, rawTestData = rawData.randomSplit(weights, seed) # Cache the data rawTrainData.cache() rawValidationData.cache() rawTestData.cache() nTrain = rawTrainData.count() nV...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(3b) Extract features We will now parse the raw training data to create an RDD that we can subsequently use to create an OHE dictionary. Note from the take() command in Part (3a) that each raw data point is a string containing several fields separated by some delimiter. For now, we will ignore the first field (which ...
# TODO: Replace <FILL IN> with appropriate code def parsePoint(point): """Converts a comma separated string into a list of (featureID, value) tuples. Note: featureIDs should start at 0 and increase to the number of features - 1. Args: point (str): A comma separated string where the first v...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(3c) Create an OHE dictionary from the dataset Note that parsePoint returns a data point as a list of (featureID, category) tuples, which is the same format as the sample dataset studied in Parts 1 and 2 of this lab. Using this observation, create an OHE dictionary using the function implemented in Part (2c). Note th...
# TODO: Replace <FILL IN> with appropriate code ctrOHEDict = createOneHotDict(parsedTrainFeat) print 'Len of ctrOHEDict: {0}'.format(len(ctrOHEDict)) numCtrOHEFeats = len(ctrOHEDict.keys()) print numCtrOHEFeats print ctrOHEDict.has_key((0, '')) theItems = ctrOHEDict.items() for i in range(0,9): print theItems[i] ...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(3d) Apply OHE to the dataset Now let's use this OHE dictionary by starting with the raw training data and creating an RDD of LabeledPoint objects using OHE features. To do this, complete the implementation of the parseOHEPoint function. Hint: parseOHEPoint is an extension of the parsePoint function from Part (3b) an...
from pyspark.mllib.regression import LabeledPoint print rawTrainData.count() r = rawTrainData.first() l = parsePoint(r) print 'Length of parsed list: %d' % len(l) print 'Here\'s the list ...' print l sv = oneHotEncoding(l, ctrOHEDict, numCtrOHEFeats) print 'Here\'s the sparsevector ...' print sv lp = LabeledPoint(float...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
Visualization 1: Feature frequency We will now visualize the number of times each of the 233,286 OHE features appears in the training data. We first compute the number of times each feature appears, then bucket the features by these counts. The buckets are sized by powers of 2, so the first bucket corresponds to feat...
x = sc.parallelize([("a", 1), ("b", 1), ("a", 1), ("a", 1),("b", 1), ("b", 1), ("b", 1), ("b", 1)], 3) y = x.reduceByKey(lambda accum, n: accum + n) y.collect() def bucketFeatByCount(featCount): """Bucket the counts by powers of two.""" for i in range(11): size = 2 ** i if featCount <= size: ...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(3e) Handling unseen features We naturally would like to repeat the process from Part (3d), e.g., to compute OHE features for the validation and test datasets. However, we must be careful, as some categorical values will likely appear in new data that did not exist in the training data. To deal with this situation, u...
# TODO: Replace <FILL IN> with appropriate code def oneHotEncoding(rawFeats, OHEDict, numOHEFeats): """Produce a one-hot-encoding from a list of features and an OHE dictionary. Note: If a (featureID, value) tuple doesn't have a corresponding key in OHEDict it should be ignored. Args: ...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(4b) Log loss Throughout this lab, we will use log loss to evaluate the quality of models. Log loss is defined as: \[ \scriptsize \ell_{log}(p, y) = \begin{cases} -\log (p) & \text{if } y = 1 \\ -\log(1-p) & \text{if } y = 0 \end{cases} \] where \( \scriptsize p\) is a probability between 0 and 1 and \( \scriptsize y...
# TODO: Replace <FILL IN> with appropriate code from math import log def computeLogLoss(p, y): """Calculates the value of log loss for a given probabilty and label. Note: log(0) is undefined, so when p is 0 we need to add a small value (epsilon) to it and when p is 1 we need to subtract a smal...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(4c) Baseline log loss Next we will use the function we wrote in Part (4b) to compute the baseline log loss on the training data. A very simple yet natural baseline model is one where we always make the same prediction independent of the given datapoint, setting the predicted value equal to the fraction of training p...
# TODO: Replace <FILL IN> with appropriate code # Note that our dataset has a very high click-through rate by design # In practice click-through rate can be one to two orders of magnitude lower classOneFracTrain = OHETrainData.map(lambda p: p.label).mean() print classOneFracTrain logLossTrBase = OHETrainData.map(lambd...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(4d) Predicted probability In order to compute the log loss for the model we trained in Part (4a), we need to write code to generate predictions from this model. Write a function that computes the raw linear prediction from this logistic regression model and then passes it through a sigmoid function \( \scriptsize \si...
# TODO: Replace <FILL IN> with appropriate code from math import exp # exp(-t) = e^-t def getP(x, w, intercept): """Calculate the probability for an observation given a set of weights and intercept. Note: We'll bound our raw prediction between 20 and -20 for numerical purposes. Args: x (...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(4e) Evaluate the model We are now ready to evaluate the quality of the model we trained in Part (4a). To do this, first write a general function that takes as input a model and data, and outputs the log loss. Then run this function on the OHE training data, and compare the result with the baseline log loss.
a = OHETrainData.map(lambda p: (getP(p.features, model0.weights, model0.intercept), p.label)) print a.count() print a.take(5) b = a.map(lambda lp: computeLogLoss(lp[0],lp[1])) print b.count() print b.take(5) # TODO: Replace <FILL IN> with appropriate code def evaluateResults(model, data): """Calculates the log los...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(4f) Validation log loss Next, following the same logic as in Parts (4c) and 4(e), compute the validation log loss for both the baseline and logistic regression models. Notably, the baseline model for the validation data should still be based on the label fraction from the training dataset.
# TODO: Replace <FILL IN> with appropriate code logLossValBase = OHEValidationData.map(lambda p: computeLogLoss(classOneFracTrain, p.label)).mean() logLossValLR0 = evaluateResults(model0, OHEValidationData) print ('OHE Features Validation Logloss:\n\tBaseline = {0:.3f}\n\tLogReg = {1:.6f}' .format(logLossValBas...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
Visualization 2: ROC curve We will now visualize how well the model predicts our target. To do this we generate a plot of the ROC curve. The ROC curve shows us the trade-off between the false positive rate and true positive rate, as we liberalize the threshold required to predict a positive outcome. A random model ...
labelsAndScores = OHEValidationData.map(lambda lp: (lp.label, getP(lp.features, model0.weights, model0.intercept))) labelsAndWeights = labelsAndScores.collect() labelsAndWeights.sort(key=lambda (k, v): v, reverse=True) labelsByWeight = np.array([k for (k, v) in labelsAndWeigh...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(5b) Creating hashed features Next we will use this hash function to create hashed features for our CTR datasets. First write a function that uses the hash function from Part (5a) with numBuckets = \( \scriptsize 2^{15} \approx 33K \) to create a LabeledPoint with hashed features stored as a SparseVector. Then use th...
feats = [(k,v) for k,v in enumerate(rawTrainData.take(1)[0][2:].split(','))] print feats hashDict = hashFunction(2 ** 15, feats) print hashDict print len(hashDict) print 2**15 # TODO: Replace <FILL IN> with appropriate code def parseHashPoint(point, numBuckets): """Create a LabeledPoint for this observation using ...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
(5c) Sparsity Since we have 33K hashed features versus 233K OHE features, we should expect OHE features to be sparser. Verify this hypothesis by computing the average sparsity of the OHE and the hashed training datasets. Note that if you have a SparseVector named sparse, calling len(sparse) returns the total number of...
s = sum(hashTrainData.map(lambda lp: len(lp.features.indices) / float(numBucketsCTR) ).collect()) / nTrain # ratios.count() s # TODO: Replace <FILL IN> with appropriate code def computeSparsity(data, d, n): """Calculates the average sparsity for the features in an RDD of LabeledPoints. Args: data (RDD...
jupyter_notebooks/CS190-1x Module 4- Feature Hashing Lab.ipynb
bwalrond/explore-notebooks
mit
Parameters are given as follows. D, radius, N_A, U, and ka_factor mean a diffusion constant, a radius of molecules, an initial number of molecules of A and B, a ratio of dissociated form of A at the steady state, and a ratio between an intrinsic association rate and collision rate defined as ka andkD below, respectivel...
D = 1 radius = 0.005 N_A = 60 U = 0.5 ka_factor = 10 # 10 is for diffusion-limited N = 20 # a number of samples
en/tests/Reversible_Diffusion_limited.ipynb
ecell/ecell4-notebooks
gpl-2.0
Start with no C molecules, and simulate 3 seconds.
y0 = {'A': N_A, 'B': N_A} duration = 0.35 opt_kwargs = {'legend': True}
en/tests/Reversible_Diffusion_limited.ipynb
ecell/ecell4-notebooks
gpl-2.0
Simulating with spatiocyte. voxel_radius is given as radius. Use alpha enough less than 1.0 for a diffusion-limited case (Bars represent standard error of the mean):
# alpha = 0.03 ret2 = ensemble_simulations(duration, ndiv=20, y0=y0, model=m, solver=('spatiocyte', radius), repeat=N) ret2.plot('o', ret1, '-', **opt_kwargs)
en/tests/Reversible_Diffusion_limited.ipynb
ecell/ecell4-notebooks
gpl-2.0
Load the lending club dataset We will be using the same LendingClub dataset as in the previous assignment.
loans = graphlab.SFrame('lending-club-data.gl/') loans.head()
ml-classification/week-3/module-5-decision-tree-assignment-2-blank.ipynb
zomansud/coursera
mit
Decision tree implementation In this section, we will implement binary decision trees from scratch. There are several steps involved in building a decision tree. For that reason, we have split the entire assignment into several sections. Function to count number of mistakes while predicting majority class Recall from t...
def intermediate_node_num_mistakes(labels_in_node): # Corner case: If labels_in_node is empty, return 0 if len(labels_in_node) == 0: return 0 # Count the number of 1's (safe loans) safe_loans = (labels_in_node == 1).sum() # Count the number of -1's (risky loans) risky_loans = (...
ml-classification/week-3/module-5-decision-tree-assignment-2-blank.ipynb
zomansud/coursera
mit
Function to pick best feature to split on The function best_splitting_feature takes 3 arguments: 1. The data (SFrame of data which includes all of the feature columns and label column) 2. The features to consider for splits (a list of strings of column names to consider for splits) 3. The name of the target/label colu...
def best_splitting_feature(data, features, target): best_feature = None # Keep track of the best feature best_error = 10 # Keep track of the best error so far # Note: Since error is always <= 1, we should intialize it with something larger than 1. # Convert to float to make sure error gets c...
ml-classification/week-3/module-5-decision-tree-assignment-2-blank.ipynb
zomansud/coursera
mit
Building the tree With the above functions implemented correctly, we are now ready to build our decision tree. Each node in the decision tree is represented as a dictionary which contains the following keys and possible values: { 'is_leaf' : True/False. 'prediction' : Prediction at the leaf no...
def create_leaf(target_values): # Create a leaf node leaf = {'splitting_feature' : None, 'left' : None, 'right' : None, 'is_leaf': True } # Count the number of data points that are +1 and -1 in this node. num_ones = len(target_values[target_values == +1])...
ml-classification/week-3/module-5-decision-tree-assignment-2-blank.ipynb
zomansud/coursera
mit
We have provided a function that learns the decision tree recursively and implements 3 stopping conditions: 1. Stopping condition 1: All data points in a node are from the same class. 2. Stopping condition 2: No more features to split on. 3. Additional stopping condition: In addition to the above two stopping condition...
def decision_tree_create(data, features, target, current_depth = 0, max_depth = 10): remaining_features = features[:] # Make a copy of the features. target_values = data[target] print "--------------------------------------------------------------------" print "Subtree, depth = %s (%s data points)....
ml-classification/week-3/module-5-decision-tree-assignment-2-blank.ipynb
zomansud/coursera
mit
Quiz question: What was the feature that my_decision_tree first split on while making the prediction for test_data[0]? Quiz question: What was the first feature that lead to a right split of test_data[0]? Quiz question: What was the last feature split on before reaching a leaf node for test_data[0]? Evaluating your d...
def evaluate_classification_error(tree, data, target): # Apply the classify(tree, x) to each row in your data prediction = data.apply(lambda x: classify(tree, x)) # Once you've made the predictions, calculate the classification error and return it accuracy = (prediction == data[target]).sum() e...
ml-classification/week-3/module-5-decision-tree-assignment-2-blank.ipynb
zomansud/coursera
mit
Now, let's use this function to evaluate the classification error on the test set.
round(evaluate_classification_error(my_decision_tree, test_data, target), 2)
ml-classification/week-3/module-5-decision-tree-assignment-2-blank.ipynb
zomansud/coursera
mit
Quiz question: What is the path of the first 3 feature splits considered along the left-most branch of my_decision_tree? Quiz question: What is the path of the first 3 feature splits considered along the right-most branch of my_decision_tree?
print_stump(my_decision_tree['right'], my_decision_tree['splitting_feature']) print_stump(my_decision_tree['right']['right'], my_decision_tree['left']['splitting_feature'])
ml-classification/week-3/module-5-decision-tree-assignment-2-blank.ipynb
zomansud/coursera
mit