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 |
|---|---|---|---|---|---|
Optimization result | optimized_control = opt_result.optimized_controls[0] + 1j * opt_result.optimized_controls[1]
plot_pulse(np.abs(optimized_control), tlist)
def propagate_opt(initial_state):
return opt_result.optimized_objectives[0].propagate(
tlist,
propagator=krotov.propagators.DensityMatrixODEPropagator(),
... | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
Plotting the population dynamics, we see the expected behavior for the $\sqrt{\text{iSWAP}}$ gate. | plot_population_dynamics(
*parallel_map(
propagate_opt_for_expvals,
values=[rho00, rho01, rho10, rho11],
)
)
def plot_convergence(result):
fig, ax = plt.subplots()
ax.semilogy(result.iters, result.info_vals)
ax.set_xlabel('OCT iteration')
ax.set_ylabel(r'optimization error $J_{T,... | _____no_output_____ | BSD-3-Clause | docs/notebooks/06_example_3states.ipynb | guruvamsi-policharla/noisy-krotov |
Working with Scikit-learnThis notebook shows how PySINDy objects interface with some useful tools from [Scikit-learn](https://scikit-learn.org/stable/). Setup | import numpy as np
from scipy.integrate import odeint
import pysindy as ps | _____no_output_____ | MIT | examples/4_scikit_learn_compatibility.ipynb | jzjosuerivera71/pysindy-1 |
Let's generate some training data from the [Lorenz system](https://en.wikipedia.org/wiki/Lorenz_system) with which to experiment. | def lorenz(z, t):
return [
10 * (z[1] - z[0]),
z[0] * (28 - z[2]) - z[1],
z[0] * z[1] - (8 / 3) * z[2]
]
# Generate training data
dt = .002
t_train = np.arange(0, 10, dt)
x0_train = [-8, 8, 27]
x_train = odeint(lorenz, x0_train, t_train)
# Evolve the Lorenz equations in time using a d... | _____no_output_____ | MIT | examples/4_scikit_learn_compatibility.ipynb | jzjosuerivera71/pysindy-1 |
Cross-validationPySINDy supports Scikit-learn-type cross-validation with a few caveats.1. We must use **uniform timesteps** using the `t_default` parameter. This is because the `fit` and `score` methods of `SINDy` differ from those used in Scikit-learn in the sense that they both have an optional `t` parameter. Settin... | from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import TimeSeriesSplit
model = ps.SINDy(t_default=dt)
param_grid = {
"optimizer__threshold": [0.001, 0.01, 0.1],
"optimizer__alpha": [0.01, 0.05, 0.1],
"feature_library": [ps.PolynomialLibrary(), ps.FourierLibrary()],
"diffe... | Best parameters: {'differentiation_method__order': 2, 'feature_library': PolynomialLibrary(), 'optimizer__alpha': 0.01, 'optimizer__threshold': 0.01}
x0' = -9.999 x0 + 9.999 x1
x1' = 27.992 x0 + -0.999 x1 + -1.000 x0 x2
x2' = -2.666 x2 + 1.000 x0 x1
| MIT | examples/4_scikit_learn_compatibility.ipynb | jzjosuerivera71/pysindy-1 |
Cross-validation without TimeSeriesSplitIf we want to use another cross-validation splitter, we'll need to (a) define a wrapper class which uses the argument "y" instead of "x_dot" and (b) precompute the derivatives. Note that (b) means that we will not be able to perform cross-validation on the parameters of the diff... | from sklearn.metrics import r2_score
class SINDyCV(ps.SINDy):
def __init__(
self,
optimizer=None,
feature_library=None,
differentiation_method=None,
feature_names=None,
t_default=1,
discrete_time=False,
n_jobs=1
):
super(SINDyCV, self).__i... | Best parameters: {'feature_library__degree': 2, 'optimizer__alpha': 0.01, 'optimizer__threshold': 0.002}
x0' = -9.999 x0 + 9.999 x1
x1' = 27.992 x0 + -0.999 x1 + -1.000 x0 x2
x2' = -2.666 x2 + 1.000 x0 x1
| MIT | examples/4_scikit_learn_compatibility.ipynb | jzjosuerivera71/pysindy-1 |
Sparse optimizersAny of Scikit-learn's [linear models ](https://scikit-learn.org/stable/modules/linear_model.html) can be used for the `optimizer` parameter of a `SINDy` object, though we only recommend using those designed for sparse regression.In the examples below we set `fit_intercept` to `False` since the default... | from sklearn.linear_model import ElasticNet
model = ps.SINDy(optimizer=ElasticNet(l1_ratio=0.9, fit_intercept=False), t_default=dt)
model.fit(x_train)
model.print()
from sklearn.linear_model import OrthogonalMatchingPursuit
model = ps.SINDy(
optimizer=OrthogonalMatchingPursuit(n_nonzero_coefs=8, fit_intercept=Fal... | x0' = -10.005 x0 + 10.003 x1
x1' = 27.990 x0 + -0.997 x1 + -1.000 x0 x2
x2' = -2.665 x2 + 0.001 x0^2 + 0.999 x0 x1
| MIT | examples/4_scikit_learn_compatibility.ipynb | jzjosuerivera71/pysindy-1 |
Apriori Importing the libraries | !pip install apyori
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd | _____no_output_____ | MIT | code/apriori/apriori.ipynb | nrkapri/machine-learning |
Data Preprocessing | dataset = pd.read_csv('Market_Basket_Optimisation.csv', header = None)
transactions = []
for i in range(0, 7501):
transactions.append([str(dataset.values[i,j]) for j in range(0, 20)]) | _____no_output_____ | MIT | code/apriori/apriori.ipynb | nrkapri/machine-learning |
Training the Apriori model on the dataset | from apyori import apriori
rules = apriori(transactions = transactions, min_support = 0.003, min_confidence = 0.2, min_lift = 3, min_length = 2, max_length = 2) | _____no_output_____ | MIT | code/apriori/apriori.ipynb | nrkapri/machine-learning |
Visualising the results Displaying the first results coming directly from the output of the apriori function | results = list(rules)
results | _____no_output_____ | MIT | code/apriori/apriori.ipynb | nrkapri/machine-learning |
Putting the results well organised into a Pandas DataFrame | def inspect(results):
lhs = [tuple(result[2][0][0])[0] for result in results]
rhs = [tuple(result[2][0][1])[0] for result in results]
supports = [result[1] for result in results]
confidences = [result[2][0][2] for result in results]
lifts = [result[2][0][3] for result in res... | _____no_output_____ | MIT | code/apriori/apriori.ipynb | nrkapri/machine-learning |
Displaying the results non sorted | resultsinDataFrame | _____no_output_____ | MIT | code/apriori/apriori.ipynb | nrkapri/machine-learning |
Displaying the results sorted by descending lifts | resultsinDataFrame.nlargest(n = 10, columns = 'Lift') | _____no_output_____ | MIT | code/apriori/apriori.ipynb | nrkapri/machine-learning |
An Introduction to Natural Language in Python using spaCy IntroductionThis tutorial provides a brief introduction to working with natural language (sometimes called "text analytics") in Pytho, using [spaCy](https://spacy.io/) and related libraries.Data science teams in industry must work with lots of text, one of the... | import spacy
nlp = spacy.load("en_core_web_sm") | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
That `nlp` variable is now your gateway to all things _spaCy_ and loaded with the `en_core_web_sm` small model for English.Next, let's run a small "document" through the natural language parser: | text = "The rain in Spain falls mainly on the plain."
doc = nlp(text)
for token in doc:
print(token.text, token.lemma_, token.pos_, token.is_stop) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
First we created a [doc](https://spacy.io/api/doc) from the text, which is a container for a document and all of its annotations. Then we iterated through the document to see what _spaCy_ had parsed.Good, but it's a lot of info and a bit difficult to read. Let's reformat the _spaCy_ parse of that sentence as a [pandas]... | import pandas as pd
cols = ("text", "lemma", "POS", "explain", "stopword")
rows = []
for t in doc:
row = [t.text, t.lemma_, t.pos_, spacy.explain(t.pos_), t.is_stop]
rows.append(row)
df = pd.DataFrame(rows, columns=cols)
df | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Much more readable!In this simple case, the entire document is merely one short sentence.For each word in that sentence _spaCy_ has created a [token](https://spacy.io/api/token), and we accessed fields in each token to show: - raw text - [lemma](https://en.wikipedia.org/wiki/Lemma_(morphology)) – a root form of the wor... | from spacy import displacy
displacy.render(doc, style="dep", jupyter=True) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Does that bring back memories of grade school? Frankly, for those of us coming from more of a computational linguistics background, that diagram sparks joy.But let's backup for a moment. How do you handle multiple sentences?There are features for _sentence boundary detection_ (SBD) – also known as _sentence segmentatio... | text = "We were all out at the zoo one day, I was doing some acting, walking on the railing of the gorilla exhibit. I fell in. Everyone screamed and Tommy jumped in after me, forgetting that he had blueberries in his front pocket. The gorillas just went wild."
doc = nlp(text)
for sent in doc.sents:
print(">", sen... | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
When _spaCy_ creates a document, it uses a principle of _non-destructive tokenization_ meaning that the tokens, sentences, etc., are simply indexes into a long array. In other words, they don't carve the text stream into little pieces. So each sentence is a [span](https://spacy.io/api/span) with a _start_ and an _end_ ... | for sent in doc.sents:
print(">", sent.start, sent.end) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
We can index into the document array to pull out the tokens for one sentence: | doc[48:54] | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Or simply index into a specific token, such as the verb `went` in the last sentence: | token = doc[51]
print(token.text, token.lemma_, token.pos_) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
At this point we can parse a document, segment that document into sentences, then look at annotations about the tokens in each sentence. That's a good start. Acquiring TextNow that we can parse texts, where do we get texts?One quick source is to leverage the interwebs.Of course when we download web pages we'll get HTM... | import sys
import warnings
warnings.filterwarnings("ignore") | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Character Encoding The following shows examples of how to use [codecs](https://docs.python.org/3/library/codecs.html) and [normalize unicode](https://docs.python.org/3/library/unicodedata.htmlunicodedata.normalize). NB: the example text comes from the article "[Metal umlat](https://en.wikipedia.org/wiki/Metal_umlaut)"... | x = "Rinôçérôse screams flow not unlike an encyclopædia, \
'TECHNICIÄNS ÖF SPÅCE SHIP EÅRTH THIS IS YÖÜR CÄPTÅIN SPEÄKING YÖÜR ØÅPTÅIN IS DEA̋D' to Spın̈al Tap."
type(x) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
The variable `x` is a *string* in Python: | repr(x) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Its translation into [ASCII](http://www.asciitable.com/) is unusable by parsers: | ascii(x) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Encoding as [UTF-8](http://unicode.org/faq/utf_bom.html) doesn't help much: | x.encode('utf8') | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Ignoring difficult characters is perhaps an even worse strategy: | x.encode('ascii', 'ignore') | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
However, one can *normalize* text, then encode… | import unicodedata
unicodedata.normalize('NFKD', x).encode('ascii','ignore') | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Even before this normalization and encoding, you may need to convert some characters explicitly **before** parsing. For example: | x = "The sky “above” the port … was the color of ‘cable television’ – tuned to the Weather Channel®"
ascii(x) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Consider the results for that line: | unicodedata.normalize('NFKD', x).encode('ascii', 'ignore') | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
...which still drops characters that may be important for parsing a sentence.So a more advanced approach could be: | x = x.replace('“', '"').replace('”', '"')
x = x.replace("‘", "'").replace("’", "'")
x = x.replace('…', '...').replace('–', '-')
x = unicodedata.normalize('NFKD', x).encode('ascii', 'ignore').decode('utf-8')
print(x) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Parsing HTML In the following function `get_text()` we'll parse the HTML to find all of the `` tags, then extract the text for those: | from bs4 import BeautifulSoup
import requests
import traceback
def get_text (url):
buf = []
try:
soup = BeautifulSoup(requests.get(url).text, "html.parser")
for p in soup.find_all("p"):
buf.append(p.get_text())
return "\n".join(buf)
except:
print(t... | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Now let's grab some text from online sources.We can compare open source licenses hosted on the [Open Source Initiative](https://opensource.org/licenses/) site: | lic = {}
lic["mit"] = nlp(get_text("https://opensource.org/licenses/MIT"))
lic["asl"] = nlp(get_text("https://opensource.org/licenses/Apache-2.0"))
lic["bsd"] = nlp(get_text("https://opensource.org/licenses/BSD-3-Clause"))
for sent in lic["bsd"].sents:
print(">", sent) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
One common use case for natural language work is to compare texts. For example, with those open source licenses we can download their text, parse, then compare [similarity](https://spacy.io/api/docsimilarity) metrics among them: | pairs = [
["mit", "asl"],
["asl", "bsd"],
["bsd", "mit"]
]
for a, b in pairs:
print(a, b, lic[a].similarity(lic[b])) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
That is interesting, since the [BSD](https://opensource.org/licenses/BSD-3-Clause) and [MIT](https://opensource.org/licenses/MIT) licenses appear to be the most similar documents.In fact they are closely related.Admittedly, there was some extra text included in each document due to the OSI disclaimer in the footer – bu... | text = "Steve Jobs and Steve Wozniak incorporated Apple Computer on January 3, 1977, in Cupertino, California."
doc = nlp(text)
for chunk in doc.noun_chunks:
print(chunk.text) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Not bad. The noun phrases in a sentence generally provide more information content – as a simple filter used to reduce a long document into a more "distilled" representation.We can take this approach further and identify [named entities](https://spacy.io/usage/linguistic-featuresnamed-entities) within the text, i.e., t... | for ent in doc.ents:
print(ent.text, ent.label_) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
The _displaCy_ library provides an excellent way to visualize named entities: | displacy.render(doc, style="ent", jupyter=True) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
If you're working with [knowledge graph](https://www.akbc.ws/) applications and other [linked data](http://linkeddata.org/), your challenge is to construct links between the named entities in a document and other related information for the entities – which is called [entity linking](http://nlpprogress.com/english/enti... | import nltk
nltk.download("wordnet") | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Note that _spaCy_ runs as a "pipeline" and allows means for customizing parts of the pipeline in use.That's excellent for supporting really interesting workflow integrations in data science work.Here we'll add the `WordnetAnnotator` from the _spacy-wordnet_ project: | !pip install spacy-wordnet
from spacy_wordnet.wordnet_annotator import WordnetAnnotator
print("before", nlp.pipe_names)
if "WordnetAnnotator" not in nlp.pipe_names:
nlp.add_pipe(WordnetAnnotator(nlp.lang), after="tagger")
print("after", nlp.pipe_names) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Within the English language, some words are infamous for having many possible meanings. For example, click through the results online in a [WordNet](http://wordnetweb.princeton.edu/perl/webwn?s=star&sub=Search+WordNet&o2=&o0=1&o8=1&o1=1&o7=&o5=&o9=&o6=&o3=&o4=&h=) search to find the meanings related to the word `withdr... | token = nlp("withdraw")[0]
token._.wordnet.synsets()
token._.wordnet.lemmas()
token._.wordnet.wordnet_domains() | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Again, if you're working with knowledge graphs, those "word sense" links from WordNet could be used along with graph algorithms to help identify the meanings for a particular word. That can also be used to develop summaries for larger sections of text through a technique called _summarization_. It's beyond the scope o... | domains = ["finance", "banking"]
sentence = nlp("I want to withdraw 5,000 euros.")
enriched_sent = []
for token in sentence:
# get synsets within the desired domains
synsets = token._.wordnet.wordnet_synsets_for_domain(domains)
if synsets:
lemmas_for_synset = []
for s in syns... | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
That example may look simple but, if you play with the `domains` list, you'll find that the results have a kind of combinatorial explosion when run without reasonable constraints.Imagine having a knowledge graph with millions of elements: you'd want to constrain searches where possible to avoid having every query take ... | !pip install scattertext
import scattertext as st
if "merge_entities" not in nlp.pipe_names:
nlp.add_pipe(nlp.create_pipe("merge_entities"))
if "merge_noun_chunks" not in nlp.pipe_names:
nlp.add_pipe(nlp.create_pipe("merge_noun_chunks"))
convention_df = st.SampleCorpora.ConventionData2012.get_data()
corpus ... | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Once you have the `corpus` ready, generate an interactive visualization in HTML: | html = st.produce_scattertext_explorer(
corpus,
category="democrat",
category_name="Democratic",
not_category_name="Republican",
width_in_pixels=1000,
metadata=convention_df["speaker"]
) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Now we'll render the HTML – give it a minute or two to load, it's worth the wait... | from IPython.display import IFrame
from IPython.core.display import display, HTML
import sys
IN_COLAB = "google.colab" in sys.modules
print(IN_COLAB) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
**NB: use the following cell on Google Colab:** | if IN_COLAB:
display(HTML("<style>.container { width:98% !important; }</style>"))
display(HTML(html)) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
**NB: use the following cell instead on Jupyter in general:** | file_name = "foo.html"
with open(file_name, "wb") as f:
f.write(html.encode("utf-8"))
IFrame(src=file_name, width = 1200, height=700) | _____no_output_____ | MIT | spaCy_tuTorial.ipynb | DerwenAI/conda_sux |
Inference for ResNet 50 using ONNX RuntimeThis example demonstrates how to load an image classification model from the [ONNX model zoo](https://github.com/onnx/models) and confirm its accuracy based on included test data. | import numpy as np # we're going to use numpy to process input and output data
import onnxruntime # to inference ONNX models, we use the ONNX Runtime
import onnx
from onnx import numpy_helper
import urllib.request
onnx_model_url = "https://s3.amazonaws.com/onnx-model-zoo/resnet/resnet50v2/resnet50v2.tar.gz"
# re... | _____no_output_____ | MIT | onnx-ecosystem/inference_demos/resnet50_modelzoo_onnxruntime_inference.ipynb | pridkett/onnx-docker |
Load sample inputs and outputs | test_data_dir = 'resnet50v2/test_data_set'
test_data_num = 3
import glob
import os
# Load inputs
inputs = []
for i in range(test_data_num):
input_file = os.path.join(test_data_dir + '_{}'.format(i), 'input_0.pb')
tensor = onnx.TensorProto()
with open(input_file, 'rb') as f:
tensor.ParseFromString(f... | _____no_output_____ | MIT | onnx-ecosystem/inference_demos/resnet50_modelzoo_onnxruntime_inference.ipynb | pridkett/onnx-docker |
Inference using ONNX Runtime | # Run the model on the backend
session = onnxruntime.InferenceSession('resnet50v2/resnet50v2.onnx', None)
# get the name of the first input of the model
input_name = session.get_inputs()[0].name
print('Input Name:', input_name)
%%time
outputs = [session.run([], {input_name: inputs[i]})[0] for i in range(test_data_n... | _____no_output_____ | MIT | onnx-ecosystem/inference_demos/resnet50_modelzoo_onnxruntime_inference.ipynb | pridkett/onnx-docker |
Aufgabe 1: Lade das Dataset mit allen Features rein. | dataset = load_iris()
x = dataset.data
y = dataset.target | _____no_output_____ | MIT | Chapter10_Clustering/KMeansExercise/KMeans_solution.ipynb | tomex74/UdemyML |
Aufgabe 2: Wende das k-Means mit einer beliebigen Anzahl an Cluster an. | scores = []
s_scores = []
for n_clusters in [2, 3, 4, 5, 6]:
max_iter = 10_000
kmeans = KMeans(
n_clusters=n_clusters,
max_iter=max_iter,
n_jobs=-1
)
kmeans.fit(x)
y_pred = kmeans.predict(x)
s_scores.append(silhouette_score(x, y_pred))
scores.append(kmeans.score(x)) | _____no_output_____ | MIT | Chapter10_Clustering/KMeansExercise/KMeans_solution.ipynb | tomex74/UdemyML |
Aufgabe 3: Berechne den Score für verschiedene Setups. | print(f"Scores: {scores}")
print(f"silhouette_score: {s_scores}") | Scores: [-152.347951760358, -78.85144142614602, -57.25600931571815, -46.44618205128204, -39.05497786747788]
silhouette_score: [0.681046169211746, 0.5528190123564091, 0.49745518901737446, 0.4887488870931048, 0.3664804028900824]
| MIT | Chapter10_Clustering/KMeansExercise/KMeans_solution.ipynb | tomex74/UdemyML |
SciPy 2016 Scikit-learn Tutorial In Depth - Support Vector Machines SVM stands for "support vector machines". They are efficient and easy to use estimators.They come in two kinds: SVCs, Support Vector Classifiers, for classification problems, and SVRs, Support Vector Regressors, for regression problems. Linear SVMs... | from sklearn.metrics.pairwise import rbf_kernel
line = np.linspace(-3, 3, 100)[:, np.newaxis]
kernel_value = rbf_kernel(line, [[0]], gamma=1)
plt.plot(line, kernel_value); | _____no_output_____ | MIT | scipy-2016-sklearn/notebooks/18 In Depth - Support Vector Machines.ipynb | sunny2309/scipy_conf_notebooks |
The rbf kernel has an inverse bandwidth-parameter gamma, where large gamma mean a very localized influence for each data point, andsmall values mean a very global influence.Let's see these two parameters in action: | from figures import plot_svm_interactive
plot_svm_interactive() | /home/sunny/anaconda2/lib/python2.7/site-packages/IPython/html.py:14: ShimWarning: The `IPython.html` package has been deprecated since IPython 4.0. You should import from `notebook` instead. `IPython.html.widgets` has moved to `ipywidgets`.
"`IPython.html.widgets` has moved to `ipywidgets`.", ShimWarning)
| MIT | scipy-2016-sklearn/notebooks/18 In Depth - Support Vector Machines.ipynb | sunny2309/scipy_conf_notebooks |
Exercise: tune a SVM on the digits dataset | from sklearn.datasets import load_digits
from sklearn.svm import SVC
digits = load_digits()
X_digits, y_digits = digits.data, digits.target
# split the dataset, apply grid-search
#%load solutions/18_svc_grid.py | _____no_output_____ | MIT | scipy-2016-sklearn/notebooks/18 In Depth - Support Vector Machines.ipynb | sunny2309/scipy_conf_notebooks |
Think BayesThis notebook presents example code and exercise solutions for Think Bayes.Copyright 2018 Allen B. DowneyMIT License: https://opensource.org/licenses/MIT | # Configure Jupyter so figures appear in the notebook
%matplotlib inline
# Configure Jupyter to display the assigned value after an assignment
%config InteractiveShell.ast_node_interactivity='last_expr_or_assign'
# import classes from thinkbayes2
from thinkbayes2 import Hist, Pmf, Suite, Beta
import thinkplot | _____no_output_____ | MIT | examples/unreliable_soln.ipynb | chwebster/ThinkBayes2 |
Unreliable observationSuppose that instead of observing coin tosses directly, you measure the outcome using an instrument that is not always correct. Specifically, suppose there is a probability `y` that an actual heads is reported as tails, or actual tails reported as heads.Write a class that estimates the bias of a ... | # Solution
# Here's a class that models an unreliable coin
class UnreliableCoin(Suite):
def __init__(self, prior, y):
"""
prior: seq or map
y: probability of accurate measurement
"""
super().__init__(prior)
self.y = y
def Likelihood(self, data, hypo):
... | _____no_output_____ | MIT | examples/unreliable_soln.ipynb | chwebster/ThinkBayes2 |
YahooFinance - Get Stock Update **Tags:** yahoofinance usdinr plotly investors analytics automation plotly **Author:** [Megha Gupta](https://github.com/megha2907) Description: With this template you will get INR USD rate visualized on a chart Input Import Libraries | import naas
from naas_drivers import yahoofinance, plotly
import markdown2
from IPython.display import Markdown as md | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Setup Yahoo parameters 👉 Here you can input:- yahoo ticker : get tickers here- date from- date to | TICKER = 'INR=X'
date_from = -30
date_to = 'today' | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Setup your email parameters👉 Here you can input your sender email and destination emailNote: emails are sent from notification@naass.ai by default | email_to = ["template@naas.ai"]
email_from = None | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Model Get the data from yahoo finance using naas drivers | #data cleaning
df = yahoofinance.get(TICKER, date_from=date_from, date_to = date_to)
df = df.dropna()# drop the na values from the dataframe
df.reset_index(drop=True)
df = df.sort_values("Date", ascending=False).reset_index(drop=True)
df.head() | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Extract value from data | LASTOPEN = round(df.loc[0, "Open"], 2)
LASTCLOSE = round(df.loc[0, "Close"], 2)
YESTERDAYOPEN = round(df.loc[1, "Open"], 2)
YESTERDAYCLOSE = round(df.loc[1, "Close"], 2)
MAXRATE = round(df['Open'].max(),2)
MXDATEOPEN = df.loc[df['Open'].idxmax(), "Date"].strftime("%Y-%m-%d")
MINRATE = round(df['Open'].min(),2)
MNDATEOP... | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Plot the data | last_date = df.loc[df.index[0], "Date"].strftime("%Y-%m-%d")
output = plotly.linechart(df,
x="Date",
y=['Open','Close'],
title=f"<b>INR USD rates of last month</b><br><span style='font-size: 13px;'>Last value as of {last_date}: Open={LASTOPE... | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Output Save the dataset in csv | df.to_csv(f"{TICKER}_LastMonth.csv", index=False) | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Create markdown template | %%writefile message.md
Hello world,
The **TICKER** price is Open LASTOPEN and Close LASTCLOSE right now. <br>
**Yesterday Open**: YESTERDAYOPEN <br>
**Yesterday Close**: YESTERDAYCLOSE <br>
The Max Open rate of **TICKER** was on MXDATEOPEN which was MAXRATE. <br>
The Min Open rate of **TICKER** was on MNDATEOPEN w... | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Add email template as dependency | naas.dependency.add("message.md") | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Replace values in template | markdown_file = "message.md"
content = open(markdown_file, "r").read()
md = markdown2.markdown(content)
md
post = md.replace("LASTOPEN", str(LASTOPEN))
post = post.replace("LASTCLOSE", str(LASTCLOSE))
post = post.replace("YESTERDAYOPEN", str(YESTERDAYOPEN))
post = post.replace("YESTERDAYCLOSE", str(YESTERDAYCLOSE))
pos... | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Add webhook to run your notebook again | link_webhook = naas.webhook.add() | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Send by email | subject = f"📈 {TICKER} Open and close rates as of today"
content = post
files = [f"{TICKER}_LastMonth.csv"]
naas.notification.send(email_to=email_to,
subject=subject,
html=content,
email_from=email_from,
files=files) | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Schedule your notebookPlease uncomment and run the cell below to schedule your notebook everyday at 8:00 during business days | # import naas
# naas.scheduler.add("0 8 1-5 * *") | _____no_output_____ | BSD-3-Clause | YahooFinance/YahooFinance_Get_Stock_Update.ipynb | krajai/testt |
Before we begin, let's execute the cell below to display information about the CUDA driver and GPUs running on the server by running the `nvidia-smi` command. To do this, execute the cell block below by giving it focus (clicking on it with your mouse), and hitting Ctrl-Enter, or pressing the play button in the toolbar ... | !nvidia-smi | _____no_output_____ | Apache-2.0 | hpc/nways/nways_labs/nways_MD/English/Fortran/jupyter_notebook/openacc/nways_openacc_opt_2.ipynb | programmah/gpubootcamp |
Learning objectivesThe **goal** of this lab is to:- Dig deeper into kernels by analyzing it with Nsight Compute In the previous section, we learned to optimize the parallel [RDF](../serial/rdf_overview.ipynb) application using OpenACC. Moreover, we used NVIDIA Nsight Systems to get a system-wide performance analysis. ... | #compile the solution for Tesla GPU
!cd ../../source_code/openacc && nvfortran -acc -ta=tesla,lineinfo -Minfo=accel -o rdf nvtx.f90 SOLUTION/rdf_collapse.f90 -L/opt/nvidia/hpc_sdk/Linux_x86_64/21.3/cuda/11.2/lib64 -lnvToolsExt
#profile the solution with Nsight Systems
!cd ../../source_code/openacc && nsys profile -t n... | _____no_output_____ | Apache-2.0 | hpc/nways/nways_labs/nways_MD/English/Fortran/jupyter_notebook/openacc/nways_openacc_opt_2.ipynb | programmah/gpubootcamp |
Let's checkout the profiler's report. Download and save the report file by holding down Shift and Right-Clicking [Here](../../source_code/openacc/rdf_collapse_solution.qdrep) and open it via the GUI. Now, right click on the kernel `rdf_98_gpu` and click on "Analyze the Selected Kernel with NVIDIA Nsight Compute" (see b... | #profile the selected kernel in the solution with Nsight compute
!cd ../../source_code/openacc && ncu --set full --launch-skip 1 --launch-count 1 -o rdf_collapse_solution ./rdf | _____no_output_____ | Apache-2.0 | hpc/nways/nways_labs/nways_MD/English/Fortran/jupyter_notebook/openacc/nways_openacc_opt_2.ipynb | programmah/gpubootcamp |
Let's checkout the Nsight Compute profiler's report together. Download and save the report file by holding down Shift and Right-Clicking [Here](../../source_code/openacc/rdf_collapse_solution.ncu-rep) and open it via the GUI. Let's checkout the first section called "GPU Speed Of Light". This section gives an overview o... | %%bash
cd ..
rm -f nways_files.zip
zip -r nways_files.zip * | _____no_output_____ | Apache-2.0 | hpc/nways/nways_labs/nways_MD/English/Fortran/jupyter_notebook/openacc/nways_openacc_opt_2.ipynb | programmah/gpubootcamp |
*FAÇA UM PROGRAMA QUE LEIA O COMPRIMENTO DO CATETO OPOSTO E DO CATETO ADJACENTE DE UM TRIANGULO RETANGULO CALCULE E MOSTRE O CUMPRIMENTO DA HPOTENUSA* | from math import hypot
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprirmtno do cateto adjacente: '))
hi = hypot(co,ca)
print('A hipotenusa vai medir {:.2f}'.format(hi))
co = float(input('Comprimento do cateto oposto: '))
ca = float(input('Comprimento do cateto adjacente: '))
hi=hypot... | _____no_output_____ | MIT | Exercicio_17_Catetos_e_Hipotenusa.ipynb | samucale/Curso_em_Video |
Face and Facial Keypoint detectionAfter you've trained a neural network to detect facial keypoints, you can then apply this network to *any* image that includes faces. The neural network expects a Tensor of a certain size as input and, so, to detect any face, you'll first have to do some pre-processing.1. Detect all t... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
%matplotlib inline | _____no_output_____ | MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | jenchen/facial-keypoint-detection |
Select an image Select an image to perform facial keypoint detection on; you can select any image of faces in the `images/` directory. | import cv2
# load in color image for face detection
image = cv2.imread('images/obamas.jpg')
# switch red and blue color channels
# --> by default OpenCV assumes BLUE comes first, not RED as in many images
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# plot the image
fig = plt.figure(figsize=(9,9))
plt.imshow(image... | _____no_output_____ | MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | jenchen/facial-keypoint-detection |
Detect all faces in an imageNext, you'll use one of OpenCV's pre-trained Haar Cascade classifiers, all of which can be found in the `detector_architectures/` directory, to find any faces in your selected image.In the code below, we loop over each face in the original image and draw a red square on each face (in a copy... | # load in a haar cascade classifier for detecting frontal faces
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
# run the detector
# the output here is an array of detections; the corners of each detection box
# if necessary, modify these parameters until you successf... | _____no_output_____ | MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | jenchen/facial-keypoint-detection |
Loading in a trained modelOnce you have an image to work with (and, again, you can select any image of faces in the `images/` directory), the next step is to pre-process that image and feed it into your CNN facial keypoint detector.First, load your best model by its filename. | import torch
from models import Net
net = Net()
## COMPLETED: load the best saved model parameters (by your path name)
## You'll need to un-comment the line below and add the correct name for *your* saved model
net.load_state_dict(torch.load('saved_models/keypoints_model_rms_prop_20.pt'))
## print out your net and p... | _____no_output_____ | MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | jenchen/facial-keypoint-detection |
Keypoint detectionNow, we'll loop over each detected face in an image (again!) only this time, you'll transform those faces in Tensors that your CNN can accept as input images. TODO: Transform each detected face into an input TensorYou'll need to perform the following steps for each detected face:1. Convert the face f... | def show_keypoints(image, keypoints):
plt.figure(figsize=(5,5))
keypoints = keypoints.data.numpy()
keypoints = keypoints * 60.0 + 96
keypoints = np.reshape(keypoints, (68, -1)) # reshape to 2 X 68 keypoint
image = image.numpy()
image = np.transpose(image, (1, 2, 0)) # (H x W x C)
... | (1, 224, 224)
(1, 224, 224)
| MIT | 3. Facial Keypoint Detection, Complete Pipeline.ipynb | jenchen/facial-keypoint-detection |
Given a 2D board and a word, find if the word exists in the grid.The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.Example: board = [ ['A','B','C','E'], ['S'... | class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
visited = {}
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(board, word, i, j, visited):... | _____no_output_____ | MIT | DSA/backtracking/wordSearch.ipynb | lance-lh/Data-Structures-and-Algorithms |
Recruitment Across DatasetsIn this notebook, we further examine the capability of ODIF to transfer across datasets, building upon the prior FTE/BTE experiments on MNIST and Fashion-MNIST. Using the datasets found in [this repo](https://github.com/neurodata/LLF_tidy_images), we perform a series of experiments to evalua... | import functions.recruitacrossdatasets_functions as fn | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
**Note:** This notebook tutorial uses functions stored externally within `functions/recruitacrossdatasets_functions.py` to simplify presentation of code. These functions are imported above, along with other libraries. FTE/BTE ExperimentWe begin our examination of ODIF's transfer capabilities across datasets with the F... | data, classes = fn.import_data(normalize=False) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
Define HyperparametersWe then define the hyperparameters to be used for the experiment:- `model`: model to be used for FTE/BTE experiment- `num_tasks`: number of tasks- `num_trees`: nuber of trees- `reps`: number of repetitions, fewer than actual figures to reduce running time | ##### MAIN HYPERPARAMS ##################
model = "odif"
num_tasks = 5
num_trees = 10
reps = 4
######################################### | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
Taking each dataset as a separate task, we have `5` tasks, and we also set a default of `10` trees, with the experiment being run for `30` reps.Note, in comparison to previous FTE/BTE experiments, the lack of the `num_points_per_task` parameter. Here, we sample based on the label with the least number of samples and ta... | accuracy_all_task = fn.ftebte_exp(
data, classes, model, num_tasks, num_trees, reps, shift=0
) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
Using the accuracies over all tasks, we can calculate the error, the forwards transfer efficiency (FTE), the backwards transfer efficiency (BTE), and the overall transfer efficiency (TE). | err, bte, fte, te = fn.get_metrics(accuracy_all_task, num_tasks) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
These results are therefore plotted using the function as follows: | fn.plot_ftebte(num_tasks, err, bte, fte, te) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
As can be seen from above, there is generally positive forwards and backwards transfer efficiency when evaluating transfer across datasets, even though the datasets contained very different content. Varying the Number of TreesWe were also curious how changing the number of trees would affect the results of the FTE/BTE... | ##### MAIN HYPERPARAMS ##################
model = "odif"
num_tasks = 5
num_trees = 50
reps = 4
######################################### | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
Running the experiment, we find the following results: | accuracy_all_task = fn.ftebte_exp(
data, classes, model, num_tasks, num_trees, reps, shift=0
)
err, bte, fte, te = fn.get_metrics(accuracy_all_task, num_tasks)
fn.plot_ftebte(num_tasks, err, bte, fte, te) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
It seems as if more trees leads to lower transfer efficiency. We use `10` trees for the remainder of the experiments to save on computing power. Recruitment ExperimentNow that we have roughly assessed the performance of ODIF via the FTE/BTE experiment, we are also interested in which recruitment scheme works the best ... | ############################
### Main hyperparameters ###
############################
num_tasks = 5
num_trees = 10
reps = 4
estimation_set = 0.63 | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
Run Experiment and Plot ResultsWe call our experiment function and input the main hyperparameters: | # run recruitment experiment
means, stds, last_task_sample = fn.recruitment_exp(
data, classes, num_tasks, num_trees, reps, estimation_set, shift=0
) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
And then we plot the results: | # plot results
fn.recruitment_plot(means, stds, last_task_sample, num_tasks) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
We therefore see that though generalization error remains high on the final task, the lifelong learning algorithm still outperforms the other recruitment schemes overall. Shifting Dataset OrderSince the above experiment involves fixing DTD as the final dataset, a further experiment involves shifting the order of datas... | # run recruitment experiment
means, stds, last_task_sample = fn.recruitment_exp(
data, classes, num_tasks, num_trees, reps, estimation_set, shift=1
)
# plot results
fn.recruitment_plot(means, stds, last_task_sample, num_tasks) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
A `shift=2` results in a dataset order of:1. CIFAR-1002. Food-1013. DTD4. Caltech-1015. CIFAR-10 | # run recruitment experiment
means, stds, last_task_sample = fn.recruitment_exp(
data, classes, num_tasks, num_trees, reps, estimation_set, shift=2
)
# plot results
fn.recruitment_plot(means, stds, last_task_sample, num_tasks) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
`shift=3` gives us:1. Food-1012. DTD3. Caltech-1014. CIFAR-105. CIFAR-100 | # run recruitment experiment
means, stds, last_task_sample = fn.recruitment_exp(
data, classes, num_tasks, num_trees, reps, estimation_set, shift=3
)
# plot results
fn.recruitment_plot(means, stds, last_task_sample, num_tasks) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
And finally, `shift=4` yields:1. DTD2. Caltech-1013. CIFAR-104. CIFAR-1005. Food-101 | # run recruitment experiment
means, stds, last_task_sample = fn.recruitment_exp(
data, classes, num_tasks, num_trees, reps, estimation_set, shift=4
)
# plot results
fn.recruitment_plot(means, stds, last_task_sample, num_tasks) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
Throughout all the above experiments, even though generalization error remains high due to the sheer amount of different labels across all the different datsets, our lifelong learning algorithm still outperforms the other recruitment methods. Other Experiments Effect of NormalizationWhen examining data across differe... | # normalize across dataset
data1, classes1 = fn.import_data(normalize="dataset")
# normalize across each image
data2, classes2 = fn.import_data(normalize="image") | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
Define HyperparametersWe use the same parameters as before: | ##### MAIN HYPERPARAMS ##################
model = "odif"
num_tasks = 5
num_trees = 10
reps = 4
######################################### | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
Run Experiment and Plot ResultsWe first run the FTE/BTE experiment by normalizing across each dataset, such that the images in each dataset have a range of [0,1] in each channel. | accuracy_all_task = fn.ftebte_exp(
data1, classes1, model, num_tasks, num_trees, reps, shift=0
)
err, bte, fte, te = fn.get_metrics(accuracy_all_task, num_tasks)
fn.plot_ftebte(num_tasks, err, bte, fte, te) | _____no_output_____ | MIT | docs/experiments/recruitment_across_datasets.ipynb | AishwaryaSeth/ProgLearn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.