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
We can see that we got the resources that we requested. Now let's delete the slice.
return_status, result = slice_manager.delete(slice_object=slice) print("Response Status {}".format(return_status)) print("Response received {}".format(result))
_____no_output_____
MIT
fabric_examples/basic_examples/setting_node_capaciites.ipynb
fabric-testbed/jupyternb-template
2. Beyond simple plotting--- In this lecture we'll go a bit further with plotting.We will:- Create figures of different sizes;- Use Numpy to generate data for plotting;- Further change the appearance of our plots; - Add multiple axes to the same figure.
from matplotlib import pyplot as plt %matplotlib inline
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
2.1 Figures of different sizes We can create figures with different sizes by specifying the `figsize` argument.
fig, axes = plt.subplots(figsize=(12,4))
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
--- 2.2 Plotting Numpy data The `plot` method also supports numpy arrays. For example, we canuse Numpy to plot a sine wave:
import numpy as np # Create the data x_values = np.linspace(-np.pi, np.pi, 200) y_values = np.sin(x_values) # Plot and show the figure axes.plot(x_values, y_values,'--b') fig
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
--- 2.3 More options for you plots We can use the `set_xlim` and `set_ylim` methods to change the range of the x and y axis.
axes.set_xlim([-np.pi, np.pi]) axes.set_ylim([-1, 1]) fig
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
Or use `axis('tight')` for automatically getting axis ranges that fit the data inside it (not as tightly as one would expect, though).
axes.axis('tight') fig
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
We can add a grid with the `grid` method. See the [`grid` method documentation](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.grid.html) for more information about different styles of grids.
axes.grid(linestyle='dashed', linewidth=0.5) fig
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
Also, we can explicitly choose where we want the ticks in the x and y axis and their labels, with the methods `set_xticks`, `set_yticks`, `set_xticklabels` and `set_yticklabels`.
axes.set_xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) axes.set_yticks([-1, -0.5, 0, 0.5, 1]) fig axes.set_xticklabels([r'$-\pi$', r'$-\pi/2$', 0, r'$\pi/2$', r'$\pi$']) axes.set_yticklabels([-1,r'$-\frac{1}{2}$',0,r'$\frac{1}{2}$',1]) fig
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
Finally, we can save a figure using the `savefig` method.
fig.savefig('filename.png')
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
--- 2.4 Multiple axes in the same figure To have multiple axes in the same figure, you can simply specify the arguments `nrows` and `ncols` when calling `subplots`.
fig, axes = plt.subplots(nrows=2, ncols=3)
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
To make the axis not overlap, we use the method `subplots_adjust`.
fig.subplots_adjust(hspace=0.6, wspace=0.6) fig
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
And now we can simply plot in each individual axes separately.
axes[0][1].plot([1,2,3,4]) fig axes[1,2].plot([4,4,4,2,3,3],'b--') fig axes[0][1].plot([2,2,2,-1],'-.o') fig
_____no_output_____
MIT
Python Crash Course/Module 3 - Matplotlib/L2 Matplotlib.ipynb
yuxuanx/deep-machine-learning
Gromos Tutorial Pipeline
import os, sys from pygromos.utils import bash root_dir = os.getcwd() #if package is not installed and path not set correct - this helps you out :) sys.path.append(root_dir+"/..") import pygromos from pygromos.gromos.gromosPP import GromosPP from pygromos.gromos.gromosXX import GromosXX gromosPP_bin = None gromosXX...
_____no_output_____
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
Build initial files generate Topology build single topologies
from pygromos.data.ff import Gromos54A7 topo_dir = bash.make_folder(project_dir+'/a_topo') ## Make Cl- sequence = "CL-" solvent = "H2O" top_cl = topo_dir+"/cl.top" gromPP.make_top(in_building_block_lib_path=Gromos54A7.mtb, in_parameter_lib_path=Gromos54A7.ifp, in_sequence=sequence, in...
_____no_output_____
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
combine topology
top_system = topo_dir+"/vac_sys.top" gromPP.com_top(in_topo_paths=[top_peptide, top_cl], topo_multiplier=[1,2], out_top_path=top_system)
_____no_output_____
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
generate coordinates
coord_dir = bash.make_folder(project_dir+"/b_coord") in_pdb = input_dir+"/peptide.pdb" cnf_peptide = coord_dir+"/cnf_vacuum_peptide.cnf" cnf_peptide = gromPP.pdb2gromos(in_pdb_path=in_pdb, in_top_path=top_peptide, out_cnf_path=cnf_peptide)
_____no_output_____
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
add hydrogens
cnf_hpeptide = coord_dir+"/vacuum_hpeptide.cnf" cnf_hpeptide = gromPP.protonate(in_cnf_path=cnf_peptide, in_top_path=top_peptide, out_cnf_path=cnf_hpeptide)
_____no_output_____
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
cnf to pdb
out_pdb = coord_dir+"/vacuum_hpeptide.pdb" out_pdb = gromPP.frameout(in_coord_path=cnf_hpeptide, in_top_path=top_peptide, out_file_path=out_pdb, periodic_boundary_condition="v", out_file_format="pdb", time=0)
_____no_output_____
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
energy minimization - Vacuum
from pygromos.data.simulation_parameters_templates import template_emin_vac from pygromos.files.gromos_system import gromos_system out_prefix = "vacuum_emin" vacuum_emin_dir = bash.make_folder(project_dir+"/c_"+out_prefix) os.chdir(vacuum_emin_dir) grom_system = gromos_system.Gromos_System(work_folder=vacuum_emin_dir...
_____no_output_____
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
Solvatistation and Solvent Energy Minimization build box system
from pygromos.data.solvent_coordinates import spc out_prefix = "box" box_dir = bash.make_folder(project_dir+"/d_"+out_prefix) cnf_box = gromPP.sim_box(in_top_path=top_peptide, in_cnf_path=cnf_emin_vacuum,in_solvent_cnf_file_path=spc, out_cnf_path=box_dir+"/"+out_prefix+".cnf", ...
sim_box @topo /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/a_topo/peptide.top @pbc r @pos /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/c_vacuum_emin/vacuum_emin.cnf @solvent /home/bschroed/Documents/code/pygromos/pygromos/data/solvent_coordinates/spc.cnf...
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
Add Ions
out_prefix = "ion" cnf_ion = gromPP.ion(in_cnf_path=cnf_box, in_top_path=top_peptide, out_cnf_path=box_dir+"/"+out_prefix+".cnf", negative=[2, "CL-"],verbose=True )
ion @topo /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/a_topo/peptide.top @pos /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/d_box/box.cnf @pbc v @potential 0.8 @mindist 0.8 @negative 2 CL-
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
Energy Minimization BOX
from pygromos.data.simulation_parameters_templates import template_emin from pygromos.files.gromos_system import gromos_system out_prefix = "box_emin" box_emin_dir = bash.make_folder(project_dir+"/e_"+out_prefix) os.chdir(box_emin_dir) grom_system = gromos_system.Gromos_System(work_folder=box_emin_dir, ...
Cnf POSRES /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/e_box_emin/box_emin_posres.pos COMMAND: md @topo /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/a_topo/vac_sys.top @conf /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/...
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
Simulation Equilibration NVP To be implemented!
from pygromos.data.simulation_parameters_templates import template_md_tut as template_md from pygromos.files.gromos_system import gromos_system out_prefix = "eq_NVP" eq_NVP_dir = bash.make_folder(project_dir+"/f_"+out_prefix) os.chdir(eq_NVP_dir) grom_system = gromos_system.Gromos_System(work_folder=eq_NVP_dir, ...
_____no_output_____
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
MD NVP
grom_system from pygromos.data.simulation_parameters_templates import template_md from pygromos.files.gromos_system import gromos_system out_prefix = "md" md_dir = bash.make_folder(project_dir+"/g_"+out_prefix) os.chdir(md_dir) grom_system = gromos_system.Gromos_System(work_folder=md_dir, ...
COMMAND: md @topo /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/g_md/in_md.top @conf /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/g_md/in_md.cnf @input /home/bschroed/Documents/code/pygromos/examples/example_files/Tutorial_System/g_md/in_md.imd @fin /hom...
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
Analysis
out_prefix = "ana" md_dir = bash.make_folder(project_dir+"/h_"+out_prefix) os.chdir(md_dir)
_____no_output_____
MIT
docs/sphinx_project/_build/html/Tutorials/tutorial_gromos_pipeline.ipynb
SalomeRonja/PyGromosTools
Self-Driving Car Engineer Nanodegree Project: **Finding Lane Lines on the Road** ***In this project, you will use the tools you learned about in the lesson to identify lane lines on the road. You can develop your pipeline on a series of individual images, and later apply the result to a video stream (really just a se...
#importing some useful packages import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 %matplotlib inline
_____no_output_____
MIT
P1.ipynb
elim1234/lane_detection_P1
Read in an Image
#reading in an image image = mpimg.imread('test_images/solidWhiteRight.jpg') #printing out some stats and plotting print('This image is:', type(image), 'with dimensions:', image.shape) plt.imshow(image) # if you wanted to show a single color channel image called 'gray', for example, call as plt.imshow(gray, cmap='gra...
This image is: <class 'numpy.ndarray'> with dimensions: (540, 960, 3)
MIT
P1.ipynb
elim1234/lane_detection_P1
Ideas for Lane Detection Pipeline **Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:**`cv2.inRange()` for color selection `cv2.fillPoly()` for regions selection `cv2.line()` to draw lines on an image given endpoints `cv2.addWeighted()` to coadd / overlay two i...
import math def grayscale(img): """Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray')""" return cv2.cvtColor(img, c...
_____no_output_____
MIT
P1.ipynb
elim1234/lane_detection_P1
Test ImagesBuild your pipeline to work on the images in the directory "test_images" **You should make sure your pipeline works well on these images before you try the videos.**
import os img_list = os.listdir("test_images/")
_____no_output_____
MIT
P1.ipynb
elim1234/lane_detection_P1
Build a Lane Finding Pipeline Build the pipeline and run your solution on all test_images. Make copies into the `test_images_output` directory, and you can use the images in your writeup report.Try tuning the various parameters, especially the low and high Canny thresholds as well as the Hough lines parameters.
# TODO: Build your pipeline that will draw lane lines on the test_images # then save them to the test_images_output directory. def draw_lane_lines_on_image(img): # Convert image to grey scale img_grey = grayscale(img) # Apply Gaussian blur kernel_size = 5 img_blur = gaussian_blur(img_grey, kernel...
_____no_output_____
MIT
P1.ipynb
elim1234/lane_detection_P1
Test on VideosYou know what's cooler than drawing lanes over images? Drawing lanes over video!We can test our solution on two provided videos:`solidWhiteRight.mp4``solidYellowLeft.mp4`**Note: if you get an import error when you run the next cell, try changing your kernel (select the Kernel menu above --> Change Kernel...
# Import everything needed to edit/save/watch video clips from moviepy.editor import VideoFileClip from IPython.display import HTML def process_image(image): # NOTE: The output you return should be a color image (3 channel) for processing video below # TODO: put your pipeline here, # you should return the f...
_____no_output_____
MIT
P1.ipynb
elim1234/lane_detection_P1
Let's try the one with the solid white lane on the right first ...
white_output = 'test_videos_output/solidWhiteRight.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and...
[MoviePy] >>>> Building video test_videos_output/solidWhiteRight.mp4 [MoviePy] Writing video test_videos_output/solidWhiteRight.mp4
MIT
P1.ipynb
elim1234/lane_detection_P1
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice.
HTML(""" <video width="960" height="540" controls> <source src="{0}"> </video> """.format(white_output))
_____no_output_____
MIT
P1.ipynb
elim1234/lane_detection_P1
Improve the draw_lines() function**At this point, if you were successful with making the pipeline and tuning parameters, you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about de...
yellow_output = 'test_videos_output/solidYellowLeft.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start an...
_____no_output_____
MIT
P1.ipynb
elim1234/lane_detection_P1
Writeup and SubmissionIf you're satisfied with your video outputs, it's time to make the report writeup in a pdf or markdown file. Once you have this Ipython notebook ready along with the writeup, it's time to submit for review! Here is a [link](https://github.com/udacity/CarND-LaneLines-P1/blob/master/writeup_templat...
challenge_output = 'test_videos_output/challenge.mp4' ## To speed up the testing process you may want to try your pipeline on a shorter subclip of the video ## To do so add .subclip(start_second,end_second) to the end of the line below ## Where start_second and end_second are integer values representing the start and e...
_____no_output_____
MIT
P1.ipynb
elim1234/lane_detection_P1
Download MNIST data
transformer = transforms.Compose([ transforms.Resize(105), transforms.ToTensor(), transforms.Normalize(mean=0.5,std=0.5)]) # If you run this code first time, make 'download' option True test_data = dset.MNIST(root='MNIST_data/',train=False,transform=transform...
_____no_output_____
MIT
siamese/MNIST_Test.ipynb
SoongE/MetaLearning-pytorch
Make Dataloader
class MNISTTest(Dataset): def __init__(self, dataset,trial): self.dataset = dataset self.trial = trial if trial > 950: self.trial = 950 def __len__(self): return self.trial * 10 def __getitem__(self, index): share, remain = divmod(index,10) label...
_____no_output_____
MIT
siamese/MNIST_Test.ipynb
SoongE/MetaLearning-pytorch
Declare model and configuration
config = get_config() config.num_model = "1" config.logs_dir = "./result/1" model = SiameseNet() is_best = False device = 'cuda' if torch.cuda.is_available() else 'cpu'
[*] use GPU Quadro RTX 4000
MIT
siamese/MNIST_Test.ipynb
SoongE/MetaLearning-pytorch
Load trained model
if is_best: model_path = os.path.join(config.logs_dir, './models/best_model.pt') else: model_path = sorted(glob(config.logs_dir + './models/model_ckpt_*.pt'), key=len)[-1] ckpt = torch.load(model_path) model.load_state_dict(ckpt['model_state']) model.to(device) print(f"[*] Load model {os.path.basename(model_p...
[*] Load model model_ckpt_50.pt, best accuracy 0.903125
MIT
siamese/MNIST_Test.ipynb
SoongE/MetaLearning-pytorch
Test
correct_sum = 0 num_test = len(test_loader) print(f"[*] Test on {num_test} pairs.") pbar = tqdm(enumerate(test_loader), total=num_test, desc="Test") for i, (x1, x2, y) in pbar: # plt.figure(figsize=(20,7)) # plt.subplot(1,4,1) # plt.title("Target") # plt.imshow(x1[0].squeeze().numpy(), cmap='gray') ...
[*] Test on 950 pairs. Test Acc: 296/950 (31.16%)
MIT
siamese/MNIST_Test.ipynb
SoongE/MetaLearning-pytorch
MAT281 Aplicaciones de la Matemática en la Ingeniería Módulo 03 Clase 01: Teoría y Landscape de Visualizaciones Objetivos* Comprender la importancia de las visualizaciones.* Conocer las librerías de visualización en Python. Contenidos* [¿Por qué aprenderemos sobre visualización?](why)* [Teoría](theory)* [Python Lan...
import numpy as np import pandas as pd import os import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv(os.path.join("data","anscombe.csv")) df df.describe()
_____no_output_____
MIT
m03_data_visualization/m03_c01_theory_and_landscape/m03_c01_theory_and_landscape.ipynb
Taz-Ricardo/mat281_portafolio
¿Por qué es un ejemplo clásico?
for i in range(1, 4 + 1): x = df.loc[:, f"x{i}"].values y = df.loc[:, f"y{i}"].values slope, intercept = np.polyfit(x, y, 1) print(f"Grupo {i}:\n\tTiene pendiente {slope:.2f} e intercepto {intercept:.2f}.\n") groups = range(1, 4 + 1) x_columns = [col for col in df if "x" in col] x_aux = np.arange( d...
_____no_output_____
MIT
m03_data_visualization/m03_c01_theory_and_landscape/m03_c01_theory_and_landscape.ipynb
Taz-Ricardo/mat281_portafolio
Teoría Sistema visual humano Buenas noticias* Gráficos entregan información que la estadística podría no revelar.* Despliegue visual es esencial para comprensión. Malas noticias * La atención es selectiva y puede ser fácilmente engañada. La atención es selectiva y puede ser fácilmente engañada. Con...
## Example from https://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/pie_features.html#sphx-glr-gallery-pie-and-polar-charts-pie-features-py # Pie chart, where the slices will be ordered and plotted counter-clockwise: labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' sizes = [15, 30, 45, 10] explode = (0, 0.1, 0, 0) # on...
_____no_output_____
MIT
m03_data_visualization/m03_c01_theory_and_landscape/m03_c01_theory_and_landscape.ipynb
Taz-Ricardo/mat281_portafolio
2. PriorizaciónDato más importante debe utilizar elemento de mejor percepción.
np.random.seed(42) N = 31 x = np.arange(N) y1 = 80 + 20 *x / N + 5 * np.random.rand(N) y2 = 75 + 25 *x / N + 5 * np.random.rand(N) fig, axs = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(16,8)) axs[0][0].plot(x, y1, 'ok') axs[0][0].plot(x, y2, 'sk') axs[0][1].plot(x, y1, 'ob') axs[0][1].plot(x, y2, 'or') ax...
_____no_output_____
MIT
m03_data_visualization/m03_c01_theory_and_landscape/m03_c01_theory_and_landscape.ipynb
Taz-Ricardo/mat281_portafolio
Elementos de mejor percepciónNo todos los elementos tienen la misma percepción a nivel del sistema visual.En particular, el color y la forma son elementos preatentivos: un color distinto o una forma distinta se reconocen de manera no conciente.Ejemplos de elementos preatentivos. ¿En que orden creen que el sistema vi...
import matplotlib.cm as cm from scipy.stats import multivariate_normal x, y = np.mgrid[-3:3:.025, -2:2:.025] pos = np.empty(x.shape + (2,)) pos[:, :, 0] = x pos[:, :, 1] = y z1 = multivariate_normal.pdf( pos, mean=[-1.0, -1.0], cov=[[1.0, 0.0], [0.0, 0.1]] ) z2 = multivariate_normal.pdf( pos, mean=...
_____no_output_____
MIT
m03_data_visualization/m03_c01_theory_and_landscape/m03_c01_theory_and_landscape.ipynb
Taz-Ricardo/mat281_portafolio
Consejo: evite mientras pueda los colormaps. Por ejemplo, utilizando contour plots.
fig, axs = plt.subplots(2, 2, figsize=(20, 12), sharex=True, sharey=True) cmaps = [cm.rainbow, cm.autumn, cm.coolwarm, cm.gray] countour_styles = [ {"cmap": cm.rainbow}, {"cmap": cm.rainbow}, {"colors": "k", "linestyles": "solid"}, {"colors": "k", "linestyles": "dashed"}, ] for i, ax in zip(range(len(c...
_____no_output_____
MIT
m03_data_visualization/m03_c01_theory_and_landscape/m03_c01_theory_and_landscape.ipynb
Taz-Ricardo/mat281_portafolio
3. Sobre la ExpresividadMostrar los datos y sólo los datos. Los datos deben utilizar elementos con atribuciones adecuadas: _Not all data is born equal_.Clasificación de datos:* ***Datos Cuantitativos***: Cuantificación absoluta. * Cantidad de azúcar en fruta: 50 [gr/kg] * Operaciones =, $\neq$, , +, −, * , /* ***Dat...
brands = { "MSI": "Taiwan", "Asus": "Taiwan", "Acer": "Taiwan", "HP": "EEUU", "Dell": "EEUU", "Apple": "EEUU", "Sony": "Japon", "Toshiba": "Japon", "Lenovo": "Hong Kong", "Samsung": "Corea del Sur" } C2N = {"Taiwan": 1, "EEUU": 2, "Japon": 3, "Hong Kong": 4, "Corea del Sur": 7} x...
_____no_output_____
MIT
m03_data_visualization/m03_c01_theory_and_landscape/m03_c01_theory_and_landscape.ipynb
Taz-Ricardo/mat281_portafolio
Clasificación de datos:* ***Datos Cuantitativos***: Cuantificación absoluta. * Cantidad de azúcar en fruta: 50 [gr/kg] * Operaciones =, $\neq$, , +, −, * , / * **Utilizar posición, largo, pendiente o ángulo** * ***Datos Posicionales***: Cuantificación relativa. * Fecha de cosecha: 1 Agosto 2014, 2 Agosto 2014. ...
x = list(range(1, 13)) y = 80 + 20 * np.random.rand(12) x_ticks = list("EFMAMJJASOND") fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(20, 8)) ax1.plot(x, y, 'o-') ax1.set_xticks(x) ax1.set_xticklabels(x_ticks) ax1.grid(alpha=0.5) ax2.plot(x, y,'o-') ax2.set_xticks(x) ax2.set_xticklabels(x_ticks) ax2.set_ylim([0, 11...
_____no_output_____
MIT
m03_data_visualization/m03_c01_theory_and_landscape/m03_c01_theory_and_landscape.ipynb
Taz-Ricardo/mat281_portafolio
Utilizar la misma codificación visual entre gráficos similares
x = np.linspace(0, 1, 50) f1 = x ** 2 + .2 * np.random.rand(50) g1 = x + .2 * np.random.rand(50) f2 = 0.5 - 0.2 * x + .2 * np.random.rand(50) g2 = x ** 3 + .2 * np.random.rand(50) fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(20, 12), sharex=True) ax1.set_title("Antes de MAT281") ax1.plot(x, f1, 'b', label='Chil...
_____no_output_____
MIT
m03_data_visualization/m03_c01_theory_and_landscape/m03_c01_theory_and_landscape.ipynb
Taz-Ricardo/mat281_portafolio
Regresi LinearKali ini kita akan belajar tentang Regresi Linear. Seperti biasa, kita import library terlebih dahulu:
import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy as np %matplotlib inline
_____no_output_____
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
Kita akan gunakan data contoh dari IBM Object Storage.
!wget -O FuelConsumption.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv
--2022-04-18 16:21:40-- https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/FuelConsumptionCo2.csv Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 67.228.254.196 Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-a...
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
`FuelConsumption.csv`:Dataset ini berisi konsumsi bahan bakar mesin dan estimasi dari emisi karbon dioksida yang dihasilkan. Data ini dari kendaraan-kendaraan yang baru dijual di Kanada. [Dataset source](http://open.canada.ca/data/en/dataset/98f1a129-f628-4ce4-b24d-6f16bf24dd64)- **MODELYEAR** e.g. 2014- **MAKE** e.g....
# Ubah data ke bentuk dataframe df = pd.read_csv("FuelConsumption.csv") # Lihat isi dataframe df.tail(10)
_____no_output_____
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
Explore-DataMari kita lihat dataset tersebut dengan statistik deskriptif.
# Rangkuman isi dataset df.describe() cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']] cdf.head()
_____no_output_____
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
Sekarang kita cek beberapa fitur/kolom:
viz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']] viz.hist() plt.show()
_____no_output_____
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
Nah sekarang, kita lihat beberapa fitur dibandingkan dengan fitur **Emission**, untuk melihat seberapa linear hubungan mereka:
plt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS, color='blue') plt.xlabel("FUELCONSUMPTION_COMB") plt.ylabel("Emission") plt.show() plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue') plt.xlabel("Engine size") plt.ylabel("Emission") plt.show()
_____no_output_____
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
LATIHANCoba tampilkan plot __CYLINDER__ vs the **Emission**, untuk lihat seberapa linera hubungannya:
# Tulis kodingmu di sini
_____no_output_____
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
Klik __2X__ untuk lihat jawaban.<!-- Jawabannya: plt.scatter(cdf.CYLINDERS, cdf.CO2EMISSIONS, color='blue')plt.xlabel("Cylinders")plt.ylabel("Emission")plt.show()--> Training dan test datasetSeperti biasa, untuk menghasilkan model kita harus melakukan split terhadap dataset yang kita punya. Satu bagian sebagai data...
msk = np.random.rand(len(df)) < 0.8 train = cdf[msk] test = cdf[~msk]
_____no_output_____
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
Train data distribution
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue') plt.xlabel("Engine size") plt.ylabel("Emission") plt.show()
_____no_output_____
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
ModelingKita gunakan paket **sklearn** untuk membuat **model data**.
from sklearn import linear_model regr = linear_model.LinearRegression() train_x = np.asanyarray(train[['ENGINESIZE']]) train_y = np.asanyarray(train[['CO2EMISSIONS']]) regr.fit (train_x, train_y) # The coefficients print ('Koefisien: ', regr.coef_) print ('Intersep: ',regr.intercept_)
Koefisien: [[38.85392477]] Intersep: [125.56993994]
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
Silakan baca2 lagi materi Regresi supaya lebih paham apa itu, __Coefficient__ dan __Intercept__. Plot outputsSekarang kita tampilkan garis lurus disepanjang data:
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue') plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r') plt.xlabel("Engine size") plt.ylabel("Emission")
_____no_output_____
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
EvaluationUntuk cek apakah model yang kita buat sudah benar, kita harus lakukan evaluasi dengan melakukan perhitungan akurasi.
from sklearn.metrics import r2_score test_x = np.asanyarray(test[['ENGINESIZE']]) test_y = np.asanyarray(test[['CO2EMISSIONS']]) test_y_ = regr.predict(test_x) print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_ - test_y))) print("R2-score: %.2f" % r2_score(test_y_ , test_y) )
Mean absolute error: 24.59 R2-score: 0.66
Apache-2.0
Regresi_Linear.ipynb
Rivaldop/metodologidatascience
Import the modules we are going to use.
import statsmodels.api as sm import pandas as pd import numpy as np
_____no_output_____
MIT
demos/5-12/logistic_regression_example.ipynb
maetshju/Ling471
Load in our data. **Note that the `display()` function does not work in the default Python console. Calling `display` is equivalent to just typing the variable name and just pressing "Enter" to have Python display the variable.**
X = np.loadtxt('h95_ih_iy_adult_male.txt') display(X[:5, :])
_____no_output_____
MIT
demos/5-12/logistic_regression_example.ipynb
maetshju/Ling471
Extract the different vowel categories from our data set.
iy = np.vstack((X[:,0].T, np.zeros(45))).T ih = np.vstack((X[:,1], np.ones(45))).T display(iy[:5,:]) display(ih[:5,:])
_____no_output_____
MIT
demos/5-12/logistic_regression_example.ipynb
maetshju/Ling471
Stack our two matrices on top of each other vertically and then make a data frame.
vowels = np.vstack((iy, ih)) d = pd.DataFrame({'f1': vowels[:,0], 'vowel':vowels[:,1]}) display(d)
_____no_output_____
MIT
demos/5-12/logistic_regression_example.ipynb
maetshju/Ling471
Add the ones column to the data frame.
d = sm.add_constant(d) display(d)
_____no_output_____
MIT
demos/5-12/logistic_regression_example.ipynb
maetshju/Ling471
Fit the logistic regression and display the results.
m = sm.Logit(d.vowel, d[['const', 'f1']]).fit() m.summary()
Optimization terminated successfully. Current function value: 0.192784 Iterations 9
MIT
demos/5-12/logistic_regression_example.ipynb
maetshju/Ling471
Prepare papermill for schulung3.geomar.de Make sure you have activated the correct kernel Install kernel manually
!python -m ipykernel install --user --name parcels-container_2021.09.29-09ab0ce !jupyter kernelspec list
Available kernels: parcels-container_2021.03.17-6c459b7 /home/jupyter-workshop007/.local/share/jupyter/kernels/parcels-container_2021.03.17-6c459b7 parcels-container_2021.09.29-09ab0ce /home/jupyter-workshop007/.local/share/jupyter/kernels/parcels-container_2021.09.29-09ab0ce py3_lagrange_v2.2.2 ...
MIT
notebooks/exploratory/309_afox_papermill.ipynb
alanfox/spg_fresh_blob_202104
Run papermill on schulung3.geomar.de
%%bash for year in {1990..2019}; do papermill 309_afox_trackendsandpaths_sumsandmeans_nonorth_21_0_final.ipynb \ ../executed/309_afox_fullstats/309_afox_trackendsandpaths_sumsandmeans_nonorth_21_0_final_${year}.ipynb \ -p year $year \ -p nsubsets 32 \ -k parcels-container_2021.09.29-09a...
Input Notebook: 309_afox_trackendsandpaths_sumsandmeans_nonorth_21_0_final.ipynb Output Notebook: ../executed/309_afox_fullstats/309_afox_trackendsandpaths_sumsandmeans_nonorth_21_0_final_1990.ipynb Generating grammar tables from /opt/tljh/user/envs/parcels-container_2021.09.29-09ab0ce/lib/python3.9/site-packages/blib...
MIT
notebooks/exploratory/309_afox_papermill.ipynb
alanfox/spg_fresh_blob_202104
Tutorial Part 10: Exploring Quantum Chemistry with GDB1k Most of the tutorials we've walked you through so far have focused on applications to the drug discovery realm, but DeepChem's tool suite works for molecular design problems generally. In this tutorial, we're going to walk through an example of how to train a si...
!curl -Lo conda_installer.py https://raw.githubusercontent.com/deepchem/deepchem/master/scripts/colab_install.py import conda_installer conda_installer.install() !/root/miniconda/bin/conda info -e !pip install --pre deepchem import deepchem deepchem.__version__
Requirement already satisfied: deepchem in /usr/local/lib/python3.6/dist-packages (2.4.0rc1.dev20200805143010) Requirement already satisfied: scipy in /usr/local/lib/python3.6/dist-packages (from deepchem) (1.4.1) Requirement already satisfied: pandas in /usr/local/lib/python3.6/dist-packages (from deepchem) (1.0.5) Re...
MIT
examples/tutorials/10_Exploring_Quantum_Chemistry_with_GDB1k.ipynb
nihal-rao/deepchem
With our setup in place, let's do a few standard imports to get the ball rolling.
import os import unittest import numpy as np import deepchem as dc import numpy.random from deepchem.utils.evaluate import Evaluator from sklearn.ensemble import RandomForestRegressor from sklearn.kernel_ridge import KernelRidge
_____no_output_____
MIT
examples/tutorials/10_Exploring_Quantum_Chemistry_with_GDB1k.ipynb
nihal-rao/deepchem
The ntext step we want to do is load our dataset. We're using a small dataset we've prepared that's pulled out of the larger GDB benchmarks. The dataset contains the atomization energies for 1K small molecules.
tasks = ["atomization_energy"] dataset_file = "../../datasets/gdb1k.sdf" smiles_field = "smiles" mol_field = "mol"
_____no_output_____
MIT
examples/tutorials/10_Exploring_Quantum_Chemistry_with_GDB1k.ipynb
nihal-rao/deepchem
We now need a way to transform molecules that is useful for prediction of atomization energy. This representation draws on foundational work [1] that represents a molecule's 3D electrostatic structure as a 2D matrix $C$ of distances scaled by charges, where the $ij$-th element is represented by the following charge str...
featurizer = dc.feat.CoulombMatrixEig(23, remove_hydrogens=False)
_____no_output_____
MIT
examples/tutorials/10_Exploring_Quantum_Chemistry_with_GDB1k.ipynb
nihal-rao/deepchem
Note that in this case, we set the maximum number of atoms to $N = 23$. Let's now load our dataset file into DeepChem. As in the previous tutorials, we use a `Loader` class, in particular `dc.data.SDFLoader` to load our `.sdf` file into DeepChem. The following snippet shows how we do this:
# loader = dc.data.SDFLoader( # tasks=["atomization_energy"], smiles_field="smiles", # featurizer=featurizer, # mol_field="mol") # dataset = loader.featurize(dataset_file)
_____no_output_____
MIT
examples/tutorials/10_Exploring_Quantum_Chemistry_with_GDB1k.ipynb
nihal-rao/deepchem
For the purposes of this tutorial, we're going to do a random split of the dataset into training, validation, and test. In general, this split is weak and will considerably overestimate the accuracy of our models, but for now in this simple tutorial isn't a bad place to get started.
# random_splitter = dc.splits.RandomSplitter() # train_dataset, valid_dataset, test_dataset = random_splitter.train_valid_test_split(dataset)
_____no_output_____
MIT
examples/tutorials/10_Exploring_Quantum_Chemistry_with_GDB1k.ipynb
nihal-rao/deepchem
One issue that Coulomb matrix featurizations have is that the range of entries in the matrix $C$ can be large. The charge $q_1q_2/r^2$ term can range very widely. In general, a wide range of values for inputs can throw off learning for the neural network. For this, a common fix is to normalize the input values so that ...
# transformers = [ # dc.trans.NormalizationTransformer(transform_X=True, dataset=train_dataset), # dc.trans.NormalizationTransformer(transform_y=True, dataset=train_dataset)] # for dataset in [train_dataset, valid_dataset, test_dataset]: # for transformer in transformers: # dataset = transformer.transf...
_____no_output_____
MIT
examples/tutorials/10_Exploring_Quantum_Chemistry_with_GDB1k.ipynb
nihal-rao/deepchem
Now that we have the data cleanly transformed, let's do some simple machine learning. We'll start by constructing a random forest on top of the data. We'll use DeepChem's hyperparameter tuning module to do this.
# def rf_model_builder(model_params, model_dir): # sklearn_model = RandomForestRegressor(**model_params) # return dc.models.SklearnModel(sklearn_model, model_dir) # params_dict = { # "n_estimators": [10, 100], # "max_features": ["auto", "sqrt", "log2", None], # } # metric = dc.metrics.Metric(dc.metrics.mea...
_____no_output_____
MIT
examples/tutorials/10_Exploring_Quantum_Chemistry_with_GDB1k.ipynb
nihal-rao/deepchem
Let's build one more model, a kernel ridge regression, on top of this raw data.
# def krr_model_builder(model_params, model_dir): # sklearn_model = KernelRidge(**model_params) # return dc.models.SklearnModel(sklearn_model, model_dir) # params_dict = { # "kernel": ["laplacian"], # "alpha": [0.0001], # "gamma": [0.0001] # } # metric = dc.metrics.Metric(dc.metrics.mean_absolute_erro...
_____no_output_____
MIT
examples/tutorials/10_Exploring_Quantum_Chemistry_with_GDB1k.ipynb
nihal-rao/deepchem
Temperature Forcasting with Jena climate dataset
from google.colab import files files.upload() !mkdir -p ~/.kaggle !cp kaggle.json ~/.kaggle/ !chmod 600 ~/.kaggle/kaggle.json !kaggle datasets download -d kusuri/jena-climate !ls -d $PWD/* !unzip \*.zip && rm *.zip !ls -d $PWD/* file_dir = '/content/jena_climate_2009_2016.csv' import numpy as np import pandas as pd jen...
_____no_output_____
MIT
regression/temperature_forcasting_with_RNN.ipynb
Chiebukar/Deep-Learning
User's Guide, Chapter 46: Streams 3: Manipulation, inPlace, and deepcopy Just getting started here... Replace all consecutive notes of a Stream with intervals while maintaining the hierarchy
import copy def intervalStream(inputStream): out = copy.deepcopy(inputStream) for n in out[note.Note]: nNext = n.next(note.GeneralNote) if nNext is None or not nNext.isNote: continue # Rests, Chords, etc. n.activeSite.replace(n, interval.Interval(n, nNext)) for other in ...
{0.0} <music21.stream.Part Soprano> {0.0} <music21.stream.Measure 0 offset=0.0> {0.0} <music21.interval.Interval M-2> {0.5} <music21.interval.Interval M-2> {1.0} <music21.stream.Measure 1 offset=1.0> {0.0} <music21.interval.Interval M2> {1.0} <music21.interval.Interval M2> ...
MIT
documentation/source/usersGuide/usersGuide_46_streams3.ipynb
cuthbertLab/music21
PPO, Actor-Critic Style_______________________&nbsp;&nbsp;**for** iteration=1,2,... do&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;**for** actor=1,2,...,N do&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Run policy $\pi_{\theta_{old}}$ in environment for T timesteps&nbsp;&nbsp;&nbsp;&nbsp;&...
import gym import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.distributions import Normal from torch.distributions import Categorical import torch.multiprocessing as mp # from torch.utils.tensorboard import SummaryWriter import numpy as np from IPython.display impo...
_____no_output_____
Apache-2.0
algorithm_implement/PPO2/Proximal_Policy_Optimization(PPO2)_continuous.ipynb
sunnyswag/RL_notes_and_codes
多线程又双叒叕来了
def worker(worker_id, master_end, worker_end, env_name): master_end.close() env = gym.make(env_name) env.seed(worker_id) while True: cmd, data = worker_end.recv() if cmd == 'step': state, reward, done, info = env.step(data) if done: state = en...
_____no_output_____
Apache-2.0
algorithm_implement/PPO2/Proximal_Policy_Optimization(PPO2)_continuous.ipynb
sunnyswag/RL_notes_and_codes
定义网络
class Actor_critic(nn.Module): def __init__(self, in_dim, out_dim): super(Actor_critic, self).__init__() self.actor_linear1 = nn.Linear(in_dim, 64) self.critic_linear1 = nn.Linear(in_dim, 64) self.linear2 = nn.Linear(64, 32) self.actor_linear3 = nn.Linear(32, out_dim) ...
_____no_output_____
Apache-2.0
algorithm_implement/PPO2/Proximal_Policy_Optimization(PPO2)_continuous.ipynb
sunnyswag/RL_notes_and_codes
画图
def smooth_plot(factor, item, plot_decay): item_x = np.arange(len(item)) item_smooth = [np.mean(item[i:i+factor]) if i > factor else np.mean(item[0:i+1]) for i in range(len(item))] for i in range(len(item)// plot_decay): item_x = item_x[::2] item_smooth = item_smooth[::2] ...
_____no_output_____
Apache-2.0
algorithm_implement/PPO2/Proximal_Policy_Optimization(PPO2)_continuous.ipynb
sunnyswag/RL_notes_and_codes
PPO训练更新
import pdb def ppo_iter(states, actions, log_probs, advantages, td_target_list): batch_size = actions.size(0) for _ in range(batch_size // mini_batch_size): ids = np.random.choice(batch_size, mini_batch_size, replace=False) yield states[ids, :], actions[ids, :], log_probs[ids, :], advantages[ids...
_____no_output_____
Apache-2.0
algorithm_implement/PPO2/Proximal_Policy_Optimization(PPO2)_continuous.ipynb
sunnyswag/RL_notes_and_codes
Create TensorFlow model This notebook illustrates: Creating a model using the high-level Estimator API
# change these to try this notebook out BUCKET = 'qwiklabs-gcp-37b9fafbd24bf385' PROJECT = 'qwiklabs-gcp-37b9fafbd24bf385' REGION = 'us-central1' import os os.environ['BUCKET'] = BUCKET os.environ['PROJECT'] = PROJECT os.environ['REGION'] = REGION %%bash if ! gsutil ls | grep -q gs://${BUCKET}/; then gsutil mb -l ${R...
_____no_output_____
MIT
week2/3_tensorflow_dnn.ipynb
isacmoura/machine-learning-tf-google-cloud
Create TensorFlow model using TensorFlow's Estimator API First, write an input_fn to read the data. Lab Task 1Verify that the headers match your CSV output
import shutil import numpy as np import tensorflow as tf # Determine CSV, label, and key columns CSV_COLUMNS = 'weight_pounds,is_male,mother_age,plurality,gestation_weeks,key'.split(',') LABEL_COLUMN = 'weight_pounds' KEY_COLUMN = 'key' # Set default values for each CSV column DEFAULTS = [[0.0], ['null'], [0.0], ['nul...
_____no_output_____
MIT
week2/3_tensorflow_dnn.ipynb
isacmoura/machine-learning-tf-google-cloud
Lab Task 2Fill out the details of the input function below
# Create an input function reading a file using the Dataset API # Then provide the results to the Estimator API def read_dataset(filename_pattern, mode, batch_size = 512): def _input_fn(): def decode_csv(line_of_text): # TODO #1: Use tf.decode_csv to parse the provided line columns = tf.decode_csv(lin...
_____no_output_____
MIT
week2/3_tensorflow_dnn.ipynb
isacmoura/machine-learning-tf-google-cloud
Lab Task 3Use the TensorFlow feature column API to define appropriate feature columns for your raw features that come from the CSV. Bonus: Separate your columns into wide columns (categorical, discrete, etc.) and deep columns (numeric, embedding, etc.)
# Define feature columns # Define feature columns def get_categorical(name, values): return tf.feature_column.indicator_column( tf.feature_column.categorical_column_with_vocabulary_list(name, values)) def get_cols(): # Define column types return [\ get_categorical('is_male', ['True', 'False', 'Unkn...
_____no_output_____
MIT
week2/3_tensorflow_dnn.ipynb
isacmoura/machine-learning-tf-google-cloud
Lab Task 4To predict with the TensorFlow model, we also need a serving input function (we'll use this in a later lab). We will want all the inputs from our user.Verify and change the column names and types here as appropriate. These should match your CSV_COLUMNS
# Create serving input function to be able to serve predictions later using provided inputs def serving_input_fn(): feature_placeholders = { 'is_male': tf.placeholder(tf.string, [None]), 'mother_age': tf.placeholder(tf.float32, [None]), 'plurality': tf.placeholder(tf.string, [None]), ...
_____no_output_____
MIT
week2/3_tensorflow_dnn.ipynb
isacmoura/machine-learning-tf-google-cloud
Lab Task 5Complete the TODOs in this code:
# Create estimator to train and evaluate def train_and_evaluate(output_dir): EVAL_INTERVAL = 300 run_config = tf.estimator.RunConfig(save_checkpoints_secs = EVAL_INTERVAL, keep_checkpoint_max = 3) # TODO #1: Create your estimator estimator = tf.estimator.DNNRegressor( ...
_____no_output_____
MIT
week2/3_tensorflow_dnn.ipynb
isacmoura/machine-learning-tf-google-cloud
Finally, train!
# Run the model shutil.rmtree('babyweight_trained', ignore_errors = True) # start fresh each time train_and_evaluate('babyweight_trained')
INFO:tensorflow:Using config: {'_num_worker_replicas': 1, '_save_summary_steps': 100, '_model_dir': 'babyweight_trained', '_keep_checkpoint_every_n_hours': 10000, '_is_chief': True, '_evaluation_master': '', '_keep_checkpoint_max': 3, '_task_id': 0, '_global_id_in_cluster': 0, '_train_distribute': None, '_task_type': '...
MIT
week2/3_tensorflow_dnn.ipynb
isacmoura/machine-learning-tf-google-cloud
When I ran it, the final lines of the output (above) were:INFO:tensorflow:Saving dict for global step 1000: average_loss = 1.2693067, global_step = 1000, loss = 635.9226INFO:tensorflow:Restoring parameters from babyweight_trained/model.ckpt-1000INFO:tensorflow:Assets added to graph.INFO:tensorflow:No assets to write.IN...
from google.datalab.ml import TensorBoard TensorBoard().start('./babyweight_trained') for pid in TensorBoard.list()['pid']: TensorBoard().stop(pid) print('Stopped TensorBoard with pid {}'.format(pid))
Stopped TensorBoard with pid 3769
MIT
week2/3_tensorflow_dnn.ipynb
isacmoura/machine-learning-tf-google-cloud
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/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
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/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Precio del activo subyacente
aapl_opt.Underlying_Price[0]
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
Datos de la opción
aapl_opt.loc[0, 'JSON']
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
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/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
o en que fecha expiran
pd.set_option('display.max_rows', 10) aapl_opt.loc[:, 'Expiry']
_____no_output_____
MIT
TEMA-3/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I
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/Clase22_ValuacionOpciones.ipynb
AndresHdzJmz/SPF-2021-I