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 |
|---|---|---|---|---|---|
This dataframe contains: - **independent variables** : filter observations - **dependent variables** : physical planet parameters | data= pk.load(open('wfirst_colors_dataframe.pk','rb'))
data=data.dropna()[~data.dropna().isin([np.inf, -np.inf])].dropna() #drop infinities and nans
#let's specicy our y of interest for this tutorial, feel free to play around with this
yofinterest = 'metallicity'
#lets also specify a filter set. Let's just focus on WFI... | _____no_output_____ | MIT | notebooks/4_StatsMethods.ipynb | natashabatalha/colorcolor |
Explore Correlation Matrix: Fig 6 Batalha+2018In figure 6 we looked at the difference between the correlation matrix with and without the cloud sample | #lets look at only the cloud free sample
corr_matrix = data.loc[(data['cloud']==0)].corr()
fig, ax = plt.subplots(figsize=(25,10))
#here I am simplifying the image by adding in an absolute value
#you can remove it if you are interested in seeing what is positive and nagatively correlated
sns.heatmap(abs(corr_matrix),... | _____no_output_____ | MIT | notebooks/4_StatsMethods.ipynb | natashabatalha/colorcolor |
Figure 6 in Batalha 2018 is a subset of this larger block | #lets look at everything
corr_matrix = data.corr()
fig, ax = plt.subplots(figsize=(25,10))
#here I am simplifying the image by adding in an absolute value
#you can remove it if you are interested in seeing what is positive and nagatively correlated
sns.heatmap(abs(corr_matrix), vmax=1, square=False, linewidths=.5, ax... | _____no_output_____ | MIT | notebooks/4_StatsMethods.ipynb | natashabatalha/colorcolor |
** See immediately how there are less strongly correlated values for physical parameters versus filters??** Try Linear Discriminant Analysis For Classification | #try cloud free first
subset = data.loc[(data['cloud']==0) & (data['phase']==90)]
#separate independent
X = subset.loc[:,filter_combinations]
#and dependent variables (also this make it a string so we can turn it into a label)
y = subset[yofinterest].astype(str)
lda_values=stats.lda_analysis(X,y) | _____no_output_____ | MIT | notebooks/4_StatsMethods.ipynb | natashabatalha/colorcolor |
These warnings are coming up because we have used both absolute and relative filters. Because LDA, like regression techniques involves computing a matrix inversion, which is inaccurate if the determinant is close to 0 (i.e. two or more variables are almost a linear combination of each other). This means that our relati... | #Now lets unconstrain the phase
subset = data.loc[(data['cloud']==0)]
#separate independent
X = subset.loc[:,filter_combinations]
#and dependent variables (also this make it a string so we can turn it into a label)
y = subset[yofinterest].astype(str)
lda_values=stats.lda_analysis(X,y)
#Now lets unconstrain everythi... | _____no_output_____ | MIT | notebooks/4_StatsMethods.ipynb | natashabatalha/colorcolor |
Preparação bases de treinamento e testes | clean_df = pd.DataFrame(columns=df.columns, index=df.index)
residual_df = pd.DataFrame(columns=df.columns, index=df.index)
for col in df.columns:
residual, clean = remove_periodic(df[col].tolist(), df.index, frequency_threshold=0.01e12)
clean_df[col] = clean.tolist()
residual_df[col] = residual.tolist()
tr... | _____no_output_____ | MIT | notebooks/180425 - Oahu Mean Shift.ipynb | cseveriano/spatio-temporal-forecasting |
Mean Shift Normalização dos dados | from sklearn import preprocessing
x = ms_df.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
bandwidth
bandwidth = estimate_bandwidth(x_scaled, quantile=0.2, n_samples=int(len(ms_df)*0.1), n_jobs=-1)
ms = MeanShift(bandwidth=bandwidth, n_jobs=-1)
ms... | _____no_output_____ | MIT | notebooks/180425 - Oahu Mean Shift.ipynb | cseveriano/spatio-temporal-forecasting |
loading an image | from PIL import Image
im = Image.open("lena.png") | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
examine the file contents | from __future__ import print_function
print(im.format, im.size, im.mode) | PNG (512, 512) RGB
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- The *format* attribute identifies the source of an image. If the image was not read from a file, it is set to None. - The *size* attribute is a 2-tuple containing width and height (in pixels). - The *mode* attribute defines the number and names of the bands in the image, let’s display the image we just loaded | im.show() | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- The standard version of show() is not very efficient, since it saves the image to a temporary file and calls the xv utility to display the image. If you don’t have xv installed, it won’t even work. When it does work though, it is very handy for debugging and tests. Reading and writing images - Python Imaging Library... | ## ------------ignore--------------
from __future__ import print_function
import os, sys
from PIL import Image
for infile in sys.argv[1:]:
f, e = os.path.splitext(infile)
outfile = f + ".jpg"
if infile != outfile:
try:
Image.open(infile).save(outfile)
except IOError:
... | .ipynb_checkpoints
.ipynb_checkpoints.jpg
cannot convert .ipynb_checkpoints
lena
.jpg
lena.jpg
lena
.png
lena.jpg
converted lena.png to lena.jpg
Python Imaging Library
.ipynb
Python Imaging Library.jpg
cannot convert Python Imaging Library.ipynb
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Create JPEG thumbnails | from __future__ import print_function
import os, sys
from PIL import Image
size = (128, 128)
for infile in os.listdir(os.getcwd()):
outfile = os.path.splitext(infile)[0] + ".thumbnail"
print(infile, outfile)
if infile != outfile:
try:
im = Image.open(infile)
im.thumbnail(si... | ('how/are/you/a', '.png')
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- It is important to note that the library doesn’t decode or load the raster data unless it really has to. When you open a file, the file header is read to determine the file format and extract things like mode, size, and other properties required to decode the file, but the rest of the file is not processed until late... | from __future__ import print_function
import sys
from PIL import Image
for infile in os.listdir(os.getcwd()):
#print(infile)
try:
with Image.open(infile) as im:
print(infile, im.format, "%dx%d" % im.size, im.mode)
print(type(im.size))
except IOError:
pass | lena.jpg JPEG 512x512 RGB
<class 'tuple'>
lena.png PNG 512x512 RGB
<class 'tuple'>
lena.thumbnail JPEG 128x128 RGB
<class 'tuple'>
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Cutting, pasting, and merging images - The Image class contains methods allowing you to manipulate regions within an image. To extract a sub-rectangle from an image, use the crop() method. Copying a subrectangle from an image | im = Image.open("lena.png")
box = (100, 100, 400, 400)
region = im.crop(box) | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- The region could now be processed in a certain manner and pasted back. Processing a subrectangle, and pasting it back | region = region.transpose(Image.ROTATE_180)
im.paste(region, box)
im.show()
im.save('pasted.png') | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Rolling an image | def roll(image, delta):
"Roll an image sideways"
xsize, ysize = image.size #width and height
delta = delta % xsize
if delta == 0: return image
part1 = image.crop((0, 0, delta, ysize))
part2 = image.crop((delta, 0, xsize, ysize))
image.paste(part2, (0, 0, xsize-delta, ysize))
image.pas... | (512, 512)
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Splitting and merging bands | im = Image.open("lena.png")
r, g, b = im.split()
im1 = Image.merge("RGB", (b, g, r))
im2 = Image.merge("RGB", (r, r, r))
im3 = Image.merge("RGB", (g, g, g))
im4 = Image.merge("RGB", (b, b, b))
im5 = Image.merge("RGB", (g, r, b))
print(im1.mode)
#im1.show()
#im2.show()
#im3.show()
#im4.show()
im5.show() | RGB
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- Note that for a single-band image, split() returns the image itself. To work with individual color bands, you may want to convert the image to “RGB” first. Geometrical transforms - The PIL.Image.Image class contains methods to resize() and rotate() an image. The former takes a tuple giving the new size, the latter t... | im = Image.open("lena.png")
out = im.resize((128, 128))
out.show()
out = im.rotate(45) # degrees counter-clockwise
out.show()
out.save('rotated.png') | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- To rotate the image in 90 degree steps, you can either use the rotate() method or the transpose() method. The latter can also be used to flip an image around its horizontal or vertical axis. Transposing an image | out = im.transpose(Image.FLIP_LEFT_RIGHT)
out.save('transposing/l2r.png')
out = im.transpose(Image.FLIP_TOP_BOTTOM)
out.save('transposing/t2b.png')
out = im.transpose(Image.ROTATE_90)
out.save('transposing/90degree.png')
out = im.transpose(Image.ROTATE_180)
out.save('transposing/180degree.png')
out = im.transpose(Image... | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- There’s no difference in performance or result between **transpose(ROTATE)** and corresponding **rotate()** operations. - A more general form of image transformations can be carried out via the transform() method. Color transforms - The Python Imaging Library allows you to convert images between different pixel repr... | im = Image.open("lena.png").convert("L")
im.show() | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- The library supports transformations between each supported mode and the “L” and “RGB” modes. To convert between other modes, you may have to use an intermediate image (typically an “RGB” image). Image enhancement Applying filters - The **ImageFilter** module contains a number of pre-defined enhancement filters tha... | # multiply each pixel by 1.2
im = Image.open("lena.png")
im.save('point/orig.png')
out = im.point(lambda i: i * 1.2)
out.save('point/out.png') | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- Using the above technique, you can quickly apply any simple expression to an image. You can also combine the point() and paste() methods to selectively modify an image: Processing individual bands | im = Image.open("lena.png")
# split the image into individual bands
source = im.split()
R, G, B = 0, 1, 2
# select regions where red is less than 100
mask = source[R].point(lambda i: i < 100 and 255) # if i < 100 returns 255 else returns false(0)
# process the green band
out = source[G].point(lambda i: i * 0.7)
# ... | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
- Python only evaluates the portion of a logical expression as is necessary to determine the outcome, and returns the last value examined as the result of the expression. So if the expression above is false (0), Python does not look at the second operand, and thus returns 0. Otherwise, it returns 255. Enhancement | from PIL import Image
from PIL import ImageEnhance
im = Image.open("lena.png")
enh = ImageEnhance.Contrast(im)
enh.enhance(1.3).show("30% more contrast") | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Image sequences Reading sequences | from PIL import Image
im = Image.open("animation.gif")
im.seek(1) # skip to the second frame
try:
while 1:
im.seek(im.tell()+1)
im.show()
# do something to im
except EOFError as e:
print(e)
pass # end of sequence | no more images in GIF file
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
A sequence iterator class | from PIL import Image
im = Image.open("animation.gif")
class ImageSequence:
def __init__(self, im):
self.im = im
def __getitem__(self, ix):
try:
if ix:
self.im.seek(ix)
return self.im
except EOFError:
print('ddd')
raise Ind... | ddd
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Postscript printing Drawing Postscript | from PIL import Image
from PIL import PSDraw
im = Image.open("lena.png")
title = "lena"
box = (1*72, 2*72, 7*72, 10*72) # in points
ps = PSDraw.PSDraw() # default is sys.stdout
ps.begin_document(title)
# draw the image (75 dpi)
ps.image(box, im, 75)
ps.rectangle(box)
# draw title
ps.setfont("HelveticaNarrow-Bold", ... | %!PS-Adobe-3.0
save
/showpage { } def
%%EndComments
%%BeginDocument
/S { show } bind def
/P { moveto show } bind def
/M { moveto } bind def
/X { 0 rmoveto } bind def
/Y { 0 exch rmoveto } bind def
/E { findfont
dup maxlength dict begin
{
1 index /FID ne { def } { pop pop } ifelse
... | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
More on reading images Reading from an open file | fp = open("lena.png", "rb")
im = Image.open(fp)
im.show() | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Reading from a string | !pip install StringIO
import StringIO
im = Image.open(StringIO.StringIO(buffer)) | ERROR: Could not find a version that satisfies the requirement StringIO
ERROR: No matching distribution found for StringIO
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Reading from a tar archive | from PIL import TarIO
fp = TarIO.TarIO("Imaging.tar", "lena.png")
im = Image.open(fp) | _____no_output_____ | MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Controlling the decoder Reading in draft mode | from __future__ import print_function
from PIL import Image
im = Image.open('lena.png')
print("original =", im.mode, im.size)
im.draft("L", (100, 100))
print("draft =", im.mode, im.size)
| original = RGB (512, 512)
draft = RGB (512, 512)
| MIT | Deep Learning Guide/8. Pillow image processing/.ipynb_checkpoints/Python Imaging Library-checkpoint.ipynb | nomancseku/NSL-HW |
Execute the following block of code by selecting it and clicking ``ctrl + enter`` to create an ``NvidiaRacecar`` class. | from jetracer.nvidia_racecar import NvidiaRacecar
car = NvidiaRacecar() | _____no_output_____ | MIT | notebooks/basic_motion.ipynb | rezaarrazi/jetracer |
The ``NvidiaRacecar`` implements the ``Racecar`` class, so it has two attributes ``throttle`` and ``steering``. We can assign values in the range ``[-1, 1]`` to these attributes. Execute the following to set the steering to 0.4.> If the car does not respond, it may still be in ``manual`` mode. Flip the manual overrid... | car.steering = 0.3 | _____no_output_____ | MIT | notebooks/basic_motion.ipynb | rezaarrazi/jetracer |
The ``NvidiaRacecar`` class has two values ``steering_gain`` and ``steering_bias`` that can be used to calibrate the steering.We can view the default values by executing the cells below. | print(car.steering_gain)
print(car.steering_offset) | _____no_output_____ | MIT | notebooks/basic_motion.ipynb | rezaarrazi/jetracer |
The final steering value is computed using the equation$y = a \times x + b$Where,* $a$ is ``car.steering_gain``* $b$ is ``car.steering_offset``* $x$ is ``car.steering``* $y$ is the value written to the motor driverYou can adjust these values calibrate the car so that setting a value of ``0`` moves forward, and setting ... | car.throttle = 0.0 | _____no_output_____ | MIT | notebooks/basic_motion.ipynb | rezaarrazi/jetracer |
The throttle also has a gain value that could be used to control the speed response. The throttle output is computed as$y = a \times x$Where,* $a$ is ``car.throttle_gain``* $x$ is ``car.throttle``* $y$ is the value written to the speed controllerExecute the following to print the default gain | print(car.throttle_gain) | _____no_output_____ | MIT | notebooks/basic_motion.ipynb | rezaarrazi/jetracer |
Set the following to limit the throttle to half | car.throttle_gain = 0.5 | _____no_output_____ | MIT | notebooks/basic_motion.ipynb | rezaarrazi/jetracer |
Verification: 2D-preliminar | # calculate geometry
rf = 1.27/2 - 0.0125 # cm
rg = 1.27/2 # cm
rc = 1.59/2 # cm
rm = 1.885 - rc # cm
rg2 = rm - 0.01;
rc2 = np.sqrt(rc**2 + rm**2)
rc2
# coolant flow and film thermal conductivity
rho = 4.94e-6 # kg/cm3
cp = 5.188e3 # J/kg/K
mlc = 0.0176 # kg/s
v = mlc/rho/np.pi/rc**2
print('v: ', v, 'cm/s')
mu ... | _____no_output_____ | BSD-3-Clause | moltres-thermal-fluids/verification/notes.ipynb | arfc/mhtgr350-benchmark |
Trabajando con opciones Una opción puede negociarse en el mercado secundario por lo que es importante determinar su valor $V_t$ para cada tiempo $t\in [0, T]$. La ganancia que obtiene quién adquiere la opción se llama función de pago o "payoff" y claramente depende del valor del subyacente. Hay una gran variedad de op... | #importar los paquetes que se van a usar
import pandas as pd
import pandas_datareader.data as web
import numpy as np
import datetime
import matplotlib.pyplot as plt
import scipy.stats as st
import seaborn as sns
%matplotlib inline
#algunas opciones para Pandas
pd.set_option('display.notebook_repr_html', True)
pd.set_op... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Usando el paquete `pandas_datareader` también podemos descargar datos de opciones. Por ejemplo, descarguemos los datos de las opciones cuyo activo subyacente son las acciones de Apple | aapl = web.YahooOptions('AAPL')
aapl_opt = aapl.get_all_data().reset_index()
aapl_opt.set_index('Expiry')
# aapl | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Precio del activo subyacente | aapl_opt.Underlying_Price[0] | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Datos de la opción | aapl_opt.loc[0, 'JSON'] | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Conceptos claves- El precio de la oferta ('bid') se refiere al precio más alto que un comprador pagará por un activo.- El precio de venta ('ask') se refiere al precio más bajo que un vendedor aceptará por un activo.- La diferencia entre estos dos precios se conoce como 'spread'; cuanto menor es el spread, mayor es la ... | aapl_opt.loc[:, 'Type'] | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
o en que fecha expiran | pd.set_option('display.max_rows', 10)
aapl_opt.loc[:, 'Expiry'] | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Por otra parte, podríamos querer consultar todas las opciones de compra (call) que expiran en cierta fecha (2020-06-19) | fecha1 = '2021-06-18'
fecha2 = '2022-09-16'
call06_f1 = aapl_opt.loc[(aapl_opt.Expiry== fecha1) & (aapl_opt.Type=='call')]
call06_f2 = aapl_opt.loc[(aapl_opt.Expiry== fecha2) & (aapl_opt.Type=='call')]
call06_f1
| _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
2. ¿Qué es la volatilidad implícita? **Volatilidad:** desviación estándar de los rendimientos.- ¿Cómo se calcula?- ¿Para qué calcular la volatilidad? - **Para valuar derivados**, por ejemplo **opciones**.- Método de valuación de riesgo neutral (se supone que el precio del activo $S_t$ no se ve afectado por el riesgo d... | # para los call de la fecha 1
ax = call06_f1.set_index('Strike').loc[:, 'IV'].plot(figsize=(8,6))
ax.axvline(call06_f1.Underlying_Price.iloc[0], color='g');
# para los call de la fecha 2
ax = call06_f2.set_index('Strike').loc[:, 'IV'].plot(figsize=(8,6))
ax.axvline(call06_f2.Underlying_Price.iloc[0], color='g'); | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Analicemos ahora datos de los `put` | put06_f1 = aapl_opt.loc[(aapl_opt.Expiry==fecha1) & (aapl_opt.Type=='put')]
put06_f1 | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Para los `put` de la `fecha 1` | ax = put06_f1.set_index('Strike').loc[:, 'IV'].plot(figsize=(8,6))
ax.axvline(put06_f1.Underlying_Price.iloc[0], color='g') | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Con lo que hemos aprendido, deberíamos ser capaces de crear una función que nos devuelva un `DataFrame` de `pandas` con los precios de cierre ajustados de ciertas compañías en ciertas fechas:- Escribir la función a continuación | # Función para descargar precios de cierre ajustados:
def get_adj_closes(tickers, start_date=None, end_date=None):
# Fecha inicio por defecto (start_date='2010-01-01') y fecha fin por defecto (end_date=today)
# Descargamos DataFrame con todos los datos
closes = web.DataReader(name=tickers, data_source='yaho... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
- Obtener como ejemplo los precios de cierre de Apple del año pasado hasta la fecha. Graficar... | ticker = ['AAPL']
start_date = '2017-01-01'
closes_aapl = get_adj_closes(ticker, start_date)
closes_aapl.plot(figsize=(8,5));
plt.legend(ticker); | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
- Escribir una función que pasándole el histórico de precios devuelva los rendimientos logarítmicos: | def calc_daily_ret(closes):
return np.log(closes/closes.shift(1)).iloc[1:] | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
- Graficar... | ret_aapl = calc_daily_ret(closes_aapl)
ret_aapl.plot(figsize=(8,6)); | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
También, descargar datos de opciones de Apple: | aapl = web.YahooOptions('AAPL')
aapl_opt = aapl.get_all_data().reset_index()
aapl_opt.set_index('Expiry').sort_index()
K = 110 # strike price
indice_opt = aapl_opt.loc[(aapl_opt.Type=='call') & (aapl_opt.Strike==K) & (aapl_opt.Expiry=='2021-01-15')]
indice_opt
i_opt= indice_opt.index
opcion_valuar = aapl_opt.loc[i_opt[... | Precio del activo subyacente actual = 115.17
| MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Simulación de precios usando rendimiento simple y logarítmico    * Comenzaremos por suponer que los rendimientos son un p.e. estacionario que distribuyen $\mathcal{N}(\mu,\sigma)$. Rendimiento Simple | # Obtenemos el rendimiento simple
Ri = closes_aapl.pct_change(1).iloc[1:]
# Obtenemos su media y desviación estándar de los rendimientos
mu_R = Ri.mean()[0]
sigma_R = Ri.std()[0]
Ri
opcion_valuar.Expiry
from datetime import date
# Encontrar la fecha de hoy en formato timestamp
today = pd.Timestamp(date.today())
# Obt... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Mostrar como simular precios usando los rendimientos 1. Usando rendimiento simple | # Simular los rendimientos
# Rendimiento diario
dt = 1
# Z ~ N(0,1) normal estándar (ndays, nscen)
Z = np.random.randn(ndays, nscen)
# Simulación normal de los rendimientos
Ri_dt = pd.DataFrame(mu_R * dt + Z * sigma_R * np.sqrt(dt), index=dates)
# Simulación del precio
S_0 = closes_aapl.iloc[-1,0]
S_T = S_0*(1+Ri_d... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
2. Rendimiento Logarítmico | # Calcular rendimiento logarítmico
ri = calc_daily_ret(closes_aapl)
# Usando la media y desviación estándar de los rendimientos logarítmicos
mu_r = ri.mean()[0]
sigma_r = ri.std()[0]
# Simulación del rendimiento
Z = np.random.randn(ndays, nscen)
sim_ret_ri = pd.DataFrame(mu_r * dt + Z * sigma_r * np.sqrt(dt), index=d... | Las std usando rendimientos logarítmicos y simples son similares
| MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Con los precios simulados debemos de encontrar el valor de la opción según la función de pago correspondiente. Para este caso es:$$max(S_T - K,0)$$ | opcion_valuar['JSON'] | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Valuación usando el modelo de Black and ScholesLos supuestos que hicieron Black y Scholes cuando dedujeron su fórmula para la valoración de opciones fueron los siguientes:1. El comportamiento del precio de la acción corresponde al modelo logarítmico normal, con $\mu$ y $\sigma$constantes.2. No hay costos de transición... | mu = ret_aapl.mean()[0]
sigma = ret_aapl.std()[0]
mu, sigma | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
No se toma la media sino la tasa libre de riesgo> Referencia: https://www.treasury.gov/resource-center/data-chart-center/interest-rates/Pages/TextView.aspx?data=yield | # Tasa de bonos de 1 yr de fecha 11/24/20 -> 0.11%
r = 0.0011/360 # Tasa diaria | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
- Simularemos el tiempo de contrato desde `HOY` hasta la fecha de `Expiry`, 10 escenarios: - Generar fechas | from datetime import date
today = pd.Timestamp(date.today())
expiry = opcion_valuar.Expiry
nscen = 10
dates = pd.date_range(start=today, periods = ndays)
ndays = len(dates)
| _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
- Generamos 10 escenarios de rendimientos simulados y guardamos en un dataframe | sim_ret = pd.DataFrame(sigma*np.random.randn(ndays,nscen)+r, index=dates)
sim_ret.cumsum()
# Las columnas son los escenarios y las filas son las días de contrato | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
- Con los rendimientos simulados, calcular los escenarios de precios respectivos: | S0 = closes_aapl.iloc[-1,0] # Condición inicial del precio a simular
sim_closes = S0*np.exp(sim_ret.cumsum())
sim_closes | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
- Graficar: | sim_closes.plot(figsize=(8,6));
# Se muestran los precios simulados con los precios descargados
pd.concat([closes_aapl,sim_closes]).plot(figsize=(8,6));
K = opcion_valuar.Strike
call = np.exp(-r*ndays) * np.fmax(S_T - K, 0).mean(axis=1)
call
opcion_valuar['JSON']
# sigma = 0.3064034204101562/np.sqrt(252)
# sigma
from ... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
La valuación de la opción es: | call.iloc[-1] | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Intervalo de confianza del 99% | confianza = 0.99
sigma_est = sim_closes.iloc[-1].sem()
mean_est = call.iloc[-1].Prima
i2 = st.norm.interval(confianza, loc=mean_est, scale=sigma_est)
print(i2)
opcion_valuar['JSON'] | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Precios simulados usando técnicas de reducción de varianza | # Usando muestreo estratificado----> #estratros = nscen
U = (np.arange(0,nscen)+np.random.rand(ndays,nscen))/nscen
Z = st.norm.ppf(U)
sim_ret2 = pd.DataFrame(sigma*Z+r,index=dates)
sim_closes2 = S0*np.exp(sim_ret.cumsum())
# Función de pago
strike = pd.DataFrame(K*np.ones([ndays,nscen]), index=dates)
call = pd.DataFr... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
La valuación de la opción es: | call.iloc[-1] | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Intervalo de confianza del 99% | confianza = 0.99
sigma_est = sim_closes2.iloc[-1].sem()
mean_est = call.iloc[-1].Prima
i2 = st.norm.interval(confianza, loc=mean_est, scale=sigma_est)
print(i2) | (9.179939817813485, 9.255166213304454)
| MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Análisis de la distribución de los rendimientos Ajustando norm | ren = calc_daily_ret(closes_aapl) # rendimientos
y,x,des = plt.hist(ren['AAPL'],bins=50,density=True,label='Histograma rendimientos')
mu_fit,sd_fit = st.norm.fit(ren) # Se ajustan los parámetros de una normal
# Valores máximo y mínimo de los rendiemientos a generar
ren_max = max(x);ren_min = min(x)
# Vector de rendim... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Ajustando t | # rendimientos
ren = calc_daily_ret(closes_aapl)
# Histograma de los rendimientos
y, x, _ = plt.hist(ren['AAPL'], bins=50, density=True, label='Histograma rendimientos')
# Se ajustan los parámetros de una distribución
dist = 't'
params = getattr(st, dist).fit(ren.values)
# Generación de la pdf de la distribución ... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
3. Valuación usando simulación: uso del histograma de rendimientosTodo el análisis anterior se mantiene. Solo cambia la forma de generar los números aleatorios para la simulación montecarlo.Ahora, generemos un histograma de los rendimientos diarios para generar valores aleatorios de los rendimientos simulados. - Prime... | nscen = 10 | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
- Del histograma anterior, ya conocemos las probabilidades de ocurrencia, lo que se llamó como variable `y` | prob = y/np.sum(y)
values = x[1:]
prob.sum() | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
- Con esto, generamos los números aleatorios correspondientes a los rendimientos (tantos como días por número de escenarios). | dates = pd.date_range(start=Hoy,end=opcion_valuar.Expiry, freq='B')
ndays = len(dates)
ret = np.random.choice(values, ndays*nscen, p=prob)
sim_ret_hist = pd.DataFrame(ret.reshape((ndays,nscen)),index=dates)
sim_ret_hist
sim_closes_hist = (closes_aapl.iloc[-1,0])*np.exp(sim_ret_hist.cumsum())
sim_closes_hist
sim_close... | _____no_output_____ | MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Intervalo de confianza del 95% | confianza = 0.95
sigma_est = sim_closes_hist.iloc[-1].sem()
mean_est = call_hist.iloc[-1].Prima
i2 = st.norm.interval(confianza, loc=mean_est, scale=sigma_est)
print(i2)
| (9.03172920765023, 9.59548003107524)
| MIT | TEMA-3/Clase23_ValuacionOpciones.ipynb | duarteandres/SPF-2020-II-G1 |
Mesh visualisationWe are now going to have a look at different mesh visualisation options. We are going to use the following mesh: | import discretisedfield as df
p1 = (0, 0, 0)
p2 = (100e-9, 50e-9, 20e-9)
n = (20, 10, 4)
region = df.Region(p1=p1, p2=p2)
mesh = df.Mesh(region=region, n=n) | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
Same as the region object, there are two main ways how we can visualise mesh in `discretisedfield`:1. Using `matplotlib` (static 2D plots, usually with some tricks to make them look 3D)2. Using `k3d` (interactive 3D plots)All `matplotlib` method names start with `mpl`, whereas all `k3d` plots start with `k3d`. We will ... | mesh.mpl() | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
`mpl` plots two cubic regions. The larger one corresponds to the region and the smaller one to the discretisation cell. Without passing any parameters to `mpl` function, some default settings are chosen. We can see that `matplotlib` is not good in showing the right proportions of the region. More precisely, we know tha... | # NBVAL_IGNORE_OUTPUT
mesh.k3d() | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
Similar to the `mpl` plot, we can see the region as well as the discretisation cell in this plot. This can be useful to get an impression of the discretisation cell size with respect to the region we discretise. `k3d` plot is an interactive plot, which we can zoom, rotate, etc. In addition, a small contol panel is show... | mesh.mpl() | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
If we want to change the figure size, we can pass `figsize` parameter. Its value must be a lenth-2 tuple, with the first element being the size in the horizontal direction, whereas the second element is the size in the vertical direction. | region.mpl(figsize=(10, 5)) | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
The color of the lines depicting the region and the discretisation cell we can choose by passing `color` argument. `color` must be a lenght-2 tuple which consists of valid `matplotlib` colours. For instance, it can be a pair of RGB hex-strings ([online converter](http://www.javascripter.net/faq/rgbtohex.htm)). The firs... | mesh.mpl(color=('#9400D3', '#0000FF')) | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
`discretisedfield` automatically chooses the SI prefix (nano, micro, etc.) it is going to use to divide the axes with and show those units on the axes. Sometimes (e.g. for thin films), `discretisedfield` does not choose the SI prefix we expected. In those cases, we can explicitly pass it using `multiplier` argument. ``... | mesh.mpl(multiplier=1e-6) | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
If we want to save the plot, we pass `filename`, mesh plot is going to be shown and the plot saved in our working directory as a PDF. | mesh.mpl(filename='my-mesh-plot.pdf') | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
`mpl` mesh plot is based on [`matplotlib.pyplot.plot` function](https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.plot.html). Therefore, any parameter accepted by it can be passed. For instance: | mesh.mpl(marker='o', linestyle='dashed') | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
Finally, we show how to expose the axes on which the mesh is plotted, so that we can customise them. We do that by creating the axes ourselves and then passing them to `mpl` function. | import matplotlib.pyplot as plt
# Create the axes
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(111, projection='3d')
# Add the region to the axes
mesh.mpl(ax=ax)
# Customise the axes
ax.set_xlabel('length')
ax.set_ylabel('width')
ax.set_zlabel('height') | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
This way, by exposing the axes and passing any allowed `matplotlib.pyplot.plot` argument, we can customise the plot any way we like (as long as it is allowed by `matplotlib`). `k3d`Default k3d plot is: | # NBVAL_IGNORE_OUTPUT
mesh.k3d() | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
If we want to change the color, we can pass `color` argument. It is a length-2 tuple of integer colours. The first number in the tuple is the colour of the region, whereas the second colour is the colour of the discretisation cell. | # NBVAL_IGNORE_OUTPUT
mesh.k3d(color=(754321, 123456)) | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
Similar to the `mpl` plot, we can change the axes multiplier. | # NBVAL_IGNORE_OUTPUT
mesh.k3d(multiplier=1e-6) | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
`k3d` plot is based on [k3d.voxels](https://k3d-jupyter.org/k3d.htmlk3d.factory.voxels), so any parameter accepted by it can be passed. For instance: | # NBVAL_IGNORE_OUTPUT
mesh.k3d(opacity=0.2) | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
We can also expose `k3d.Plot` object and customise it. | # NBVAL_IGNORE_OUTPUT
import k3d
# Expose plot object
plot = k3d.plot()
plot.display()
# Add region to the plot
mesh.k3d(plot=plot)
# Customise the plot
plot.axes = [r'\text{length}', r'\text{width}', r'\text{height}'] | _____no_output_____ | BSD-3-Clause | tutorials/mesh-visualisation.ipynb | askeyjw/workshop |
Hello World Text DetectionA very basic introduction to OpenVINO that shows how to do text detection on a given IR model.We use the [horizontal-text-detection-0001](https://docs.openvinotoolkit.org/latest/omz_models_model_horizontal_text_detection_0001.html) model from [Open Model Zoo](https://github.com/openvinotoolki... | import numpy as np
import cv2
import matplotlib.pyplot as plt
import numpy as np
from openvino.inference_engine import IECore | _____no_output_____ | Apache-2.0 | notebooks/004-hello-detection/004-hello-detection.ipynb | bdattoma/openvino_notebooks |
Load the Model | ie = IECore()
net = ie.read_network(
model="model/horizontal-text-detection-0001.xml",
weights="model/horizontal-text-detection-0001.bin",
)
exec_net = ie.load_network(net, "CPU")
output_layer_ir = next(iter(exec_net.outputs))
input_layer_ir = next(iter(exec_net.input_info)) | _____no_output_____ | Apache-2.0 | notebooks/004-hello-detection/004-hello-detection.ipynb | bdattoma/openvino_notebooks |
Load an Image | # Text detection models expects image in BGR format
image = cv2.imread("data/intel_rnb.jpg")
# N,C,H,W = batch size, number of channels, height, width
N, C, H, W = net.input_info[input_layer_ir].tensor_desc.dims
# Resize image to meet network expected input sizes
resized_image = cv2.resize(image, (W, H))
# Reshape t... | _____no_output_____ | Apache-2.0 | notebooks/004-hello-detection/004-hello-detection.ipynb | bdattoma/openvino_notebooks |
Do Inference | result = exec_net.infer(inputs={input_layer_ir: input_image})
# Extract list of boxes from results
boxes = result["boxes"]
# Remove zero only boxes
boxes = boxes[~np.all(boxes == 0, axis=1)] | _____no_output_____ | Apache-2.0 | notebooks/004-hello-detection/004-hello-detection.ipynb | bdattoma/openvino_notebooks |
Visualize Results | # For each detection, the description has the format: [x_min, y_min, x_max, y_max, conf]
# Image passed here is in BGR format with changed width and height. To display it in colors expected by matplotlib we use cvtColor funtion
def convert_result_to_image(bgr_image, resized_image, boxes, threshold=0.3, conf_labels=Tr... | _____no_output_____ | Apache-2.0 | notebooks/004-hello-detection/004-hello-detection.ipynb | bdattoma/openvino_notebooks |
Sin CythonEste programa genera $N$ enteros aleatorios entre $1$ y $M$, y una vez obtenidos los eleva al cuadrado y devuelve la suma de los cuadrados. Por tanto, calcula el cuadrado de la longitud de un vector aleatorio con coordenadas enteros en el intervalo $[1,M]$. | def cuadrados(N,M):
res = 0
for muda in xrange(N):
x = randint(1,M)
res += x*x
return res
for n in srange(3,8):
%time A = cuadrados(10^n,10^6) | CPU times: user 5.61 ms, sys: 263 µs, total: 5.87 ms
Wall time: 6.09 ms
CPU times: user 44.7 ms, sys: 0 ns, total: 44.7 ms
Wall time: 57.6 ms
CPU times: user 477 ms, sys: 57.1 ms, total: 534 ms
Wall time: 480 ms
CPU times: user 4.39 s, sys: 130 ms, total: 4.52 s
Wall time: 4.42 s
CPU times: user 43.3 s, sys: 403 ms, to... | Apache-2.0 | 2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROBA/114-PROBA-Generador-cython.ipynb | AlejandroSantorum/Apuntes_Mat_IngInf |
Con CythonMismo cálculo: | %%cython
import math
import random
def cuadrados_cy(long long N, long long M):
cdef long long res = 0
cdef long long muda
cdef long long x
for muda in xrange(N):
x = random.randint(1,M)
res += math.pow(x,2)
return res
for n in srange(3,8):
%time A = cuadrados_cy(10^n,10^6) | CPU times: user 2.94 ms, sys: 48 µs, total: 2.99 ms
Wall time: 2.83 ms
CPU times: user 28.7 ms, sys: 34 µs, total: 28.7 ms
Wall time: 33.3 ms
CPU times: user 259 ms, sys: 24.3 ms, total: 284 ms
Wall time: 252 ms
CPU times: user 2.47 s, sys: 167 ms, total: 2.64 s
Wall time: 2.44 s
CPU times: user 22.9 s, sys: 258 ms, to... | Apache-2.0 | 2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROBA/114-PROBA-Generador-cython.ipynb | AlejandroSantorum/Apuntes_Mat_IngInf |
Optimizando el cálculo de números aleatorios: | %%cython
cdef extern from 'gsl/gsl_rng.h':
ctypedef struct gsl_rng_type:
pass
ctypedef struct gsl_rng:
pass
gsl_rng_type *gsl_rng_mt19937
gsl_rng *gsl_rng_alloc(gsl_rng_type * T)
cdef gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937)
cdef extern from 'gsl/gsl_randist.h':
long int uniform 'g... | CPU times: user 68 µs, sys: 1e+03 ns, total: 69 µs
Wall time: 72 µs
CPU times: user 568 µs, sys: 0 ns, total: 568 µs
Wall time: 511 µs
CPU times: user 4.82 ms, sys: 0 ns, total: 4.82 ms
Wall time: 4.83 ms
CPU times: user 48.1 ms, sys: 0 ns, total: 48.1 ms
Wall time: 48.5 ms
CPU times: user 479 ms, sys: 0 ns, total: 479... | Apache-2.0 | 2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROBA/114-PROBA-Generador-cython.ipynb | AlejandroSantorum/Apuntes_Mat_IngInf |
Problema similar sin números aleatorios: | %%cython
def cuadrados_cy3(long long int N):
cdef long long int res = 0
cdef long long int k
for k in range(N):
res += k**2
return res
for n in srange(3,8):
%time A = cuadrados_cy3(10^n)
def cuadrados5(N):
res = 0
for k in range(N):
res += k**2
return res
for n in srange(... | CPU times: user 643 µs, sys: 0 ns, total: 643 µs
Wall time: 487 µs
CPU times: user 1.35 ms, sys: 3.95 ms, total: 5.31 ms
Wall time: 4.26 ms
CPU times: user 25.5 ms, sys: 12 ms, total: 37.4 ms
Wall time: 37.4 ms
CPU times: user 373 ms, sys: 28.2 ms, total: 402 ms
Wall time: 387 ms
CPU times: user 3.75 s, sys: 169 ms, to... | Apache-2.0 | 2_Curso/Laboratorio/SAGE-noteb/IPYNB/PROBA/114-PROBA-Generador-cython.ipynb | AlejandroSantorum/Apuntes_Mat_IngInf |
Plot multi-class SGD on the iris datasetPlot decision surface of multi-class SGD on iris dataset.The hyperplanes corresponding to the three one-versus-all (OVA) classifiersare represented by the dashed lines. | print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.linear_model import SGDClassifier
# import some data to play with
iris = datasets.load_iris()
# we only take the first two features. We could
# avoid this ugly slicing by using a two-dim dataset
X = iris.data[... | _____no_output_____ | MIT | sklearn/sklearn learning/demonstration/auto_examples_jupyter/linear_model/plot_sgd_iris.ipynb | wangyendt/deeplearning_models |
!curl -O https://raw.githubusercontent.com/franciscadias/data/master/abcnews-date-text.csv
import pandas as pd
df_data = pd.read_csv('./abcnews-date-text.csv')
df_data.head(3)
df_data = df_data.head(10000)
head_text = df_data[['headline_text']]
type(head_text)
import nltk
nltk.download('punkt')
head_text['title_text'] ... | _____no_output_____ | Apache-2.0 | topic_modeling_LDA.ipynb | SolbiChoi/test_deeplearning | |
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License.  ... | import logging
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
import os
from sklearn.model_selection import train_test_split
import azureml.dataprep as dprep
import azureml.core
from azureml.core.experiment import Experiment
from azureml.core.workspace import Workspace
from azureml.trai... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.