markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Class Label | target = pd.DataFrame(pd.Series(data.target).value_counts(), columns=('Frequency',))
target['Percentage'] = (target['Frequency'] / target['Frequency'].sum()) * 100
target.index = ['Negative (Legitimate Trx)', 'Positive (Fraud Trx)']
target.loc['Total Trx'] = [data.target.shape[0], 1.]
print(target) | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Features | pd.DataFrame(data.feature_names[:4], columns=('Features',)) | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Features | df = pd.DataFrame(data.data[:, :4], columns=data.feature_names[:4])
df.head(10) | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Aggregated Features | df = pd.DataFrame(data.data[:, 4:], columns=data.feature_names[4:])
df.head(10) | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Fraud Detection as a classification problem
Split in training and testing | from sklearn.cross_validation import train_test_split
X = data.data[:, [2, 3] + list(range(4, data.data.shape[1]))].astype(np.float)
X_train, X_test, y_train, y_test, cost_mat_train, cost_mat_test = \
train_test_split(X, data.target, data.cost_mat, test_size=0.33, random_state=10) | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Fraud Detection as a classification problem
Fit models | from sklearn.ensemble import RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
classifiers = {"RF": {"f": RandomForestClassifier()},
"DT": {"f": DecisionTreeClassifier()}}
ci_models = ['DT', 'RF']
# Fit the classifiers using the training dataset
for model in classifiers.keys():
... | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Models performance
Evaluate metrics and plot results | import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
import matplotlib.pyplot as plt
from IPython.core.pylabtools import figsize
import seaborn as sns
colors = sns.color_palette()
figsize(12, 8)
from sklearn.metrics import f1_score, precision_score, recall_score, accuracy_score
measures = {"F1Score":... | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Models performance | def fig_acc():
plt.bar(np.arange(results.shape[0])-0.3, results['Accuracy'], 0.6, label='Accuracy', color=colors[0])
plt.xticks(range(results.shape[0]), results.index)
plt.tick_params(labelsize=22); plt.title('Accuracy', size=30)
plt.show()
fig_acc() | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Models performance | def fig_f1():
plt.bar(np.arange(results.shape[0])-0.3, results['Precision'], 0.2, label='Precision', color=colors[0])
plt.bar(np.arange(results.shape[0])-0.3+0.2, results['Recall'], 0.2, label='Recall', color=colors[1])
plt.bar(np.arange(results.shape[0])-0.3+0.4, results['F1Score'], 0.2, label='F1Score', c... | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Models performance
None of these measures takes into account the business and economical realities that take place in fraud detection.
Losses due to fraud or customer satisfaction costs, are not considered in the evaluation of the different models.
<h1 class="bigtitle">Financial Evaluation of a Fraud Detection ... | # The cost matrix is already calculated for the dataset
# cost_mat[C_FP,C_FN,C_TP,C_TN]
print(data.cost_mat[[10, 17, 50]]) | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Financial savings
The financial cost of using a classifier $f$ on $\mathcal{S}$ is calculated by
$$ Cost(f(\mathcal{S})) = \sum_{i=1}^N y_i(1-c_i)C_{FN_i} + (1-y_i)c_i C_{FP_i}.$$
Then the financial savings are defined as the cost of the algorithm versus the cost of using no algorithm at all.
$$ Savings(f(\mathca... | # Calculation of the cost and savings
from costcla.metrics import savings_score, cost_loss
# Evaluate the savings for each model
results["Savings"] = np.zeros(results.shape[0])
for model in ci_models:
results["Savings"].loc[model] = savings_score(y_test, classifiers[model]["c"], cost_mat_test)
# Plot the results
... | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Models Savings | fig_sav() | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Threshold Optimization
Convert a classifier cost-sensitive by selecting a proper threshold
from training instances according to the savings
$$ t \quad = \quad argmax_t \: Savings(c(t), y) $$
Threshold Optimization - Code
costcla.models.ThresholdingOptimization(calibration=True)
fit(y_prob_train=None, cost_mat, y_true_... | from costcla.models import ThresholdingOptimization
for model in ci_models:
classifiers[model+"-TO"] = {"f": ThresholdingOptimization()}
# Fit
classifiers[model+"-TO"]["f"].fit(classifiers[model]["p_train"], cost_mat_train, y_train)
# Predict
classifiers[model+"-TO"]["c"] = classifiers[model+"-TO"]... | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Threshold Optimization | fig_sav() | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Models Savings
There are significant differences in the results when evaluating a model using a traditional cost-insensitive measures
Train models that take into account the different financial costs
<h1 class="bigtitle">Example-Dependent Cost-Sensitive Classification</h1>
*Why "Example-Dependent"
Cost-sensitiv... | from costcla.models import BayesMinimumRiskClassifier
for model in ci_models:
classifiers[model+"-BMR"] = {"f": BayesMinimumRiskClassifier()}
# Fit
classifiers[model+"-BMR"]["f"].fit(y_test, classifiers[model]["p"])
# Calibration must be made in a validation set
# Predict
classifiers[model+"-BM... | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
BMR Results | fig_sav() | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
BMR Results
Why so important focusing on the Recall
Average cost of a False Negative | print(data.data[data.target == 1, 2].mean()) | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Average cost of a False Positive | print(data.cost_mat[:,0].mean()) | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
BMR Results
Bayes Minimum Risk increases the savings by using a cost-insensitive method and then introducing the costs
Why not introduce the costs during the estimation of the methods?
Cost-Sensitive Decision Trees (CSDT)
A a new cost-based impurity measure taking into account the costs when all the examples in a lea... | from costcla.models import CostSensitiveDecisionTreeClassifier
from costcla.models import CostSensitiveRandomForestClassifier
classifiers = {"CSDT": {"f": CostSensitiveDecisionTreeClassifier()},
"CSRF": {"f": CostSensitiveRandomForestClassifier(combination='majority_bmr')}}
# Fit the classifiers using... | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
CSDT & CSRF Results | fig_sav() | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
Lessons Learned (so far ...)
Selecting models based on traditional statistics does not give the best results in terms of cost
Models should be evaluated taking into account real financial costs of the application
Algorithms should be developed to incorporate those financial costs
<center>
<img src="https://raw.... | #Format from https://github.com/ellisonbg/talk-2013-scipy
from IPython.display import display, HTML
s = """
<style>
.rendered_html {
font-family: "proxima-nova", helvetica;
font-size: 100%;
line-height: 1.3;
}
.rendered_html h1 {
margin: 0.25em 0em 0.5em;
color: #015C9C;
text-align: center;
... | doc/tutorials/slides_edcs_fraud_detection.ipynb | albahnsen/CostSensitiveClassification | bsd-3-clause |
We will import the appropriate parts from AdaptiveMD as we go along so it is clear what it needed at what stage. Usually you will have the block of imports at the beginning of your script or notebook as suggested in PEP8. | from adaptivemd import Project | examples/rp/1_example_setup_project.ipynb | thempel/adaptivemd | lgpl-2.1 |
Let's open a project with a UNIQUE name. This will be the name used in the DB so make sure it is new and not too short. Opening a project will always create a non-existing project and reopen an exising one. You cannot chose between opening types as you would with a file. This is a precaution to not accidentally delete ... | project = Project('test') | examples/rp/1_example_setup_project.ipynb | thempel/adaptivemd | lgpl-2.1 |
Now we have a handle for our project. First thing is to set it up to work on a resource.
1. Set the resource
What is a resource? A Resource specifies a shared filesystem with one or more clusteres attached to it. This can be your local machine or just a regular cluster or even a group of cluster that can access the sam... | from adaptivemd import LocalCluster AllegroCluster
resource_id = 'local.jhp'
if resource_id == 'local.jhp':
project.initialize(LocalJHP())
elif resource_id == 'local.sheep':
project.initialize(LocalSheep())
elif resource_id == 'fub.allegro':
project.initialize(AllegroCluster()) | examples/rp/1_example_setup_project.ipynb | thempel/adaptivemd | lgpl-2.1 |
TaskGenerators
TaskGenerators are instances whose purpose is to create tasks to be executed. This is similar to the
way Kernels work. A TaskGenerator will generate Task objects for you which will be translated into a ComputeUnitDescription and executed. In simple terms:
The task generator creates the bash scripts for y... | from adaptivemd.engine.openmm import OpenMMEngine
from adaptivemd.analysis.pyemma import PyEMMAAnalysis
from adaptivemd import File, Directory | examples/rp/1_example_setup_project.ipynb | thempel/adaptivemd | lgpl-2.1 |
The engine
A task generator that will create jobs to run simulations. Currently it uses a little python script that will excute OpenMM. It requires conda to be added to the PATH variable or at least openmm to be installed on the cluster. If you setup your resource correctly then this should all happen automatically.
Fi... | pdb_file = File('file://../files/alanine/alanine.pdb').named('initial_pdb') | examples/rp/1_example_setup_project.ipynb | thempel/adaptivemd | lgpl-2.1 |
Here we used a special prefix that can point to specific locations.
file:// points to files on your local machine.
unit:// specifies files on the current working directory of the executing node. Usually these are temprary files for a single execution.
shared:// specifies the root shared FS directory (e.g. NO_BACKUP/... | engine = OpenMMEngine(
pdb_file=pdb_file,
system_file=File('file://../files/alanine/system.xml'),
integrator_file=File('file://../files/alanine/integrator.xml'),
args='-r --report-interval 1 -p CPU --store-interval 1'
).named('openmm') | examples/rp/1_example_setup_project.ipynb | thempel/adaptivemd | lgpl-2.1 |
Again we name it pyemma for later reference.
Add generators to project
Next step is to add these to the project for later usage. We pick the .generators store and just add it. Consider a store to work like a set() in python. It contains objects only once and is not ordered. Therefore we need a name to find the objects ... | import datetime
datetime.datetime.fromtimestamp(modeller.__time__).strftime("%Y-%m-%d %H:%M:%S")
project.generators.add(engine)
project.generators.add(modeller)
print project.generators | examples/rp/1_example_setup_project.ipynb | thempel/adaptivemd | lgpl-2.1 |
The Gelman-Rubin statistic and emcee
In this post, I'll give a simple demo of using the Gelman-Rubin statistic (see this paper for an overview and alternatives to quantify convergance when using the emcee software package. There are issues with this approach which remain to be addressed. The Gelman-Rubin statistic appl... | # Model parameters
A = 2.3
f = 1
X0 = 2.5
# Noise parameter
sigma = 0.6
N = 500
t = np.sort(np.random.uniform(0, 10, N))
X = X0 + A * np.sin(2 * np.pi * f * t) + np.random.normal(0, sigma, N)
plt.plot(t, X, "o")
plt.xlabel("$t$")
plt.ylabel(r"$X_{\mathrm{obs}}$")
plt.show() | _notebooks/09-02-2017-The-Gelman-Rubin-Statistic-and-emcee.ipynb | ga7g08/ga7g08.github.io | mit |
Set-up for using emcee
Define some generic helper functions | def Generic_lnuniformprior(theta, theta_lims):
""" Generic uniform priors on theta
Parameters
----------
theta : array_like
Value of the parameters
theta_lims: array_like of shape (len(theta), 2)
Array of pairs [min, max] for each theta paramater
"""
thet... | _notebooks/09-02-2017-The-Gelman-Rubin-Statistic-and-emcee.ipynb | ga7g08/ga7g08.github.io | mit |
Define model and uniform prior | def model(theta, t):
A, f, X0 = theta
return X0 + A * np.sin(2 * np.pi * f * t)
lnlike = lambda theta, x, y: Generic_lnlike(theta, x, y, model)
# Tie the two together
def lnprob(theta, x, y):
""" Generic function ties together the lnprior and lnlike """
lp = lnprior(theta)
if not np.i... | _notebooks/09-02-2017-The-Gelman-Rubin-Statistic-and-emcee.ipynb | ga7g08/ga7g08.github.io | mit |
Calculating the PSRF
Here, I follow the description on this blog for how to calculate the Potential Scale Reduction Factor (PSRF), a measure of the converegance. For PSRF < 1.2, Gelman & Rubin state the the chains have converged.
In practical terms, the sampler is run for a number of steps, the PSRF is calculated, and ... | def get_convergence_statistic(i, sampler, nwalkers, convergence_length=10,
convergence_period=10):
s = sampler.chain[:, i-convergence_length+1:i+1, :]
within_std = np.mean(np.var(s, axis=1), axis=0)
per_walker_mean = np.mean(s, axis=1)
mean = np.mean(per_walker_mean, axis=0... | _notebooks/09-02-2017-The-Gelman-Rubin-Statistic-and-emcee.ipynb | ga7g08/ga7g08.github.io | mit |
Okay, now here is an example | ndim = 4
nwalkers = 100
nsteps = 400
# Initialise the walkers
walker_pos = [[np.random.uniform(tl[0], tl[1]) for tl in theta_lims]
for i in range(nwalkers)]
# Run the sampler
sampler = emcee.EnsembleSampler(nwalkers, ndim, lnprob, args=(t, X))
PSRF = []
PSRFx ... | _notebooks/09-02-2017-The-Gelman-Rubin-Statistic-and-emcee.ipynb | ga7g08/ga7g08.github.io | mit |
pyspark.sql.functions functions
pyspark.sql.functions is collection of built-in functions for creating column expressions. These functions largely increase methods that we can use to manipulate DataFrame and DataFrame columns.
There are many sql functions from the pyspark.sql.functions module. Here I only choose a few ... | from pyspark.sql import functions as F | notebooks/02-data-manipulation/2.8-sql-functions-to-extend-column-expressions.ipynb | MingChen0919/learning-apache-spark | mit |
abs(): create column expression that returns absolute values of a column | from pyspark.sql import Row
df = sc.parallelize([Row(x=1), Row(x=-1), Row(x=-2)]).toDF()
df.show()
x_abs = F.abs(df.x)
x_abs
df.select(df.x, x_abs).show() | notebooks/02-data-manipulation/2.8-sql-functions-to-extend-column-expressions.ipynb | MingChen0919/learning-apache-spark | mit |
concat(): create column expression that concatenates multiple column values into one | df = sc.parallelize([Row(a='apple', b='tree'), Row(a='orange', b='flowers')]).toDF()
df.show()
ab_concat = F.concat(df.a, df.b)
ab_concat
df.select(df.a, df.b, ab_concat).show() | notebooks/02-data-manipulation/2.8-sql-functions-to-extend-column-expressions.ipynb | MingChen0919/learning-apache-spark | mit |
corr(): create column expression that returns pearson correlation coefficient between two columns | mtcars = spark.read.csv('../../data/mtcars.csv', inferSchema=True, header=True)
mtcars.show(5)
drat_wt_corr = F.corr(mtcars.drat, mtcars.wt)
drat_wt_corr
mtcars.select(drat_wt_corr).show() | notebooks/02-data-manipulation/2.8-sql-functions-to-extend-column-expressions.ipynb | MingChen0919/learning-apache-spark | mit |
array(): create column expression that merge multiple column values into an array
This function can be used to build feature column in machine learning models. | cols = [eval('mtcars.' + col) for col in mtcars.columns[1:]]
cols
cols_array = F.array(cols)
cols_array
mtcars.select(cols_array).show(truncate=False) | notebooks/02-data-manipulation/2.8-sql-functions-to-extend-column-expressions.ipynb | MingChen0919/learning-apache-spark | mit |
Next, set the environment variables related to your GCP Project. | PROJECT = "cloud-training-demos" # Replace with your PROJECT
BUCKET = "cloud-training-bucket" # Replace with your BUCKET
REGION = "us-central1" # Choose an available region for Cloud MLE
TFVERSION = "1.14" # TF version for CMLE to use
import os
os.environ["BUCKET"] = BUCKET
os.environ["PROJ... | courses/machine_learning/deepdive/05_review/4_preproc.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Save the query from earlier
The data is natality data (record of births in the US). My goal is to predict the baby's weight given a number of factors about the pregnancy and the baby's mother. Later, we will want to split the data into training and eval datasets. The hash of the year-month will be used for that. | # Create SQL query using natality data after the year 2000
query_string = """
SELECT
weight_pounds,
is_male,
mother_age,
plurality,
gestation_weeks,
FARM_FINGERPRINT(CONCAT(CAST(YEAR AS STRING), CAST(month AS STRING))) AS hashmonth
FROM
publicdata.samples.natality
WHERE
year > 2000
"""
... | courses/machine_learning/deepdive/05_review/4_preproc.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Create ML dataset using Dataflow
Let's use Cloud Dataflow to read in the BigQuery data, do some preprocessing, and write it out as CSV files.
Instead of using Beam/Dataflow, I had three other options:
Use Cloud Dataprep to visually author a Dataflow pipeline. Cloud Dataprep also allows me to explore the data, so we co... | import apache_beam as beam
import datetime, os
def to_csv(rowdict):
# Pull columns from BQ and create a line
import hashlib
import copy
CSV_COLUMNS = "weight_pounds,is_male,mother_age,plurality,gestation_weeks".split(',')
# Create synthetic data where we assume that no ultrasound has been performe... | courses/machine_learning/deepdive/05_review/4_preproc.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
For a Cloud preprocessing job (i.e. setting in_test_mode to False), the above step will take 20+ minutes. Go to the GCP web console, navigate to the Dataflow section and <b>wait for the job to finish</b> before you run the follwing step.
View results
We can have a look at the elements in our bucket to see the results o... | !gsutil ls gs://$BUCKET/babyweight/preproc/*-00000* | courses/machine_learning/deepdive/05_review/4_preproc.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Preprocessing with BigQuery
Create SQL query for BigQuery that will union all both the ultrasound and no ultrasound datasets. | query = """
WITH CTE_Raw_Data AS (
SELECT
weight_pounds,
CAST(is_male AS STRING) AS is_male,
mother_age,
plurality,
gestation_weeks,
FARM_FINGERPRINT(CONCAT(CAST(YEAR AS STRING), CAST(month AS STRING))) AS hashmonth
FROM
publicdata.samples.natality
WHERE
year > 2000
AND weight_pounds > 0
AND mother_... | courses/machine_learning/deepdive/05_review/4_preproc.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Create temporary BigQuery dataset | from google.cloud import bigquery
# Construct a BigQuery client object.
client = bigquery.Client()
# Set dataset_id to the ID of the dataset to create.
dataset_name = "temp_babyweight_dataset"
dataset_id = "{}.{}".format(client.project, dataset_name)
# Construct a full Dataset object to send to the API.
dataset = bi... | courses/machine_learning/deepdive/05_review/4_preproc.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Execute query and write to BigQuery table. | job_config = bigquery.QueryJobConfig()
for step in ["train", "eval"]:
if step == "train":
selquery = "SELECT * FROM ({}) WHERE ABS(MOD(hashmonth, 100)) < 80".format(query)
elif step == "eval":
selquery = "SELECT * FROM ({}) WHERE ABS(MOD(hashmonth, 100)) >= 80 AND ABS(MOD(hashmonth, 100)) < 90".... | courses/machine_learning/deepdive/05_review/4_preproc.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Export BigQuery table to CSV in GCS. | dataset_ref = client.dataset(dataset_id=dataset_name, project=PROJECT)
for step in ["train", "eval"]:
destination_uri = "gs://{}/{}".format(BUCKET, "babyweight/bq_data/{}*.csv".format(step))
table_name = "babyweight_{}".format(step)
table_ref = dataset_ref.table(table_name)
extract_job = client.extract... | courses/machine_learning/deepdive/05_review/4_preproc.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
View results
We can have a look at the elements in our bucket to see the results of our pipeline above. | !gsutil ls gs://$BUCKET/babyweight/bq_data/*000000000000* | courses/machine_learning/deepdive/05_review/4_preproc.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
The above python statement created an instance of project-k object.
2. Try the Virtual Machine's basic features
Let's try some project-k vm methods: | vm.dictate("123").stack | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
vm.dictate() method is the way project-k VM receives your commands (in a multiple lines string). It actually is also the way we feed it an entire Forth source code file. "123" means: "please push this number into the FORTH data stack". vm.stack is the Forth VM data stack which was empty at first and now has one item, 1... | vm.dictate("code hi print('Hello World!!') end-code hi"); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
A code word is defined between code and end-code. The first token after the leading code, which is 'hi' in this example, is the name of the new FORTH word. All the rests down to the ending end-code are python statements. Note after end-code above we execute hi the new word immediately and it works!
4. Define the 'words... | vm.dictate("code words print([w.name for w in words['forth'][1:]]) end-code words"); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
Where the vm.words that appears in above definition is project-k vm's word-list that is a common component of a FORTH system. We can see it this way: | vm.words | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
5. Define commands + , .s , and s".
These examples demonstrate project-k built-in methods push(), pop(), and nexttoken(). | vm.dictate("code + push(pop(1)+pop()) end-code"); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
The vm knows how to do the '+' now, let's try: | vm.stack=[] # clear the data stack
vm.dictate("123 456 +").stack | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
FORTH is a programming language of postfix-expression. "123 456 +" means: "Please push 123 into the data stack, please push 456 too. Now please get the top two cells out of the data stack, add them and push the result back to the data stack". The result is 579 left in the data stack.
The common FORTH word to view its ... | vm.dictate("code .s print(stack) end-code");
vm.execute('.s'); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
Another FORTH word that quotes a text string is s" that can be defined like this: | vm.dictate('code s" push(nexttoken(\'"\'));nexttoken() end-code'); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
The FORTH term TIB (terminal input buffer) is simply the string given from vm.dictate('I am the TIB'). nexttoken() is a project-k built-in function that gets a quote out of the TIB from the current position to the given delimiter which is " in the example above. So FORTH strings can now be expressed by s" this is a str... | # Put a string onto the TOS (Top of the data stack)
vm.dictate('s" The wise build bridges, " .s');
vm.dictate('s" while the foolish build barriers." .s'); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
and according to the + word we defined above, it can concatenate two strings too. So let's execute + and check the result on the data stack: | vm.execute('+').execute('.s'); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
The two strings are correctly concatenated into one.
Look into the project-k module object
6. See them all at a glance
First, let's see what are in the vm. When in a code word definition these properties are global variables and global functions being seen in that new word. | # list all global functions and global variables seen in a code word definition.
print([propertie for propertie in dir(vm) if not propertie.startswith('__')])
# List only functions out of the aboves
print([method for method in dir(vm) if callable(getattr(vm,method))]) | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
7. Get help of project-k global functions
Project-k built-in functions are explained with comments in the projectk.py source code. View them by using the python help() function. | help(vm.tos)
help(vm.pop)
help(vm.push)
help(vm.nexttoken) | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
8. Self-reference of a code word | vm.dictate("code see-locals print(locals()) end-code see-locals"); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
The _me object points to the new word itself. For example, this word prints its own name: | vm.dictate("code who-am-I? print('My name is: ' + _me.name) end-code").execute('who-am-I?'); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
9. Let's see the globals
You will want to know about the globals when at the view point in a code word definition. Many of them have been seen above yet this is from a different view point. | vm.dictate("code see-globals print(globals().keys()) end-code see-globals"); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
The __name__ is 'projectk', as shown below, that indicates that the namespace of this small world is within the FORTH virtual machine. We can't see anything in the outside world unless vm.push() passes them into the data stack. | vm.dictate("code see__name__ print(globals()['__name__']) end-code see__name__"); | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
For example, this jupyter notebook itself is the main program we are running and through vm.push() we can pass this information into the FORTH vm and get it back by vm.pop(): | vm.push(__name__).pop()
vm.push(__IPYTHON__).pop() # see another property from the main program | Play with the FORTH kernel on jupyter notebook.ipynb | hcchengithub/project-k | mit |
Attention: Please avoid using the TPU runtime (TPU=True) for now. The notebook contains an optional part on TPU usage at the end if you're interested. You can change the runtime via: "Runtime > Change runtime type > Hardware Accelerator" in Colab.
Data from Protobufs | # Load data from Drive (Colab only).
data_path = '/content/gdrive/My Drive/amld_data/zoo_img'
# Or, you can load data from different sources, such as:
# From your local machine:
# data_path = './amld_data'
# Or use a prepared dataset from Cloud (Colab only).
# - 50k training examples, including pickled DataFrame.
# d... | extras/amld/notebooks/exercises/2_keras.ipynb | tensorflow/workshops | apache-2.0 |
Linear model | # Sample linear model.
linear_model = tf.keras.Sequential()
linear_model.add(tf.keras.layers.Flatten(input_shape=(64, 64,)))
linear_model.add(tf.keras.layers.Dense(len(labels), activation='softmax'))
# "adam, categorical_crossentropy, accuracy" and other string constants can be
# found at https://keras.io.
linear_mode... | extras/amld/notebooks/exercises/2_keras.ipynb | tensorflow/workshops | apache-2.0 |
Convolutional model | # Let's define a convolutional model:
conv_model = tf.keras.Sequential([
tf.keras.layers.Reshape(target_shape=(64, 64, 1), input_shape=(64, 64)),
tf.keras.layers.Conv2D(filters=32,
kernel_size=(10, 10),
padding='same',
activatio... | extras/amld/notebooks/exercises/2_keras.ipynb | tensorflow/workshops | apache-2.0 |
Store model | tf.io.gfile.makedirs(models_path)
# Save model as Keras model.
keras_path = os.path.join(models_path, 'linear.h5')
linear_model.save(keras_path)
# Keras model is a single file.
!ls -hl "$keras_path"
# Load Keras model.
loaded_keras_model = tf.keras.models.load_model(keras_path)
loaded_keras_model.summary()
# Save m... | extras/amld/notebooks/exercises/2_keras.ipynb | tensorflow/workshops | apache-2.0 |
----- Optional part -----
Learn from errors
Looking at classification mistakes is a great way to better understand how a model is performing. This section walks you through the necessary steps to load some examples from the dataset, make predictions, and plot the mistakes. | import collections
Mistake = collections.namedtuple('Mistake', 'label pred img_64')
mistakes = []
eval_ds_iter = iter(eval_ds)
for img_64_batch, label_onehot_batch in eval_ds_iter:
break
img_64_batch.shape, label_onehot_batch.shape
# YOUR ACTION REQUIRED:
# Use model.predict() to get a batch of predictions.
preds =... | extras/amld/notebooks/exercises/2_keras.ipynb | tensorflow/workshops | apache-2.0 |
Data from DataFrame
For comparison, this section shows how you would load data from a pandas.DataFrame and then use Keras for training. Note that this approach does not scale well and can only be used for quite small datasets. | # Note: used memory BEFORE loading the DataFrame.
!free -h
# Loading all the data in memory takes a while (~40s).
import pickle
df = pickle.load(tf.io.gfile.GFile('%s/dataframe.pkl' % data_path, mode='rb'))
print(len(df))
print(df.columns)
df_train = df[df.split == b'train']
len(df_train)
# Note: used memory AFTER l... | extras/amld/notebooks/exercises/2_keras.ipynb | tensorflow/workshops | apache-2.0 |
TPU Support
For using TF with a TPU we'll need to make some adjustments. Generally, please note that several TF TPU features are experimental and might not work as smooth as it does with a CPU or GPU.
Attention: Please make sure to switch the runtime to TPU for this part. You can do so via: "Runtime > Change runtime t... | %tensorflow_version 2.x
import json, os
import numpy as np
from matplotlib import pyplot as plt
import tensorflow as tf
# Disable duplicate logging output in TF.
logger = tf.get_logger()
logger.propagate = False
# This will fail if no TPU is connected...
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
# Se... | extras/amld/notebooks/exercises/2_keras.ipynb | tensorflow/workshops | apache-2.0 |
Attention: TPUs require all files (input and models) to be stored in cloud storage buckets (gs://bucket-name/...). If you plan to use TPUs please choose the data_path below accordingly. Otherwise, you might run into File system scheme '[local]' not implemented errors. | from google.colab import auth
auth.authenticate_user()
# Browse datasets:
# https://console.cloud.google.com/storage/browser/amld-datasets
# - 50k training examples, including pickled DataFrame.
data_path = 'gs://amld-datasets/zoo_img_small'
# - 1M training examples, without pickled DataFrame.
# data_path = 'gs://aml... | extras/amld/notebooks/exercises/2_keras.ipynb | tensorflow/workshops | apache-2.0 |
Load & Read Datasets | train = pd.read_csv('train.tsv', delimiter='\t')
test = pd.read_csv('test.tsv', delimiter='\t')
train.shape, test.shape
train.head()
test.head()
# unique sentiment labels
train.Sentiment.unique()
train.info()
train.Sentiment.value_counts()
train.Sentiment.value_counts() / train.Sentiment.count() | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Extracting features
In order to perform machine learning on text documents, we first need to turn the text content into numerical feature vectors.
Bags of words
The most intuitive way to do so is the bags of words representation:
assign a fixed integer id to each word occurring in any document of the training set (fo... | X_train = train['Phrase']
y_train = train['Sentiment']
# Convert a collection of text documents to a matrix of token counts
count_vect = CountVectorizer()
# Fit followed by Transform
# Learn the vocabulary dictionary and return term-document matrix
X_train_counts = count_vect.fit_transform(X_train)
#X_train_count =... | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Convert Occurrence to Frequency
Problem with occurrence count of words:
- longer documents will have higher average count values than shorter documents, even though they might talk about the same topics
Solution:
- divide the number of occurrences of each word in a document by the total number of words in the document
... | tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts)
X_train_tf = tf_transformer.transform(X_train_counts)
# 156060 rows of train data & 15240 features (one for each vocabulary word)
X_train_tf.shape
# print some values of tf-idf transformed feature vector
print X_train_tf[1:2] | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
In the above code, we first used the fit() method to fit our estimator and then the transform() method to transform our count-matrix to a tf-idf representation.
These two steps can be combined using fit_transform() method. | tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
X_train_tfidf.shape | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Train Classifier
We train our classifier by inputing our features and expecting our classifier to output/predict the sentiment value for each phrase in test dataset.
Naive Bayes Classifier | clf = MultinomialNB().fit(X_train_tfidf, y_train)
predicted = clf.predict(X_train_tfidf)
np.mean(predicted == y_train) | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Building a Pipeline
In order to make the vectorizer => transformer => classifier easier to work with, scikit-learn provides a Pipeline class that behaves like a compound classifier.
You can compare the above accuracy result of the classifier without using Pipeline and the below accuracy result of the classifier while u... | text_clf = Pipeline([
('vect', CountVectorizer()),
('tfidf', TfidfTransformer()),
('clf', MultinomialNB()),
])
text_clf.fit(X_train, y_train)
predicted = text_clf.predict(X_train)
np.mean(predicted == y_train) | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Let's use stop words filter in CountVectorizer method and see how it affects the classifier's accuracy. We see that this increases accuracy. | text_clf = Pipeline([
('vect', CountVectorizer(stop_words='english')),
('tfidf', TfidfTransformer()),
('clf', MultinomialNB()),
])
text_clf.fit(X_train, y_train)
predicted = text_clf.predict(X_train)
np.mean(predicted == y_train) | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Classification Report (precision, recall, f1-score) | target_names = y_train.unique()
#np.array(map(str, target_names))
#np.char.mod('%d', target_names)
target_names = ['0', '1', '2', '3', '4']
print (classification_report(
y_train, \
predicted, \
target_names = target_names
)) | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Confusion Matrix | print (confusion_matrix(y_train, predicted)) | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Stochastic Gradient Descent (SGD) Classifier | text_clf = Pipeline([
('vect', CountVectorizer(stop_words='english')),
('tfidf', TfidfTransformer()),
('clf', SGDClassifier(loss='modified_huber', shuffle=True, penalty='l2', alpha=1e-3, random_state=42, max_iter=5, tol=None)),
])
text_clf.fit(X_train, y_train)
predicted = text_clf.predict(X_train)
np.mean... | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Logistic Regression Classifier | text_clf = Pipeline([
('vect', CountVectorizer(stop_words='english', max_features=5000)),
('tfidf', TfidfTransformer()),
('clf', LogisticRegression())
])
text_clf.fit(X_train, y_train)
predicted = text_clf.predict(X_train)
np.mean(predicted == y_train) | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
OneVsOne Classifier | text_clf = Pipeline([
('vect', CountVectorizer(stop_words='english', max_features=5000)),
('tfidf', TfidfTransformer()),
('clf', OneVsOneClassifier(LinearSVC()))
])
text_clf.fit(X_train, y_train)
predicted = text_clf.predict(X_train)
np.mean(predicted == y_train) | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Create Submission | test.info()
X_test = test['Phrase']
phraseIds = test['PhraseId']
predicted = text_clf.predict(X_test)
output = pd.DataFrame( data={"PhraseId":phraseIds, "Sentiment":predicted} )
#output.to_csv( "submission.csv", index=False, quoting=3 ) | Sentiment Analysis on Movie Reviews/Sentiment-Analysis-on-Movie-Reviews-Detail-using-multiple-models.ipynb | chapagain/kaggle-competitions-solution | mit |
Fetch the dataset
Below you may find some general instructions how to fetch the dataset.
cd /opt/Temp/
git clone https://github.com/ramp-kits/autism.git
cd autism/data/fmri/
wget -c wget https://zenodo.org/record/3625740/files/msdl.zip
unzip msdl.zip
Parse dataset | curr_dir = pathlib.Path("./")
rsfmri_basedir = str((curr_dir / "raw_data/autism/").resolve()) | tutorials/fMRI - 0 - Retrieve and parse.ipynb | makism/dyfunconn | bsd-3-clause |
The following code is heavily based on the code provided by the competition's organizers. | def parse_dataset():
_target_column_name = 'asd'
_prediction_label_names = [0, 1]
subject_id = pd.read_csv(os.path.join(rsfmri_basedir, 'data', 'train.csv'), header=None)
# read the list of the subjects
df_participants = pd.read_csv(os.path.join(rsfmri_basedir, 'data', 'participants.csv'), inde... | tutorials/fMRI - 0 - Retrieve and parse.ipynb | makism/dyfunconn | bsd-3-clause |
Dump arrays | np.save('data/fmri_autism_ts.npy', fmri)
np.save('data/fmri_autism_anatomy.npy', anatomy)
np.save('data/fmri_autism_labels.npy', labels) | tutorials/fMRI - 0 - Retrieve and parse.ipynb | makism/dyfunconn | bsd-3-clause |
Nodes will be Author objects, each of which holds a list of Commit objects. | class Commit:
def __init__(self, message, hexsha, parents):
self.message = message
self.hexsha = hexsha
self.parents = parents
def __repr__(self):
return ' '.join(self.message.split(' ')[:4])
class Author:
def __init__(self, name, commits):
self.name = ... | examples/experimental_notebooks/Git Interaction Graph.ipynb | sbenthall/bigbang | agpl-3.0 |
We create a list of authors, also separately keeping track of committer names to make sure we only add each author once. If a commit by an already stored author is found, we add it to that authors list of commits. | def get_authors():
authors = []
names = []
for index, row in full_info.iterrows():
name = row["Committer Name"]
hexsha = row["HEXSHA"]
parents = row["Parent Commit"]
message = row["Commit Message"]
if name not in names:
authors.append(Author(name, [Commi... | examples/experimental_notebooks/Git Interaction Graph.ipynb | sbenthall/bigbang | agpl-3.0 |
We create our graph by forming an edge whenever an author has a commit which is the parent of another author's commit, and only increasing the weight of that edge if an edge between those two authors already exists. | def make_graph(nodes):
G = nx.Graph()
for author in nodes:
for commit in author.commits:
for other in nodes:
for other_commit in other.commits:
if commit.hexsha in other_commit.parents:
if G.has_edge(author, other):
... | examples/experimental_notebooks/Git Interaction Graph.ipynb | sbenthall/bigbang | agpl-3.0 |
A function to download nifti images as nibabel objects
We will describe each step in the function in the rest of the document. | def download_nifti(object_name, cci):
'''Use cottoncandy to download a nifti image from the OpenNeuro S3 database
Parameters
----------
object_name : str
The name of the image to download
cci : object
A cottoncandy instance
Returns
-------
nifti_image : nibabel.Nifti1Image
... | cottoncandy/examples/ccexample_openneuro.ipynb | gallantlab/cottoncandy | bsd-2-clause |
Setting up the cottoncandy connection
In order to run this example, you will need to enter your AWS keys below | ACCESSKEY = 'FAKEAK'
SECRETKEY = 'FAKESK'
import cottoncandy as cc
cci = cc.get_interface('openneuro.org', ACCESS_KEY=ACCESSKEY, SECRET_KEY=SECRETKEY, endpoint_url='https://s3.amazonaws.com') | cottoncandy/examples/ccexample_openneuro.ipynb | gallantlab/cottoncandy | bsd-2-clause |
Downloading and uncompressing the data | # Get the data stream
nifti_object_name = 'ds000255/sub-02/ses-02/func/sub-02_ses-02_task-viewFigure_run-06_bold.nii.gz'
data_stream = cci.download_stream(nifti_object_name)
# This is a GZIP Nifti so we need to uncompress it
uncompressed_data = cc.utils.GzipInputStream(data_stream.content) | cottoncandy/examples/ccexample_openneuro.ipynb | gallantlab/cottoncandy | bsd-2-clause |
Creating a file object | try:
from cStringIO import StringIO
except ImportError:
from io import BytesIO as StringIO
# make a file-object
container = StringIO()
container.write(uncompressed_data.read())
container.seek(0) | cottoncandy/examples/ccexample_openneuro.ipynb | gallantlab/cottoncandy | bsd-2-clause |
Creating a nibabel image | import nibabel as nib
# make an image container
nifti_map = nib.Nifti1Image.make_file_map()
nifti_map['image'].fileobj = container
# make a nifti image
nii = nib.Nifti1Image.from_file_map(nifti_map)
# Get the data!
arr = nii.get_data().T
print(arr.shape) | cottoncandy/examples/ccexample_openneuro.ipynb | gallantlab/cottoncandy | bsd-2-clause |
Plotting the data | import matplotlib.pyplot as plt
plt.matshow(arr[100,15], cmap='inferno')
plt.grid(False)
__ = plt.title('Sample slice from image', fontsize=30)
tsnr = arr.mean(0)/arr.std(0)
plt.matshow(tsnr[15], cmap='inferno')
plt.grid(False)
__ = plt.title('Temporal SNR image', fontsize=30) | cottoncandy/examples/ccexample_openneuro.ipynb | gallantlab/cottoncandy | bsd-2-clause |
Iterating through multiple nifti images from OpenNeuro S3 bucket | cci = cc.get_interface('openneuro.org', ACCESS_KEY=ACCESSKEY, SECRET_KEY=SECRETKEY, endpoint_url='https://s3.amazonaws.com')
dirs = cci.lsdir()
print('Sample datasets:\n%s'%', '.join(dirs[-10:])) | cottoncandy/examples/ccexample_openneuro.ipynb | gallantlab/cottoncandy | bsd-2-clause |
Explore one dataset | cci.lsdir('ds000255') | cottoncandy/examples/ccexample_openneuro.ipynb | gallantlab/cottoncandy | bsd-2-clause |
Information about the dataset | from pprint import pprint
# print metadata from JSON file
pprint(cci.download_json('ds000255/dataset_description.json'))
# print the 1000 characters in the readm
print(cci.download_object('ds000255/README')[:1000])
# list the contents of the functional directory for sub02 in session 02
cci.lsdir('ds000255/sub-02/ses... | cottoncandy/examples/ccexample_openneuro.ipynb | gallantlab/cottoncandy | bsd-2-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.