markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Now, a Spark dataframe 'nyvDF' will be created using SQL that will contain the restaurant name (FACILITY), latitude, longitude and violations. Note that the latitude and longitude are combined in the final column (Location1) of the retrieved data. They will be extracted separately using regular expressions in the SQL... | query = """
select
FACILITY,
trim(regexp_extract(location1, '(\\\()(.*),(.*)(\\\))',2)) as lat,
trim(regexp_extract(location1, '(\\\()(.*),(.*)(\\\))',3)) as lon,
cast(`TOTAL # CRITICAL VIOLATIONS` as int) as Violations
from nyrDF
order by Violations desc
limit 1000
"""
nyvDF = sqlContext.sql(query)... | New York Restaurants Demo.ipynb | sharynr/notebooks | apache-2.0 |
Brunel visualization will be used to map the latitude and longitude to a New York state map. Colors represent the number of violations as noted in the key. | import brunel
nyvPan = nyvDF.toPandas()
%brunel map ('NY') + data('nyvPan') x(lon) y(lat) color(Violations) tooltip(FACILITY) | New York Restaurants Demo.ipynb | sharynr/notebooks | apache-2.0 |
One of the many key strengths of Watson Studio is the ability to easily search and quickly learn about various topics. For example, to find articles, tutorials or notebooks on Brunel, click on the 'link' icon on the top right hand corner of this web page ('Find Resources in the Commuity'). A side palette will appear ... | from pixiedust.display import *
display(nyvDF) | New York Restaurants Demo.ipynb | sharynr/notebooks | apache-2.0 |
NOTE: Check the init function calls, in the above example. | class Parent:
def override(self):
print( "PARENT override()")
def implicit(self):
print ("PARENT implicit()")
def altered(self):
print ("PARENT altered()")
class Child(Parent):
def override(self):
print ("CHILD override()")
def altered(self):
p = super(C... | Section 1 - Core Python/Chapter 09 - Classes & OOPS/OOPs Fundamentals - Inheritance.ipynb | mayank-johri/LearnSeleniumUsingPython | gpl-3.0 |
The Reason for super()
This should seem like common sense, but then we get into trouble with a thing called multiple inheritance. Multiple inheritance is when you define a class that inherits from one or more classes, like this:
python
class SuperFun(Child, BadStuff):
pass
This is like saying, "Make a class named S... | class Child(Parent):
def __init__(self, stuff):
self.stuff = stuff
super(Child, self).__init__() | Section 1 - Core Python/Chapter 09 - Classes & OOPS/OOPs Fundamentals - Inheritance.ipynb | mayank-johri/LearnSeleniumUsingPython | gpl-3.0 |
Quiz Question. Among the words that appear in both Barack Obama and Francisco Barrio, take the 5 that appear most frequently in Obama. How many of the articles in the Wikipedia dataset contain all of those 5 words?
Hint:
* Refer to the previous paragraph for finding the words that appear in both articles. Sort the comm... | common_words = combined_words['word'][:5]
common_words = set(common_words)
def has_top_words(word_count_vector):
# extract the keys of word_count_vector and convert it to a set
unique_words = set(word_count_vector.keys())
print "length of unique words = " + str(len(unique_words))
# return True if ... | ml-clustering-and-retrieval/week-2/0_nearest-neighbors-features-and-metrics_blank.ipynb | zomansud/coursera | mit |
Quiz Question. Measure the pairwise distance between the Wikipedia pages of Barack Obama, George W. Bush, and Joe Biden. Which of the three pairs has the smallest distance?
Hint: To compute the Euclidean distance between two dictionaries, use graphlab.toolkits.distances.euclidean. Refer to this link for usage. | obama = wiki[wiki['name'] == 'Barack Obama']
bush = wiki[wiki['name'] == 'George W. Bush']
biden = wiki[wiki['name'] == 'Joe Biden']
isinstance(obama['word_count'][0], dict)
# pair-wise distances
obama_bush = graphlab.toolkits.distances.euclidean(obama['word_count'][0], bush['word_count'][0])
print "distance b/w obam... | ml-clustering-and-retrieval/week-2/0_nearest-neighbors-features-and-metrics_blank.ipynb | zomansud/coursera | mit |
Quiz Question. Collect all words that appear both in Barack Obama and George W. Bush pages. Out of those words, find the 10 words that show up most often in Obama's page. | bush_words = top_words('Francisco Barrio')
bush_words
new_combined_words = obama_words.join(bush_words, on='word')
new_combined_words
new_combined_words = new_combined_words.rename({'count':'Obama', 'count.1':'Bush'})
new_combined_words
new_combined_words.sort('Obama', ascending=False)
new_combined_words.print_rows(... | ml-clustering-and-retrieval/week-2/0_nearest-neighbors-features-and-metrics_blank.ipynb | zomansud/coursera | mit |
Using the join operation we learned earlier, try your hands at computing the common words shared by Obama's and Schiliro's articles. Sort the common words by their TF-IDF weights in Obama's document. | combined_words_tf_idf = obama_tf_idf.join(schiliro_tf_idf, on='word')
combined_words_tf_idf
combined_words_tf_idf = combined_words_tf_idf.rename({'weight': 'Obama', 'weight.1' : 'Schiliro'})
combined_words_tf_idf
combined_words_tf_idf.sort('Obama', ascending=False)
combined_words_tf_idf.print_rows(10) | ml-clustering-and-retrieval/week-2/0_nearest-neighbors-features-and-metrics_blank.ipynb | zomansud/coursera | mit |
The first 10 words should say: Obama, law, democratic, Senate, presidential, president, policy, states, office, 2011.
Quiz Question. Among the words that appear in both Barack Obama and Phil Schiliro, take the 5 that have largest weights in Obama. How many of the articles in the Wikipedia dataset contain all of those 5... | common_words = set(combined_words_tf_idf['word'][:5])
common_words
def has_top_words(word_count_vector):
# extract the keys of word_count_vector and convert it to a set
unique_words = set(word_count_vector.keys())
# return True if common_words is a subset of unique_words
# return False otherwise
... | ml-clustering-and-retrieval/week-2/0_nearest-neighbors-features-and-metrics_blank.ipynb | zomansud/coursera | mit |
Notice the huge difference in this calculation using TF-IDF scores instead of raw word counts. We've eliminated noise arising from extremely common words.
Choosing metrics
You may wonder why Joe Biden, Obama's running mate in two presidential elections, is missing from the query results of model_tf_idf. Let's find out... | obama = wiki[wiki['name'] == 'Barack Obama']
biden = wiki[wiki['name'] == 'Joe Biden']
obama_biden = graphlab.toolkits.distances.euclidean(obama['tf_idf'][0], biden['tf_idf'][0])
print "distance between obama and biden based on tf-idf = " + str(obama_biden) | ml-clustering-and-retrieval/week-2/0_nearest-neighbors-features-and-metrics_blank.ipynb | zomansud/coursera | mit |
Un détour par le Web : comment fonctionne un site ?
Même si nous n'allons pas aujourd'hui faire un cours de web, il vous faut néanmoins certaines bases pour comprendre comment un site internet fonctionne et comment sont structurées les informations sur une page.
Un site Web est un ensemble de pages codées en HTML qui p... | import urllib
import bs4
#help(bs4) | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
1ere page HTML
On va commencer facilement, prenons une page wikipedia, par exemple celle de la Ligue 1 de football : Championnat de France de football 2016-2017. On va souhaiter récupérer la liste des équipes, ainsi que les url des pages Wikipedia de ces équipes. | # Etape 1 : se connecter à la page wikipedia et obtenir le code source
url_ligue_1 = "https://fr.wikipedia.org/wiki/Championnat_de_France_de_football_2016-2017"
from urllib import request
request_text = request.urlopen(url_ligue_1).read()
print(request_text[:1000])
# Etape 2 : utiliser le package BeautifulS... | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
La methode .find ne renvoie que la première occurence de l'élément | print(page.find("table")) | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
Pour trouver toutes les occurences, on utilise .findAll(). | print("Il y a", len(page.findAll("table")), "éléments dans la page qui sont des <table>")
print(" Le 2eme tableau de la page : Hiérarchie \n", page.findAll("table")[1])
print("--------------------------------------------------------")
print("Le 3eme tableau de la page : Palmarès \n",page.findAll("table")[2]) | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
Exercice guidé : obtenir la liste des équipes de Ligue 1
La liste des équipes est dans le tableau "Participants" : dans le code source, on voit que ce tableau est celui qui a class="DebutCarte". On voit également que les balises qui encerclent les noms et les urls des clubs sont de la forme suivante
<a href="url_clu... | for item in page.find('table', {'class' : 'DebutCarte'}).findAll({'a'})[0:5] :
print(item, "\n-------") | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
On n'a pas envie de prendre le premier élément qui ne correspond pas à un club mais à une image.
Or cet élément est le seul qui n'ait pas de title="". Il est conseillé d'exclure les élements qui ne nous intéressent pas en indiquant les éléments que la ligne doit avoir au lieu de les exclure en fonction de leur place da... | ### condition sur la place dans la liste >>>> MAUVAIS
for e, item in enumerate(page.find('table', {'class' : 'DebutCarte'}).findAll({'a'})[0:5]) :
if e == 0:
pass
else :
print(item)
#### condition sur les éléments que doit avoir la ligne >>>> BIEN
for item in page.find('table', {'class' : ... | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
Enfin la dernière étape, consiste à obtenir les informations souhaitées, c'est à dire dans notre cas, le nom et l'url des 20 clubs. Pour cela, nous allons utiliser deux méthodes de l'élement item :
getText() qui permet d'obtenir le texte qui est sur la page web et dans la balise <a>
get('xxxx') qui permet d'obt... | for item in page.find('table', {'class' : 'DebutCarte'}).findAll({'a'})[0:5] :
if item.get("title") :
print(item.get("href"))
print(item.getText())
# pour avoir le nom officiel, on aurait utiliser l'élément <title>
for item in page.find('table', {'class' : 'DebutCarte'}).findAll({'a'})[0:5] :
... | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
Exercice de web scraping avec BeautifulSoup
Pour cet exercice, nous vous demandons d'obtenir 1) les informations personnelles des 721 pokemons sur le site internet pokemondb.net. Les informations que nous aimerions obtenir au final pour les pokemons sont celles contenues dans 4 tableaux :
Pokédex data
Training
Breedin... | # Si selenium n'est pas installé.
# !pip install selenium
import selenium #pip install selenium
# télécharger le chrome driver https://chromedriver.storage.googleapis.com/index.html?path=74.0.3729.6/
path_to_web_driver = "chromedriver"
import os, sys
from pyquickhelper.filehelper import download, unzip_files
version ... | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
On soumet la requête. | import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--verbose')
browser = webdriver.Chrome(executable_path=path_to_web_d... | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
On extrait les résultats. | from selenium.common.exceptions import StaleElementReferenceException
links = browser.find_elements_by_xpath("//div/a[@class='title'][@href]")
results = []
for link in links:
try:
url = link.get_attribute('href')
except StaleElementReferenceException as e:
print("Issue with '{0}' and '{1}'".for... | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
Obtenir des informations entre deux dates sur Google News
En réalité, l'exemple de Google News aurait pu se passer de Selenium et être utilisé directement avec BeautifulSoup et les url qu'on réussit à deviner de Google.
Ici, on utilise l'url de Google News pour créer une petite fonction qui donne pour chaque ensemble ... | import time
from selenium import webdriver
def get_news_specific_dates (beg_date, end_date, subject, hl="fr",
gl="fr", tbm="nws", authuser="0") :
'''
Permet d obtenir pour une requete donnée et un intervalle temporel
précis les 10 premiers résultats
d articles de presse p... | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
On appelle la fonction créée à l'instant. | browser = webdriver.Chrome(executable_path=path_to_web_driver,
options=chrome_options)
articles = get_news_specific_dates("3/15/2018", "3/31/2018", "alstom", hl="fr")
print(articles) | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
Utiliser selenium pour jouer à 2048
Dans cet exemple, on utilise le module pour que python appuie lui même sur les touches du clavier afin de jouer à 2048.
Note : ce bout de code ne donne pas une solution à 2048, il permet juste de voir ce qu'on peut faire avec selenium | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
# on ouvre la page internet du jeu 2048
browser = webdriver.Chrome(executable_path=path_to_web_driver,
options=chrome_options)
browser.get('https://gabrielecirulli.github.io/2048/')
# Ce qu'on va faire : une bou... | _doc/notebooks/td2a_eco/TD2A_Eco_Web_Scraping.ipynb | sdpython/ensae_teaching_cs | mit |
Search RNA Quantification Sets Method
This instance returns a list of RNA quantification sets in a dataset. RNA quantification sets are a way to associate a group of related RNA quantifications. Note that we use the dataset_id obtained from the 1kg_metadata_service notebook. | counter = 0
for rna_quant_set in c.search_rna_quantification_sets(dataset_id=dataset.id):
if counter > 5:
break
counter += 1
print(" id: {}".format(rna_quant_set.id))
print(" dataset_id: {}".format(rna_quant_set.dataset_id))
print(" name: {}\n".format(rna_quant_set.name)) | python_notebooks/1kg_rna_quantification_service.ipynb | david4096/bioapi-examples | apache-2.0 |
Get RNA Quantification Set by id method
This method obtains an single RNA quantification set by it's unique identifier. This id was chosen arbitrarily from the returned results. | single_rna_quant_set = c.get_rna_quantification_set(
rna_quantification_set_id=rna_quant_set.id)
print(" name: {}\n".format(single_rna_quant_set.name)) | python_notebooks/1kg_rna_quantification_service.ipynb | david4096/bioapi-examples | apache-2.0 |
Search RNA Quantifications
We can list all of the RNA quantifications in an RNA quantification set. The rna_quantification_set_id was chosen arbitrarily from the returned results. | counter = 0
for rna_quant in c.search_rna_quantifications(
rna_quantification_set_id=rna_quant_set.id):
if counter > 5:
break
counter += 1
print("RNA Quantification: {}".format(rna_quant.name))
print(" id: {}".format(rna_quant.id))
print(" description: {}\n".format(rna_quant.descript... | python_notebooks/1kg_rna_quantification_service.ipynb | david4096/bioapi-examples | apache-2.0 |
Get RNA Quantification by Id
Similar to RNA quantification sets, we can retrieve a single RNA quantification by specific id. This id was chosen arbitrarily from the returned results.
The RNA quantification reported contains details of the processing pipeline which include the source of the reads as well as the annotat... | single_rna_quant = c.get_rna_quantification(
rna_quantification_id=test_quant.id)
print(" name: {}".format(single_rna_quant.name))
print(" read_ids: {}".format(single_rna_quant.read_group_ids))
print(" annotations: {}\n".format(single_rna_quant.feature_set_ids)) | python_notebooks/1kg_rna_quantification_service.ipynb | david4096/bioapi-examples | apache-2.0 |
Search Expression Levels
The feature level expression data for each RNA quantification is reported as a set of Expression Levels. The rna_quantification_service makes it easy to search for these. | def getUnits(unitType):
units = ["", "FPKM", "TPM"]
return units[unitType]
counter = 0
for expression in c.search_expression_levels(
rna_quantification_id=test_quant.id):
if counter > 5:
break
counter += 1
print("Expression Level: {}".format(expression.name))
print(" id: {}".fo... | python_notebooks/1kg_rna_quantification_service.ipynb | david4096/bioapi-examples | apache-2.0 |
It is also possible to restrict the search to a specific feature or to request expression values exceeding a threshold amount. | counter = 0
for expression in c.search_expression_levels(
rna_quantification_id=test_quant.id, feature_ids=[]):
if counter > 5:
break
counter += 1
print("Expression Level: {}".format(expression.name))
print(" id: {}".format(expression.id))
print(" feature: {}\n".format(expression.fea... | python_notebooks/1kg_rna_quantification_service.ipynb | david4096/bioapi-examples | apache-2.0 |
Let's look for some high expressing features. | counter = 0
for expression in c.search_expression_levels(
rna_quantification_id=test_quant.id, threshold=1000):
if counter > 5:
break
counter += 1
print("Expression Level: {}".format(expression.name))
print(" id: {}".format(expression.id))
print(" expression: {} {}\n".format(expressi... | python_notebooks/1kg_rna_quantification_service.ipynb | david4096/bioapi-examples | apache-2.0 |
TODO: Implementing the basic functions
Here is your turn to shine. Implement the following formulas, as explained in the text.
- Sigmoid activation function
$$\sigma(x) = \frac{1}{1+e^{-x}}$$
Output (prediction) formula
$$\hat{y} = \sigma(w_1 x_1 + w_2 x_2 + b)$$
Error function
$$Error(y, \hat{y}) = - y \log(\hat{y... | # Implement the following functions
# Activation (sigmoid) function
def sigmoid(x):
pass
# Output (prediction) formula
def output_formula(features, weights, bias):
pass
# Error (log-loss) formula
def error_formula(y, output):
pass
# Gradient descent step
def update_weights(x, y, weights, bias, learnrate... | gradient-descent/GradientDescent.ipynb | samirma/deep-learning | mit |
Model summary
Run done with model with three convolutional layers, two fully connected layers and a final softmax layer, with a constant of 48 channels per convolutional layer. Initially run with dropout in two fully connected layers and minor random augmentation (4 rotations and flip), when learning appeared to stop t... | print('## Model structure summary\n')
print(model)
params = model.get_params()
n_params = {p.name : p.get_value().size for p in params}
total_params = sum(n_params.values())
print('\n## Number of parameters\n')
print(' ' + '\n '.join(['{0} : {1} ({2:.1f}%)'.format(k, v, 100.*v/total_params)
... | notebooks/model_modifications/Fewer convolutional channels with dropout experiment (large).ipynb | Neuroglycerin/neukrill-net-work | mit |
Train and valid set NLL trace
The discontinuity at just over 80 epoch is due to resuming without dropout and with more augmentation. | tr = np.array(model.monitor.channels['valid_y_y_1_nll'].time_record) / 3600.
fig = plt.figure(figsize=(12,8))
ax1 = fig.add_subplot(111)
ax1.plot(model.monitor.channels['valid_y_y_1_nll'].val_record)
ax1.plot(model.monitor.channels['train_y_y_1_nll'].val_record)
ax1.set_xlabel('Epochs')
ax1.legend(['Valid', 'Train'])
a... | notebooks/model_modifications/Fewer convolutional channels with dropout experiment (large).ipynb | Neuroglycerin/neukrill-net-work | mit |
To initialize a new class instance, we make use of the constructor method from_array(): | coeffs_l5m2 = SHCoeffs.from_array(coeffs) | examples/notebooks/tutorial_3.ipynb | MMesch/SHTOOLS | bsd-3-clause |
When initializing a new class instance, the default is to assume that the input coefficients are 4-pi normalized excluding the Condon-Shortley phase. This normalization convention can be overridden by setting the optional parameter 'normalization', which takes values of '4pi', 'ortho' or 'schmidt', along with the param... | fig, ax = coeffs_l5m2.plot_spectrum(xscale='log') | examples/notebooks/tutorial_3.ipynb | MMesch/SHTOOLS | bsd-3-clause |
To plot the function that corresponds to the coefficients, we first need to expand it on a grid, which can be accomplished using the expand() method: | grid_l5m2 = coeffs_l5m2.expand('DH2') | examples/notebooks/tutorial_3.ipynb | MMesch/SHTOOLS | bsd-3-clause |
This returns a new SHGrid class instance. The resolution of the grid is determined automatically to correspond to the maximum degree of the spherical harmonic coefficients in order to ensure good sampling. The optional parameter 'grid' can be 'DH2' for a Driscoll and Healy sampled grid with nlon = 2 * nlat, 'DH' for a ... | fig, ax = grid_l5m2.plot() | examples/notebooks/tutorial_3.ipynb | MMesch/SHTOOLS | bsd-3-clause |
Initialize with a random model
Another constructor for the SHCoeffs class is the from_random() method. It takes a power spectrum (power per degree l of the coefficients) and generates coefficients that are independent normal distributed random variables with the provided expected power spectrum. This corresponds to a s... | a = 10 # scale length
ls = np.arange(lmax+1, dtype=np.float)
power = 1. / (1. + (ls / a) ** 2) ** 0.5
coeffs_global = SHCoeffs.from_random(power)
fig, ax = coeffs_global.plot_spectrum(unit='per_dlogl', xscale='log')
fig, ax = coeffs_global.expand('DH2').plot() | examples/notebooks/tutorial_3.ipynb | MMesch/SHTOOLS | bsd-3-clause |
Rotating the coordinate system
Spherical harmonics coefficients can be expressed in a different coordinate system very efficiently. Importantly, the power per degree spectrum is invariant under rotation. We demonstrate this by rotating a zonal spherical harmonic (m=0) that is centered about the north-pole to the equato... | coeffs_l5m0 = SHCoeffs.from_zeros(lmax)
coeffs_l5m0.set_coeffs(1., 5, 0)
alpha = 0. # around z-axis
beta = 90. # around x-axis (lon=0)
gamma = 10. # around z-axis again
coeffs_l5m0_rot = coeffs_l5m0.rotate(alpha, beta, gamma, degrees=True)
fig, ax = coeffs_l5m0_rot.plot_spectrum(xscale='log', show=False)
ax.set(y... | examples/notebooks/tutorial_3.ipynb | MMesch/SHTOOLS | bsd-3-clause |
Addition, multiplication, and subtraction
Similar grids can be added, multiplied and subtracted using standard python operators. It is easily verified that the following sequence of operations return the same rotated grid as above: | grid_new = (2 * grid_l5m0_rot + grid_l5m2**2 - grid_l5m2 * grid_l5m2) / 2.0
grid_new.plot()
coeffs = grid_new.expand()
fig, ax = coeffs.plot_spectrum() | examples/notebooks/tutorial_3.ipynb | MMesch/SHTOOLS | bsd-3-clause |
Jak wygrać konkursy 2
1. Bagging - Uzupełnienie
Ważenie podczas głosowania/uśredniania
W Bagging, losujemy $m$ przykładów z powtorzeniami.
Prawie 40% danych nie jest wykorzystywanych, ponieważ $\lim_{n \rightarrow \infty}\left(1-\frac{1}{n}\right)^n = e^{-1} \approx 0.368 $.
Możemy te dany wykorzystać jako zestaw wali... | def runningMeanFast(x, N):
return np.convolve(x, np.ones((N,))/N, mode='valid')
def powerme(x1,x2,n):
X = []
for m in range(n+1):
for i in range(m+1):
X.append(np.multiply(np.power(x1,i),np.power(x2,(m-i))))
return np.hstack(X)
def safeSigmoid(x, eps=0):
y = 1.0/(1.0 + np.exp(-... | Wyklady/08/Konkursy2.ipynb | emjotde/UMZ | cc0-1.0 |
이진 분류 결과표 Binary Confusion Matrix
클래스가 0과 1 두 종류 밖에 없는 경우에는 일반적으로 클래스 이름을 "Positive"와 "Negative"로 표시한다.
또, 분류 모형의 예측 결과가 맞은 경우, 즉 Positive를 Positive라고 예측하거나 Negative를 Negative라고 예측한 경우에는 "True"라고 하고 예측 결과가 틀린 경우, 즉 Positive를 Negative라고 예측하거나 Negative를 Positive라고 예측한 경우에는 "False"라고 한다.
이 경우의 이진 분류 결과의 명칭과 결과표는 다음과 같다. ... | from sklearn.metrics import classification_report
y_true = [0, 1, 2, 2, 2]
y_pred = [0, 0, 2, 2, 1]
target_names = ['class 0', 'class 1', 'class 2']
print(classification_report(y_true, y_pred, target_names=target_names))
y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
y_pred = ["ant", "ant", "cat", "cat", "ant",... | 18. 분류의 기초/04. 분류(classification) 성능 평가.ipynb | zzsza/Datascience_School | mit |
Intermediate Python - List Comprehension
In this Colab, we will discuss list comprehension, an extremely useful and idiomatic way to process lists in Python.
List Comprehension
List comprehension is a compact way to create a list of data. Say you want to create a list containing ten random numbers. One way to do this i... | import random
[
random.randint(0, 100),
random.randint(0, 100),
random.randint(0, 100),
random.randint(0, 100),
random.randint(0, 100),
random.randint(0, 100),
random.randint(0, 100),
random.randint(0, 100),
random.randint(0, 100),
random.randint(0, 100),
] | content/00_prerequisites/01_intermediate_python/03-list-comprehension.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
Note: In the code above, we've introduced the random module. random is a Python package that comes as part of the standard Python distribution. To use Python packages we rely on the import keyword.
That's pretty intensive, and requires a bit of copy-paste work. We could clean it up with a for loop: | import random
my_list = []
for _ in range(10):
my_list.append(random.randint(0, 100))
my_list | content/00_prerequisites/01_intermediate_python/03-list-comprehension.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
This looks much nicer. Less repetition is always a good thing.
Note: Did you notice the use of the underscore to consume the value returned from range? You can use this when you don't actually need the range value, and it saves Python from assigning it to memory.
There is an even more idiomatic way of creating this l... | import random
my_list = [random.randint(0, 100) for _ in range(10)]
my_list | content/00_prerequisites/01_intermediate_python/03-list-comprehension.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
Let's start by looking at the "for _ in range()" part. This looks like the for loop that we are familiar with. In this case, it is a loop over the range from zero through nine.
The strange part is the for doesn't start the expression. We are used to seeing a for loop with a body of statements indented below it. In this... | [x for x in range(10) if x % 2 == 0] | content/00_prerequisites/01_intermediate_python/03-list-comprehension.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
You can add multiple if statements by using boolean operators. | print([x for x in range(10) if x % 2 == 0 and x % 3 == 0])
print([x for x in range(10) if x % 2 == 0 or x % 3 == 0]) | content/00_prerequisites/01_intermediate_python/03-list-comprehension.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
You can even have multiple loops chained in a single list comprehension. The left-most loop is the outer loop and the subsequent loops are nested within. However, when cases become sufficiently complicated, we recommend using standard loop notation, to enhance code readability. | [(x, y) for x in range(5) for y in range(3)] | content/00_prerequisites/01_intermediate_python/03-list-comprehension.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
Exercises
Exercise 1
Create a list expansion that builds a list of numbers between 5 and 67 (inclusive) that are divisible by 7 but not divisible by 3.
Student Solution | ### YOUR CODE HERE ### | content/00_prerequisites/01_intermediate_python/03-list-comprehension.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
Exercise 2
Use list comprehension to find the lengths of all the words in the following sentence.
Student Solution | sentence = "I love list comprehension so much it makes me want to cry"
words = sentence.split()
print(words)
### YOUR CODE GOES HERE ### | content/00_prerequisites/01_intermediate_python/03-list-comprehension.ipynb | google/applied-machine-learning-intensive | apache-2.0 |
Initial set-up
Load experiments used for unified dataset calibration:
- Steady-state activation [Wang1993]
- Activation time constant [Courtemanche1998]
- Deactivation time constant [Courtemanche1998]
- Steady-state inactivation [Wang1993]
- Inactivation time constant [Courtemanche1998]
- Recovery time constant [... | from experiments.ito_wang import wang_act, wang_inact
from experiments.ito_courtemanche import courtemanche_kin, courtemanche_rec, courtemanche_deact
modelfile = 'models/nygren_ito.mmt' | docs/examples/human-atrial/nygren_ito_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Combine model and experiments to produce:
- observations dataframe
- model function to run experiments and return traces
- summary statistics function to accept traces | observations, model, summary_statistics = setup(modelfile,
wang_act,
wang_inact,
courtemanche_kin,
courtemanche_deact,
... | docs/examples/human-atrial/nygren_ito_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Run ABC-SMC inference
Set-up path to results database. | db_path = ("sqlite:///" + os.path.join(tempfile.gettempdir(), "nygren_ito_unified.db"))
logging.basicConfig()
abc_logger = logging.getLogger('ABC')
abc_logger.setLevel(logging.DEBUG)
eps_logger = logging.getLogger('Epsilon')
eps_logger.setLevel(logging.DEBUG) | docs/examples/human-atrial/nygren_ito_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Analysis of results | history = History('sqlite:///results/nygren/ito/unified/nygren_ito_unified.db')
df, w = history.get_distribution()
df.describe() | docs/examples/human-atrial/nygren_ito_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Plot summary statistics compared to calibrated model output. | sns.set_context('poster')
mpl.rcParams['font.size'] = 14
mpl.rcParams['legend.fontsize'] = 14
g = plot_sim_results(modelfile,
wang_act,
wang_inact,
courtemanche_kin,
courtemanche_deact,
courtemanche_rec,
... | docs/examples/human-atrial/nygren_ito_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Plot gating functions | import pandas as pd
N = 100
nyg_par_samples = df.sample(n=N, weights=w, replace=True)
nyg_par_samples = nyg_par_samples.set_index([pd.Index(range(N))])
nyg_par_samples = nyg_par_samples.to_dict(orient='records')
sns.set_context('talk')
mpl.rcParams['font.size'] = 14
mpl.rcParams['legend.fontsize'] = 14
f, ax = plot_v... | docs/examples/human-atrial/nygren_ito_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
Plot parameter posteriors | from ionchannelABC.visualization import plot_kde_matrix_custom
import myokit
import numpy as np
m,_,_ = myokit.load(modelfile)
originals = {}
for name in limits.keys():
if name.startswith("log"):
name_ = name[4:]
else:
name_ = name
val = m.value(name_)
if name.startswith("log"):
... | docs/examples/human-atrial/nygren_ito_unified.ipynb | c22n/ion-channel-ABC | gpl-3.0 |
1) First example | x,y = sp.symbols('x,y')
f = x**2 + y**2
gs = [x+y>=4, x+y<=4]
print_problem(f, gs)
sol = mp.solvers.solve_GMP(f, gs)
mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 1) | polynomial_optimization.ipynb | sidaw/mompy | mit |
2) Unconstrained optimization: the six hump camel back function
A plot of this function can be found at library of simutations. MATLAB got the solution $x^ = [0.0898 -0.7127]$ and corresponding optimal values of $f(x^) = -1.0316$ | x1,x2 = sp.symbols('x1:3')
f = 4*x1**2+x1*x2-4*x2**2-2.1*x1**4+4*x2**4+x1**6/3
print_problem(f)
sol = mp.solvers.solve_GMP(f, rounds=1)
mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 2)
| polynomial_optimization.ipynb | sidaw/mompy | mit |
3) Multiple rounds
Generally more rounds are needed to get the correct solutions. | x1,x2,x3 = sp.symbols('x1:4')
f = -(x1 - 1)**2 - (x1 - x2)**2 - (x2 - 3)**2
gs = [1 - (x1 - 1)**2 >= 0, 1 - (x1 - x2)**2 >= 0, 1 - (x2 - 3)**2 >= 0]
print_problem(f, gs)
sol = mp.solvers.solve_GMP(f, gs, rounds=4)
mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 3) | polynomial_optimization.ipynb | sidaw/mompy | mit |
Yet another example | x1,x2,x3 = sp.symbols('x1:4')
f = -2*x1 + x2 - x3
gs = [0<=x1, x1<=2, x2>=0, x3>=0, x3<=3, x1+x2+x3<=4, 3*x2+x3<=6,\
24-20*x1+9*x2-13*x3+4*x1**2 - 4*x1*x2+4*x1*x3+2*x2**2-2*x2*x3+2*x3**2>=0]; hs = [];
print_problem(f, gs)
sol = mp.solvers.solve_GMP(f, gs, hs, rounds=4)
print mp.extractors.extract_solutions_lasser... | polynomial_optimization.ipynb | sidaw/mompy | mit |
4) Motzkin polynomial
The Motzkin polynomial is non-negative, but cannot be expressed in sum of squares. It attains global minimum of 0 at $|x_1| = |x_2| = \sqrt{3}/3$ (4 points). The first few relaxations are unbounded and might take a while for cvxopt to realize this. | x1,x2 = sp.symbols('x1:3')
f = x1**2 * x2**2 * (x1**2 + x2**2 - 1) + 1./27
print_problem(f)
sol = mp.solvers.solve_GMP(f, rounds=7)
print mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 4, maxdeg=3) | polynomial_optimization.ipynb | sidaw/mompy | mit |
Generalized Moment Problem (GMP)
The GMP is to
$
\begin{align}
\text{minimize} \quad &f(x)\
\text{subject to} \quad &g_i(x) \geq 0,\quad i=1,\ldots,N\
\quad &\mathcal{L}(h_j(x)) \geq 0,\quad j=1,\ldots,M
\end{align}
$
where $x \in \Re^d$ and $f(x), g_i(x), h_j(x) \in \Re[x]$ are polynomials, and $\mathcal{L}(\c... | beta = sp.symbols('beta')
beta0 = [1,2]; pi0 = [0.5,0.5]
hs = [beta**m - (pi0[0]*beta0[0]**m+pi0[1]*beta0[1]**m) for m in range(1,5)]
f = sum([beta**(2*i) for i in range(3)])
# note that hs are the LHS of h==0, whereas gs are sympy inequalities
print_problem(f, None, hs)
sol = mp.solvers.solve_GMP(f, None, hs)
print m... | polynomial_optimization.ipynb | sidaw/mompy | mit |
Now we try to solve the problem with insufficient moment conditions, but extra constraints on the parameters themselves. | gs=[beta>=1]
f = sum([beta**(2*i) for i in range(3)])
hs_sub = hs[0:2]
print_problem(f, gs, hs_sub)
sol = mp.solvers.solve_GMP(f, gs, hs_sub)
print mp.extractors.extract_solutions_lasserre(sol['MM'], sol['x'], 2, tol = 1e-3) | polynomial_optimization.ipynb | sidaw/mompy | mit |
Plotting an ROC curve with an 1-D np.ndarray input | plot_curve(y, x1, kind="roc") | examples/plot_curve_examples.ipynb | jeongyoonlee/Kaggler | mit |
Plotting an ROC curve with two 1-D np.ndarray inputs | plot_curve(y, [x1, x2], name=["x1", "x2"], kind="roc") | examples/plot_curve_examples.ipynb | jeongyoonlee/Kaggler | mit |
Plotting an ROC curve with pd.DataFrame | plot_curve(y, df[["x1", "x2"]], kind="roc") | examples/plot_curve_examples.ipynb | jeongyoonlee/Kaggler | mit |
Plotting an PR curve with pd.DataFrame | plot_curve(y, df[["x1", "x2"]], kind="pr") | examples/plot_curve_examples.ipynb | jeongyoonlee/Kaggler | mit |
Reading Metadata from An archive | import tarfile
with tarfile.open('example.tar', 'r') as t:
print(t.getnames())
import tarfile
import time
with tarfile.open('example.tar', 'r') as t:
for member_info in t.getmembers():
print(member_info.name)
print(' Modified:', time.ctime(member_info.mtime))
print(' Mode :', oct(... | DataCompression/tarfile.ipynb | gaufung/PythonStandardLibrary | mit |
Creating New Archive | import tarfile
print('creating archive')
with tarfile.open('tarfile_add.tar', mode='w') as out:
print('add zlib_server.py')
out.add('zlib_server.py')
print()
print('Contents:')
with tarfile.open('tarfile_add.tar', mode='r') as t:
for member_info in t.getmembers():
print(member_info.name) | DataCompression/tarfile.ipynb | gaufung/PythonStandardLibrary | mit |
Appending to Archives | import tarfile
print('creating archive')
with tarfile.open('tarfile_append.tar', mode='w') as out:
out.add('gzip.ipynb')
print('contents:',)
with tarfile.open('tarfile_append.tar', mode='r') as t:
print([m.name for m in t.getmembers()])
print('adding index.rst')
with tarfile.open('tarfile_append.tar', mode='... | DataCompression/tarfile.ipynb | gaufung/PythonStandardLibrary | mit |
We expect X to have 100 rows (data samples) and two columns (features), whereas the
vector y should have a single column that contains all the target labels: | X.shape, y.shape | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Visualizing the dataset
We can plot these data points in a scatter plot using Matplotlib. Here, the idea is to plot the
$x$ values (found in the first column of X, X[:, 0]) against the $y$ values (found in the second
column of X, X[:, 1]). A neat trick is to pass the target labels as color values (c=y): | import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.set_cmap('jet')
%matplotlib inline
plt.figure(figsize=(10, 6))
plt.scatter(X[:, 0], X[:, 1], c=y, s=100)
plt.xlabel('x values')
plt.ylabel('y values') | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
You can see that, for the most part, data points of the two classes are clearly separated.
However, there are a few regions (particularly near the left and bottom of the plot) where
the data points of both classes intermingle. These will be hard to classify correctly, as we
will see in just a second.
Preprocessing the ... | import numpy as np
X = X.astype(np.float32)
y = y * 2 - 1 | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Now we can pass the data to scikit-learn's train_test_split function, like we did in the
earlier chapters: | from sklearn import model_selection as ms
X_train, X_test, y_train, y_test = ms.train_test_split(
X, y, test_size=0.2, random_state=42
) | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Here I chose to reserve 20 percent of all data points for the test set, but you can adjust this
number according to your liking.
Building the support vector machine
In OpenCV, SVMs are built, trained, and scored the same exact way as every other learning
algorithm we have encountered so far, using the following steps.
... | import cv2
svm = cv2.ml.SVM_create() | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
As shown in the following command, there are different modes in which we can
operate an SVM. For now, all we care about is the case we discussed in the
previous example: an SVM that tries to partition the data with a straight line. This
can be specified with the setKernel method: | svm.setKernel(cv2.ml.SVM_LINEAR) | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Call the classifier's train method to find the optimal decision boundary: | svm.train(X_train, cv2.ml.ROW_SAMPLE, y_train); | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Call the classifier's predict method to predict the target labels of all data
samples in the test set: | _, y_pred = svm.predict(X_test) | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Use scikit-learn's metrics module to score the classifier: | from sklearn import metrics
metrics.accuracy_score(y_test, y_pred) | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Congratulations, we got 80 percent correctly classified test samples!
Of course, so far we have no idea what happened under the hood. For all we know, we
might as well have gotten these commands off a web search and typed them into the
terminal, without really knowing what we're doing. But this is not who we want to be... | def plot_decision_boundary(svm, X_test, y_test):
# create a mesh to plot in
h = 0.02 # step size in mesh
x_min, x_max = X_test[:, 0].min() - 1, X_test[:, 0].max() + 1
y_min, y_max = X_test[:, 1].min() - 1, X_test[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
... | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Now we get a better sense of what is going on!
The SVM found a straight line (a linear decision boundary) that best separates the blue and
the red data samples. It didn't get all the data points right, as there are three blue dots in the
red zone and one red dot in the blue zone.
However, we can convince ourselves that... | kernels = [cv2.ml.SVM_LINEAR, cv2.ml.SVM_INTER, cv2.ml.SVM_SIGMOID, cv2.ml.SVM_RBF] | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Do you remember what all of these stand for?
Setting a different SVM kernel is relatively simple. We take an entry from the kernels list
and pass it to the setKernels method of the SVM class. That's all.
The laziest way to repeat things is to use a for loop: | plt.figure(figsize=(14, 8))
for idx, kernel in enumerate(kernels):
svm = cv2.ml.SVM_create()
svm.setKernel(kernel)
svm.train(X_train, cv2.ml.ROW_SAMPLE, y_train)
_, y_pred = svm.predict(X_test)
plt.subplot(2, 2, idx + 1)
plot_decision_boundary(svm, X_test, y_test)
plt.title('accuracy = ... | notebooks/06.01-Implementing-Your-First-Support-Vector-Machine.ipynb | mbeyeler/opencv-machine-learning | mit |
Pandas is also provides a very easy and fast API to read stock data from various finance data providers. | from pandas_datareader import data, wb # pandas data READ API
import datetime
googPrices = data.get_data_yahoo("GOOG", start=datetime.datetime(2014, 5, 1),
end=datetime.datetime(2014, 5, 7))
googFinalPrices=pd.DataFrame(googPrices['Close'], index=tradeDates)
googFinalPrices | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
We now have a time series that depicts the closing price of Google's stock from May 1, 2014 to May 7, 2014 with gaps in the date range since the trading only occur on business days. If we want to change the date range so that it shows calendar days (that is, along with the weekend), we can change the frequency of the t... | googClosingPricesCDays = googClosingPrices.asfreq('D')
googClosingPricesCDays | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
Note that we have now introduced NaN values for the closingPrice for the weekend dates of May 3, 2014 and May 4, 2014.
We can check which values are missing by using the isnull() and notnull() functions as follows: | googClosingPricesCDays.isnull()
googClosingPricesCDays.notnull() | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
A Boolean DataFrame is returned in each case. In datetime and pandas Timestamps, missing values are represented by the NaT value. This is the equivalent of NaN in pandas for time-based types | tDates=tradeDates.copy()
tDates[1]=np.NaN
tDates[4]=np.NaN
tDates
FBVolume=[82.34,54.11,45.99,55.86,78.5]
TWTRVolume=[15.74,12.71,10.39,134.62,68.84]
socialTradingVolume=pd.concat([pd.Series(FBVolume), pd.Series(TWTRVolume),
tradeDates], axis=1,keys=['FB','TWTR','TradeDate'])
socialTradi... | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
We can perform arithmetic operations on data containing missing values. For example, we can calculate the total trading volume (in millions of shares) across the two stocks for Facebook and Twitter as follows: | socialTradingVolTSCal['FB']+socialTradingVolTSCal['TWTR'] | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
By default, any operation performed on an object that contains missing values will return a missing value at that position as shown in the following command: | pd.Series([1.0,np.NaN,5.9,6])+pd.Series([3,5,2,5.6])
pd.Series([1.0,25.0,5.5,6])/pd.Series([3,np.NaN,2,5.6]) | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
There is a difference, however, in the way NumPy treats aggregate calculations versus what pandas does.
In pandas, the default is to treat the missing value as 0 and do the aggregate calculation, whereas for NumPy, NaN is returned if any of the values are missing. Here is an illustration: | np.mean([1.0,np.NaN,5.9,6])
np.sum([1.0,np.NaN,5.9,6]) | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
However, if this data is in a pandas Series, we will get the following output: | pd.Series([1.0,np.NaN,5.9,6]).sum()
pd.Series([1.0,np.NaN,5.9,6]).mean() | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
It is important to be aware of this difference in behavior between pandas and NumPy. However, if we wish to get NumPy to behave the same way as pandas, we can use the np.nanmean and np.nansum functions, which are illustrated as follows: | np.nanmean([1.0,np.NaN,5.9,6])
np.nansum([1.0,np.NaN,5.9,6]) | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
Handling Missing Values
There are various ways to handle missing values, which are as follows:
1. By using the fillna() function to fill in the NA values: | socialTradingVolTSCal
socialTradingVolTSCal.fillna(100) | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
We can also fill forward or backward values using the ffill() or bfill() arguments: | socialTradingVolTSCal.fillna(method='ffill')
socialTradingVolTSCal.fillna(method='bfill') | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
2. By using the dropna() function to drop/delete rows and columns with missing values. | socialTradingVolTSCal.dropna() | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
3. We can also interpolate and fill in the missing values by using the interpolate() function | pd.set_option('display.precision',4)
socialTradingVolTSCal.interpolate() | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
The interpolate() function also takes an argument—method that denotes the method. These methods include linear, quadratic, cubic spline, and so on.
Plotting using matplotlib
The matplotlib api is imported using the standard convention, as shown in the following command: import matplotlib.pyplot as plt
Series and DataFr... | X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
f,g = np.cos(X)+np.sin(X), np.sin(X)-np.cos(X)
f_ser=pd.Series(f)
g_ser=pd.Series(g)
plotDF=pd.concat([f_ser,g_ser],axis=1)
plotDF.index=X
plotDF.columns=['sin(x)+cos(x)','sin(x)-cos(x)']
plotDF.head()
plotDF.columns=['f(x)','g(x)']
plotDF.plot(title='Plot of f(x)=si... | _oldnotebooks/Introduction_to_Pandas-4.ipynb | eneskemalergin/OldBlog | mit |
Introduction
Are you a machine learning engineer looking to use Keras
to ship deep-learning powered features in real products? This guide will serve
as your first introduction to core Keras API concepts.
In this guide, you will learn how to:
Prepare your data before training a model (by turning it into either NumPy
a... | from tensorflow.keras.layers import TextVectorization
# Example training data, of dtype `string`.
training_data = np.array([["This is the 1st sample."], ["And here's the 2nd sample."]])
# Create a TextVectorization layer instance. It can be configured to either
# return integer token indices, or a dense token represe... | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Example: turning strings into sequences of one-hot encoded bigrams | from tensorflow.keras.layers import TextVectorization
# Example training data, of dtype `string`.
training_data = np.array([["This is the 1st sample."], ["And here's the 2nd sample."]])
# Create a TextVectorization layer instance. It can be configured to either
# return integer token indices, or a dense token represe... | guides/ipynb/intro_to_keras_for_engineers.ipynb | keras-team/keras-io | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.