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
Predicting Attacks for some sensors in the train data set 2 The Loop below will select the best parameters for the model.**It takes some minutes to run , please be advised**_The code will just select the best parameters based on the train set 2 - nothing else_
#############train #L_T7 L_T7=parameterselection(dftrain1["L_T7"],dftrain2_L_T7[" L_T7"],dftrain2_L_T7[' ATT_FLAG']) #F_PU10 F_PU10=parameterselection(dftrain1["F_PU10"],dftrain2_F_PU10[" F_PU10"],dftrain2_F_PU10[' ATT_FLAG']) #F_PU11 F_PU11=parameterselection(dftrain1["F_PU11"],dftrain2_F_PU11[" F_PU11"],dftrain2_F_...
0.06684491978609626 0.014204545454545454 0.0 0.1286764705882353 0.08227848101265822 0.08849557522123894 0.036290322580645164
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Predicting Attacks for some sensors in the test data According to the information provided about the BATADAL dataset, Anomalies can be found at 'L_T3', 'F_PU4', 'F_PU5', 'L_T2, 'V2', 'P_J14', 'P_J422, 'L_T7', 'F_PU10', 'F_PU11', 'L_T6'.The parameters for prediction will be those optimized by on the traindataset 2. Whe...
#'L_T3' trainset=dftrain1['L_T3'] testset=dftest['L_T3'] sax=L_T1[1]["sax"] paa=L_T1[1]["paa"] n=L_T1[1]["ngram"] t=L_T1[1]["threshold"] results=dftest_L_T3[' ATT_FLAG'] MODEL_LT3=model_to_predict(trainset,testset,results,sax,int(len(dftrain1)/paa),n,t) #'F_PU4' trainset=dftrain1['F_PU4'] testset=dftest['F_PU4'] sax=F_...
{'recall': 0.06666666666666667, 'precision': 0.011904761904761904, 'Accuracy': 0.9071325993298229, 'F1': 0.014245014245014244}
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Aggregating all the predictions Aggregating all the predictions in one dataset
#Getting the predictions for anomalies dftest_with_predictions=dftest #Loop that aggregate all the predictions in a column with the test set with predictions Model_set=[MODEL_LT3,MODEL_F_PU4,MODEL_F_PU5,MODEL_L_T2,MODEL_P_J14,MODEL_P_J422,MODEL_L_T7,MODEL_F_PU10,MODEL_F_PU11,MODEL_L_T6] pred=[0]*len(model[3]) for mode...
_____no_output_____
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Calculating the performance for the aggregate model
cm=confusion_matrix(list(dftest[" ATT_FLAG"]), pred) #True positive, false positive, false negative and true positive tn, fp, fn, tp = cm.ravel() #Getting the ratios recall=tp/(tp+fn) precision=tp/(tp+fp) #Ploting ploting_cm(cm) #Printing performance print("Recall: "+str(recall)) print("Precision: "+str(precision))
Recall: 0.8574938574938575 Precision: 0.20069005175388155
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Checking the type of anomaly Calculating per each type of anomaly the recall rate
#Calculating number of anomalies per type Total_Collective_Anomalies=len(dftest_with_predictions[dftest_with_predictions["anomalytype"]=="collective"]) Total_Contextual_Anomalies=len(dftest_with_predictions[dftest_with_predictions["anomalytype"]=="contextual"]) #Calculating number of anomalies predicted per type Predi...
Percentage of Collective Anomalies Predicted: 0.8643067846607669 Percentage of Contextual Anomalies Predicted: 0.8285714285714286
MIT
batadal/Task3_Discrete.ipynb
imchengh/Cyber-Data-Analytics
Custom Expectation Value Program for the Qiskit RuntimePaul NationIBM Quantum Partners Technical Enablement TeamHere we will show how to make a program that takes a circuit, or list of circuits, and computes the expectation values of one or more diagonal operators. Prerequisites- You must have the latest Qiskit insta...
#%%writefile sample_expval.py import mthree from qiskit import transpile # The entrypoint for our Runtime Program def main( backend, user_messenger, circuits, expectation_operators="", shots=8192, transpiler_config={}, run_config={}, skip_transpilation=False, return_stddev=False, ...
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
Local testingHere we test with a local "Fake" backend that mimics the noise properties of a real system and a 4-qubit GHZ state.
from qiskit import QuantumCircuit from qiskit.test.mock import FakeSantiago from qiskit_ibm_runtime import UserMessenger msg = UserMessenger() backend = FakeSantiago() qc = QuantumCircuit(4) qc.h(2) qc.cx(2, 1) qc.cx(1, 0) qc.cx(2, 3) qc.measure_all() main( backend, msg, qc, expectation_operators=["ZZZ...
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
If we have done our job correctly, the above should print out two expectation values close to one and a final expectation value close to zero. Program metadataNext we add the needed program data to a dictionary for uploading with our program.
meta = { "name": "sample-expval", "description": "A sample expectation value program.", "max_execution_time": 1000, "spec": {}, } meta["spec"]["parameters"] = { "$schema": "https://json-schema.org/draft/2019-09/schema", "properties": { "circuits": { "description": "A single ...
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
Upload the programWe are now in a position to upload the program. To do so we first uncomment and excute the line `%%writefile sample_expval.py` giving use the `sample_expval.py` file we need to upload.
from qiskit_ibm_runtime import IBMRuntimeService service = IBMRuntimeService(auth="legacy") program_id = service.upload_program(data="sample_expval.py", metadata=meta) program_id
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
Delete program if needed
# service.delete_program(program_id)
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
Wrapping the runtime programAs always, it is best to wrap the call to the runtime program with a function (or possibly a class) that makes input easier and does some validation.
def expectation_value_runner( backend, circuits, expectation_operators="", shots=8192, transpiler_config={}, run_config={}, skip_transpilation=False, return_stddev=False, use_measurement_mitigation=False, ): """Compute expectation values for a list of operators after executi...
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
Trying it outLets try running the program here with our previously made GHZ state and running on the simulator.
backend = "ibmq_qasm_simulator" all_zeros_proj = {"0000": 1} all_ones_proj = {"1111": 1} job = expectation_value_runner(backend, qc, [all_zeros_proj, all_ones_proj, "ZZZZ"]) job.result()
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
The first two projectors should be nearly $0.50$ as they tell use the probability of being in the all zeros and ones states, respectively, which should be 50/50 for our GHZ state. The final expectation value of `ZZZZ` should be one since this is a GHZ over an even number of qubits. It should go close to zero for an o...
qc2 = QuantumCircuit(3) qc2.h(2) qc2.cx(2, 1) qc2.cx(1, 0) qc2.measure_all() all_zeros_proj = {"000": 1} all_ones_proj = {"111": 1} job2 = expectation_value_runner(backend, qc2, [all_zeros_proj, all_ones_proj, "ZZZ"]) job2.result()
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
Quantum Volume as an expectation valueHere we formulate QV as an expectation value of a projector onto the heavy-output elements on a distribution. We can then use our expectation value routine to compute whether a given circuit has passed the QV metric.QV is defined in terms of heavy-ouputs of a distribution. Heavy-...
def heavy_projector(qv_probs): """Forms the projection operator onto the heavy-outputs of a given probability distribution. Parameters: qv_probs (dict): A dictionary of bitstrings and associated probabilities. Returns: dict: Projector onto the heavy-set. """ median_prob = np.median...
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
Now we generate 10 QV circuits as our dataset.
import numpy as np from qiskit.quantum_info import Statevector from qiskit.circuit.library import QuantumVolume # Generate QV circuits N = 10 qv_circs = [QuantumVolume(5) for _ in range(N)]
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
Next, we have to determine the heavy-set of each circuit from the ideal answer, and then pass this along to our heavy-set projector function that we defined above.
ideal_probs = [ Statevector.from_instruction(circ).probabilities_dict() for circ in qv_circs ] heavy_projectors = [heavy_projector(probs) for probs in ideal_probs]
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
QV circuits have no meaasurements on them so need to add them:
circs = [circ.measure_all(inplace=False) for circ in qv_circs]
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
With a list of circuits and projection operators we now need only to pass both sets to our above expection value runner targeting the desired backend. We will also set the best transpiler arguments to give us a sporting chance of getting some passing scores.
backend = "ibmq_manila" job3 = expectation_value_runner( backend, circs, heavy_projectors, transpiler_config={ "optimization_level": 3, "layout_method": "sabre", "routing_method": "sabre", }, ) qv_scores = job3.result() qv_scores
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
A passing QV score is one where the value of the heavy-set projector is above $2/3$. So let us see who passed:
qv_scores > 2 / 3 from qiskit.tools.jupyter import * %qiskit_copyright
_____no_output_____
Apache-2.0
docs/tutorials/sample_expval_program/qiskit_runtime_expval_program.ipynb
daka1510/qiskit-ibm-runtime
Plagiarism Detection ModelNow that you've created training and test data, you are ready to define and train a model. Your goal in this notebook, will be to train a binary classification model that learns to label an answer file as either plagiarized or not, based on the features you provide the model.This task will be...
import pandas as pd import boto3 import sagemaker """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # session and role sagemaker_session = sagemaker.Session() role = sagemaker.get_execution_role() # create an S3 bucket bucket = sagemaker_session.default_bucket()
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
EXERCISE: Upload your training data to S3Specify the `data_dir` where you've saved your `train.csv` file. Decide on a descriptive `prefix` that defines where your data will be uploaded in the default S3 bucket. Finally, create a pointer to your training data by calling `sagemaker_session.upload_data` and passing in th...
# should be the name of directory you created to save your features data data_dir = 'plagiarism_data' # set prefix, a descriptive name for a directory prefix = 'plagiarism' # upload all data to S3 input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix) input_data
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
Test cellTest that your data has been successfully uploaded. The below cell prints out the items in your S3 bucket and will throw an error if it is empty. You should see the contents of your `data_dir` and perhaps some checkpoints. If you see any other files listed, then you may have some old model files that you can ...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # confirm that data is in S3 bucket empty_check = [] for obj in boto3.resource('s3').Bucket(bucket).objects.all(): empty_check.append(obj.key) print(obj.key) assert len(empty_check) !=0, 'S3 bucket is empty.' print('Test passed!')
boston-xgboost-HL/output/sagemaker-xgboost-2019-11-03-22-54-54-949/output/model.tar.gz boston-xgboost-HL/output/sagemaker-xgboost-2019-11-04-00-24-26-893/output/model.tar.gz boston-xgboost-HL/test.csv boston-xgboost-HL/train.csv boston-xgboost-HL/validation.csv ggwm_sagemaker/sentiment_rnn/train.csv ggwm_sagemaker/sent...
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
--- ModelingNow that you've uploaded your training data, it's time to define and train a model!The type of model you create is up to you. For a binary classification task, you can choose to go one of three routes:* Use a built-in classification algorithm, like LinearLearner.* Define a custom Scikit-learn classifier, a ...
# directory can be changed to: source_sklearn or source_pytorch !pygmentize source_sklearn/train.py
from __future__ import print_function import argparse import os import pandas as pd from sk...
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
Provided codeIf you read the code above, you can see that the starter code includes a few things:* Model loading (`model_fn`) and saving code* Getting SageMaker's default hyperparameters* Loading the training data by name, `train.csv` and extracting the features and labels, `train_x`, and `train_y`If you'd like to rea...
# your import and estimator code, here from sagemaker.sklearn.estimator import SKLearn sklearn = SKLearn( entry_point="train.py", source_dir="source_sklearn", train_instance_type="ml.c4.xlarge", role=role, sagemaker_session=sagemaker_session, hyperparameters={'n_estimators': 50 , 'max_depth':5...
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
EXERCISE: Train the estimatorTrain your estimator on the training data stored in S3. This should create a training job that you can monitor in your SageMaker console.
%%time # Train your estimator on S3 training data sklearn.fit({'train': input_data})
2019-12-13 23:28:35 Starting - Starting the training job... 2019-12-13 23:28:36 Starting - Launching requested ML instances...... 2019-12-13 23:29:41 Starting - Preparing the instances for training... 2019-12-13 23:30:24 Downloading - Downloading input data... 2019-12-13 23:30:56 Training - Downloading the training ima...
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
EXERCISE: Deploy the trained modelAfter training, deploy your model to create a `predictor`. If you're using a PyTorch model, you'll need to create a trained `PyTorchModel` that accepts the trained `.model_data` as an input parameter and points to the provided `source_pytorch/predict.py` file as an entry point. To dep...
%%time # uncomment, if needed # from sagemaker.pytorch import PyTorchModel # deploy your model to create a predictor predictor = sklearn.deploy(initial_instance_count=1, instance_type="ml.m4.xlarge")
---------------------------------------------------------------------------------------------------------------!CPU times: user 600 ms, sys: 0 ns, total: 600 ms Wall time: 9min 27s
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
--- Evaluating Your ModelOnce your model is deployed, you can see how it performs when applied to our test data.The provided cell below, reads in the test data, assuming it is stored locally in `data_dir` and named `test.csv`. The labels and features are extracted from the `.csv` file.
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ import os # read in test data, assuming it is stored locally test_data = pd.read_csv(os.path.join(data_dir, "test.csv"), header=None, names=None) # labels are in the first column test_y = test_data.iloc[:,0] test_x = test_data.iloc[:,1:]
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
EXERCISE: Determine the accuracy of your modelUse your deployed `predictor` to generate predicted, class labels for the test data. Compare those to the *true* labels, `test_y`, and calculate the accuracy as a value between 0 and 1.0 that indicates the fraction of test data that your model classified correctly. You may...
# First: generate predicted, class labels test_y_preds = predictor.predict(test_x) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # test that your model generates the correct number of labels assert len(test_y_preds)==len(test_y), 'Unexpected number of predictions.' print('Test passed!') from skl...
1.0 Predicted class labels: [1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 1 0 1 1 0 0] True class labels: [1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 1 0 1 1 0 0]
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
Question 1: How many false positives and false negatives did your model produce, if any? And why do you think this is? ** Answer**: i see 100% accuracy with no false positivies and no false negatives.there could be overfitting possible data leakage Question 2: How did you decide on the type of model to use? ** Answe...
# uncomment and fill in the line below! # <name_of_deployed_predictor>.delete_endpoint() predictor.delete_endpoint()
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
Deleting S3 bucketWhen you are *completely* done with training and testing models, you can also delete your entire S3 bucket. If you do this before you are done training your model, you'll have to recreate your S3 bucket and upload your training data again.
# deleting bucket, uncomment lines below bucket_to_delete = boto3.resource('s3').Bucket(bucket) bucket_to_delete.objects.all().delete()
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
gowtham91m/ML_SageMaker_Studies
Scikit-Learn * É considerada como a biblitoca de Python mais utilizada para a implementação de métodos baseados em algoritmos de aprendizagem de máquina (*machine learning*).* A versão atual é a 0.24.2 (abril 2021).* URL: http://scikit-learn.org Formulação do Problema * Problema de classificação **supervisionada...
import pandas as pd df = pd.read_csv('http://tiagodemelo.info/datasets/dataset-uol.csv') df.head() df.shape df.CATEGORIA.unique()
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Verificar dados nulos (NaN)
df.isnull().any() df.isnull().sum() index_with_nan = df.index[df.isnull().any(axis=1)] index_with_nan.shape df.drop(index_with_nan, 0, inplace=True) df.shape
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Adicionar coluna ao *dataset*
ids_categoria = df['CATEGORIA'].factorize()[0] df['ID_CATEGORIA'] = ids_categoria df.head(n=10) df.ID_CATEGORIA.unique() column_values = df[["ID_CATEGORIA", "CATEGORIA"]].values.ravel() unique_values = pd.unique(column_values) print(unique_values) category_id_df = df[['CATEGORIA', 'ID_CATEGORIA']].drop_duplicates().sor...
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Distribuição das notícias entre as categorias
import matplotlib.pyplot as plt fig = plt.figure(figsize=(8,6)) df.groupby('CATEGORIA').TEXTO.count().plot.bar() plt.show()
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
* Um problema recorrente é o **desbalanceamento das classes**.* Os algoritmos convencionais tendem a favorecer as classes mais frequentes, ou seja, não consideram as classes menos frequentes.* As classes menos frequentes costumam ser tratadas como *outliers*.* Estratégias de *undersampling* ou *oversampling* são a...
TAMANHO_DATASET = 200 #quantidade de artigos por classe. categorias = list(set(df['ID_CATEGORIA'])) data = [] for cat in categorias: total = TAMANHO_DATASET for c,t,i in zip(df['CATEGORIA'], df['TEXTO'], df['ID_CATEGORIA']): if total>0 and cat == i: total-=1 data.append([c,t,i]) df = pd.DataFrame(...
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Representação do Texto * Os métodos de aprendizagem de máquina lidam melhor com representações numéricas ao invés de representação textual.* Portanto, os textos precisam ser convertidos.* *Bag of words* é uma forma comum de representar os textos.* Nós vamos calcular a medida de *Term Frequency* e *Inverse Document...
import nltk nltk.download('punkt') from nltk.tokenize import word_tokenize sentenca1 = "Os brasileiros gostam de futebol" sentenca2 = "Os americanos adoram futebol e adoram basquete" texto1 = word_tokenize(sentenca1) texto2 = word_tokenize(sentenca2) print (texto1) print (texto2) from nltk.probability import FreqDis...
[('Os', 2), ('futebol', 2), ('adoram', 2), ('brasileiros', 1), ('gostam', 1), ('de', 1), ('americanos', 1), ('e', 1), ('basquete', 1)]
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
sentença 1: "Os brasileiros gostam de futebol"sentença 2: "Os americanos adoram futebol e adoram basquete" ![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABC0AAAA/CAIAAABLv6XfAAAl/klEQVR4nO3dCTyU+R8H8N8crnGfSZGSHEUl3SulpINUoqWkNl0oxRYVrRK1kvTf1X3poOQqSodCB23laDs2lmxY5L7lmJn/jCuFMeaR8djv+9XrpTme5/k9n+f3+z3Pb5...
from sklearn.feature_extraction.text import TfidfVectorizer import nltk nltk.download('stopwords') from nltk.corpus import stopwords tfidf = TfidfVectorizer(min_df=5, encoding='latin-1', ngram_range=(1, 2), stop_words=stopwords.words('portuguese')) features = tfidf.fit_transform(df.TEXTO.values.astype('U')).toarray()...
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Nós podemos usar o `sklearn.feature_selection.chi2` para achar os termos que estão mais correlacionados com cada categoria.
from sklearn.feature_selection import chi2 import numpy as np N = 2 for Categoria, category_id in sorted(id_to_category.items()): features_chi2 = chi2(features, labels == category_id) indices = np.argsort(features_chi2[0]) feature_names = np.array(tfidf.get_feature_names())[indices] unigrams = [v for v in fea...
# '0': . Unigramas mais correlacionados: . equipe . único . Bigramas mais correlacionados: . duas vezes . entrevista coletiva # '1': . Unigramas mais correlacionados: . equipe . único . Bigramas mais correlacionados: . duas vezes . entrevista coletiva # '2': . Unigramas mais correlacionados: . equipe . único ...
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Criação de Classificador Importar bibliotecas:
from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Dividir *dataset* em **treino** e **teste**
X_train, X_test, y_train, y_test = train_test_split(df['TEXTO'], df['CATEGORIA'], test_size=0.2, random_state = 0)
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Criar um modelo (Naive Bayes)
count_vect = CountVectorizer() X_train_counts = count_vect.fit_transform(X_train.values.astype('U')) tfidf_transformer = TfidfTransformer() X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts) clf = MultinomialNB().fit(X_train_tfidf, y_train)
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Testar o classificador criado:
sentenca = 'O brasileiro gosta de futebol.' print(clf.predict(count_vect.transform([sentenca])))
['esporte']
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Seleção do Modelo Nós agora vamos experimentar diferentes modelos de aprendizagem de máquina e avaliar a sua acurácia.Serão considerados os seguintes modelos:* Logistic Regression (LR)* Multinomial Naive Bayes (NB)* Linear Support Vector Machine (SVM)* Random Forest (RF) Importar bibliotecas:
from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.svm import LinearSVC from sklearn.model_selection import cross_val_score
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Lista com os modelos:
models = [ RandomForestClassifier(n_estimators=200, max_depth=3, random_state=0), LinearSVC(C=10, class_weight=None, dual=True, fit_intercept=True, intercept_scaling=1, loss='squared_hinge', max_iter=1000, multi_class='ovr', penalty='l2', random_state=None, tol=0.0001, verbose=0), MultinomialNB(), Logis...
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Validação Cruzada A validação cruzada é um método de reamostragem e tem como objetivo avaliar a capacidade de **generalização** do modelo. Normalmente a distribuição entre treino e teste é feita da seguinte forma: ![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAn8AAABnCAYAAABxVCQkAAAABHNCSVQICAgIfAhkiAAAHU...
CV = 5
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Geração dos modelos:
cv_df = pd.DataFrame(index=range(CV * len(models))) entries = [] for model in models: model_name = model.__class__.__name__ accuracies = cross_val_score(model, features, labels, scoring='accuracy', cv=CV) for fold_idx, accuracy in enumerate(accuracies): entries.append((model_name, fold_idx, accuracy)) cv_df...
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Gráfico BoxPlot ![image.png](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABAAAAAKYCAYAAADt+IqXAAAABHNCSVQICAgIfAhkiAAAIABJREFUeF7svQu0JWV5rosJAzkcjofNYbDZpNN7pdP2IIQQTocgu0NwpTcSREREVEKQIPEWvG3jPe5sh8PhTjxuh8Nbsr0hXuIVFRERCWKLbUsQERERAduVtm0REQkSQEU479PWj2UxLzXnWt1r1pzPN8bbVavqvz7/XzX/76uas3fZRZOABCQgAQlIQAISkIAEJCAB...
import seaborn as sns sns.boxplot(x='model_name', y='accuracy', data=cv_df) sns.stripplot(x='model_name', y='accuracy', data=cv_df, size=8, jitter=True, edgecolor="gray", linewidth=2) plt.show()
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Acurácia média entre os 5 modelos:
cv_df.groupby('model_name').accuracy.mean()
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Matriz de Confusão Geração de modelo baseado em SVM:
model = LinearSVC() X_train, X_test, y_train, y_test, indices_train, indices_test = train_test_split(features, labels, df.index, test_size=0.33, random_state=0) model.fit(X_train, y_train) y_pred = model.predict(X_test)
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Plotar matriz de confusão para o modelo SVM:
from sklearn.metrics import confusion_matrix conf_mat = confusion_matrix(y_test, y_pred) fig, ax = plt.subplots(figsize=(10,10)) sns.heatmap(conf_mat, annot=True, fmt='d', xticklabels=category_id_df.CATEGORIA.values, yticklabels=category_id_df.CATEGORIA.values) plt.ylabel('Actual') plt.xlabel('Predicted'...
_____no_output_____
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Vamos avaliar os resultados incorretos.Apresentação de textos classificados incorretamente:
from IPython.display import display for predicted in category_id_df.ID_CATEGORIA: for actual in category_id_df.ID_CATEGORIA: if predicted != actual and conf_mat[actual, predicted] >= 5: print("'{}' predicted as '{}' : {} examples.".format(id_to_category[actual], id_to_category[predicted], conf_mat[actual, ...
'esporte' predicted as 'coronavirus' : 6 examples.
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
Reportar o resultado do classificador em cada classe:
from sklearn import metrics print(metrics.classification_report(y_test, y_pred, target_names=df['CATEGORIA'].unique()))
precision recall f1-score support coronavirus 0.35 0.26 0.30 66 politica 0.67 0.69 0.68 58 esporte 0.70 0.58 0.63 78 carro 0.65 0.50 0.56 70 educacao 0.48 0.74 ...
MIT
MO_Aula_SciKit.ipynb
anarossati/Mineracao_dados_Ocean_05_2021
UUV Single-Agent Environment Creating the environment
# initialize setup from fimdpenv import setup, UUVEnv setup() # create envionment from fimdpenv.UUVEnv import SingleAgentEnv env = SingleAgentEnv(grid_size=[20,20], capacity=50, reloads=[22,297], targets=[67, 345, 268], init_state=350, enhanced_actionspace=0) env # get consmdp mdp, targets = env.get_consmdp() # list of...
_____no_output_____
MIT
examples/UUVEnv_singleagent.ipynb
pthangeda/FiMDPEnv
Creating and visualizing strategies
# generate strategies from fimdp.objectives import BUCHI from fimdp.energy_solvers import GoalLeaningES from fimdp.core import CounterStrategy env.create_counterstrategy(solver=GoalLeaningES, objective=BUCHI, threshold=0.1) # animate strategies env.animate_simulation(num_steps=50, interval=100) # histories #env.state_...
_____no_output_____
MIT
examples/UUVEnv_singleagent.ipynb
pthangeda/FiMDPEnv
Resetting strategies and single transition
env.reset(init_state=98, reset_energy=20) env env.strategies env.state_histories env.step() env env.state_histories
_____no_output_____
MIT
examples/UUVEnv_singleagent.ipynb
pthangeda/FiMDPEnv
Enhanced action space
# create envionment with enchanced action space from fimdpenv.UUVEnv import SingleAgentEnv env2 = SingleAgentEnv(grid_size=[20,20], capacity=50, reloads=[22,297, 198, 76], targets=[67, 345, 268], init_state=350, enhanced_actionspace=1) env2 # create strategies from fimdp.objectives import BUCHI from fimdp.energy_solv...
_____no_output_____
MIT
examples/UUVEnv_singleagent.ipynb
pthangeda/FiMDPEnv
Configurable closed-loop optimization with Ax `Scheduler`*We recommend reading through the ["Developer API" tutorial](https://ax.dev/tutorials/gpei_hartmann_developer.html) before getting started with the `Scheduler`, as using it in this tutorial will require an Ax `Experiment` and an understanding of the experiment's...
from typing import Any, Dict, NamedTuple, List, Union from time import time from random import randint from ax.core.base_trial import TrialStatus from ax.utils.measurement.synthetic_functions import branin class MockJob(NamedTuple): """Dummy class to represent a job scheduled on `MockJobQueue`.""" id: int ...
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
3. Set up an experiment according to the mock external systemAs mentioned above, using a `Scheduler` requires a fully set up experiment with metrics and a runner. Refer to the "Building Blocks of Ax" tutorial to learn more about those components, as here we assume familiarity with them. The following runner and metric...
from ax.core.runner import Runner from ax.core.base_trial import BaseTrial from ax.core.trial import Trial class MockJobRunner(Runner): # Deploys trials to external system. def run(self, trial: BaseTrial) -> Dict[str,Any]: """Deploys a trial and returns dict of run metadata.""" if not isinsta...
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
Now we can set up the experiment using the runner and metric we defined. This experiment will have a single-objective optimization config, minimizing the Branin function, and the search space that corresponds to that function.
from ax import * def make_branin_experiment_with_runner_and_metric() -> Experiment: parameters = [ RangeParameter( name="x1", parameter_type=ParameterType.FLOAT, lower=-5, upper=10, ), RangeParameter( name="x2", par...
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
4. Setting up a `Scheduler` 4a. Subclassing `Scheduler`The base Ax `Scheduler` is abstract and must be subclassed, but only one method must be implemented on the subclass: `poll_trial_status`.
from typing import Dict, Set from random import randint from collections import defaultdict from ax.service.scheduler import Scheduler, SchedulerOptions, TrialStatus class MockJobQueueScheduler(Scheduler): def poll_trial_status(self) -> Dict[TrialStatus, Set[int]]: """Queries the external system to comput...
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
4B. Auto-selecting a generation strategyA `Scheduler` also requires an Ax `GenerationStrategy` specifying the algorithm to use for the optimization. Here we use the `choose_generation_strategy` utility that auto-picks a generation strategy based on the search space properties. To construct a custom generation strategy...
from ax.modelbridge.dispatch_utils import choose_generation_strategy generation_strategy = choose_generation_strategy( search_space=experiment.search_space, max_parallelism_cap=3, )
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
Now we have all the components needed to start the scheduler:
scheduler = MockJobQueueScheduler( experiment=experiment, generation_strategy=generation_strategy, options=SchedulerOptions(), )
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
5. Running the optimizationOnce the `Scheduler` instance is set up, user can execute `run_n_trials` as many times as needed, and each execution will add up to the specified `max_trials` trials to the experiment. The number of trials actually run might be less than `max_trials` if the optimization was concluded (e.g. t...
scheduler.run_n_trials(max_trials=3)
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
We can examine `experiment` to see that it now has three trials:
from ax.service.utils.report_utils import exp_to_df exp_to_df(experiment)
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
Now we can run `run_n_trials` again to add three more trials to the experiment.
scheduler.run_n_trials(max_trials=3)
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
Examiniming the experiment, we now see 6 trials, one of which is produced by Bayesian optimization (GPEI):
exp_to_df(experiment)
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
For each call to `run_n_trials`, one can specify a timeout; if `run_n_trials` has been running for too long without finishing its `max_trials`, the operation will exit gracefully:
scheduler.run_n_trials(max_trials=3, timeout_hours=0.00001)
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
6. Leveraging SQL storage and experiment resumptionWhen a scheduler is SQL-enabled, it will automatically save all updates it makes to the experiment in the course of the optimization. The experiment can then be resumed in the event of a crash or after a pause.To store state of optimization to an SQL backend, first fo...
from ax.storage.sqa_store.structs import DBSettings from ax.storage.sqa_store.db import init_engine_and_session_factory, get_engine, create_all_tables from ax.storage.metric_registry import register_metric from ax.storage.runner_registry import register_runner register_metric(BraninForMockJobMetric) register_runner(Mo...
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
To resume a stored experiment:
reloaded_experiment_scheduler = MockJobQueueScheduler.from_stored_experiment( experiment_name='branin_test_experiment', options=SchedulerOptions(), # `DBSettings` are also required here so scheduler has access to the # database, from which it needs to load the experiment. db_settings=db_settings, )
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
With the newly reloaded experiment, the `Scheduler` can continue the optimization:
reloaded_experiment_scheduler.run_n_trials(max_trials=3)
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
7. Configuring the scheduler`Scheduler` exposes many options to configure the exact settings of the closed-loop optimization to perform. A few notable ones are:- `trial_type` –– currently only `Trial` and not `BatchTrial` is supported, but support for `BatchTrial`-s will follow,- `tolerated_trial_failure_rate` and `mi...
print(SchedulerOptions.__doc__)
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
8. Advanced functionality 8a. Reporting results to an external systemThe `Scheduler` can report the optimization result to an external system each time there are new completed trials if the user-implemented subclass implements `MySchedulerSubclass.report_results` to do so. For example, the folliwing method:```class My...
class ResultReportingScheduler(MockJobQueueScheduler): def report_results(self): return True, { "trials so far": len(self.experiment.trials), "currently producing trials from generation step": self.generation_strategy._curr.model_name, "running trials": [t.index for ...
_____no_output_____
MIT
tutorials/scheduler.ipynb
trsvchn/Ax
Imports
import os import multiprocessing #import rasterio import tensorflow as tf from glob import glob import pickle import numpy as np import os from tensorflow.keras.models import * from tensorflow.keras.layers import * from tensorflow.keras import layers import keras import pandas as pd #import matplotlib.pyplot as plt tf....
_____no_output_____
MIT
model-development/_archive/ml_explore_David_2.ipynb
Project-Canopy/SSRC_New_Model_Development
Test with Simple CNN and Data Loader
import boto3 import rasterio as rio import numpy as np import io from data_loader import DataLoader batch_size = 20 gen = DataLoader(label_file_path_train="labels_test_v1.csv", label_file_path_val="val_labels.csv", label_mapping_path="labels.json", bucket_name='canopy-pro...
3/3 [==============================] - 35s 10s/step - loss: 0.1902
MIT
model-development/_archive/ml_explore_David_2.ipynb
Project-Canopy/SSRC_New_Model_Development
Resnet50
def Resnet50(numclasses, input_shape): model = Sequential() model.add(keras.applications.ResNet50(include_top=False, pooling='avg', weights=None, input_shape=input_shape)) model.add(Flatten()) model.add(BatchNormalization()) model.add(Dense(2048, activation='relu')) model.add(BatchNormalization(...
_____no_output_____
MIT
model-development/_archive/ml_explore_David_2.ipynb
Project-Canopy/SSRC_New_Model_Development
TEST with bigearthnet-resnet50
import tensorflow_hub as hub IMAGE_SIZE = (100,100) num_classes = 10 model_handle = "https://tfhub.dev/google/remote_sensing/bigearthnet-resnet50/1" model_bigearthnet = tf.keras.Sequential([ tf.keras.layers.InputLayer(input_shape=IMAGE_SIZE + (3,)), # reshape? hub.KerasLayer(model_handle, trainable=False, ...
_____no_output_____
MIT
model-development/_archive/ml_explore_David_2.ipynb
Project-Canopy/SSRC_New_Model_Development
Preproduction Candidate: ResNet50 pretrained on ImageNet
gen = DataLoader(label_file_path_train="labels_test_v1.csv", #or labels.csv label_file_path_val="val_labels.csv", bucket_name='canopy-production-ml', data_extension_type='.tif', training_data_shape=(100, 100, 18), ...
Epoch 1/20 1/Unknown - 0s 0s/step - loss: 0.7377 - accuracy: 0.8900
MIT
model-development/_archive/ml_explore_David_2.ipynb
Project-Canopy/SSRC_New_Model_Development
Evaluation
model.evaluate(gen.validation_dataset)
3/3 [==============================] - 9s 3s/step - loss: 0.6661 - accuracy: 0.9473
MIT
model-development/_archive/ml_explore_David_2.ipynb
Project-Canopy/SSRC_New_Model_Development
Sandbox
# Applying albumentations help(gen.training_dataset) # necessary imports import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # import tensorflow_datasets as tfds from functools import partial from albumentations import ( Compose, RandomBrightness, JpegCompression, HueSaturationValue, RandomCo...
Help on package tensorflow._api.v2.image in tensorflow._api.v2: NAME tensorflow._api.v2.image - Image ops. DESCRIPTION The `tf.image` module contains various functions for image processing and decoding-encoding Ops. Many of the encoding/decoding functions are also available in the core `tf.io...
MIT
model-development/_archive/ml_explore_David_2.ipynb
Project-Canopy/SSRC_New_Model_Development
David's area
import boto3 import rasterio as rio import numpy as np import io import tensorflow as tf from tensorflow.keras.layers import Input, Conv2D, GlobalAveragePooling2D, Dense from tensorflow.keras.models import Model import keras from data_loader import DataLoader batch_size = 20 gen = DataLoader(label_file_path_train="lab...
_____no_output_____
MIT
model-development/_archive/ml_explore_David_2.ipynb
Project-Canopy/SSRC_New_Model_Development
Statistical Natural Language Processing in Python.orHow To Do Things With Words. And Counters.orEverything I Needed to Know About NLP I learned From Sesame Street.Except Kneser-Ney Smoothing.The Count Didn't Cover That. *One, two, three, ah, ah, ah!* &mdash; The Count (1) Data: Text and Words========Before we can do t...
TEXT = file('big.txt').read() len(TEXT)
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
So, six million characters.Now let's break the text up into words (or more formal-sounding, *tokens*). For now we'll ignore all the punctuation and numbers, and anything that is not a letter.
def tokens(text): "List all the word tokens (consecutive letters) in a text. Normalize to lowercase." return re.findall('[a-z]+', text.lower()) tokens('This is: A test, 1, 2, 3, this is.') WORDS = tokens(TEXT) len(WORDS)
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
So, a million words. Here are the first 10:
print(WORDS[:10])
['the', 'project', 'gutenberg', 'ebook', 'of', 'the', 'adventures', 'of', 'sherlock', 'holmes']
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
(2) Models: Bag of Words====The list `WORDS` is a list of the words in the `TEXT`, but it can also serve as a *generative model* of text. We know that language is very complicated, but we can create a simplified model of language that captures part of the complexity. In the *bag of words* model, we ignore the order of...
def sample(bag, n=10): "Sample a random n-word sentence from the model described by the bag of words." return ' '.join(random.choice(bag) for _ in range(n)) sample(WORDS)
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
Another representation for a bag of words is a `Counter`, which is a dictionary of `{'word': count}` pairs. For example,
Counter(tokens('Is this a test? It is a test!'))
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
A `Counter` is like a `dict`, but with a few extra methods. Let's make a `Counter` for the big list of `WORDS` and get a feel for what's there:
COUNTS = Counter(WORDS) print COUNTS.most_common(10) for w in tokens('the rare and neverbeforeseen words'): print COUNTS[w], w
80029 the 83 rare 38312 and 0 neverbeforeseen 460 words
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
In 1935, linguist George Zipf noted that in any big text, the *n*th most frequent word appears with a frequency of about 1/*n* of the most frequent word. He get's credit for *Zipf's Law*, even though Felix Auerbach made the same observation in 1913. If we plot the frequency of words, most common first, on a log-log pl...
M = COUNTS['the'] yscale('log'); xscale('log'); title('Frequency of n-th most frequent word and 1/n line.') plot([c for (w, c) in COUNTS.most_common()]) plot([M/i for i in range(1, len(COUNTS)+1)]);
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
(3) Task: Spelling Correction========Given a word *w*, find the most likely correction *c* = `correct(`*w*`)`.**Approach:** Try all candidate words *c* that are known words that are near *w*. Choose the most likely one.How to balance *near* and *likely*?For now, in a trivial way: always prefer nearer, but when there i...
def correct(word): "Find the best spelling correction for this word." # Prefer edit distance 0, then 1, then 2; otherwise default to word itself. candidates = (known(edits0(word)) or known(edits1(word)) or known(edits2(word)) or [word]) return max...
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
The functions `known` and `edits0` are easy; and `edits2` is easy if we assume we have `edits1`:
def known(words): "Return the subset of words that are actually in the dictionary." return {w for w in words if w in COUNTS} def edits0(word): "Return all strings that are zero edits away from word (i.e., just word itself)." return {word} def edits2(word): "Return all strings that are two edits a...
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
Now for `edits1(word)`: the set of candidate words that are one edit away. For example, given `"wird"`, this would include `"weird"` (inserting an `e`) and `"word"` (replacing a `i` with a `o`), and also `"iwrd"` (transposing `w` and `i`; then `known` can be used to filter this out of the set of final candidates). How ...
def edits1(word): "Return all strings that are one edit away from this word." pairs = splits(word) deletes = [a+b[1:] for (a, b) in pairs if b] transposes = [a+b[1]+b[0]+b[2:] for (a, b) in pairs if len(b) > 1] replaces = [a+c+b[1:] for (a, b) in pairs for c in alphabet i...
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
Can we make the output prettier than that?
def correct_text(text): "Correct all the words within a text, returning the corrected text." return re.sub('[a-zA-Z]+', correct_match, text) def correct_match(match): "Spell-correct word in match, and preserve proper upper/lower/title case." word = match.group() return case_of(word)(correct(word.lo...
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
So far so good. You can probably think of a dozen ways to make this better. Here's one: in the text "three, too, one, blastoff!" we might want to correct "too" with "two", even though "too" is in the dictionary. We can do better if we look at a *sequence* of words, not just an individual word one at a time. But how...
def pdist(counter): "Make a probability distribution, given evidence from a Counter." N = sum(counter.values()) return lambda x: counter[x]/N Pword = pdist(COUNTS) # Print probabilities of some words for w in tokens('"The" is most common word in English'): print Pword(w), w
0.0724106075672 the 0.00884356018896 is 0.000821562579453 most 0.000259678921039 common 0.000269631771671 word 0.0199482270806 in 0.000190913771217 english
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
Now, what is the probability of a *sequence* of words? Use the definition of a joint probability:$P(w_1 \ldots w_n) = P(w_1) \times P(w_2 \mid w_1) \times P(w_3 \mid w_1 w_2) \ldots \times \ldots P(w_n \mid w_1 \ldots w_{n-1})$In the bag of words model, each word is drawn from the bag *independently* of the others. ...
def Pwords(words): "Probability of words, assuming each word is independent of others." return product(Pword(w) for w in words) def product(nums): "Multiply the numbers together. (Like `sum`, but with multiplication.)" result = 1 for x in nums: result *= x return result tests = ['this ...
2.98419543271e-11 this is a test 8.64036404331e-16 this is a unusual test 0.0 this is a neverbeforeseen test
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
Yikes&mdash;it seems wrong to give a probability of 0 to the last one; it should just be very small. We'll come back to that later. The other probabilities seem reasonable. (5) Task: Word Segmentation====**Task**: *given a sequence of characters with no spaces separating words, recover the sequence of words.* Why? ...
def memo(f): "Memoize function f, whose args must all be hashable." cache = {} def fmemo(*args): if args not in cache: cache[args] = f(*args) return cache[args] fmemo.cache = cache return fmemo max(len(w) for w in COUNTS) def splits(text, start=0, L=20): "Return a lis...
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
That's a problem. We'll come back to it later.
segment('smallandinsignificant') segment('largeandinsignificant') print(Pwords(['large', 'and', 'insignificant'])) print(Pwords(['large', 'and', 'in', 'significant']))
4.1121373609e-10 1.06638804821e-11
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
Summary: - Looks pretty good!- The bag-of-words assumption is a limitation.- Recomputing Pwords on each recursive call is somewhat inefficient.- Numeric underflow for texts longer than 100 or so words; we'll need to use logarithms, or other tricks. (6) Data: Mo' Data, Mo' Better Let's move up from millions to *bill...
def load_counts(filename, sep='\t'): """Return a Counter initialized from key-value pairs, one on each line of filename.""" C = Counter() for line in open(filename): key, count = line.split(sep) C[key] = int(count) return C COUNTS1 = load_counts('count_1w.txt') COUNTS2 = load_counts...
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
(7) Theory and Practice: Segmentation With Bigram Data===A less-wrong approximation: $P(w_1 \ldots w_n) = P(w_1 \mid start) \times P(w_2 \mid w_1) \times P(w_3 \mid w_2) \ldots \times \ldots P(w_n \mid w_{n-1})$This is called the *bigram* model, and is equivalent to taking a text, cutting it up into slips of paper ...
def Pwords2(words, prev='<S>'): "The probability of a sequence of words, using bigram data, given prev word." return product(cPword(w, (prev if (i == 0) else words[i-1]) ) for (i, w) in enumerate(words)) P = P1w # Use the big dictionary for the probability of a word def cPword(word, prev): ...
2.98419543271e-11 6.41367629438e-08 1.18028600367e-11
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
To make `segment2`, we copy `segment`, and make sure to pass around the previous token, and to evaluate probabilities with `Pwords2` instead of `Pwords`.
@memo def segment2(text, prev='<S>'): "Return best segmentation of text; use bigram data." if not text: return [] else: candidates = ([first] + segment2(rest, first) for (first, rest) in splits(text, 1)) return max(candidates, key=lambda words: Pwords2(word...
['a', 'dry', 'bare', 'sandy', 'hole', 'with', 'nothing', 'in', 'it', 'to', 'sit', 'down', 'on', 'or', 'to', 'eat'] ['a', 'dry', 'bare', 'sandy', 'hole', 'with', 'nothing', 'in', 'it', 'to', 'sit', 'down', 'on', 'or', 'to', 'eat']
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
Conclusion? Bigram model is a little better, but not much. Hundreds of billions of words still not enough. (Why not trillions?) Could be made more efficient. (8) Theory: Evaluation===So far, we've got an intuitive feel for how this all works. But we don't have any solid metrics that quantify the results. Without met...
def test_segmenter(segmenter, tests): "Try segmenter on tests; report failures; return fraction correct." return sum([test_one_segment(segmenter, test) for test in tests]), len(tests) def test_one_segment(segmenter, test): words = tokens(test) result = segmenter(cat(words)) correct ...
_____no_output_____
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes
This confirms that both segmenters are very good, and that `segment2` is slightly better. There is much more that can be done in terms of the variety of tests, and in measuring statistical significance. (9) Theory and Practice: Smoothing======Let's go back to a test we did before, and add some more test cases:
tests = ['this is a test', 'this is a unusual test', 'this is a nongovernmental test', 'this is a neverbeforeseen test', 'this is a zqbhjhsyefvvjqc test'] for test in tests: print Pwords(tokens(test)), test
2.98419543271e-11 this is a test 8.64036404331e-16 this is a unusual test 0.0 this is a nongovernmental test 0.0 this is a neverbeforeseen test 0.0 this is a zqbhjhsyefvvjqc test
MIT
ipynb/How to Do Things with Words.ipynb
mikiec84/pytudes