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 |
|---|---|---|---|---|---|
Test out the RNN modelIt's always a good idea to run a few simple checks on our model to see that it behaves as expected. First, we can use the `Model.summary` function to print out a summary of our model's internal workings. Here we can check the layers in the model, the shape of the output of each of the layers, th... | model.summary() | Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding_1 (Embedding) (32, None, 256) 21248
__________________________________... | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
We can also quickly check the dimensionality of our output, using a sequence length of 100. Note that the model can be run on inputs of any length. | x, y = get_batch(vectorized_songs, seq_length=100, batch_size=32)
pred = model(x)
print("Input shape: ", x.shape, " # (batch_size, sequence_length)")
print("Prediction shape: ", pred.shape, "# (batch_size, sequence_length, vocab_size)")
x
y
pred | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
Predictions from the untrained modelLet's take a look at what our untrained model is predicting.To get actual predictions from the model, we sample from the output distribution, which is defined by a `softmax` over our character vocabulary. This will give us actual character indices. This means we are using a [categor... | # for batch 0, input sequence size: 100, so output sequence size: 100
sampled_indices = tf.random.categorical(pred[0], num_samples=1)
sampled_indices = tf.squeeze(sampled_indices,axis=-1).numpy()
sampled_indices
x[0] | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
We can now decode these to see the text predicted by the untrained model: | print("Input: \n", repr("".join(idx2char[x[0]])))
print()
print("Next Char Predictions: \n", repr("".join(idx2char[sampled_indices]))) | Input:
'AG|F2D DED|FEF GFG|!\nA3 cAG|AGA cde|fed cAG|Ad^c d2:|!\ne|f2d d^cd|f2a agf|e2c cBc|e2f gfe|!\nf2g agf|'
Next Char Predictions:
'^VIQXjybPEk-^_G/>#T9ZLYJ"CkYXBE\nUUDBU<AwqWFDa(]X09T)0GpF(5Q"k|\nKHU1fhFeuSM)s"i9F8hjYcj[Dl5\'KQzecQkKs'
| MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
As you can see, the text predicted by the untrained model is pretty nonsensical! How can we do better? We can train the network! 2.5 Training the model: loss and training operationsNow it's time to train the model!At this point, we can think of our next character prediction problem as a standard classification problem... | ### Defining the loss function ###
'''TODO: define the loss function to compute and return the loss between
the true labels and predictions (logits). Set the argument from_logits=True.'''
def compute_loss(labels, logits):
loss = tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True) # ... | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
Let's start by defining some hyperparameters for training the model. To start, we have provided some reasonable values for some of the parameters. It is up to you to use what we've learned in class to help optimize the parameter selection here! | ### Hyperparameter setting and optimization ###
# Optimization parameters:
num_training_iterations = 2000 # Increase this to train longer
batch_size = 4 # Experiment between 1 and 64
seq_length = 100 # Experiment between 50 and 500
learning_rate = 5e-3 # Experiment between 1e-5 and 1e-1
# Model parameters:
vocab... | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
Now, we are ready to define our training operation -- the optimizer and duration of training -- and use this function to train the model. You will experiment with the choice of optimizer and the duration for which you train your models, and see how these changes affect the network's output. Some optimizers you may like... | ### Define optimizer and training operation ###
'''TODO: instantiate a new model for training using the `build_model`
function and the hyperparameters created above.'''
#model = build_model('''TODO: arguments''')
model = build_model(vocab_size, embedding_dim=embedding_dim, rnn_units=rnn_units, batch_size=batch_size)... | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
2.6 Generate music using the RNN modelNow, we can use our trained RNN model to generate some music! When generating music, we'll have to feed the model some sort of seed to get it started (because it can't predict anything without something to start with!).Once we have a generated seed, we can then iteratively predict... | '''TODO: Rebuild the model using a batch_size=1'''
model = build_model(vocab_size, embedding_dim=embedding_dim, rnn_units=rnn_units, batch_size=1)
# Restore the model weights for the last checkpoint after training
model.load_weights(tf.train.latest_checkpoint(checkpoint_dir))
model.build(tf.TensorShape([1, None]))
mo... | Model: "sequential_3"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding_3 (Embedding) (1, None, 256) 21248
__________________________________... | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
Notice that we have fed in a fixed `batch_size` of 1 for inference. The prediction procedureNow, we're ready to write the code to generate text in the ABC music format:* Initialize a "seed" start string and the RNN state, and set the number of characters we want to generate.* Use the start string and the RNN state to ... | ### Prediction of a generated song ###
def generate_text(model, start_string, generation_length=1000):
# Evaluation step (generating ABC text using the learned RNN model)
'''TODO: convert the start string to numbers (vectorize)'''
input_eval = [char2idx[s] for s in start_string] # TODO
# input_eval = ['''TODO... | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
Play back the generated music!We can now call a function to convert the ABC format text to an audio file, and then play that back to check out our generated music! Try training longer if the resulting song is not long enough, or re-generating the song! | ### Play back generated songs ###
generated_songs = mdl.lab1.extract_song_snippet(generated_text)
for i, song in enumerate(generated_songs):
# Synthesize the waveform from a song
waveform = mdl.lab1.play_song(song)
# If its a valid song (correct syntax), lets play it!
if waveform:
print("Generated song... | _____no_output_____ | MIT | lab1/Part2_Music_Generation.ipynb | mukesh5237/introtodeeplearning |
Working with Text Data Types of data represented as strings Example application: Sentiment analysis of movie reviews | ! wget -nc http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz -P data
! tar xzf data/aclImdb_v1.tar.gz --skip-old-files -C data
!tree -dL 2 data/aclImdb
!rm -r data/aclImdb/train/unsup
from sklearn.datasets import load_files
reviews_train = load_files("data/aclImdb/train/")
# load_files returns a bunch, co... | Number of documents in test data: 25000
Samples per class (test): [12500 12500]
| MIT | introduction_to_ml_with_python-master/07-working-with-text-data.ipynb | nosy0411/Programming_for_Data_Science |
Representing text data as Bag of Words  Applying bag-of-words to a toy dataset | bards_words =["The fool doth think he is wise,",
"but the wise man knows himself to be a fool"]
from sklearn.feature_extraction.text import CountVectorizer
vect = CountVectorizer()
vect.fit(bards_words)
print("Vocabulary size: {}".format(len(vect.vocabulary_)))
print("Vocabulary content:\n {}".format(vect... | Dense representation of bag_of_words:
[[0 0 1 1 1 0 1 0 0 1 1 0 1]
[1 1 0 1 0 1 0 1 1 1 0 1 1]]
| MIT | introduction_to_ml_with_python-master/07-working-with-text-data.ipynb | nosy0411/Programming_for_Data_Science |
Bag-of-word for movie reviews | vect = CountVectorizer().fit(text_train)
X_train = vect.transform(text_train)
print("X_train:\n{}".format(repr(X_train)))
feature_names = vect.get_feature_names()
print("Number of features: {}".format(len(feature_names)))
print("First 20 features:\n{}".format(feature_names[:20]))
print("Features 20010 to 20030:\n{}".fo... | Best cross-validation score: 0.89
| MIT | introduction_to_ml_with_python-master/07-working-with-text-data.ipynb | nosy0411/Programming_for_Data_Science |
Stop-words | from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
print("Number of stop words: {}".format(len(ENGLISH_STOP_WORDS)))
print("Every 10th stopword:\n{}".format(list(ENGLISH_STOP_WORDS)[::10]))
# Specifying stop_words="english" uses the built-in list.
# We could also augment it and pass our own.
vect = CountVec... | Best cross-validation score: 0.88
| MIT | introduction_to_ml_with_python-master/07-working-with-text-data.ipynb | nosy0411/Programming_for_Data_Science |
Rescaling the Data with tf-idf\begin{equation*}\text{tfidf}(w, d) = \text{tf} \log\big(\frac{N + 1}{N_w + 1}\big) + 1\end{equation*} | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import make_pipeline
pipe = make_pipeline(TfidfVectorizer(min_df=5, norm=None),
LogisticRegression())
param_grid = {'logisticregression__C': [0.001, 0.01, 0.1, 1, 10]}
grid = GridSearchCV(pipe, param_grid, cv=5)
grid... | Features with lowest idf:
['the' 'and' 'of' 'to' 'this' 'is' 'it' 'in' 'that' 'but' 'for' 'with'
'was' 'as' 'on' 'movie' 'not' 'have' 'one' 'be' 'film' 'are' 'you' 'all'
'at' 'an' 'by' 'so' 'from' 'like' 'who' 'they' 'there' 'if' 'his' 'out'
'just' 'about' 'he' 'or' 'has' 'what' 'some' 'good' 'can' 'more' 'when'
't... | MIT | introduction_to_ml_with_python-master/07-working-with-text-data.ipynb | nosy0411/Programming_for_Data_Science |
Investigating model coefficients | mglearn.tools.visualize_coefficients(
grid.best_estimator_.named_steps["logisticregression"].coef_,
feature_names, n_top_features=40) | _____no_output_____ | MIT | introduction_to_ml_with_python-master/07-working-with-text-data.ipynb | nosy0411/Programming_for_Data_Science |
Bag of words with more than one word (n-grams) | print("bards_words:\n{}".format(bards_words))
cv = CountVectorizer(ngram_range=(1, 1)).fit(bards_words)
print("Vocabulary size: {}".format(len(cv.vocabulary_)))
print("Vocabulary:\n{}".format(cv.get_feature_names()))
cv = CountVectorizer(ngram_range=(2, 2)).fit(bards_words)
print("Vocabulary size: {}".format(len(cv.voc... | _____no_output_____ | MIT | introduction_to_ml_with_python-master/07-working-with-text-data.ipynb | nosy0411/Programming_for_Data_Science |
Advanced tokenization, stemming and lemmatization | import spacy
import nltk
# load spacy's English-language models
en_nlp = spacy.load('en')
# instantiate nltk's Porter stemmer
stemmer = nltk.stem.PorterStemmer()
# define function to compare lemmatization in spacy with stemming in nltk
def compare_normalization(doc):
# tokenize document in spacy
doc_spacy = e... | Best cross-validation score (standard CountVectorizer): 0.721
Best cross-validation score (lemmatization): 0.731
| MIT | introduction_to_ml_with_python-master/07-working-with-text-data.ipynb | nosy0411/Programming_for_Data_Science |
Topic Modeling and Document Clustering Latent Dirichlet Allocation | vect = CountVectorizer(max_features=10000, max_df=.15)
X = vect.fit_transform(text_train)
from sklearn.decomposition import LatentDirichletAllocation
lda = LatentDirichletAllocation(n_topics=10, learning_method="batch",
max_iter=25, random_state=0)
# We build the model and transform the ... | _____no_output_____ | MIT | introduction_to_ml_with_python-master/07-working-with-text-data.ipynb | nosy0411/Programming_for_Data_Science |
CER100 - Configure Cluster with Self Signed Certificates========================================================This notebook will:1. Generate a new Root CA in the Big Data Cluster2. Create new certificates for each endpoint (Management, Gateway, App-Proxy and Controller)3. Sign each new certificate with the new ... | import getpass
common_name = "SQL Server Big Data Clusters Test CA"
country_name = "US"
state_or_province_name = "Illinois"
locality_name = "Chicago"
organization_name = "Contoso"
organizational_unit_name = "Finance"
email_address = f"{getpass.getuser()}@contoso.com"
days = "825" # the number of days to certify the ... | _____no_output_____ | MIT | Big-Data-Clusters/CU3/Public/content/cert-management/cer100-create-root-ca-install-certs.ipynb | gantz-at-incomm/tigertoolbox |
Define notebooks and their arguments | import os
import copy
cer00_args = { "country_name": country_name, "state_or_province_name": state_or_province_name, "locality_name": locality_name, "organization_name": organization_name, "organizational_unit_name": organizational_unit_name, "common_name": common_name, "email_address": email_address, "days": days, "t... | _____no_output_____ | MIT | Big-Data-Clusters/CU3/Public/content/cert-management/cer100-create-root-ca-install-certs.ipynb | gantz-at-incomm/tigertoolbox |
Common functionsDefine helper functions used in this notebook. | # Define `run` function for transient fault handling, hyperlinked suggestions, and scrolling updates on Windows
import sys
import os
import re
import json
import platform
import shlex
import shutil
import datetime
from subprocess import Popen, PIPE
from IPython.display import Markdown
retry_hints = {}
error_hints = {... | _____no_output_____ | MIT | Big-Data-Clusters/CU3/Public/content/cert-management/cer100-create-root-ca-install-certs.ipynb | gantz-at-incomm/tigertoolbox |
Create a temporary directory to stage files | # Create a temporary directory to hold configuration files
import tempfile
temp_dir = tempfile.mkdtemp()
print(f"Temporary directory created: {temp_dir}") | _____no_output_____ | MIT | Big-Data-Clusters/CU3/Public/content/cert-management/cer100-create-root-ca-install-certs.ipynb | gantz-at-incomm/tigertoolbox |
Helper function for running notebooks with `azdata notebook run`To pass ‘list’ types to `azdata notebook run --arguments`, flatten tostring | # Define helper function 'run_notebook'
def run_notebook(name, arguments):
for key, value in arguments.items():
if isinstance(value, list):
arguments[key] = str(value).replace("'", "")
# --arguments have to be passed as \" \" quoted strings on Windows cmd line
#
# `app create` and `... | _____no_output_____ | MIT | Big-Data-Clusters/CU3/Public/content/cert-management/cer100-create-root-ca-install-certs.ipynb | gantz-at-incomm/tigertoolbox |
Run the notebooks | for notebook in notebooks:
run_notebook(notebook[0], notebook[1])
print("Notebooks ran successfully.")
print('Notebook execution complete.') | _____no_output_____ | MIT | Big-Data-Clusters/CU3/Public/content/cert-management/cer100-create-root-ca-install-certs.ipynb | gantz-at-incomm/tigertoolbox |
Bernoulli Naive Bayes Classifier with Normalize This code template is facilitates to solve the problem of classification problem using Bernoulli Naive Bayes Algorithm using Normalize technique. Required Packages | !pip install imblearn
import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as se
from imblearn.over_sampling import RandomOverSampler
from sklearn.pipeline import make_pipeline
from sklearn.naive_bayes import BernoulliNB
from sklearn.preprocessing import La... | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
InitializationFilepath of CSV file | #filepath
file_path= "" | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
List of features which are required for model training . | #x_values
features=[] | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Target feature for prediction. | #y_value
target='' | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Data FetchingPandas is an open-source, BSD-licensed library providing high-performance, easy-to-use data manipulation and data analysis tools.We will use panda's library to read the CSV file using its storage path.And we use the head function to display the initial row or entry. | df=pd.read_csv(file_path)
df.head() | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Feature SelectionsIt is the process of reducing the number of input variables when developing a predictive model. Used to reduce the number of input variables to both reduce the computational cost of modelling and, in some cases, to improve the performance of the model.We will assign all the required input features to... | X = df[features]
Y = df[target] | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_dummies(df)... | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | f,ax = plt.subplots(figsize=(18, 18))
matrix = np.triu(X.corr())
se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)
plt.show() | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Distribution of Target Variable | plt.figure(figsize = (10,6))
se.countplot(Y) | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123) | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Handling Target ImbalanceThe challenge of working with imbalanced datasets is that most machine learning techniques will ignore, and in turn have poor performance on, the minority class, although typically it is performance on the minority class that is most important.One approach to addressing imbalanced datasets is ... | x_train,y_train = RandomOverSampler(random_state=123).fit_resample(x_train, y_train) | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Data Rescalingsklearn.preprocessing.Normalizer()Normalize samples individually to unit norm.more details at [scikit-learn.org](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.Normalizer.htmlsklearn.preprocessing.Normalizer) | Scaler=Normalizer()
x_train=Scaler.fit_transform(x_train)
x_test=Scaler.transform(x_test) | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
ModelBernoulli Naive Bayes Classifier is used for discrete data and it works on Bernoulli distribution. The main feature of Bernoulli Naive Bayes is that it accepts features only as binary values like true or false, yes or no, success or failure, 0 or 1 and so on. So when the feature values are **binary** we know that... | # BernoulliNB.
model = BernoulliNB()
model.fit(x_train, y_train) | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Model Accuracyscore() method return the mean accuracy on the given test data and labels.In multi-label classification, this is the subset accuracy which is a harsh metric since you require for each sample that each label set be correctly predicted. | print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100)) | Accuracy score 41.25 %
| Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Confusion MatrixA confusion matrix is utilized to understand the performance of the classification model or algorithm in machine learning for a given test set where results are known. | plot_confusion_matrix(model,x_test,y_test,cmap=plt.cm.Blues) | _____no_output_____ | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Classification ReportA Classification report is used to measure the quality of predictions from a classification algorithm. How many predictions are True, how many are False.* **where**: - Precision:- Accuracy of positive predictions. - Recall:- Fraction of positives that were correctly identified. - f1-score... | print(classification_report(y_test,model.predict(x_test))) | precision recall f1-score support
0 0.54 0.44 0.48 50
1 0.28 0.37 0.32 30
accuracy 0.41 80
macro avg 0.41 0.40 0.40 80
weighted avg 0.44 0.41 0.42 ... | Apache-2.0 | Classification/Naive Bayes/BernoulliNB_Normalize.ipynb | shreepad-nade/ds-seed |
Tutorial on collocating a datafile with lagged data | import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
import pandas as pd
import warnings
import timeit
# filter some warning messages
warnings.filterwarnings("ignore")
#from geopy.distance import geodesic
####################you will need to change some paths here!#####################
#list of inp... | _____no_output_____ | Apache-2.0 | Tutorials/Collocate_cloud_data_with_cvs_file.ipynb | caitlinkroeger/cloud_science |
Reading CSV datasets | #read in csv file in to panda dataframe & into xarray
df_bird = pd.read_csv(filename_bird)
# calculate time, it needs a datetime64[ns] format
df_bird.insert(3,'Year',df_bird['year'])
df_bird.insert(4,'Month',df_bird['month'])
df_bird.insert(5,'Day',df_bird['day'])
df_bird=df_bird.drop(columns={'day','month','year'})
d... | _____no_output_____ | Apache-2.0 | Tutorials/Collocate_cloud_data_with_cvs_file.ipynb | caitlinkroeger/cloud_science |
Collocate all data with bird data | len(ds_bird.lat)
ds_data = ds
for var in ds_data:
var_tem=var
ds_bird[var_tem]=xr.DataArray(np.empty(ilen_bird, dtype=str(ds_data[var].dtype)), coords={'index': ds_bird.index}, dims=('index'))
ds_bird[var_tem].attrs=ds_data[var].attrs
print('var',var_tem)
for i in range(len(ds_bird.lat)):
# for i in ran... | _____no_output_____ | Apache-2.0 | Tutorials/Collocate_cloud_data_with_cvs_file.ipynb | caitlinkroeger/cloud_science |
Plagiarism Detection, Feature EngineeringIn this project, you will be tasked with building a plagiarism detector that examines an answer text file and performs binary classification; labeling that file as either plagiarized or not, depending on how similar that text file is to a provided, source text. Your first task ... | # NOTE:
# you only need to run this cell if you have not yet downloaded the data
# otherwise you may skip this cell or comment it out
!wget https://s3.amazonaws.com/video.udacity-data.com/topher/2019/January/5c4147f9_data/data.zip
!unzip data
# import libraries
import pandas as pd
import numpy as np
import os | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
This plagiarism dataset is made of multiple text files; each of these files has characteristics that are is summarized in a `.csv` file named `file_information.csv`, which we can read in using `pandas`. | csv_file = 'data/file_information.csv'
plagiarism_df = pd.read_csv(csv_file)
# print out the first few rows of data info
plagiarism_df.head() | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Types of PlagiarismEach text file is associated with one **Task** (task A-E) and one **Category** of plagiarism, which you can see in the above DataFrame. Tasks, A-EEach text file contains an answer to one short question; these questions are labeled as tasks A-E. For example, Task A asks the question: "What is inheri... | # Read in a csv file and return a transformed dataframe
def numerical_dataframe(csv_file='data/file_information.csv'):
'''Reads in a csv file which is assumed to have `File`, `Category` and `Task` columns.
This function does two things:
1) converts `Category` column values to numerical values
... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Test cellsBelow are a couple of test cells. The first is an informal test where you can check that your code is working as expected by calling your function and printing out the returned result.The **second** cell below is a more rigorous test cell. The goal of a cell like this is to ensure that your code is working a... | # informal testing, print out the results of a called function
# create new `transformed_df`
transformed_df = numerical_dataframe(csv_file ='data/file_information.csv')
# check work
# check that all categories of plagiarism have a class label = 1
transformed_df.head(10)
# test cell that creates `transformed_df`, if te... | Tests Passed!
Example data:
| MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Text Processing & Splitting DataRecall that the goal of this project is to build a plagiarism classifier. At it's heart, this task is a comparison text; one that looks at a given answer and a source text, compares them and predicts whether an answer has plagiarized from the source. To effectively do this comparison, a... | """
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
import helpers
# create a text column
text_df = helpers.create_text_column(transformed_df)
text_df.head()
# after running the cell above
# check out the processed text for a single file, by row index
row_idx = 9 # feel free to change this index
samp... | Sample processed text:
dynamic programming is a method for solving mathematical programming problems that exhibit the properties of overlapping subproblems and optimal substructure this is a much quicker method than other more naive methods the word programming in dynamic programming relates optimization which is com... | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Split data into training and test setsThe next cell will add a `Datatype` column to a given DataFrame to indicate if the record is: * `train` - Training data, for model training.* `test` - Testing data, for model evaluation.* `orig` - The task's original answer from wikipedia. Stratified samplingThe given code uses a ... | random_seed = 1 # can change; set for reproducibility
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
import helpers
# create new df with Datatype (train, test, orig) column
# pass in `text_df` from above to create a complete dataframe, with all the information you need
complete_df = helpers.train_... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Determining PlagiarismNow that you've prepared this data and created a `complete_df` of information, including the text and class associated with each file, you can move on to the task of extracting similarity features that will be useful for plagiarism classification. > Note: The following code exercises, assume that... | # Calculate the ngram containment for one answer file/source file pair in a df
from sklearn.feature_extraction.text import CountVectorizer
def calculate_containment(df, n, answer_filename):
'''Calculates the containment between a given answer text and its associated source text.
This function creates a count... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Test cellsAfter you've implemented the containment function, you can test out its behavior. The cell below iterates through the first few files, and calculates the original category _and_ containment values for a specified n and file.>If you've implemented this correctly, you should see that the non-plagiarized have l... | # select a value for n
n = 1
# indices for first few files
test_indices = range(5)
# iterate through files and calculate containment
category_vals = []
containment_vals = []
for i in test_indices:
# get level of plagiarism for a given file index
category_vals.append(complete_df.loc[i, 'Category'])
# calcu... | Tests Passed!
| MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
QUESTION 1: Why can we calculate containment features across *all* data (training & test), prior to splitting the DataFrame for modeling? That is, what about the containment calculation means that the test and training data do not influence each other? **Answer:**It's a property of a single entry (a feature) and not a... | # Compute the normalized LCS given an answer text and a source text
def lcs_norm_word(answer_text, source_text):
'''Computes the longest common subsequence of words in two texts; returns a normalized value.
:param answer_text: The pre-processed text for an answer text
:param source_text: The pre-proce... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Test cellsLet's start by testing out your code on the example given in the initial description.In the below cell, we have specified strings A (answer text) and S (original source text). We know that these texts have 20 words in common and the submitted answer is 27 words long, so the normalized, longest common subsequ... | # Run the test scenario from above
# does your function return the expected value?
A = "i think pagerank is a link analysis algorithm used by google that uses a system of weights attached to each element of a hyperlinked set of documents"
S = "pagerank is a link analysis algorithm used by the google internet search en... | LCS = 0.7407407407407407
Test passed!
| MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
This next cell runs a more rigorous test. | # run test cell
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
# test lcs implementation
# params: complete_df from before, and lcs_norm_word function
tests.test_lcs(complete_df, lcs_norm_word) | Tests Passed!
| MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Finally, take a look at a few resultant values for `lcs_norm_word`. Just like before, you should see that higher values correspond to higher levels of plagiarism. | # test on your own
test_indices = range(5) # look at first few files
category_vals = []
lcs_norm_vals = []
# iterate through first few docs and calculate LCS
for i in test_indices:
category_vals.append(complete_df.loc[i, 'Category'])
# get texts to compare
answer_text = complete_df.loc[i, 'Text']
task... | Original category values:
[0, 3, 2, 1, 0]
Normalized LCS values:
[0.1917808219178082, 0.8207547169811321, 0.8464912280701754, 0.3160621761658031, 0.24257425742574257]
| MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
--- Create All FeaturesNow that you've completed the feature calculation functions, it's time to actually create multiple features and decide on which ones to use in your final model! In the below cells, you're provided two helper functions to help you create multiple features and store those in a DataFrame, `features_... | """
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
# Function returns a list of containment features, calculated for a given n
# Should return a list of length 100 for all files in a complete_df
def create_containment_features(df, n, column_name=None):
containment_values = []
if(colum... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Creating LCS featuresBelow, your complete `lcs_norm_word` function is used to create a list of LCS features for all the answer files in a given DataFrame (again, this assumes you are passing in the `complete_df`. It assigns a special value for our original, source files, -1. | """
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
# Function creates lcs feature and add it to the dataframe
def create_lcs_features(df, column_name='lcs_word'):
lcs_values = []
# iterate through files in dataframe
for i in df.index:
# Computes LCS_norm words feature using... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
EXERCISE: Create a features DataFrame by selecting an `ngram_range`The paper suggests calculating the following features: containment *1-gram to 5-gram* and *longest common subsequence*. > In this exercise, you can choose to create even more features, for example from *1-gram to 7-gram* containment features and *longe... | # Define an ngram range
ngram_range = range(1,10)
# The following code may take a minute to run, depending on your ngram_range
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
features_list = []
# Create features in a features_df
all_features = np.zeros((len(ngram_range)+1, len(complete_df)))
# Ca... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Correlated FeaturesYou should use feature correlation across the *entire* dataset to determine which features are ***too*** **highly-correlated** with each other to include both features in a single model. For this analysis, you can use the *entire* dataset due to the small sample size we have. All of our features try... | """
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
# Create correlation matrix for just Features to determine different models to test
corr_matrix = features_df.corr().abs().round(2)
# display shows all of a dataframe
display(corr_matrix) | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
EXERCISE: Create selected train/test dataComplete the `train_test_data` function below. This function should take in the following parameters:* `complete_df`: A DataFrame that contains all of our processed text data, file info, datatypes, and class labels* `features_df`: A DataFrame of all calculated features, such as... | # Takes in dataframes and a list of selected features (column names)
# and returns (train_x, train_y), (test_x, test_y)
def train_test_data(complete_df, features_df, selected_features):
'''Gets selected training and test features from given dataframes, and
returns tuples for training and test features and ... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Test cellsBelow, test out your implementation and create the final train/test data. | """
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
test_selection = list(features_df)[:2] # first couple columns as a test
# test that the correct train/test data is created
(train_x, train_y), (test_x, test_y) = train_test_data(complete_df, features_df, test_selection)
# params: generated train/test d... | Tests Passed!
| MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
EXERCISE: Select "good" featuresIf you passed the test above, you can create your own train/test data, below. Define a list of features you'd like to include in your final mode, `selected_features`; this is a list of the features names you want to include. | # Select your list of features, this should be column names from features_df
# ex. ['c_1', 'lcs_word']
selected_features = ['c_1', 'c_9', 'lcs_word']
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
(train_x, train_y), (test_x, test_y) = train_test_data(complete_df, features_df, selected_features)
... | Training size: 70
Test size: 25
Training df sample:
[[0.39814815 0. 0.19178082]
[0.86936937 0.21962617 0.84649123]
[0.59358289 0.01117318 0.31606218]
[0.54450262 0. 0.24257426]
[0.32950192 0. 0.16117216]
[0.59030837 0. 0.30165289]
[0.75977654 0.07017544 0.48430493]
[0.5161290... | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Question 2: How did you decide on which features to include in your final model? **Answer:**By checking the correlation matrix we created, I selected two variables that are not strongly correlated (0.86), plus the wordLCS. --- Creating Final Data FilesNow, you are almost ready to move on to training a model in SageMa... | def make_csv(x, y, filename, data_dir):
'''Merges features and labels and converts them into one csv file with labels in the first column.
:param x: Data features
:param y: Data labels
:param file_name: Name of csv file, ex. 'train.csv'
:param data_dir: The directory where files will be ... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Test cellsTest that your code produces the correct format for a `.csv` file, given some text features and labels. | """
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
fake_x = [ [0.39814815, 0.0001, 0.19178082],
[0.86936937, 0.44954128, 0.84649123],
[0.44086022, 0., 0.22395833] ]
fake_y = [0, 1, 1]
make_csv(fake_x, fake_y, filename='to_delete.csv', data_dir='test_csv')
# read in and test di... | _____no_output_____ | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
If you've passed the tests above, run the following cell to create `train.csv` and `test.csv` files in a directory that you specify! This will save the data in a local directory. Remember the name of this directory because you will reference it again when uploading this data to S3. | # can change directory, if you want
data_dir = 'plagiarism_data'
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
make_csv(train_x, train_y, filename='train.csv', data_dir=data_dir)
make_csv(test_x, test_y, filename='test.csv', data_dir=data_dir) | 0 0 1 2
0 0 0.398148 0.000000 0.191781
1 1 0.869369 0.219626 0.846491
2 1 0.593583 0.011173 0.316062
3 0 0.544503 0.000000 0.242574
4 0 0.329502 0.000000 0.161172
.. .. ... ... ...
65 1 0.845188 0.225108 0.643725
66 1 0.485000 0.000000 0.242... | MIT | Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb | brunokiyoshi/ML_SageMaker_Studies |
Jugando con Probabilidades y Python La coincidencia de cumpleañosAquí vemos la solución de la paradija del cumpleaños que vimos en el apartado de proabilidad.La [paradoja del cumpleaños](https://es.wikipedia.org/wiki/Paradoja_del_cumplea%C3%B1os) es un problema muy conocido en el campo de la probabilidad. Plantea las ... | # Ejemplo situación 2 La coincidencia de cumpleaños
prob = 1.0
asistentes = 50
# Calculamos el número de asistentes necesarios para asegurar
# que la probabilidad de coincidencia sea mayor del 50%
# asistentes = 50
asistentes = 1
prob = 1
while 1 - prob <= 0.5:
asistentes += 1
prob = prob * (365 - (asistentes... | 0.5072972343239855
Para asegurar que la probabilidad es mayor del 50% necesitamos 23 asistentes
| MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
Variables aleatorias. Vamos a tirar un dadoVamos a trabajar con variables discretas, y en este caso vamos a vamos a reproducir un dado con la librería `random` que forma parte de la librería estandar de Python: | # importa la libreria random. puedes utilizar dir() para entender lo que ofrece
# utiliza help para obtener ayuda sobre el metodo randint
# utiliza randint() para simular un dado y haz una tirada
# ahora haz 20 tiradas, y crea una lista con las tiradas
# Vamos a calcular la media de las tiradas
# Calcula ahora la ... | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
Viendo como evoluciona el número de 6 cuando sacamos más jugadasVamos a ver ahora como evoluciona el número de seises que obtenemos al lanzar el dado 10000 veces. Vamos a crear una lista en la que cada elemento sea el número de ocurrencias del número 6 dividido entre el número de lanzamientos. crea una lista llamadada... | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | |
Vamos a tratar de hacerlo gráficamente¿Hacia que valor debería converger los números que forman la lista frecuencia_seis? Revisa la ley de los grandes números para la moneda, y aplica un poco de lógica para este caso. | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | |
Resolviendo el problema de Monty HallEste problema, más conocido con el nombre de [Monty Hall](https://es.wikipedia.org/wiki/Problema_de_Monty_Hall).En primer lugar trata de simular el problema de Monty Hall con Python, para ver cuantas veces gana el concursante y cuantas pierde. Realiza por ejemplo 10000 simulaciones... | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | |
Monthy Hall - una aproximación bayesianaTrata de resolver ahora el problema de Monthy Hall utilizando el teorema de Bayes.Puedes escribir la solución, o programar el código. Lo que prefieras. | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | |
El problema de las CookiesImagina que tienes 2 botes con galletas. El primero contiene 30 cookies de vainilla y 10 cookies de chocolate. El segundo bote tiene 20 cookies de chocolate y 20 cookies de vainilla.Ahora vamos a suponer que sacamos un cookie sin ver de que bote lo sacamos. El cookie es de vainilla. ¿Cuál es ... | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | |
El problema de los M&Ms En 1995 M&Ms lanzó los M&M’s azules. - Antes de ese año la distibución de una bolsa era: 30% Marrones, 20% Amarillos, 20% Rojos, 10% Verdes, 10% Naranjas, 10% Marron Claros. - Después de 1995 la distribución en una bolsa era la siguiente: 24% Azul , 20% Verde, 16% Naranjas, 14% Amarillos, 13% R... | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | |
Creando un clasificador basado en el teorema de Bayes Este es un problema extraido de la página web de Chris Albon, que ha replicado un ejemplo que puedes ver en la wikipedia. Trata de reproducirlo y entenderlo. Naive bayes is simple classifier known for doing well when only a small number of observations is availabl... | import pandas as pd
import numpy as np | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
Create DataOur dataset is contains data on eight individuals. We will use the dataset to construct a classifier that takes in the height, weight, and foot size of an individual and outputs a prediction for their gender. | # Create an empty dataframe
data = pd.DataFrame()
# Create our target variable
data['Gender'] = ['male','male','male','male','female','female','female','female']
# Create our feature variables
data['Height'] = [6,5.92,5.58,5.92,5,5.5,5.42,5.75]
data['Weight'] = [180,190,170,165,100,150,130,150]
data['Foot_Size'] = [1... | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
The dataset above is used to construct our classifier. Below we will create a new person for whom we know their feature values but not their gender. Our goal is to predict their gender. | # Create an empty dataframe
person = pd.DataFrame()
# Create some feature values for this single row
person['Height'] = [6]
person['Weight'] = [130]
person['Foot_Size'] = [8]
# View the data
person | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
Bayes Theorem Bayes theorem is a famous equation that allows us to make predictions based on data. Here is the classic version of the Bayes theorem:$$\displaystyle P(A\mid B)={\frac {P(B\mid A)\,P(A)}{P(B)}}$$This might be too abstract, so let us replace some of the variables to make it more concrete. In a bayes class... | # Number of males
n_male = data['Gender'][data['Gender'] == 'male'].count()
# Number of males
n_female = data['Gender'][data['Gender'] == 'female'].count()
# Total rows
total_ppl = data['Gender'].count()
# Number of males divided by the total rows
P_male = n_male/total_ppl
# Number of females divided by the total ro... | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
Calculate Likelihood Remember that each term (e.g. $p(\text{height}\mid\text{female})$) in our likelihood is assumed to be a normal pdf. For example:$$ p(\text{height}\mid\text{female})=\frac{1}{\sqrt{2\pi\text{variance of female height in the data}}}\,e^{ -\frac{(\text{observation's height}-\text{average height of fe... | # Group the data by gender and calculate the means of each feature
data_means = data.groupby('Gender').mean()
# View the values
data_means
# Group the data by gender and calculate the variance of each feature
data_variance = data.groupby('Gender').var()
# View the values
data_variance | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
Now we can create all the variables we need. The code below might look complex but all we are doing is creating a variable out of each cell in both of the tables above. | # Means for male
male_height_mean = data_means['Height'][data_variance.index == 'male'].values[0]
print(male_height_mean)
male_weight_mean = data_means['Weight'][data_variance.index == 'male'].values[0]
male_footsize_mean = data_means['Foot_Size'][data_variance.index == 'male'].values[0]
# Variance for male
male_heigh... | 5.855
| MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
Finally, we need to create a function to calculate the probability density of each of the terms of the likelihood (e.g. $p(\text{height}\mid\text{female})$). | # Create a function that calculates p(x | y):
def p_x_given_y(x, mean_y, variance_y):
# Input the arguments into a probability density function
p = 1/(np.sqrt(2*np.pi*variance_y)) * np.exp((-(x-mean_y)**2)/(2*variance_y))
# return p
return p | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
Apply Bayes Classifier To New Data Point Alright! Our bayes classifier is ready. Remember that since we can ignore the marginal probability (the demoninator), what we are actually calculating is this:$${\displaystyle {\text{numerator of the posterior}}={P({\text{female}})\,p({\text{height}}\mid{\text{female}})\,p({\te... | # Numerator of the posterior if the unclassified observation is a male
P_male * \
p_x_given_y(person['Height'][0], male_height_mean, male_height_variance) * \
p_x_given_y(person['Weight'][0], male_weight_mean, male_weight_variance) * \
p_x_given_y(person['Foot_Size'][0], male_footsize_mean, male_footsize_variance)
# Nu... | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 |
Because the numerator of the posterior for female is greater than male, then we predict that the person is female. Crea un nuevo punto con tus datos y predice su resultado (fíjate en las unidades) | _____no_output_____ | MIT | Bloque 1 - Ramp-Up/06_Estadística/01_Probabilidad y Estadística descriptiva/06_Ejercicios.ipynb | franciscocanon-thebridge/bootcamp_thebridge_PTSep20 | |
Data Set Preprocessing | import urllib.request, json
with urllib.request.urlopen("http://statistik.easycredit-bbl.de/XML/exchange/540/Schedule.php?type=json&saison=2017&fixedGamesOnly=0") as url:
games = json.loads(url.read().decode())
print(json.dumps(games, indent=4, sort_keys=True))
arena=[]
home_ids=[]
for i in range(0,len(... | <class 'str'>
| MIT | ANN_moreFeatures.ipynb | F3rdixX/Basketball_BBL |
Deshalb parse (int) ich die Zuschauer und home_id für die weitere Berechnung | #Dataset zusammenstellen
dataset=[]
for i in range(0,len(games['competition'][0]['spiel'])):
datasetrow=[]
datasetrow.append(games['competition'][0]['spiel'][i]['home_id'])
datasetrow.append(games['competition'][0]['spiel'][i]['gast_id'])
datasetrow.append(int(games['competition'][0]['spiel'][i]['... | ['540' '422' '483' '418' '477' '421' '432' '428' '413' '420' '426' '483'
'425' '486' '517' '415' '439' '413' '517' '477' '418' '428' '430' '540'
'432' '422' '421' '433' '426' '430' '477' '486' '483' '433' '432' '415'
'425' '418' '413' '422' '428' '486' '421' '540' '421' '413' '422' '477'
'415' '433' '430' '439' '42... | MIT | ANN_moreFeatures.ipynb | F3rdixX/Basketball_BBL |
One hot encoding | from sklearn.preprocessing import LabelBinarizer
encoder = LabelBinarizer()
transformed_home_ids = encoder.fit_transform(dataset[:,0])
print(transformed_home_ids)
#ohne fit, damit die Teams eindeutig bleiben, nur transformation notwendig
transformed_gast_ids = encoder.transform(dataset[:,1])
print(transformed_gast_ids... | [[0.21655172]
[0.24848276]
[0.21213793]
[0.42758621]
[0.23772414]
[0.27606897]
[0.216 ]
[0.20689655]
[1. ]
[0.42413793]
[0.34496552]
[0.21213793]
[0.22758621]
[0.45475862]
[0.24365517]
[0.4137931 ]
[0.28965517]
[1. ]
[0.24365517]
[0.23772414]
[0.42758621]
[0.20689655]
[0.4137931 ... | MIT | ANN_moreFeatures.ipynb | F3rdixX/Basketball_BBL |
Data - Zusammenfügen der Spalten home_ids, gast_ids, zuschauer, Hallenkapazität, home_win | data=np.c_[transformed_home_ids,transformed_gast_ids,transformed_zuschauer,transformed_kap,dataset[:,2]]
print(data)
print(len(data[0])) | 39
| MIT | ANN_moreFeatures.ipynb | F3rdixX/Basketball_BBL |
Netz Modellierung | # Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Dense
# Initialising the ANN
regressor = Sequential()
# Adding the input layer and the first hidden layer
regressor.add(Dense(units = 38, kernel_initializer = 'uniform', activation = 'relu', input_shape = (38,))... | _____no_output_____ | MIT | ANN_moreFeatures.ipynb | F3rdixX/Basketball_BBL |
This is a simple workbook used to generate the starting point for the weighting process. The tables in the workbook were in a strange format so I just did it manually here. | all_rows_post = pd.read_pickle('all_rows_post2.pkl')
all_rows_post = all_rows_post.groupby(['yearSale','Sector','Technology','HeatingEfficiency','CoolingEfficiency']).sum().reset_index()
all_rows_post = all_rows_post[all_rows_post['Sector'] == 'Residential']
key_techs = ['Heat Pump','Heat Pump - Ductless','Central Air ... | _____no_output_____ | MIT | Generate Sales Mix Starting Point.ipynb | ischultz-cadeo/TO_43_Sales_Data |
Loading datas | datas = pd.read_csv('datasets/ISEAR.csv')
datas.head()
datas.columns
datas.drop('0', axis=1, inplace=True)
datas.size
datas.shape
column_name = datas.columns
datas = datas.rename(columns={column_name[0]: "Emotion",
column_name[1]: "Sentence"})
datas.head() | _____no_output_____ | FTL | notebooks/01.01_PL_sentiment_analysis_2020_05_18.ipynb | bhattbhuwan13/fuseai-training |
Adding $joy$ back to the dataset | missing_data = {"Emotion": column_name[0],
"Sentence": column_name[1]}
missing_data
datas = datas.append(missing_data, ignore_index=True) | _____no_output_____ | FTL | notebooks/01.01_PL_sentiment_analysis_2020_05_18.ipynb | bhattbhuwan13/fuseai-training |
Visualizing emotion ditribution | sns.catplot(kind='count', x='Emotion', data = datas)
plt.show()
datas.isna().sum()
datas.tail()
y = datas['Emotion']
y.head()
X = datas['Sentence']
X.head() | _____no_output_____ | FTL | notebooks/01.01_PL_sentiment_analysis_2020_05_18.ipynb | bhattbhuwan13/fuseai-training |
Converting all text to lovercase | Counter(y)
tfidf = TfidfVectorizer(tokenizer=nltk.word_tokenize, stop_words='english', min_df=3, ngram_range=(1, 2), lowercase=True)
tfidf.fit(X)
with open('tfidt_feature_vector.pkl', 'wb') as fp:
pickle.dump(tfidf, fp)
X = tfidf.transform(X)
tfidf.vocabulary_ | _____no_output_____ | FTL | notebooks/01.01_PL_sentiment_analysis_2020_05_18.ipynb | bhattbhuwan13/fuseai-training |
Making Models | bayes_classification = MultinomialNB()
dtree_classification = DecisionTreeClassifier()
Knn = KNeighborsClassifier()
def calculate_performance(test, pred, algorithm):
print(f'####For {algorithm}')
print(f'{classification_report(test, pred)}')
def train(X, y):
X_train, X_test, y_train, y_test = train_test_spl... | ####For Naive Bayes
precision recall f1-score support
anger 0.46 0.43 0.45 265
disgust 0.59 0.60 0.59 264
fear 0.62 0.66 0.64 260
guilt 0.51 0.48 0.50 262
joy 0.66 ... | FTL | notebooks/01.01_PL_sentiment_analysis_2020_05_18.ipynb | bhattbhuwan13/fuseai-training |
Python 数据类型> Guido 对语言设计美学的深入理解让人震惊。我认识不少很不错的编程语言设计者,他们设计出来的东西确实很精彩,但是从来都不会有用户。Guido 知道如何在理论上做出一定妥协,设计出来的语言让使用者觉得如沐春风,这真是不可多得。 > ——Jim Hugunin > Jython 的作者,AspectJ 的作者之一,.NET DLR 架构师Python 最好的品质之一是**一致性**:你可以轻松理解 Python 语言,并通过 Python 的语言特性在类上定义**规范的接口**,来支持 Python 的核心语言特性,从而写出具有“Python 风格”的对象。 Python 解释器在碰到特殊的句法时... | # 通过实现魔术方法,来让内置函数支持你的自定义对象
# https://github.com/fluentpython/example-code/blob/master/01-data-model/frenchdeck.py
import collections
import random
Card = collections.namedtuple('Card', ['rank', 'suit'])
class FrenchDeck:
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hear... | _____no_output_____ | MIT | 01-data-model/01-data-model.ipynb | yuechuanx/fluent-python-code-and-notes |
可以容易地获得一个纸牌对象 | beer_card = Card('7', 'diamonds')
print(beer_card) | _____no_output_____ | MIT | 01-data-model/01-data-model.ipynb | yuechuanx/fluent-python-code-and-notes |
和标准 Python 集合类型一样,使用 `len()` 查看一叠纸牌有多少张 | deck = FrenchDeck()
# 实现 __len__ 以支持下标操作
print(len(deck)) | _____no_output_____ | MIT | 01-data-model/01-data-model.ipynb | yuechuanx/fluent-python-code-and-notes |
可选取特定一张纸牌,这是由 `__getitem__` 方法提供的 | # 实现 __getitem__ 以支持下标操作
print(deck[1])
print(deck[5::13]) | _____no_output_____ | MIT | 01-data-model/01-data-model.ipynb | yuechuanx/fluent-python-code-and-notes |
随机抽取一张纸牌,使用 python 内置函数 `random.choice` | from random import choice
# 可以多运行几次观察
choice(deck) | _____no_output_____ | MIT | 01-data-model/01-data-model.ipynb | yuechuanx/fluent-python-code-and-notes |
实现特殊方法的两个好处:- 对于标准操作有固定命名- 更方便利用 Python 标准库 `__getitem__` 方法把 [] 操作交给了 `self._cards` 列表,deck 类自动支持切片操作 | deck[12::13]
deck[:3] | _____no_output_____ | MIT | 01-data-model/01-data-model.ipynb | yuechuanx/fluent-python-code-and-notes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.