markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Now try a 15th degree polynomial:
poly15_data = polynomial_sframe(sales['sqft_living'], 15) my_features15 = poly15_data.column_names() poly15_data['price'] = sales['price'] model15 = graphlab.linear_regression.create(poly15_data, target = 'price', features = my_features15, validation_set = None) plt.plot(poly15_data['power_1'],poly15_data['price'],'.'...
Course 2 - ML, Regression/week-3-polynomial-regression-assignment-blank.ipynb
dennys-bd/Coursera-Machine-Learning-Specialization
mit
What do you think of the 15th degree polynomial? Do you think this is appropriate? If we were to change the data do you think you'd get pretty much the same curve? Let's take a look. Changing the data and re-learning We're going to split the sales data into four subsets of roughly equal size. Then you will estimate a 1...
set_11, set_12 = sales.random_split(.5,seed=0) set_1, set_2 = set_11.random_split(.5,seed=0) set_3, set_4 = set_12.random_split(.5,seed=0)
Course 2 - ML, Regression/week-3-polynomial-regression-assignment-blank.ipynb
dennys-bd/Coursera-Machine-Learning-Specialization
mit
Fit a 15th degree polynomial on set_1, set_2, set_3, and set_4 using sqft_living to predict prices. Print the coefficients and make a plot of the resulting model.
set1_poly15_data = polynomial_sframe(set_1['sqft_living'], 15) set1_poly15_data['price'] = set_1['price'] set1_model15 = graphlab.linear_regression.create(set1_poly15_data, target = 'price', features = my_features15, validation_set = None) set1_model15.get("coefficients") plt.plot(set1_poly15_data['power_1'],set1_poly...
Course 2 - ML, Regression/week-3-polynomial-regression-assignment-blank.ipynb
dennys-bd/Coursera-Machine-Learning-Specialization
mit
Some questions you will be asked on your quiz: Quiz Question: Is the sign (positive or negative) for power_15 the same in all four models? Quiz Question: (True/False) the plotted fitted lines look the same in all four plots Selecting a Polynomial Degree Whenever we have a "magic" parameter like the degree of the polyno...
training_validation_set, test_data= sales.random_split(.9,seed=1) train_data, validation_data = training_validation_set.random_split(.5,seed=1)
Course 2 - ML, Regression/week-3-polynomial-regression-assignment-blank.ipynb
dennys-bd/Coursera-Machine-Learning-Specialization
mit
Next you should write a loop that does the following: * For degree in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] (to get this in python type range(1, 15+1)) * Build an SFrame of polynomial data of train_data['sqft_living'] at the current degree * hint: my_features = poly_data.column_names() gives you a...
RSS = {} for i in range(0, 15): poly_data = polynomial_sframe(train_data['sqft_living'], i) my_features = poly_data.column_names() poly_data['price'] = train_data['price'] train_model = graphlab.linear_regression.create(poly_data, target = 'price', features = my_features, validation_set = None) poly...
Course 2 - ML, Regression/week-3-polynomial-regression-assignment-blank.ipynb
dennys-bd/Coursera-Machine-Learning-Specialization
mit
Quiz Question: Which degree (1, 2, …, 15) had the lowest RSS on Validation data? Now that you have chosen the degree of your polynomial using validation data, compute the RSS of this model on TEST data. Report the RSS on your quiz.
poly_data = polynomial_sframe(train_data['sqft_living'], 5) my_features = poly_data.column_names() poly_data['price'] = train_data['price'] train_model = graphlab.linear_regression.create(poly_data, target = 'price', features = my_features, validation_set = None) poly_test = polynomial_sframe(test_data['sqft_living'], ...
Course 2 - ML, Regression/week-3-polynomial-regression-assignment-blank.ipynb
dennys-bd/Coursera-Machine-Learning-Specialization
mit
Cluster quality metrics evaluated (see Clustering performance evaluation for definitions and discussions of the metrics): | Shorthand | full name | |------------ |----------------------------- | | homo | homogeneity score | | compl | completeness score ...
from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
PCA computes linear combinations of the original features using a truncated Singular Value Decomposition of the matrix X, to project the data onto a base of the top singular vectors.
from sklearn.decomposition import PCA pca = PCA(n_components=2, whiten=True) pca.fit(X)
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Once fitted, PCA exposes the singular vectors in the components_ attribute:
pca.components_ pca.explained_variance_ratio_
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Let us project the iris dataset along those first two dimensions::
X_pca = pca.transform(X) X_pca.shape print(X_pca[2])
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Furthermore, the samples components do no longer carry any linear correlation:
np.corrcoef(X_pca.T)
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
With a number of retained components 2 or 3, PCA is useful to visualize the dataset:
target_ids = range(len(iris.target_names)) for i, c, label in zip(target_ids, 'rgbcmykw', iris.target_names):\ plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], c=c, label=label) plt.show()
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Visualization with a non-linear embedding: tSNE For visualization, more complex embeddings can be useful (for statistical analysis, they are harder to control). sklearn.manifold.TSNE is such a powerful manifold learning method. We apply it to the digits dataset, as the digits are vectors of dimension 8*8 = 64. Embeddin...
# Take the first 500 data points: it's hard to see 1500 points X = digits.data[:500] y = digits.target[:500] # Fit and transform with a TSNE from sklearn.manifold import TSNE tsne = TSNE(n_components=2, random_state=0) X_2d = tsne.fit_transform(X) # Visualize the data plt.scatter(X_2d[:, 0], X_2d[:, 1], c=y) plt.sho...
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
The eigenfaces example: chaining PCA and SVMs The goal of this example is to show how an unsupervised method and a supervised one can be chained for better prediction. It starts with a didactic but lengthy way of doing things, and finishes with the idiomatic approach to pipelining in scikit-learn. Here we’ll take a loo...
from sklearn import datasets faces = datasets.fetch_olivetti_faces() faces.data.shape from matplotlib import pyplot as plt fig = plt.figure(figsize=(8, 6)) # plot several images for i in range(15): ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) ax.imshow(faces.images[i], cmap=plt.cm.bone) from sklear...
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Spam classifier
import os import tarfile files = ["20030228_easy_ham.tar.bz2", "20050311_spam_2.tar.bz2"] SPAM_PATH = os.path.join("datasets", "spam") def fetch_spam_data(spam_url=SPAM_URL, spam_path=SPAM_PATH): for filename in (files): path = os.path.join(SPAM_PATH, filename) tar_bz2_file = tarfile.open(path) ...
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
It seems that the ham emails are more often plain text, while spam has quite a lot of HTML. Moreover, quite a few ham emails are signed using PGP, while no spam is. In short, it seems that the email structure is a usual information to have. Now let's take a look at the email headers:
for header, value in spam_emails[0].items(): print(header,":",value) spam_emails[0]["Subject"]
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Okay, let's start writing the preprocessing functions. First, we will need a function to convert HTML to plain text. Arguably the best way to do this would be to use the great BeautifulSoup library, but I would like to avoid adding another dependency to this project, so let's hack a quick & dirty solution using regular...
import re from html import unescape def html_to_plain_text(html): text = re.sub('<head.*?>.*?</head>', '', html, flags=re.M | re.S | re.I) text = re.sub('<a\s.*?>', ' HYPERLINK ', text, flags=re.M | re.S | re.I) text = re.sub('<.*?>', '', text, flags=re.M | re.S) text = re.sub(r'(\s*\n)+', '\n', text, ...
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Let's see if it works. This is HTML spam:
html_spam_emails = [email for email in X_train[y_train==1] if get_email_structure(email) == "text/html"] sample_html_spam = html_spam_emails[7] print(sample_html_spam.get_content().strip()[:1000], "...") print(html_to_plain_text(sample_html_spam.get_content())[:1000], "...") def email_to_text(ema...
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Let's throw in some stemming! For this to work, you need to install the Natural Language Toolkit (NLTK). It's as simple as running the following command (don't forget to activate your virtualenv first; if you don't have one, you will likely need administrator rights, or use the --user option):
try: import nltk stemmer = nltk.PorterStemmer() for word in ("Computations", "Computation", "Computing", "Computed", "Compute", "Compulsive"): print(word, "=>", stemmer.stem(word)) except ImportError: print("Error: stemming requires the NLTK module.") stemmer = None try: import urlextr...
Section 3 - Machine Learning/UnSupervised Learning Algorithm/0. Introduction.ipynb
mayankjohri/LetsExplorePython
gpl-3.0
Continuous Target Decoding with SPoC Source Power Comodulation (SPoC) [1]_ allows to identify the composition of orthogonal spatial filters that maximally correlate with a continuous target. SPoC can be seen as an extension of the CSP for continuous variables. Here, SPoC is applied to decode the (continuous) fluctuatio...
# Author: Alexandre Barachant <alexandre.barachant@gmail.com> # Jean-Remi King <jeanremi.king@gmail.com> # # License: BSD (3-clause) import matplotlib.pyplot as plt import mne from mne import Epochs from mne.decoding import SPoC from mne.datasets.fieldtrip_cmc import data_path from sklearn.pipeline import ma...
0.20/_downloads/cef7da557456c738c3f4db863a633b34/plot_decoding_spoc_CMC.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
API Key Create an API key in the Ovation application at Account > Settings > API Keys (https://support.ovation.io/article/52-api-overview) Connection s is a Session object representing a connection to the Ovation API
s = connect(input("Email: "), api=constants.LAB_STAGING_HOST) # use constants.LAB_PRODUCTION_HOST for production
examples/lab/samples-and-results.ipynb
physion/ovation-python
gpl-3.0
Sample results results.get_sample_results gets all Workflow Sample Results for the sample, result type, and workflow. If workflow is omitted, all sample results for the given type are returned. Get the quantification results for a sample:
sample_id = input('Sample Id: ') results = results.get_sample_results(s, result_type='quantification', sample_id=sample_id)
examples/lab/samples-and-results.ipynb
physion/ovation-python
gpl-3.0
Vertex client library: Custom training text binary classification model for batch prediction <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/custom/showcase_custom_text_binary_classification_batch.ipynb"> ...
import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG
notebooks/community/gapic/custom/showcase_custom_text_binary_classification_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Model deployment for batch prediction Now deploy the trained Vertex Model resource you created for batch prediction. This differs from deploying a Model resource for on-demand prediction. For online prediction, you: Create an Endpoint resource for deploying the Model resource to. Deploy the Model resource to the En...
import tensorflow_datasets as tfds dataset, info = tfds.load("imdb_reviews/subwords8k", with_info=True, as_supervised=True) test_dataset = dataset["test"] test_dataset.take(1) for data in test_dataset: print(data) break test_item = data[0].numpy()
notebooks/community/gapic/custom/showcase_custom_text_binary_classification_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Make the batch input file Now make a batch input file, which you will store in your local Cloud Storage bucket. Each instance in the prediction request is a dictionary entry of the form: {serving_input: content} input_name: the name of the input layer of the underlying model. content: The text da...
import json gcs_input_uri = BUCKET_NAME + "/" + "test.jsonl" with tf.io.gfile.GFile(gcs_input_uri, "w") as f: data = {serving_input: test_item.tolist()} f.write(json.dumps(data) + "\n")
notebooks/community/gapic/custom/showcase_custom_text_binary_classification_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Make batch prediction request Now that your batch of two test items is ready, let's do the batch request. Use this helper function create_batch_prediction_job, with the following parameters: display_name: The human readable name for the prediction job. model_name: The Vertex fully qualified identifier for the Model re...
BATCH_MODEL = "imdb_batch-" + TIMESTAMP def create_batch_prediction_job( display_name, model_name, gcs_source_uri, gcs_destination_output_uri_prefix, parameters=None, ): if DEPLOY_GPU: machine_spec = { "machine_type": DEPLOY_COMPUTE, "accelerator_type": DEPLOY_...
notebooks/community/gapic/custom/showcase_custom_text_binary_classification_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Get the predictions When the batch prediction is done processing, the job state will be JOB_STATE_SUCCEEDED. Finally you view the predictions stored at the Cloud Storage path you set as output. The predictions will be in a JSONL format, which you indicated at the time you made the batch prediction job, under a subfolde...
def get_latest_predictions(gcs_out_dir): """ Get the latest prediction subfolder using the timestamp in the subfolder name""" folders = !gsutil ls $gcs_out_dir latest = "" for folder in folders: subfolder = folder.split("/")[-2] if subfolder.startswith("prediction-"): if subf...
notebooks/community/gapic/custom/showcase_custom_text_binary_classification_batch.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Feedback or issues? For any feedback or questions, please open an issue. Vertex SDK for Python: Custom Tabular Model Training Example To use this Colaboratory notebook, you copy the notebook to your own Google Drive and open it with Colaboratory (or Colab). You can run each step, or cell, and see its results. To run a ...
!pip3 uninstall -y google-cloud-aiplatform !pip3 install google-cloud-aiplatform import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True) import sys if "google.colab" in sys.modules: from google.colab import auth auth.authenticate_user()
notebooks/community/sdk/SDK_End_to_End_Tabular_Custom_Training.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create a Managed Tabular Dataset from CSV A Managed dataset can be used to create an AutoML model or a custom model.
ds = aiplatform.TabularDataset.create(display_name="abalone", gcs_source=[gcs_csv_path]) ds.resource_name
notebooks/community/sdk/SDK_End_to_End_Tabular_Custom_Training.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Launch a Training Job to Create a Model Once we have defined your training script, we will create a model.
job = aiplatform.CustomTrainingJob( display_name="train-abalone-dist-1-replica", script_path="training_script.py", container_uri="gcr.io/cloud-aiplatform/training/tf-cpu.2-2:latest", requirements=["gcsfs==0.7.1"], model_serving_container_image_uri="gcr.io/cloud-aiplatform/prediction/tf2-cpu.2-2:late...
notebooks/community/sdk/SDK_End_to_End_Tabular_Custom_Training.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Deploy Model
endpoint = model.deploy(machine_type="n1-standard-4")
notebooks/community/sdk/SDK_End_to_End_Tabular_Custom_Training.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Predict on Endpoint
prediction = endpoint.predict( [ [0.435, 0.335, 0.11, 0.33399999999999996, 0.1355, 0.0775, 0.0965], [0.585, 0.45, 0.125, 0.874, 0.3545, 0.2075, 0.225], ] ) prediction
notebooks/community/sdk/SDK_End_to_End_Tabular_Custom_Training.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Q: Kako $k$ utječe na izgled granice između klasa? Q: Kako se algoritam ponaša u ekstremnim situacijama: $k=1$ i $k=100$? (b) Pomoću funkcije mlutils.knn_eval, iscrtajte pogreške učenja i ispitivanja kao funkcije hiperparametra $k\in{1,\dots,20}$, za $N={100, 500, 1000, 3000}$ primjera. Načinite 4 zasebna grafikona (ge...
hiperparams = range(1, 21) N = [100, 500, 1000, 3000] figure(figsize(11, 8)) i = 1 for n in N: [k, err_tr, err_tst] = knn_eval(n_instances=n, k_range=(1, 20)) subplot(2,2,i) plot(np.array(range(1,21)), err_tr) plot(np.array(range(1,21)), err_tst) scatter(k,err_tst[hiperparams.index(k)]) l...
STRUCE/2018/SU-2018-LAB03-0036477171.ipynb
DominikDitoIvosevic/Uni
mit
count(*) 0 10 Quiz 2 - Temp on Foggy and Nonfoggy Days
import pandas import pandasql def max_temp_aggregate_by_fog(filename): ''' This function should run a SQL query on a dataframe of weather data. The SQL query should return two columns and two rows - whether it was foggy or not (0 or 1) and the max maxtempi for that fog value (i.e., the maximum ma...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
fog max(maxtempi) 0 0 86 1 1 81 Quiz 3 - Mean Temp on Weekends
import pandas import pandasql def avg_weekend_temperature(filename): ''' This function should run a SQL query on a dataframe of weather data. The SQL query should return one column and one row - the average meantempi on days that are a Saturday or Sunday (i.e., the the average mean temperature on ...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
More about SQL's CAST function: 1. https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql 2. https://www.w3schools.com/sql/func_sqlserver_cast.asp strftime function: 1. https://www.techonthenet.com/sqlite/functions/strftime.php Quiz 4 - Mean Temp on Rainy Days
import pandas import pandasql def avg_min_temperature(filename): ''' This function should run a SQL query on a dataframe of weather data. More specifically you want to find the average minimum temperature (mintempi column of the weather dataframe) on rainy days where the minimum temperature is gre...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
Quiz 5 - Fixing Turnstile Data
import csv def fix_turnstile_data(filenames): ''' Filenames is a list of MTA Subway turnstile text files. A link to an example MTA Subway turnstile text file can be seen at the URL below: http://web.mta.info/developers/data/nyct/turnstile/turnstile_110507.txt As you can see, there are numerous...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
updated_turnstile_110528.txt A002,R051,02-00-00,05-21-11,00:00:00,REGULAR,003169391,001097585 A002,R051,02-00-00,05-21-11,04:00:00,REGULAR,003169415,001097588 A002,R051,02-00-00,05-21-11,08:00:00,REGULAR,003169431,001097607 A002,R051,02-00-00,05-21-11,12:00:00,REGULAR,003169506,001097686 A002,R051,02-00-00,05-21-11,16:...
def create_master_turnstile_file(filenames, output_file): ''' Write a function that - takes the files in the list filenames, which all have the columns 'C/A, UNIT, SCP, DATEn, TIMEn, DESCn, ENTRIESn, EXITSn', and - consolidates them into one file located at output_file. - There should be ON...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
C/A,UNIT,SCP,DATEn,TIMEn,DESCn,ENTRIESn,EXITSn A002,R051,02-00-00,05-21-11,00:00:00,REGULAR,003169391,001097585 A002,R051,02-00-00,05-21-11,04:00:00,REGULAR,003169415,001097588 A002,R051,02-00-00,05-21-11,08:00:00,REGULAR,003169431,001097607 A002,R051,02-00-00,05-21-11,12:00:00,REGULAR,003169506,001097686 ... Quiz 7 - ...
import pandas def filter_by_regular(filename): ''' This function should read the csv file located at filename into a pandas dataframe, and filter the dataframe to only rows where the 'DESCn' column has the value 'REGULAR'. For example, if the pandas dataframe is as follows: ,C/A,UNIT,SCP,DATEn...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
More detail: loc() function which is purely label-location based indexer for selection by label - https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html - More about selection by label: - https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-label Quiz 8 - Get Hourly Entries
import pandas def get_hourly_entries(df): ''' The data in the MTA Subway Turnstile data reports on the cumulative number of entries and exits per row. Assume that you have a dataframe called df that contains only the rows for a particular turnstile machine (i.e., unique SCP, C/A, and UNIT). This ...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
9 - Get Hourly Exits
import pandas def get_hourly_exits(df): ''' The data in the MTA Subway Turnstile data reports on the cumulative number of entries and exits per row. Assume that you have a dataframe called df that contains only the rows for a particular turnstile machine (i.e., unique SCP, C/A, and UNIT). This fu...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
Unnamed: 0 C/A UNIT SCP DATEn TIMEn DESCn ENTRIESn EXITSn ENTRIESn_hourly EXITSn_hourly 0 0 A002 R051 02-00-00 05-01-11 00:00:00 REGULAR 3144312 1088151 0.0 0.0 1 1 A002 R051 02-00-00 05-01-11 04:00:00 REGULAR 3144335 10881...
import pandas def time_to_hour(time): ''' Given an input variable time that represents time in the format of: "00:00:00" (hour:minutes:seconds) Write a function to extract the hour part from the input variable time and return it as an integer. For example: 1) if hour is 00, your code s...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
Unnamed: 0 UNIT DATEn TIMEn DESCn ENTRIESn_hourly EXITSn_hourly Hour 0 0 R022 05-01-11 00:00:00 REGULAR 0.0 0.0 0 1 1 R022 05-01-11 04:00:00 REGULAR 562.0 173.0 4 2 2 R022 05-01-11 08:00:00 REGULAR ...
import datetime def reformat_subway_dates(date): ''' The dates in our subway data are formatted in the format month-day-year. The dates in our weather underground data are formatted year-month-day. In order to join these two data sets together, we'll want the dates formatted the same way. Wri...
1-uIDS-quiz/ps2-wrangling-subway-data.ipynb
tanle8/Data-Science
mit
Summarize What does the range function do? Modify Change the cell below so it prints all $i$ between 0 and 20.
for i in range(11): print(i)
chapters/00_inductive-python/04_loops.ipynb
harmsm/pythonic-science
unlicense
Implement Write a loop that calculates the sum: $$ 1 + 2 + 3 + ... + 1001$$ Loops with conditionals Predict What will this code do?
for i in range(10): if i > 5: print(i)
chapters/00_inductive-python/04_loops.ipynb
harmsm/pythonic-science
unlicense
Modify Change the code below so it goes from 0 to 20 and prints all i less than 8.
for i in range(10): if i > 5: print(i)
chapters/00_inductive-python/04_loops.ipynb
harmsm/pythonic-science
unlicense
Summarize What does the break keyword do? Predict What will this code do?
for i in range(10): print("HERE") if i > 5: continue print(i)
chapters/00_inductive-python/04_loops.ipynb
harmsm/pythonic-science
unlicense
Summarize What does the continue keyword do? Implement Write a program that starts calculating the sum: $$1 + 2 + 3 + ... 100,000$$ but stops if the sum is greater than 30,000.
x = 0 for i in range(1,100001): x = x + i if x > 30000: break
chapters/00_inductive-python/04_loops.ipynb
harmsm/pythonic-science
unlicense
While loops Predict What will this code do?
x = 1 while x < 10: print(x) x = x + 1
chapters/00_inductive-python/04_loops.ipynb
harmsm/pythonic-science
unlicense
Summarize How does while work? Modify Change the following code so it will print all values of $x^2$ for $x$ between 5 and 11.
x = 0 while x < 20: print(x*x) x = x + 1
chapters/00_inductive-python/04_loops.ipynb
harmsm/pythonic-science
unlicense
Aufgabe: Plotten Sie mithilfe von plot_3_eigvalueplots die Eigenwerte der Systemmatrix für $n \in [5,10,20]$ und $\sigma = 100$,$\sigma = -100$ und $\sigma = 0$. Frage: Wie unterscheiden sich die Spektren der verschiedenen Systemmatrizen?
n=30 for sigma in [1000,0,-1000]: plot_2_eigvalueplots(system_matrix_hh1d(n,sigma),system_matrix_hh1d_periodic(n,sigma))
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Aufgabe Plotten Sie die Iterationsmatrix des gewichteten Jacobi für verschiedene $\sigma$. Zu welcher Klasse gehört diese Iterationsmatrix.
matrix_plot(iteration_matrix_wjac(10,-100))
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Gehen wir das ganze mal systematischer an!
n = 10 sigma_range = np.linspace(-100,100,100) sr_wjac_periodic = map(lambda sig : spec_rad(iteration_matrix_wjac(n, sig,periodic=True)), sigma_range) sr_wjac = map(lambda sig : spec_rad(iteration_matrix_wjac(n, sig,periodic=False)), sigma_range) # Achsen festhalten fig1, (ax1, ax2, ax3) = plt.subplots(ncols=3,figsiz...
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Frage Ist die Iterationsmatrix zyklisch?
matrix_plot(iteration_matrix_gs(10,0,True))
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Nochmal das Ganze mit mehr System!
sr_gs_periodic = map(lambda sig : spec_rad(iteration_matrix_gs(n, sig,periodic=True)), sigma_range) sr_gs = map(lambda sig : spec_rad(iteration_matrix_gs(n, sig,periodic=False)), sigma_range) fig1, (ax1, ax2, ax3) = plt.subplots(ncols=3,figsize=(15,4)) ax1.plot(sigma_range, sr_gs_periodic,'k-') ax1.set_xlabel('$\sig...
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Frage Verhält sich der gewichtete Jacobi Glätter wie in der Vorlesung vorraussgesagt? Frage: Wie gut passen eigentlich die Diagonalwerte der Fourier-transformierten Iterationsmatrix mit den Eigenwerten der Matrix für Gauss-Seidel zusammen? Was könnte man machen um Sie zu vergleichen.
It_gs = iteration_matrix_gs(16,0) eigvals = sp.linalg.eigvals(It_gs) diagonals = get_theta_eigvals(It_gs)
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Aufgabe Überlegt euch eigene Vergleichsmethoden und variiert $n$,$\sigma$ und die Periodizität, um herauszufinden, wann die get_theta_eigvals Methode die Eigenwerte gut schätzen kann. Zweigitter-Iterationsmatrix
from project.linear_transfer import LinearTransfer from project.linear_transfer_periodic import LinearTransferPeriodic
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Buntebilderaufgabe: Nutze plot_fourier_transformed um für $n=31$, $n_c=15$ und verschiedene $\sigma\in[-1000,1000]$ um die Grobgitterkorrekturiterationsmatrizen und deren Fourier-transformierten zu plotten.
plot_fourier_transformed(coarse_grid_correction(31,15,0))
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Und nun einmal der periodische Fall.
def coarse_grid_correction_periodic(n,nc, sigma): A_fine = to_dense(system_matrix_hh1d_periodic(n,sigma)) A_coarse = to_dense(system_matrix_hh1d_periodic(nc,sigma)) A_coarse_inv = sp.linalg.inv(A_coarse) lin_trans = LinearTransferPeriodic(n, nc) prolong = to_dense(lin_trans.I_2htoh) restrict = t...
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Aufgabe: Nutzen Sie coarse_grid_correction_periodic für die Grobgitterkorrektur für das periodische Problem und plotten Sie nochmal für verschiedene $\sigma$ die Matrizen und ihre Fourier-transformierten.Für welche $n_f$ und $n_c$ ist die Grobgitterkorrektur für ein periodisches Problem sinnvoll? Frage: Was genau pas...
def two_grid_it_matrix(n,nc, sigma, nu1=3,nu2=3,typ='wjac'): cg = coarse_grid_correction(n,nc,sigma) if typ is 'wjac': smoother = iteration_matrix_wjac(n,sigma, periodic=False) if typ is 'gs': smoother = iteration_matrix_gs(n,sigma, periodic=False) pre_sm = matrix_power(smoother, nu...
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Buntebilderaufgabe: Nutzen Sie plot_fourier_transformed um für $n=15$, $n_c=7$ und verschiedene $\sigma\in[-1000,1000]$ um die Zweigittermatrizen und deren Fourier-transformierten zu plotten.
plot_fourier_transformed(two_grid_it_matrix(15,7,0,typ='wjac'))
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Nun etwas genauer!
sr_2grid_var_sigma = map(lambda sig : spec_rad(two_grid_it_matrix(15,7,sig)), sigma_range) plt.semilogy(sigma_range, sr_2grid_var_sigma,'k-') plt.title('$n_f = 15, n_c = 7$') plt.xlabel('$\sigma$') plt.ylabel("spectral radius") nf_range = map(lambda k: 2**k-1,range(3,10)) nc_range = map(lambda k: 2**k-1,range(2,9)) s...
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Buntebilderaufgabe: Nutzen Sie plot_fourier_transformed um für $n=16$, $n_c=8$ und verschiedene $\sigma\in[-1000,1000]$ um die Zweigittermatrizen und deren Fourier-transformierten zu plotten.
plot_fourier_transformed(two_grid_it_matrix_periodic(16,8,-100,typ='wjac'))
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Frage Was fällt auf? (Das sind die besten Fragen... zumindest für den Übungsleiter.) Aufgabe: Nutzen Sie die Funktion two_grid_it_matrix_periodic für den periodischen Fall und plotten Sie den Spektralradius über $\sigma$ und den Spektralradius über $n$ für 3 verschiedene $\sigma$. Aufgabe: Plotten sie die Differenzen ...
n_range = np.arange(10,100) hs_sysmat_m1000 = map(lambda n: hs_norm(to_dense(system_matrix_hh1d(n,-1000))-to_dense(system_matrix_hh1d_periodic(n,-1000))),n_range) hs_sysmat_0 = map(lambda n: hs_norm(to_dense(system_matrix_hh1d(n,0.001))-to_dense(system_matrix_hh1d_periodic(n,0.001))),n_range) hs_sysmat_p1000 = map(lamb...
notebooks/InteraktivesUebungsblatt.ipynb
Parallel-in-Time/pyMG-2016
bsd-2-clause
Independent Graph Assumption
vectorized = np.reshape(X, (X.shape[0]**2, X.shape[2])).T covar = np.cov(vectorized) from mpl_toolkits.axes_grid1 import make_axes_locatable # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. plt.figure(figsize=(7,7)) ax = plt....
code/test_assumptions.ipynb
Upward-Spiral-Science/grelliam
apache-2.0
From the above, we conclude that the assumption that the graphs were independent is false. This is because the off-diagonal components of the covariance are highly significant in the cross-graph covariance matrix. Identical Graph Assumption
import sklearn.mixture i = np.linspace(1,15,15,dtype='int') print i bic = np.array(()) for idx in i: print "Fitting and evaluating model with " + str(idx) + " clusters." gmm = sklearn.mixture.GMM(n_components=idx,n_iter=1000,covariance_type='diag') gmm.fit(vectorized.T) bic = np.append(bic, gmm.bic(vect...
code/test_assumptions.ipynb
Upward-Spiral-Science/grelliam
apache-2.0
From the above we observe that, since the elbow of the bic curve lies at 6, that our data may not have been sampled identically from one distribution. This assumption based on the evidence provided is also false. Independent Edge Assumption
vect = np.reshape(X, (X.shape[0]**2, X.shape[2])) covar = np.cov(vect) plt.figure(figsize=(7,7)) ax = plt.gca() im = ax.imshow(np.log(covar/100000+1), interpolation='None') im.set_clim([0, np.max(np.log(covar/100000))]) plt.title('Covariance of Edges') # plt.xticks((0, 20, 41), ('1', '21', '42')) # plt.yticks((0, 20...
code/test_assumptions.ipynb
Upward-Spiral-Science/grelliam
apache-2.0
From the above, we can conclude that the edges are not independent of one another, as the ratio of on- to off-diagonal covariance is very small. This assumption is false. Identical Edge Assumption
import sklearn.mixture i = np.linspace(1,15,15,dtype='int') print i bic = np.array(()) for idx in i: print "Fitting and evaluating model with " + str(idx) + " clusters." gmm = sklearn.mixture.GMM(n_components=idx,n_iter=1000,covariance_type='diag') gmm.fit(vect.T) bic = np.append(bic, gmm.bic(vect.T)) p...
code/test_assumptions.ipynb
Upward-Spiral-Science/grelliam
apache-2.0
From the above we can see quite plainly that our classifier fails to separate subjects based on their edge probability. Thus, this assumption is also false. Class covariances are different
g_0 = np.zeros((70, 70, sum([1 if x == 0 else 0 for x in y]))) g_1 = np.zeros((70, 70, sum([1 if x == 1 else 0 for x in y]))) c0=0 c1=0 for idx, val in enumerate(y): if val == 0: g_0[:,:,c1] = X[:,:,idx] c0 += 1 else: g_1[:,:,c1] = X[:,:,idx] c1 +=1 print g_0.shape print g_1.sha...
code/test_assumptions.ipynb
Upward-Spiral-Science/grelliam
apache-2.0
quantulum3 quantulum3 is a Python package "for information extraction of quantities from unstructured text".
#!pip3 install quantulum3 from quantulum3 import parser for sent in sentences: print(sent) p = parser.parse(sent) if p: print('\tSpoken:',parser.inline_parse_and_expand(sent)) print('\tNumeric elements:') for q in p: display(q) print('\t\t{} :: {}'.format(q.s...
notebooks/Quantity Parsing.ipynb
psychemedia/parlihacks
mit
Finding quantity statements in large texts If we have a large block of text, we might want to quickly skim it for quantity containing sentences, we can do something like the following...
import spacy nlp = spacy.load('en_core_web_lg', disable = ['ner']) text = ''' Once upon a time, there was a thing. The thing weighed forty kilogrammes and cost £250. It was blue. It took forty five minutes to get it home. What a day that was. I didn't get back until 2.15pm. Then I had some cake for tea. ''' doc = n...
notebooks/Quantity Parsing.ipynb
psychemedia/parlihacks
mit
Annotating a dataset Can we extract numbers from sentences in a CSV file? Yes we can...
url = 'https://raw.githubusercontent.com/BBC-Data-Unit/unduly-lenient-sentences/master/ULS%20for%20Sankey.csv' import pandas as pd df = pd.read_csv(url) df.head() #get a row df.iloc[1] #and a, erm. sentence... df.iloc[1]['Original sentence (refined)'] parser.parse(df.iloc[1]['Original sentence (refined)']) def am...
notebooks/Quantity Parsing.ipynb
psychemedia/parlihacks
mit
We could then do something to split multiple amounts into multiple rows or columns... Parsing Semi-Structured Sentences The sentencing sentences look to have a reasonable degree of structure to them (or at least, there are some commenalities in the way some of them are structured). We can exploit this structure by writ...
df['Original sentence (refined)'][:20].apply(print);
notebooks/Quantity Parsing.ipynb
psychemedia/parlihacks
mit
activate - make magics use the curent view
%%px %matplotlib inline from pylab import * plot([1,2,9],[2,9,3],'o-') %pxresult
MPI/ipyparallel_mpi_tests.ipynb
marcinofulus/ProgramowanieRownolegle
gpl-3.0
@dview.remote
@dview.remote(block=True) def getpid(): import os return os.getpid() getpid() @dview.remote(block=True) def iterate_logistic(a,N,Niter): import numpy as np x = np.random.random(N) for i in range(Niter): x = a*x*(1.0-x) return x iterate_logistic(4.0,1,10000)
MPI/ipyparallel_mpi_tests.ipynb
marcinofulus/ProgramowanieRownolegle
gpl-3.0
@dview.parallel
import numpy as np x = np.random.random((2**12)) print(x.nbytes/1024**2,x.size) a = np.ones_like(x)*4.0 @dview.parallel(block=True) def iterate_logistic(x,a): import numpy as np x = np.copy(x) for i in range(100000): x = a*x*(1.0-x) return x %%time for i in range(100000): x = a*x*(1.0-x)...
MPI/ipyparallel_mpi_tests.ipynb
marcinofulus/ProgramowanieRownolegle
gpl-3.0
Configure mpi profile first: - http://ipyparallel.readthedocs.io/en/latest/process.html#parallel-process
c = ipp.Client(profile='mpi') c.ids c[:].apply_sync(lambda : "Hello, World")
MPI/ipyparallel_mpi_tests.ipynb
marcinofulus/ProgramowanieRownolegle
gpl-3.0
Interesting might be: python c = Client('/path/to/my/ipcontroller-client.json', sshserver='me@myhub.example.com')
import mpi4py %%px %%writefile psum.py from mpi4py import MPI import numpy as np def psum(a): locsum = np.sum(a) rcvBuf = np.array(0.0,'d') MPI.COMM_WORLD.Allreduce([locsum, MPI.DOUBLE], [rcvBuf, MPI.DOUBLE], op=MPI.SUM) return rcvBuf view = c[:] view.activate() view.run('psum.py')...
MPI/ipyparallel_mpi_tests.ipynb
marcinofulus/ProgramowanieRownolegle
gpl-3.0
Régression logistique en utilisant statsmodels Pour notre premier modèle, nous allons voir comment fonctionne le module statsmodels Par défaut, la regression logit n'a pas de beta zéro pour le module statsmodels : il faut donc l'ajouter
# première étape pour ce module, il faut ajouter à la main le beta zéro - l'intercept data['intercept'] = 1.0 data.rename(columns = {'default payment next month' : "Y"}, inplace = True) data.columns # variable = ['AGE', 'BILL_AMT1', 'BILL_AMT2', 'BILL_AMT3', 'BILL_AMT4', # 'BILL_AMT5', 'BILL_AMT6', 'LIMIT_BAL', ...
_unittests/ut_helpgen/data_gallery/notebooks/competitions/2016/td2a_eco_competition_modeles_logistiques.ipynb
sdpython/pyquickhelper
mit
Add magmoms to initial structure Here we define magnetic moments of individual species present in the structure, if not already present. Refer to pymatgen docs for more information on options available for the argument overwrite_magmom_mode. Here we add magmoms for all sites in the structure irrespective of input struc...
magmom = CollinearMagneticStructureAnalyzer(structure, overwrite_magmom_mode="replace_all_if_undefined") fm_structure = magmom.get_ferromagnetic_structure(make_primitive=True) # Assume an initial ferromagnetic order print(fm_structure) order = magmom.ordering # Useful if magnetic order is unknown or not user-defined...
notebooks/2021-08-26-Magnetic Structure Generation as Input for Initial DFT Calculations.ipynb
materialsvirtuallab/matgenb
bsd-3-clause
Get space group information
spa = SpacegroupAnalyzer(structure) spa.get_point_group_symbol() spa.get_space_group_symbol() fm_structure.to(filename="lfp.mcif") # Save the structure in magCIF format. spn_structure = magmom.get_structure_with_spin() # Returns spin decorated values in structure instead of magmom site properties print(spn_structure...
notebooks/2021-08-26-Magnetic Structure Generation as Input for Initial DFT Calculations.ipynb
materialsvirtuallab/matgenb
bsd-3-clause
The above structure is saved as a magCIF with .mcif extension. This can be converted back to a CIF with relevant magnetic information associated with each site. OpenBabel does this easily, on command line write- obabel -imcif lfp.mcif -ocif -O lfp.cif Analyze magnetic moment present in a calculated structure using MAPI...
# Establish rester for accessing Materials API mpr = MPRester(api_key='API_KEY') mp_id = 'mp-504263' # Previously reported structure; Co replaced at Fe site structure_from_mp = mpr.get_structure_by_material_id(mp_id) print(structure) mgmmnt = CollinearMagneticStructureAnalyzer(structure_from_mp, overwrite_magmom_mode...
notebooks/2021-08-26-Magnetic Structure Generation as Input for Initial DFT Calculations.ipynb
materialsvirtuallab/matgenb
bsd-3-clause
Configuration
max_length = 128 # Maximum length of input sentence to the model. batch_size = 32 epochs = 2 # Labels in our dataset. labels = ["contradiction", "entailment", "neutral"]
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Load the Data
!curl -LO https://raw.githubusercontent.com/MohamadMerchant/SNLI/master/data.tar.gz !tar -xvzf data.tar.gz # There are more than 550k samples in total; we will use 100k for this example. train_df = pd.read_csv("SNLI_Corpus/snli_1.0_train.csv", nrows=100000) valid_df = pd.read_csv("SNLI_Corpus/snli_1.0_dev.csv") test_d...
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Dataset Overview: sentence1: The premise caption that was supplied to the author of the pair. sentence2: The hypothesis caption that was written by the author of the pair. similarity: This is the label chosen by the majority of annotators. Where no majority exists, the label "-" is used (we will skip such samples here...
print(f"Sentence1: {train_df.loc[1, 'sentence1']}") print(f"Sentence2: {train_df.loc[1, 'sentence2']}") print(f"Similarity: {train_df.loc[1, 'similarity']}")
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Preprocessing
# We have some NaN entries in our train data, we will simply drop them. print("Number of missing values") print(train_df.isnull().sum()) train_df.dropna(axis=0, inplace=True)
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Distribution of our training targets.
print("Train Target Distribution") print(train_df.similarity.value_counts())
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Distribution of our validation targets.
print("Validation Target Distribution") print(valid_df.similarity.value_counts())
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
The value "-" appears as part of our training and validation targets. We will skip these samples.
train_df = ( train_df[train_df.similarity != "-"] .sample(frac=1.0, random_state=42) .reset_index(drop=True) ) valid_df = ( valid_df[valid_df.similarity != "-"] .sample(frac=1.0, random_state=42) .reset_index(drop=True) )
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
One-hot encode training, validation, and test labels.
train_df["label"] = train_df["similarity"].apply( lambda x: 0 if x == "contradiction" else 1 if x == "entailment" else 2 ) y_train = tf.keras.utils.to_categorical(train_df.label, num_classes=3) valid_df["label"] = valid_df["similarity"].apply( lambda x: 0 if x == "contradiction" else 1 if x == "entailment" els...
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Keras Custom Data Generator
class BertSemanticDataGenerator(tf.keras.utils.Sequence): """Generates batches of data. Args: sentence_pairs: Array of premise and hypothesis input sentences. labels: Array of labels. batch_size: Integer batch size. shuffle: boolean, whether to shuffle the data. include...
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Build the model.
# Create the model under a distribution strategy scope. strategy = tf.distribute.MirroredStrategy() with strategy.scope(): # Encoded token ids from BERT tokenizer. input_ids = tf.keras.layers.Input( shape=(max_length,), dtype=tf.int32, name="input_ids" ) # Attention masks indicates to the model...
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Create train and validation data generators
train_data = BertSemanticDataGenerator( train_df[["sentence1", "sentence2"]].values.astype("str"), y_train, batch_size=batch_size, shuffle=True, ) valid_data = BertSemanticDataGenerator( valid_df[["sentence1", "sentence2"]].values.astype("str"), y_val, batch_size=batch_size, shuffle=Fals...
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Train the Model Training is done only for the top layers to perform "feature extraction", which will allow the model to use the representations of the pretrained model.
history = model.fit( train_data, validation_data=valid_data, epochs=epochs, use_multiprocessing=True, workers=-1, )
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Fine-tuning This step must only be performed after the feature extraction model has been trained to convergence on the new data. This is an optional last step where bert_model is unfreezed and retrained with a very low learning rate. This can deliver meaningful improvement by incrementally adapting the pretrained featu...
# Unfreeze the bert_model. bert_model.trainable = True # Recompile the model to make the change effective. model.compile( optimizer=tf.keras.optimizers.Adam(1e-5), loss="categorical_crossentropy", metrics=["accuracy"], ) model.summary()
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Train the entire model end-to-end.
history = model.fit( train_data, validation_data=valid_data, epochs=epochs, use_multiprocessing=True, workers=-1, )
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Evaluate model on the test set
test_data = BertSemanticDataGenerator( test_df[["sentence1", "sentence2"]].values.astype("str"), y_test, batch_size=batch_size, shuffle=False, ) model.evaluate(test_data, verbose=1)
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Inference on custom sentences
def check_similarity(sentence1, sentence2): sentence_pairs = np.array([[str(sentence1), str(sentence2)]]) test_data = BertSemanticDataGenerator( sentence_pairs, labels=None, batch_size=1, shuffle=False, include_targets=False, ) proba = model.predict(test_data[0])[0] idx = np.argmax(proba) ...
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Check results on some example sentence pairs.
sentence1 = "Two women are observing something together." sentence2 = "Two women are standing with their eyes closed." check_similarity(sentence1, sentence2)
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0
Check results on some example sentence pairs.
sentence1 = "A smiling costumed woman is holding an umbrella" sentence2 = "A happy woman in a fairy costume holds an umbrella" check_similarity(sentence1, sentence2)
examples/nlp/ipynb/semantic_similarity_with_bert.ipynb
keras-team/keras-io
apache-2.0