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 |
|---|---|---|---|---|---|
e) Find all users who have visited only OurPlanetTitle Page We are using relation 'b' to get the total count of `url` the user has visited | %%SQL select a.user_id
from sessions a,
(select user_id, count(url) as totalUrl from sessions group by user_id) b
where a.user_id = b.user_id
and a.navigation_page = 'OurPlanetTitle'
and b.totalurl = 1 | _____no_output_____ | MIT | Netflix Exploration.ipynb | guicaro/guicaro.github.io |
**[Python Home Page](https://www.kaggle.com/learn/python)**--- Try It YourselfFunctions are powerful. Try writing some yourself.As before, don't forget to run the setup code below before jumping into question 1. | # SETUP. You don't need to worry for now about what this code does or how it works.
from learntools.core import binder; binder.bind(globals())
from learntools.python.ex2 import *
print('Setup complete.') | Setup complete.
| Apache-2.0 | exercise-functions-and-getting-help.ipynb | Mohsenselseleh/My-Projects |
Exercises 1.Complete the body of the following function according to its docstring.HINT: Python has a built-in function `round`. | def round_to_two_places(num):
"""Return the given number rounded to two decimal places.
>>> round_to_two_places(3.14159)
3.14
"""
# Replace this body with your own code.
# ("pass" is a keyword that does literally nothing. We used it as a placeholder
# because after we begin a code... | _____no_output_____ | Apache-2.0 | exercise-functions-and-getting-help.ipynb | Mohsenselseleh/My-Projects |
2.The help for `round` says that `ndigits` (the second argument) may be negative.What do you think will happen when it is? Try some examples in the following cell?Can you think of a case where this would be useful? | q2.solution()
# Check your answer (Run this code cell to receive credit!)
q2.solution() | _____no_output_____ | Apache-2.0 | exercise-functions-and-getting-help.ipynb | Mohsenselseleh/My-Projects |
3.In a previous programming problem, the candy-sharing friends Alice, Bob and Carol tried to split candies evenly. For the sake of their friendship, any candies left over would be smashed. For example, if they collectively bring home 91 candies, they'll take 30 each and smash 1.Below is a simple function that will cal... | def to_smash(total_candies, friends =3):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
>>> to_smash(91)
1
"""
return total_candies % friends
q3.check()
q3.hint()
q3.solution() | _____no_output_____ | Apache-2.0 | exercise-functions-and-getting-help.ipynb | Mohsenselseleh/My-Projects |
4. (Optional)It may not be fun, but reading and understanding error messages will be an important part of your Python career.Each code cell below contains some commented-out buggy code. For each cell...1. Read the code and predict what you think will happen when it's run.2. Then uncomment the code and run it to see wh... | round_to_two_places(9.9999)
x = -10
y = 5
# # Which of the two variables above has the smallest absolute value?
smallest_abs = min(abs(x), abs(y))
print(smallest_abs)
def f(x):
y = abs(x)
return y
print(f(5)) | _____no_output_____ | Apache-2.0 | exercise-functions-and-getting-help.ipynb | Mohsenselseleh/My-Projects |
This notebook was put together by [Jake Vanderplas](http://www.vanderplas.com). Source and license info is on [GitHub](https://github.com/jakevdp/sklearn_tutorial/). Supervised Learning In-Depth: Random Forests Previously we saw a powerful discriminative classifier, **Support Vector Machines**.Here we'll take a look a... | %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
plt.style.use('seaborn') | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
Motivating Random Forests: Decision Trees Random forests are an example of an *ensemble learner* built on decision trees.For this reason we'll start by discussing decision trees themselves.Decision trees are extremely intuitive ways to classify or label objects: you simply ask a series of questions designed to zero-in... | import fig_code
fig_code.plot_example_decision_tree() | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
The binary splitting makes this extremely efficient.As always, though, the trick is to *ask the right questions*.This is where the algorithmic process comes in: in training a decision tree classifier, the algorithm looks at the features and decides which questions (or "splits") contain the most information. Creating a ... | from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=300, centers=4,
random_state=0, cluster_std=1.0)
plt.scatter(X[:, 0], X[:, 1], c=y, s=50, cmap='rainbow'); | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
We have some convenience functions in the repository that help | from fig_code import visualize_tree, plot_tree_interactive | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
Now using IPython's ``interact`` (available in IPython 2.0+, and requires a live kernel) we can view the decision tree splits: | plot_tree_interactive(X, y); | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
Notice that at each increase in depth, every node is split in two **except** those nodes which contain only a single class.The result is a very fast **non-parametric** classification, and can be extremely useful in practice.**Question: Do you see any problems with this?** Decision Trees and over-fittingOne issue with ... | from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier()
plt.figure()
visualize_tree(clf, X[:200], y[:200], boundaries=False)
plt.figure()
visualize_tree(clf, X[-200:], y[-200:], boundaries=False) | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
The details of the classifications are completely different! That is an indication of **over-fitting**: when you predict the value for a new point, the result is more reflective of the noise in the model rather than the signal. Ensembles of Estimators: Random ForestsOne possible way to address over-fitting is to use a... | def fit_randomized_tree(random_state=0):
X, y = make_blobs(n_samples=300, centers=4,
random_state=0, cluster_std=2.0)
clf = DecisionTreeClassifier(max_depth=15)
rng = np.random.RandomState(random_state)
i = np.arange(len(y))
rng.shuffle(i)
visualize_tree(clf, X[i[:250]... | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
See how the details of the model change as a function of the sample, while the larger characteristics remain the same!The random forest classifier will do something similar to this, but use a combined version of all these trees to arrive at a final answer: | from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=100, random_state=0)
visualize_tree(clf, X, y, boundaries=False); | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
By averaging over 100 randomly perturbed models, we end up with an overall model which is a much better fit to our data!*(Note: above we randomized the model through sub-sampling... Random Forests use more sophisticated means of randomization, which you can read about in, e.g. the [scikit-learn documentation](http://sc... | from sklearn.ensemble import RandomForestRegressor
x = 10 * np.random.rand(100)
def model(x, sigma=0.3):
fast_oscillation = np.sin(5 * x)
slow_oscillation = np.sin(0.5 * x)
noise = sigma * np.random.randn(len(x))
return slow_oscillation + fast_oscillation + noise
y = model(x)
plt.errorbar(x, y, 0.3,... | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
As you can see, the non-parametric random forest model is flexible enough to fit the multi-period data, without us even specifying a multi-period model! Example: Random Forest for Classifying DigitsWe previously saw the **hand-written digits** data. Let's use that here to test the efficacy of the SVM and Random Forest... | from sklearn.datasets import load_digits
digits = load_digits()
digits.keys()
X = digits.data
y = digits.target
print(X.shape)
print(y.shape) | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
To remind us what we're looking at, we'll visualize the first few data points: | # set up the figure
fig = plt.figure(figsize=(6, 6)) # figure size in inches
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
# plot the digits: each image is 8x8 pixels
for i in range(64):
ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[])
ax.imshow(digits.images[i], cmap=... | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
We can quickly classify the digits using a decision tree as follows: | from sklearn.model_selection import train_test_split
from sklearn import metrics
Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, random_state=0)
clf = DecisionTreeClassifier(max_depth=11)
clf.fit(Xtrain, ytrain)
ypred = clf.predict(Xtest) | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
We can check the accuracy of this classifier: | metrics.accuracy_score(ypred, ytest) | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
and for good measure, plot the confusion matrix: | metrics.plot_confusion_matrix(clf, Xtest, ytest, cmap=plt.cm.Blues)
plt.grid(False) | _____no_output_____ | BSD-3-Clause | notebooks/03.2-Regression-Forests.ipynb | pletzer/sklearn_tutorial |
Understand the datasets for training and cross-validation | # Assume the datasets are downloaded to the loc. below
root = osp.expanduser('~/data/datasets') | _____no_output_____ | MIT | VOC-Data-Loaders.ipynb | 1xyz/pytorch-fcn-ext |
Pixel label values | # Map of the classe names for example 1 - aeroplane
class_names = np.array([
'background',
'aeroplane',
'bicycle',
'bird',
'boat',
'bottle',
'bus',
'car',
'cat',
'chair',
'cow',
'diningtable',
'dog',
'horse',... | _____no_output_____ | MIT | VOC-Data-Loaders.ipynb | 1xyz/pytorch-fcn-ext |
Utility functions to show images and histogram | def imshow(img):
plt.imshow(img)
plt.show()
def hist(img):
plt.hist(img)
plt.show() | _____no_output_____ | MIT | VOC-Data-Loaders.ipynb | 1xyz/pytorch-fcn-ext |
Inspect the train dataset | # The train dataset is Semantic Boundaries Dataset and Benchmark (SBD) benchmark
# . http://home.bharathh.info/pubs/codes/SBD/download.html
# Refer http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz
# Note: we set the transform to False, this ensures that the result of __... | Shape of image: (480, 360, 3) shape of the label: (480, 360)
| MIT | VOC-Data-Loaders.ipynb | 1xyz/pytorch-fcn-ext |
Print the histogram of the train dataset | label_dist = np.ravel(train_dataset[idx][1])
hist(label_dist) | _____no_output_____ | MIT | VOC-Data-Loaders.ipynb | 1xyz/pytorch-fcn-ext |
Understand the validation (dev) dataset | # Load the validation dataset (Pascal VOC)
# Again note that the transform is False, so the result is an ndarray and not a transformed tensor
valid_dataset = torchfcn.datasets.VOC2011ClassSeg(root, split='seg11valid', transform=False)
idx = 203
print("Shape of data: ", valid_dataset[idx][0].shape, "Shape of label: ", ... | Shape of data: (375, 500, 3) Shape of label: (375, 500)
| MIT | VOC-Data-Loaders.ipynb | 1xyz/pytorch-fcn-ext |
Inspect the transformed tensor | ## Let us actually inspect the transformed tensor data instead
valid_tensor_dataset = torchfcn.datasets.VOC2011ClassSeg(root, split='seg11valid', transform=True)
label_dists = valid_tensor_dataset[idx][1]
print(torch.min(label_dists))
label_dist = np.ravel(label_dists.numpy())
print("Max", np.max(label_dist), "Min", ... | tensor(-1)
Max 8 Min -1
| MIT | VOC-Data-Loaders.ipynb | 1xyz/pytorch-fcn-ext |
Inspect the dataset transformed? | mean_bgr = np.array([104.00698793, 116.66876762, 122.67891434])
def transform(img):
#img = img[:, :, ::-1] # RGB -> BGR
img = img.astype(np.float64)
img -= mean_bgr
return img
print(valid_dataset[idx][0].shape)
transformed_image = transform(valid_dataset[idx][0])
print(transformed_image.shape)
imshow(... | Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
| MIT | VOC-Data-Loaders.ipynb | 1xyz/pytorch-fcn-ext |
Code generation for Linux Real-Time Preemptionc.f. https://wiki.linuxfoundation.org/realtime/startThe generated code can be compiled using a c++ compiler as follows: $ c++ main.cpp -o main | dy.clear()
system = dy.enter_system()
# define system inputs
u = dy.system_input( dy.DataTypeFloat64(1), name='input1', default_value=1.0, value_range=[0, 25], title="input #1")
y = dy.signal() # introduce variable y
x = y + u # x[k] = y[k] + u[k]... | compiling system simulation (level 0)...
input1 1.0 double
Generated code will be written to ./ .
writing file ./simulation_manifest.json
writing file ./main.cpp
| MIT | examples/real-time/real-Time_linux.ipynb | OpenRTDynamics/openrtdynamics2 |
NumPy Exercises NumPy is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. Import NumPy as np | import numpy as np | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Create an array of 10 zeros | np.zeros(10) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Create an array of 10 ones | np.ones(10) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Create an array of 10 fives | np.ones(10) * 5 | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Create an array of the integers from 10 to 50 | np.arange(10,51) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Create an array of all the even integers from 10 to 50 | np.arange(10,51,2) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Create a 3x3 matrix with values ranging from 0 to 8 | np.arange(0,9).reshape(3,3) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Create a 3x3 identity matrix | np.eye(3) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Use NumPy to generate a random number between 0 and 1 | np.random.rand(1) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Use NumPy to generate an array of 25 random numbers sampled from a standard normal distribution | np.random.randn(25) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Create the following matrix: | np.arange(1,101).reshape(10,10)/100 | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Create an array of 20 linearly spaced points between 0 and 1: | np.linspace(0,1,20) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Numpy Indexing and SelectionNow you will be given a few matrices, and be asked to replicate the resulting matrix outputs: | mat = np.arange(1,26).reshape(5,5)
mat
# WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW
# BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWISE YOU WON'T
# BE ABLE TO SEE THE OUTPUT ANY MORE
mat[2:,1:]
# WRITE CODE HERE THAT REPRODUCES THE OUTPUT OF THE CELL BELOW
# BE CAREFUL NOT TO RUN THE CELL BELOW, OTHERWI... | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Now do the following Get the sum of all the values in mat | np.sum(mat) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Get the standard deviation of the values in mat | np.std(mat) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Get the sum of all the columns in mat | np.sum(mat, axis=0) | _____no_output_____ | MIT | Numpy-Exercises.ipynb | smalik-hub/Numpy-Exercises |
Models in Pyro: From Primitive Distributions to Stochastic FunctionsThe basic unit of Pyro programs is the _stochastic function_. This is an arbitrary Python callable that combines two ingredients:- deterministic Python code; and- primitive stochastic functions Concretely, a stochastic function can be any Python objec... | loc = 0. # mean zero
scale = 1. # unit variance
normal = dist.Normal(loc, scale) # create a normal distribution object
x = normal.sample() # draw a sample from N(0,1)
print("sample", x)
print("log prob", normal.log_prob(x)) # score the sample from N(0,1) | _____no_output_____ | MIT | tutorial/source/intro_part_i.ipynb | neerajprad/pyro |
Here, `dist.Normal` is a callable instance of the `Distribution` class that takes parameters and provides sample and score methods. Note that the parameters passed to `dist.Normal` are `torch.Tensor`s. This is necessary because we want to make use of PyTorch's fast tensor math and autograd capabilities during inference... | x = pyro.sample("my_sample", dist.Normal(loc, scale))
print(x) | _____no_output_____ | MIT | tutorial/source/intro_part_i.ipynb | neerajprad/pyro |
Just like a direct call to `dist.Normal().sample()`, this returns a sample from the unit normal distribution. The crucial difference is that this sample is _named_. Pyro's backend uses these names to uniquely identify sample statements and _change their behavior at runtime_ depending on how the enclosing stochastic fun... | def weather():
cloudy = pyro.sample('cloudy', dist.Bernoulli(0.3))
cloudy = 'cloudy' if cloudy.item() == 1.0 else 'sunny'
mean_temp = {'cloudy': 55.0, 'sunny': 75.0}[cloudy]
scale_temp = {'cloudy': 10.0, 'sunny': 15.0}[cloudy]
temp = pyro.sample('temp', dist.Normal(mean_temp, scale_temp))
return... | _____no_output_____ | MIT | tutorial/source/intro_part_i.ipynb | neerajprad/pyro |
Let's go through this line-by-line. First, in lines 2-3 we use `pyro.sample` to define a binary random variable 'cloudy', which is given by a draw from the bernoulli distribution with a parameter of `0.3`. Since the bernoulli distributions returns `0`s or `1`s, in line 4 we convert the value `cloudy` to a string so tha... | def ice_cream_sales():
cloudy, temp = weather()
expected_sales = 200. if cloudy == 'sunny' and temp > 80.0 else 50.
ice_cream = pyro.sample('ice_cream', dist.Normal(expected_sales, 10.0))
return ice_cream | _____no_output_____ | MIT | tutorial/source/intro_part_i.ipynb | neerajprad/pyro |
This kind of modularity, familiar to any programmer, is obviously very powerful. But is it powerful enough to encompass all the different kinds of models we'd like to express? Universality: Stochastic Recursion, Higher-order Stochastic Functions, and Random Control FlowBecause Pyro is embedded in Python, stochastic fun... | def geometric(p, t=None):
if t is None:
t = 0
x = pyro.sample("x_{}".format(t), dist.Bernoulli(p))
if x.item() == 0:
return x
else:
return x + geometric(p, t + 1)
print(geometric(0.5)) | _____no_output_____ | MIT | tutorial/source/intro_part_i.ipynb | neerajprad/pyro |
Note that the names `x_0`, `x_1`, etc., in `geometric()` are generated dynamically and that different executions can have different numbers of named random variables. We are also free to define stochastic functions that accept as input or produce as output other stochastic functions: | def normal_product(loc, scale):
z1 = pyro.sample("z1", dist.Normal(loc, scale))
z2 = pyro.sample("z2", dist.Normal(loc, scale))
y = z1 * z2
return y
def make_normal_normal():
mu_latent = pyro.sample("mu_latent", dist.Normal(0, 1))
fn = lambda scale: normal_product(mu_latent, scale)
return f... | _____no_output_____ | MIT | tutorial/source/intro_part_i.ipynb | neerajprad/pyro |
Preamble | from flair.datasets import ColumnCorpus
from flair.embeddings import FlairEmbeddings
from flair.embeddings import TokenEmbeddings
from flair.embeddings import StackedEmbeddings
from flair.models import SequenceTagger
from flair.trainers import ModelTrainer
from typing import List
import numpy as np
import os
import tor... | _____no_output_____ | MIT | notebooks/01-concept-spotting/06-lists-training.ipynb | fschlatt/CIKM-20 |
List-Spotter: Training | def set_seed(seed):
# For reproducibility
# (https://pytorch.org/docs/stable/notes/randomness.html)
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
torch.backends.cudnn.deterministic = True
torch.ba... | _____no_output_____ | MIT | notebooks/01-concept-spotting/06-lists-training.ipynb | fschlatt/CIKM-20 |
[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/healthcare/NER_SIGN_SYMP.ipynb) **Detect signs and symptoms... | import json
import os
from google.colab import files
license_keys = files.upload()
with open(list(license_keys.keys())[0]) as f:
license_keys = json.load(f)
# Defining license key-value pairs as local variables
locals().update(license_keys)
# Adding license key-value pairs to environment variables
os.environ.u... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/NER_SIGN_SYMP.ipynb | fcivardi/spark-nlp-workshop |
Install dependencies | # Installing pyspark and spark-nlp
! pip install --upgrade -q pyspark==3.1.2 spark-nlp==$PUBLIC_VERSION
# Installing Spark NLP Healthcare
! pip install --upgrade -q spark-nlp-jsl==$JSL_VERSION --extra-index-url https://pypi.johnsnowlabs.com/$SECRET
# Installing Spark NLP Display Library for visualization
! pip insta... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/NER_SIGN_SYMP.ipynb | fcivardi/spark-nlp-workshop |
Import dependencies into Python and start the Spark session | import pandas as pd
from pyspark.ml import Pipeline
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
import sparknlp
from sparknlp.annotator import *
from sparknlp_jsl.annotator import *
from sparknlp.base import *
import sparknlp_jsl
spark = sparknlp_jsl.start(license_keys['SECRET'])
# manuall... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/NER_SIGN_SYMP.ipynb | fcivardi/spark-nlp-workshop |
2. Select the NER model and construct the pipeline Select the NER model - Sign/symptom models: **ner_clinical, ner_jsl**For more details: https://github.com/JohnSnowLabs/spark-nlp-modelspretrained-models---spark-nlp-for-healthcare | # You can change this to the model you want to use and re-run cells below.
# Sign / symptom models: ner_clinical, ner_jsl
# All these models use the same clinical embeddings.
MODEL_NAME = "ner_clinical" | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/NER_SIGN_SYMP.ipynb | fcivardi/spark-nlp-workshop |
Create the pipeline |
document_assembler = DocumentAssembler() \
.setInputCol('text')\
.setOutputCol('document')
sentence_detector = SentenceDetector() \
.setInputCols(['document'])\
.setOutputCol('sentence')
tokenizer = Tokenizer()\
.setInputCols(['sentence']) \
.setOutputCol('token')
word_embeddings = WordEmbe... | embeddings_clinical download started this may take some time.
Approximate size to download 1.6 GB
[OK!]
ner_clinical download started this may take some time.
Approximate size to download 13.7 MB
[OK!]
| Apache-2.0 | tutorials/streamlit_notebooks/healthcare/NER_SIGN_SYMP.ipynb | fcivardi/spark-nlp-workshop |
3. Create example inputs | # Enter examples as strings in this array
input_list = [
"""The patient is a 21-day-old Caucasian male here for 2 days of congestion - mom has been suctioning yellow discharge from the patient's nares, plus she has noticed some mild problems with his breathing while feeding (but negative for any perioral cyanosis o... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/NER_SIGN_SYMP.ipynb | fcivardi/spark-nlp-workshop |
4. Use the pipeline to create outputs | empty_df = spark.createDataFrame([['']]).toDF('text')
pipeline_model = nlp_pipeline.fit(empty_df)
df = spark.createDataFrame(pd.DataFrame({'text': input_list}))
result = pipeline_model.transform(df) | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/NER_SIGN_SYMP.ipynb | fcivardi/spark-nlp-workshop |
5. Visualize results | from sparknlp_display import NerVisualizer
NerVisualizer().display(
result = result.collect()[0],
label_col = 'ner_chunk',
document_col = 'document'
) | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/healthcare/NER_SIGN_SYMP.ipynb | fcivardi/spark-nlp-workshop |
Purpose of this notebookThis notebook estimates the excitation (as photoisomerization rate at the photoreceptor level) that is expected to be caused by the images recorded with the UV/G mouse camera. | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Global dictionary
d = dict()
# Global constants
TWILIGHT = 0
DAYLIGHT = 1
UV_S = 0
UV_M = 1
G_S = 2
G_M = 3
CONE = 0
ROD = 1
CHAN_UV = 0
CHAN_G = 1 | _____no_output_____ | MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
ApproachWhen calibrating the mouse camera, we used LEDs of defined wavelength and brightness to map normalized intensity (camera pixel values, 0..1) to power meter readings (see STAR Methods in the manuscript). To relate this power to the photon flux at the cornea and finally the photoisomerisation rate at the photore... | d.update({"ac_um2": [0.2, 0.5], "peak_S": 360, "peak_M": 510, "A_stim_um2": 1e8}) | _____no_output_____ | MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
Attenuation factors of the two camera pathwaysWe first calculated the attenuation factor from the fisheye lens to the focal plane of the camera chip. To this end, we used a spectrometer (STS-UV, Ocean Optics) with an optical fiber (P50-1-UV-VIS) to first measure the spectrum of the sky directly, and then at the camera... | #%%capture
#!wget -O sky_spectrum.npy https://www.dropbox.com/s/p8uk4k6losfu309/sky_spectrum.npy?dl=0
#spect = np.load('sky_spectrum.npy', allow_pickle=True).item()
# Load spectra
# The exposure times were 4 s for `direct` and `g`, and 30 s for `uv`
spect = np.load('data/sky_spectrum.npy', allow_pickle=True).item... | _____no_output_____ | MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
Since the readout on the objective side (fisheye lens) is related to both visual angle and area, while the readout on the imaging side is only related to area, we define:$$\begin{align}P_{direct} &= P_{total} \cdot \frac{A_{fiber}}{A_{lens}} \cdot \frac{\theta_{fiber}}{\theta_{lens}}\\P_{UV} &= P_{total} \cdot \frac{A_... | direct_exp_s = 4
UV_exp_s = 30
G_exp_s = 4
P_UV2direct = 1/(np.trapz(spect["direct"][350-300:420-300])/np.trapz(spect["uv"][350-300:420-300]) *UV_exp_s/direct_exp_s)
P_G2direct = 1/(np.trapz(spect["direct"][470-300:550-300])/np.trapz(spect["g"][470-300:550-300]) *G_exp_s/direct_exp_s)
print("P_UV/P_direct = {0:.3f}... | P_UV/P_direct = 0.047
P_G/P_direct = 0.533
| MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
The diameters of the camera chip's imaging area and the fisheye lens were $2,185 \: \mu m$ and $15,000 \: \mu m$, respectively. The acception angles of the optical fiber and the fisheye lens were $\theta_{fibre}=24.8^{\circ}$ and $\theta_{lens}=180^{\circ}$, respectively. | A_cam = np.pi*(2185/2)**2
A_lens = np.pi*(15000/2)**2
theta_fiber = 24.8
theta_lens = 180 | _____no_output_____ | MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
Now we can get the attenuation factors $ \mu_{lens2cam,UV} $ and $ \mu_{lens2cam,G} $, covering the optical path from the fisheye lens to the camera chip: | mu_lens2cam = [0,0]
mu_lens2cam[CHAN_UV] = P_UV2direct *A_cam /A_lens *theta_fiber /theta_lens
mu_lens2cam[CHAN_G] = P_G2direct *A_cam /A_lens * theta_fiber /theta_lens
d.update({"mu_lens2cam": mu_lens2cam})
print("mu_lens2cam for UV,G = {0:.3e}, {1:.3e}".format(mu_lens2cam[CHAN_UV], mu_lens2cam[CHAN_G])) | mu_lens2cam for UV,G = 1.365e-04, 1.557e-03
| MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
Attenuation by mouse eye opticsAnother factor we need to consider is the wavelength-dependent attenuation by the mouse eye optics. The relative transmission for UV ($T_{Rel}(UV)$, at $\lambda=360 \: nm$) and green ($T_{Rel}(G)$, at $\lambda=510 \: nm$) is approx. 35% and 55%, respectively ([Henriksson et al., 2010](ht... | d.update({"T_rel": [0.35, 0.55]}) | _____no_output_____ | MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
In addition, the light reaching the retina depends on the ratio ($R_{pup2ret}$) between pupil area and retinal area (both in $[mm^2]$) ([Rhim et al., 2020](https://www.biorxiv.org/content/10.1101/2020.11.03.366682v1)). Here, we assume pupil areas of $0.1 \: mm^2$ (maximally constricted) at daytime and $0.22 \: mm^2$ at... | eye_axial_len_mm = 3
ret_area_mm2 = 0.6 *(eye_axial_len_mm/2)**2 *np.pi *4
pup_area_mm2 = [0.22, 0.1]
R_pup2ret= [x /ret_area_mm2 for x in pup_area_mm2]
d.update({"R_pup2ret": R_pup2ret, "pup_area_mm2": pup_area_mm2, "ret_area_mm2": ret_area_mm2})
print("mouse retinal area [mm²] = {0:.1f}".format(ret_area_m... | mouse retinal area [mm²] = 17.0
pupil area [mm²] = twilight: 0.2 daylight: 0.1
ratio of pupil area to retinal area = twilight: 0.013 daylight: 0.006
| MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
Cross-activation of S- and M-opsins ...... by the UV and green camera channels, yielding $S_{Act}(S,UV)$, $S_{Act}(S,G)$, $S_{Act}(M,UV)$, and $S_{Act}(M,G)$. | #%%capture
#!wget -O opsin_filter_spectrum.npy https://www.dropbox.com/s/doh1jjqukdcpvpy/opsin_filter_spectrum.npy?dl=0
#spect = np.load('opsin_filter_spectrum.npy', allow_pickle=True).item()
# Load opsin and filter spectra
spect = np.load('data/opsin_filter_spectrum.npy', allow_pickle=True).item()
wavelength = sp... | S_act UV -> S = 0.625
UV -> M = 0.118
G -> S = 0.000
G -> M = 0.858
| MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
Estimating photoisomerization ratesThe following function converts normalized image intensities (0...1) to $P_{el}(\lambda)$ (in $[\mu W]$), $P_{Phi}(\lambda)$ (in $[photons /s]$), and $R_{Iso}(\lambda)$ (in $[P^*/cone/s]$). | def inten2Riso(intensities, pup_area_mm2, pr_type=CONE):
"""
Transfer the normalized image intensities (0...1) to power (unit: uW),
photon flux (unit: photons/s) and photoisomerisation rate (P*/cone/s)
Input:
intensities : image intensities (0...1) for both channels as tuple
pup_area_mm2 ... | _____no_output_____ | MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
Example `[[0.18, 0.11], [0.06, 0.14]]`, with the following format `[upper[UV,G],lower[UV,G]]` | intensities=[[0.18, 0.11], [0.06, 0.14]]
for j, i in enumerate(intensities):
l = inten2Riso(i, 0.2)
print("{0:2d} (UV, G) P_el = {1:.3f}, {2:.3f}\t P_Phi = {3:.1e}, {4:.1e} ".format(j, l[0][0], l[0][1], l[1][0], l[1][1]))
print(" UV->S = {0:.1e} \t UV->M = {1:.1e} \t G->S = {2:.1e} \t G->M = {3:.1e}".format(l[2... | 0 (UV, G) P_el = 0.141, 0.730 P_Phi = 1.9e+15, 1.2e+15
UV->S = 9.6e+03 UV->M = 1.8e+03 G->S = 7.0e-01 G->M = 1.3e+04
1 (UV, G) P_el = 0.050, 0.927 P_Phi = 6.7e+14, 1.5e+15
UV->S = 3.4e+03 UV->M = 6.5e+02 G->S = 8.8e-01 G->M = 1.7e+04
| MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
Generate Supplementary Table 1 | col_names = ['Mean intensity<br>group', 'Visual<br>field', 'Camera<br>channel', 'Norm.<br>intensity', 'P_el<br>in [µW]',\
'P_Phi<br>in [photons/s]', 'Pupil area<br>in [mm2]',\
'R_Iso<br>in [P*/cone/s], S', 'R_Iso<br>in [P*/cone/s], M', 'R_Iso<br>in [P*/rod/s], rod']
data_df = pd.DataFrame(column... | _____no_output_____ | MIT | photoisomerization/cam_images_2_photoisomerization_v0_2.ipynb | yongrong-qiu/mouse-scene-cam |
[](https://notebooks.azure.com/import/gh/Alireza-Akhavan/class.vision) عملگر convolution **Convolution عمل** with a filter of 2x2 and a stride of 1 (stride = amount you move the window each time you slide) سایت زیر برای آشنایی با کرنلها بسیار مناسب است:http://... | import cv2
import numpy as np
image = cv2.imread('images/input.jpg')
cv2.imshow('Original Image', image)
cv2.waitKey(0)
# Creating our 3 x 3 kernel
kernel_3x3 = np.ones((3, 3), np.float32) / 9
# We use the cv2.fitler2D to conovlve the kernal with an image
blurred = cv2.filter2D(image, -1, kernel_3x3)
cv2.imshow('3x... | _____no_output_____ | MIT | 12-Convolutions and Blurring.ipynb | moh3n9595/class.vision |
Other commonly used blurring methods in OpenCV | import cv2
import numpy as np
image = cv2.imread('images/input.jpg')
cv2.imshow('original', image)
cv2.waitKey(0)
# Averaging done by convolving the image with a normalized box filter.
# This takes the pixels under the box and replaces the central element
# Box size needs to odd and positive
blur = cv2.blur(image, ... | _____no_output_____ | MIT | 12-Convolutions and Blurring.ipynb | moh3n9595/class.vision |
Image De-noising - Non-Local Means Denoising | import numpy as np
import cv2
image = cv2.imread('images/taj-rgb-noise.jpg')
# Parameters, after None are - the filter strength 'h' (5-10 is a good range)
# Next is hForColorComponents, set as same value as h again
#
dst = cv2.fastNlMeansDenoisingColored(image, None, 6, 6, 7, 21)
cv2.imshow('Fast Means Denoising', ... | _____no_output_____ | MIT | 12-Convolutions and Blurring.ipynb | moh3n9595/class.vision |
Quick demonstration of R-notebooks using the r-oce libraryThe IOOS notebook[environment](https://github.com/ioos/notebooks_demos/blob/229dabe0e7dd207814b9cfb96e024d3138f19abf/environment.ymlL73-L76)installs the `R` language and the `Jupyter` kernel needed to run `R` notebooks.Conda can also install extra `R` packages,... | library(gsw)
library(oce) | _____no_output_____ | MIT | notebooks/2017-01-23-R-notebook.ipynb | kellydesent/notebooks_demos |
Example 1: calculating the day length. | daylength <- function(t, lon=-38.5, lat=-13)
{
t <- as.numeric(t)
alt <- function(t)
sunAngle(t, longitude=lon, latitude=lat)$altitude
rise <- uniroot(alt, lower=t-86400/2, upper=t)$root
set <- uniroot(alt, lower=t, upper=t+86400/2)$root
set - rise
}
t0 <- as.POSIXct("2017-01-01 12:00:00", ... | _____no_output_____ | MIT | notebooks/2017-01-23-R-notebook.ipynb | kellydesent/notebooks_demos |
Example 2: least-square fit. | x <- 1:100
y <- 1 + x/100 + sin(x/5)
yn <- y + rnorm(100, sd=0.1)
L <- 4
calc <- runlm(x, y, L=L, deriv=0)
plot(x, y, type='l', lwd=7, col='gray')
points(x, yn, pch=20, col='blue')
lines(x, calc, lwd=2, col='red')
data(ctd)
rho <- swRho(ctd)
z <- swZ(ctd)
drhodz <- runlm(z, rho, deriv = 1)
g <- 9.81
rho0 <- mean(rho, n... | _____no_output_____ | MIT | notebooks/2017-01-23-R-notebook.ipynb | kellydesent/notebooks_demos |
Example 3: T-S diagram. | # Alter next three lines as desired; a and b are watermasses.
Sa <- 30
Ta <- 10
Sb <- 40
library(oce)
# Should not need to edit below this line
rho0 <- swRho(Sa, Ta, 0)
Tb <- uniroot(function(T) rho0-swRho(Sb,T,0), lower=0, upper=100)$root
Sc <- (Sa + Sb) /2
Tc <- (Ta + Tb) /2
## density change, and equiv temp change
... | _____no_output_____ | MIT | notebooks/2017-01-23-R-notebook.ipynb | kellydesent/notebooks_demos |
Example 4: find the halocline depth. | findHalocline <- function(ctd, deltap=5, plot=TRUE)
{
S <- ctd[['salinity']]
p <- ctd[['pressure']]
n <- length(p)
## trim df to be no larger than n/2 and no smaller than 3.
N <- deltap / median(diff(p))
df <- min(n/2, max(3, n / N))
spline <- smooth.spline(S~p, df=df)
SS <- predict(spli... | _____no_output_____ | MIT | notebooks/2017-01-23-R-notebook.ipynb | kellydesent/notebooks_demos |
Exploring a generic Markov model of chromatin accessibilityLast updated by: Jonathan Liu, 4/23/2021Here, we will explore a generic Markov chain model of chromatin accessibility, where we model chromatin with a series of states and Markov transitions between them. Of interest is the onset time, the time it takes for th... | #Import necessary packages
%matplotlib inline
import numpy as np
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
import scipy.special as sps
from IPython.core.debugger import set_trace
from numba import njit, prange
import numba as numba
from datetime import date
import time as Time
import seaborn ... | _____no_output_____ | MIT | GenericModelExploration.ipynb | GarciaLab/OnsetTimeTransientInputs |
The steady-state regimeFirst, let's get a feel for the model in the steady-state case. We consider a Markov chain with $k+1$ states labeled with indices $i$, with the first state labeled with index $0$. The system will begin in state $0$ at time $t=0$ and we will assume the final state $k$ is absorbing. For example, t... | #Let's visualize the distribution of onset times for the Gamma distribution case
#Function for analytical Gamma distribution
def GamPDF(x,shape,rate):
return x**(shape-1)*(np.exp(-x*rate) / sps.gamma(shape)*(1/rate)**shape)
#Pick some parameters
beta = 1 #transition rate
n = np.array([2,3,4]) #number of states
k ... | _____no_output_____ | MIT | GenericModelExploration.ipynb | GarciaLab/OnsetTimeTransientInputs |
The mean $\mu_k$ and variance $\sigma^2_k$ have simple analytical expressions and are given by\begin{equation}\mu_k = \frac{k}{\beta} \\\sigma^2_k = \frac{k}{\beta^2}\end{equation}For this analysis, we will consider a two-dimensional feature space consisting of the mean onset time on the x-axis and the squared CV (vari... | #Setting up our feature space
beta_min = 0.5 #Minimum transition rate
beta_max = 5 #Maximum transition rate
beta_step = 0.1 #Resolution in transition rates
beta_range = np.arange(beta_min,beta_max,beta_step)
n = np.array([2,3,4,5]) #Number of states
means = np.zeros((len(n),len(beta_range)))
CV2s = np.zeros((len(n),le... | _____no_output_____ | MIT | GenericModelExploration.ipynb | GarciaLab/OnsetTimeTransientInputs |
What happens if we now allow for backwards transitions as an extension to this ideal case? We'll retain the idea of equal forward transition rates $\beta$, but now allow for equal backwards transitions of magnitude $\beta f$ (except from the final absorbing state $k$). \begin{equation}0 \underset{\beta f}{\overset{\bet... | #Setting up parameters
n = 3
beta_min = 0.1
beta_max = 5.1
beta_step = 0.1
beta_range = np.arange(beta_min,beta_max,beta_step)
N_cells = 10000
#Backwards transitions
f = np.arange(0,4,1) #fractional magnitude of backwards transition relative to forwards
means = np.zeros((len(beta_range),len(f)))
CV2s = np.zeros((len(b... | _____no_output_____ | MIT | GenericModelExploration.ipynb | GarciaLab/OnsetTimeTransientInputs |
We see that as the backwards transition rate increases, the overall noise increases! This makes intuitive sense, since with a backwards transition rate, the system is more likely to spend extra time hopping between states before reaching the final absorbing state, increasing the overall time to finish as well as the va... | #Looking at steady-state vs input transient profiles
time = np.arange(0,10,0.1)
dt = 0.1
w_base = 1
w_const = w_base * np.ones(time.shape)
N_trans = 2
N_cells = 1000
#Now with transient exponential rate
tau = 3
w_trans = w_base * (1 - np.exp(-time / tau))
#Plot the inputs
TransientInputs = plt.figure()
#plt.title('In... | _____no_output_____ | MIT | GenericModelExploration.ipynb | GarciaLab/OnsetTimeTransientInputs |
Because of the time-varying nature of $\beta(t)$, the resulting distribution $P_k(t)$ for the case of equal, irreversible forward transition rates no longer obeys a simple Gamma distribution, and an analytical solution is difficult (or even impossible). Nevertheless, we can easily simulate the distributions numerically... | #Let's visualize the distribution of onset times for the case of equal, irreversible forward transition rates,
#comparing steady-state and transient input profiles, varying the "diffusion" constant tau
#Pick some parameters
beta = 1 #transition rate
n = 3 #Number of states
tau = np.array([1,3])
#Simulate the distribu... | _____no_output_____ | MIT | GenericModelExploration.ipynb | GarciaLab/OnsetTimeTransientInputs |
We see that increasing the time constant $\tau$ results in a rightward shift of the onset time distribution, as expected since the time-varying transition rate profile will results in slower initial transition rates. What impact does this have on the noise? Below we show the feature space holding $k=2$ fixed while vary... | #Exploring the impact of transient inputs
#First, fix k and vary tau
n = 3 #number of states
beta_min = 0.1
beta_max = 5.1
beta_step = 0.1
beta_range = np.arange(beta_min,beta_max,beta_step)
tau = np.arange(1,10,3)
#Simulate the distributions
N_cells = 5000
#Steady state
means_steady = np.zeros(len(beta_range))
CV2s_... | _____no_output_____ | MIT | GenericModelExploration.ipynb | GarciaLab/OnsetTimeTransientInputs |
In each case, the transient input reduces noise! It seems like for increasing $\tau$, the performance improves. This makes intuitive sense because having a time-dependent input profile will make earlier transitions "weaker," so transitions that happen before the expected time are less likely, tightening the overall dis... | #Setting up parameters
n = 3
beta_min = 0.1
beta_max = 5.1
beta_step = 0.1
beta_range = np.arange(beta_min,beta_max,beta_step)
f = 0.2
tau = np.array([0.25,0.5,1,3])
#Simulate results
N_cells = 10000
#Steady state
means_steady = np.zeros(len(beta_range))
CV2s_steady = np.zeros(len(beta_range))
for i in range(len(bet... | _____no_output_____ | MIT | GenericModelExploration.ipynb | GarciaLab/OnsetTimeTransientInputs |
Interesting! As shown earlier, the steady-state case with a backwards transition rate is worse than the ideal limit with equal, irreversible forward rates. However, using a transient rate can counterbalance this and still achieve performance better than the ideal limit in the steady-state case.This suggests that given ... | # Export figures
ToyModelDist.savefig('figures/ToyModelDist.pdf')
ToyModelFeatureSpace.savefig('figures/ToyModelFeatureSpace.pdf')
BackwardsDist.savefig('figures/BackwardsDist.pdf')
BackwardsFeatureSpace.savefig('figures/BackwardsFigureSpace.pdf')
TransientInputs.savefig('figures/TransientInputs.pdf')
TransientDist.sa... | _____no_output_____ | MIT | GenericModelExploration.ipynb | GarciaLab/OnsetTimeTransientInputs |
Mining the Social Web (3rd Edition) PrefaceWelcome! Allow me to be the first to offer my congratulations on your decision to take an interest in [_Mining the Social Web (3rd Edition)_](http://bit.ly/135dHfs)! This collection of [Jupyter Notebooks](http://ipython.org/notebook.html) provides an interactive way to follow... | # This is a Python source code comment in a Jupyter Notebook cell.
# Try executing this cell by placing your cursor in it and typing Shift-Enter
print("Hello, Social Web!")
# See Appendix A to get your virtual machine installed
# See Appendix C for a brief overview of some Python idioms and IPython Notebook tips | Hello, Social Web!
| BSD-2-Clause | notebooks/Chapter 0 - Preface.ipynb | ohshane71/Mining-the-Social-Web-3rd-Edition |
Copyright 2021 The TensorFlow Cloud Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb | anukaal/cloud |
Tuning a wide and deep model using Google Cloud View on TensorFlow.org Run in Google Colab View on GitHub Download notebook Run in Kaggle In this example we will use CloudTuner and Google Cloud to Tune a [Wide and Deep Model](https://ai.googleblog.com/2016/... | import datetime
import uuid
import numpy as np
import pandas as pd
import tensorflow as tf
import os
import sys
import subprocess
from tensorflow.keras import datasets, layers, models
from sklearn.model_selection import train_test_split
# Install the latest version of tensorflow_cloud and other required packages.
if... | _____no_output_____ | Apache-2.0 | g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb | anukaal/cloud |
Project ConfigurationsSetting project parameters. For more details on Google Cloud Specific parameters please refer to [Google Cloud Project Setup Instructions](https://www.kaggle.com/nitric/google-cloud-project-setup-instructions/). | # Set Google Cloud Specific parameters
# TODO: Please set GCP_PROJECT_ID to your own Google Cloud project ID.
GCP_PROJECT_ID = 'YOUR_PROJECT_ID' #@param {type:"string"}
# TODO: Change the Service Account Name to your own Service Account
SERVICE_ACCOUNT_NAME = 'YOUR_SERVICE_ACCOUNT_NAME' #@param {type:"string"}
SERVI... | _____no_output_____ | Apache-2.0 | g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb | anukaal/cloud |
Authenticating the notebook to use your Google Cloud ProjectFor Kaggle Notebooks click on "Add-ons"->"Google Cloud SDK" before running the cell below. | # Using tfc.remote() to ensure this code only runs in notebook
if not tfc.remote():
# Authentication for Kaggle Notebooks
if "kaggle_secrets" in sys.modules:
from kaggle_secrets import UserSecretsClient
UserSecretsClient().set_gcloud_credentials(project=GCP_PROJECT_ID)
# Authentication for... | _____no_output_____ | Apache-2.0 | g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb | anukaal/cloud |
Load the dataRead raw data and split to train and test data sets. For this step you will need to copy the dataset to your GCS bucket so it can be accessed during training. For this example we are using the dataset from https://www.kaggle.com/c/caiis-dogfood-day-2020.To do this you can run the following commands to dow... | train_URL = f'{GCS_BASE_PATH}/caiis-dogfood-day-2020/train.csv'
data = pd.read_csv(train_URL)
train, test = train_test_split(data, test_size=0.1)
# A utility method to create a tf.data dataset from a Pandas Dataframe
def df_to_dataset(df, shuffle=True, batch_size=32):
df = df.copy()
labels = df.pop('target')
ds =... | _____no_output_____ | Apache-2.0 | g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb | anukaal/cloud |
Preprocess the dataSetting up preprocessing layers for categorical and numerical input data. For more details on preprocessing layers please refer to [working with preprocessing layers](https://www.tensorflow.org/guide/keras/preprocessing_layers). | from tensorflow.keras.layers.experimental import preprocessing
def create_model_inputs():
inputs ={}
for name, column in data.items():
if name in ('id','target'):
continue
dtype = column.dtype
if dtype == object:
dtype = tf.string
else:
dtype ... | _____no_output_____ | Apache-2.0 | g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb | anukaal/cloud |
Define the model architecture and hyperparametersIn this section we define our tuning parameters using [Keras Tuner Hyper Parameters](https://keras-team.github.io/keras-tuner/the-search-space-may-contain-conditional-hyperparameters) and a model-building function. The model-building function takes an argument hp from w... | import kerastuner
# Configure the search space
HPS = kerastuner.engine.hyperparameters.HyperParameters()
HPS.Float('learning_rate', min_value=1e-4, max_value=1e-2, sampling='log')
HPS.Int('num_layers', min_value=2, max_value=5)
for i in range(5):
HPS.Float('dropout_rate_' + str(i), min_value=0.0, max_value=0.3, s... | _____no_output_____ | Apache-2.0 | g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb | anukaal/cloud |
Configure a CloudTunerIn this section we configure the cloud tuner for both remote and local execution. The main difference between the two is the distribution strategy. | from tensorflow_cloud import CloudTuner
distribution_strategy = None
if not tfc.remote():
# Using MirroredStrategy to use a single instance with multiple GPUs
# during remote execution while using no strategy for local.
distribution_strategy = tf.distribute.MirroredStrategy()
tuner = CloudTuner(
creat... | _____no_output_____ | Apache-2.0 | g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb | anukaal/cloud |
Start the remote trainingThis step will prepare your code from this notebook for remote execution and start NUM_JOBS parallel runs remotely to train the model. Once the jobs are submitted you can go to the next step to monitor the jobs progress via Tensorboard. |
# Optional: Some recommended base images. If you provide none the system will choose one for you.
TF_GPU_IMAGE= "gcr.io/deeplearning-platform-release/tf2-cpu.2-5"
TF_CPU_IMAGE= "gcr.io/deeplearning-platform-release/tf2-gpu.2-5"
tfc.run_cloudtuner(
distribution_strategy='auto',
docker_config=tfc.DockerConfig(... | _____no_output_____ | Apache-2.0 | g3doc/tutorials/hp_tuning_wide_and_deep_model.ipynb | anukaal/cloud |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.