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 |
|---|---|---|---|---|---|
Create Docker Image with the S2i utilityUsing the S2I command line interface we wrap our current model to seve it through the Seldon interface | # To create a docker image we need to create the .s2i folder configuration as below:
!cat .s2i/environment
# As well as a requirements.txt file with all the relevant dependencies
!cat requirements.txt
!s2i build . seldonio/seldon-core-s2i-python3:0.11 reddit-classifier:0.1 | ---> Installing application source...
---> Installing dependencies ...
Looking in links: /whl
Collecting scipy>=0.13.3 (from -r requirements.txt (line 1))
WARNING: Url '/whl' is ignored. It is either a non-existing path or lacks a specific scheme.
Downloading https://files.pythonhosted.org/packages/72/4c/5f81e7264b0a... | Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
3) Test your model as a docker container | # Remove previously deployed containers for this model
!docker rm -f reddit_predictor
!docker run --name "reddit_predictor" -d --rm -p 5001:5000 reddit-classifier:0.1 | be29c6a00adec0f708dc5a1c83613e0656fddc06daba4ca02d93b5a7ece9b92b
| Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
Make sure you wait for language modelSpaCy will download the English language model, so you have to make sure the container finishes downloading it before it can be used. You can view this by running the logs until you see "Linking successful". | # Here we need to wait until we see "Linking successful", as it's downloading the Spacy English model
# You can hit stop when this happens
!docker logs -t -f reddit_predictor
# We now test the REST endpoint expecting the same result
endpoint = "0.0.0.0:5001"
batch = sample
payload_type = "ndarray"
sc = SeldonClient(mi... | reddit_predictor
| Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
4) Run Seldon in your kubernetes clusterIn order to run Seldon we need to make sure that Helm is initialised and Tiller is running. For this we can run the following initialisation and waiting commands. | # If not running you can install it
# First initialise helm
!kubectl create clusterrolebinding kube-system-cluster-admin --clusterrole=cluster-admin --serviceaccount=kube-system:default
!helm init
!kubectl rollout status deploy/tiller-deploy -n kube-system | clusterrolebinding.rbac.authorization.k8s.io/kube-system-cluster-admin created
$HELM_HOME has been configured at /home/alejandro/.helm.
Warning: Tiller is already installed in the cluster.
(Use --client-only to suppress this message, or --upgrade to upgrade Tiller to the current version.)
Happy Helming!
deployment "til... | Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
Now we can install run the Seldon Operator using the latest Helm charts | !helm install seldon-core-operator --name seldon-core-operator --repo https://storage.googleapis.com/seldon-charts | NAME: seldon-core-operator
LAST DEPLOYED: Mon May 27 15:04:30 2019
NAMESPACE: default
STATUS: DEPLOYED
RESOURCES:
==> v1/ClusterRole
NAME AGE
seldon-operator-manager-role 0s
==> v1/ClusterRoleBinding
NAME AGE
seldon-operator-manager-rolebinding 0s
==> v1/P... | Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
And we can make sure that it is actually running with the following command | !kubectl get pod | grep seldon | seldon-operator-controller-manager-0 1/1 Running 1 12s
| Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
In order for us to be able to reach the model, we will need to set up an ingress. For this we will use ambassador: | !helm install stable/ambassador --name ambassador --set crds.keep=false | NAME: ambassador
LAST DEPLOYED: Mon May 27 15:04:50 2019
NAMESPACE: default
STATUS: DEPLOYED
RESOURCES:
==> v1/Deployment
NAME READY UP-TO-DATE AVAILABLE AGE
ambassador 0/3 3 0 0s
==> v1/Pod(related)
NAME READY STATUS RESTARTS AGE
ambassador-7bf... | Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
We can now see the ambassador service is running. In our case we can reach it through the external IP which is our localhost, but if you are using a cloud provider, make sure you have access to the ambassador endpoint. | !kubectl get svc ambassador | NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
ambassador LoadBalancer 10.101.89.32 localhost 80:30004/TCP,443:31350/TCP 2m43s
| Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
5) Deploy your model with SeldonWe can now deploy our model by using the Seldon graph definition: | # We'll use our seldon deployment file
!cat reddit_clf.json
!kubectl apply -f reddit_clf.json
!kubectl get pods | NAME READY STATUS RESTARTS AGE
ambassador-7bfc87f865-jkxs8 1/1 Running 0 5m2s
ambassador-7bfc87f865-nr7bn 1/1 Running 0 5m2s
ambassador-7bfc87f865-q4lng ... | Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
6) Interact with your model through APINow that our Seldon Deployment is live, we are able to interact with it through its API.There are two options in which we can interact with our new model. These are:a) Using CURL from the CLI (or another rest client like Postman)b) Using the Python SeldonClient a) Using CURL from... | %%bash
curl -X POST -H 'Content-Type: application/json' \
-d "{'data': {'names': ['text'], 'ndarray': ['Hello world this is a test']}}" \
http://127.0.0.1/seldon/default/reddit-classifier/api/v0.1/predictions | {
"meta": {
"puid": "bvj1rjiq3vvnieo0oir4h7bf6f",
"tags": {
},
"routing": {
},
"requestPath": {
"classifier": "reddit-classifier:0.1"
},
"metrics": []
},
"data": {
"names": ["t:0", "t:1"],
"ndarray": [[0.6815614604065544, 0.3184385395934456]]
}
} | Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
b) Using the Python SeldonClient | from seldon_core.seldon_client import SeldonClient
import numpy as np
host = "localhost"
port = "80" # Make sure you use the port above
batch = np.array(["Hello world this is a test"])
payload_type = "ndarray"
deployment_name="reddit-classifier"
transport="rest"
namespace="default"
sc = SeldonClient(
gateway="amb... | Success:True message:
Request:
data {
names: "text"
ndarray {
values {
string_value: "Hello world this is a test"
}
}
}
Response:
meta {
puid: "uld2famhfrb97vd7regu0q7k32"
requestPath {
key: "classifier"
value: "reddit-classifier:0.1"
}
}
data {
names: "t:0"
names: "t:1"
ndarray... | Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
7) Clean your environment | !kubectl delete -f reddit_clf.json
!helm del --purge ambassador
!helm del --purge seldon-core-operator | release "seldon-core-operator" deleted
| Apache-2.0 | examples/models/sklearn_spacy_text/sklearn_spacy_text_classifier_example.ipynb | markusgay/seldon-core |
Image segmentation with CamVid | %reload_ext autoreload
%autoreload 2
%matplotlib inline
from fastai import *
from fastai.vision import *
from fastai.callbacks.hooks import * | _____no_output_____ | Apache-2.0 | Image-Segmentation/lesson3-camvid-tiramisu.ipynb | dustinvanstee/aicoc-ai-immersion |
The One Hundred Layer Tiramisu paper used a modified version of Camvid, with smaller images and few classes. You can get it from the CamVid directory of this repo: git clone https://github.com/alexgkendall/SegNet-Tutorial.git | path = Path('./data/camvid-tiramisu')
path.ls() | _____no_output_____ | Apache-2.0 | Image-Segmentation/lesson3-camvid-tiramisu.ipynb | dustinvanstee/aicoc-ai-immersion |
Data | fnames = get_image_files(path/'val')
fnames[:3]
lbl_names = get_image_files(path/'valannot')
lbl_names[:3]
img_f = fnames[0]
img = open_image(img_f)
img.show(figsize=(5,5))
def get_y_fn(x): return Path(str(x.parent)+'annot')/x.name
codes = array(['Sky', 'Building', 'Pole', 'Road', 'Sidewalk', 'Tree',
'Sign', 'Fenc... | _____no_output_____ | Apache-2.0 | Image-Segmentation/lesson3-camvid-tiramisu.ipynb | dustinvanstee/aicoc-ai-immersion |
Datasets | bs = 8
src = (SegmentationItemList.from_folder(path)
.split_by_folder(valid='val')
.label_from_func(get_y_fn, classes=codes))
data = (src.transform(get_transforms(), tfm_y=True)
.databunch(bs=bs)
.normalize(imagenet_stats))
data.show_batch(2, figsize=(10,7)) | _____no_output_____ | Apache-2.0 | Image-Segmentation/lesson3-camvid-tiramisu.ipynb | dustinvanstee/aicoc-ai-immersion |
Model | name2id = {v:k for k,v in enumerate(codes)}
void_code = name2id['Void']
def acc_camvid(input, target):
target = target.squeeze(1)
mask = target != void_code
return (input.argmax(dim=1)[mask]==target[mask]).float().mean()
metrics=acc_camvid
wd=1e-2
learn = unet_learner(data, models.resnet34, metrics=metrics... | _____no_output_____ | Apache-2.0 | Image-Segmentation/lesson3-camvid-tiramisu.ipynb | dustinvanstee/aicoc-ai-immersion |
Go big | learn=None
gc.collect() | _____no_output_____ | Apache-2.0 | Image-Segmentation/lesson3-camvid-tiramisu.ipynb | dustinvanstee/aicoc-ai-immersion |
You may have to restart your kernel and come back to this stage if you run out of memory, and may also need to decrease `bs`. | size = src_size
bs=8
data = (src.transform(get_transforms(), size=size, tfm_y=True)
.databunch(bs=bs)
.normalize(imagenet_stats))
learn = unet_learner(data, models.resnet34, metrics=metrics, wd=wd, bottle=True).load('stage-2');
lr_find(learn)
learn.recorder.plot()
lr=1e-3
learn.fit_one_cycle(10, slice(l... | _____no_output_____ | Apache-2.0 | Image-Segmentation/lesson3-camvid-tiramisu.ipynb | dustinvanstee/aicoc-ai-immersion |
fin | # start: 480x360
print(learn.summary()) | _____no_output_____ | Apache-2.0 | Image-Segmentation/lesson3-camvid-tiramisu.ipynb | dustinvanstee/aicoc-ai-immersion |
Laboratorio 2cumplir con cada uno de los 9 retos en sus grupos de trabajoy subir el Colab a el repositorio de un seleccionado,for: 30/05/2022 12:59 1. Define a procedure histogram () that takes a list of whole numbers and prints a histogram on the screen. Example: procedure ([4, 9, 7]) should print the following:*****... | def histogram(lista):
for i in lista:
if i != lista[0]:
print((i-lista[0])*'*')
else:
print(lista[0]*'*')
histogram([4,9,7])
# profe esto fue lo que yo entendi ya que en el ejemplo lo mostraba de esa forma,
# si se puede corregir lo corrijo, gracias!! | ****
*****
***
| MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
2. Write a longer_long () function that takes a list of words and returns the longest. | def longer_long(lista):
la_mas_larga = 0
index_del_mas_largo = 0
for i in list(enumerate(lista)):
if len(i[1]) > la_mas_larga:
la_mas_larga = len(i[1])
index_del_mas_largo = i[0]
print(lista[index_del_mas_largo])
longer_long(['uno', 'dos', 'tres', 'larga', 'cuatro', 'demasiado', 'cin... | demasiado
| MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
3. Write a program that tells the user to enter a string. The program has to evaluate the string and say how many capital letters it has. | def filt_words(string):
num_of_capital = 0
for i in string:
if i.isupper() == True:
num_of_capital = num_of_capital + 1
return f'This string have {num_of_capital} capital letters'
filt_words(str(input('Write a string for be processed: ')))
| Write a string for be processed: Hola mundo
| MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
4.Build a small program that converts binary numbers to integers. Example::
num_deci = 0
for position, digit_string in enumerate(num_bin[::-1]):
num_deci += int(digit_string) * 2 ** position
return num_deci
print(aDecimal('01110')) | 14
| MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
5.Create a function count_vols (), which receives a word and counts how many letters "a" it has, how many letters "e" it has, and so on until all the vowels are completed.You can make the user who chooses the word.only in lower letters | def contar_vocales(cadena):
dicc = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
n = 1
for i in cadena:
for x in dicc.keys():
if i.lower() == x and i.lower() in dicc and dicc[x] != 0:
dicc[x] = dicc.get(x) + 1
elif i.lower() == x:
dicc[x] = 1
... | vocal ___ cantidad
a | 4
e | 0
i | 2
o | 1
u | 1
| MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
6.Write a function is leap () that determines if a given year is a leap year A leap year is divisible by 4, but not by 100. It is also divisible by 400 | agno = int(input())
if (agno % 4 == 0 and agno % 100 != 0) or (agno % 100 == 0 and agno % 400 == 0):
print("Es un año bisiesto")
elif agno % 100 == 0 and agno % 400 != 0:
print("No es un año bisiesto")
else:
print("No es un año bisiesto") | 2040
Es un año bisiesto
| MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
7. Write a program that asks for two words and tells whether or not they rhyme. If the last three letters match, you have to say that they rhyme. If only the last two coincide, he has to say that they rhyme a bit and if not, that they do not rhyme.Example::
if uno[-1] == dos[-1] and uno[-2] == dos[-2] and uno[-3] == dos[-3]:
return 'Riman'
elif uno[-1] == dos[-1] and uno[-2] == dos[-2]:
return 'Riman un poco'
else:
return 'No riman'
print(rim('accion', 'pretencion'))
print(rim('venta', 'pretencion'))
print(rim('algoritmo', 'acerrimo'))
| Riman
No riman
Riman un poco
| MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
8.It has a program that asks the user for a dollar amount, an interest rate, and a number of years. It shows on the screen how much the initial capital will have been converted after those years if the interest rate entered is applied each year.Remember that a capital C dollars at an interest of x percent for n years b... | def calculo(dinero, inte, cant_anos):
resultado = dinero * (1 + inte / 100)**cant_anos
print(f'los intereses de sus {dinero} USD$ a {cant_anos} años son {resultado:.2f} USD$')
calculo(10000, 4.5, 20) | los intereses de sus 10000 USD$ a 20 años son 24117.14 USD$
| MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
9. Create an algorithm that generates 10 files iteratively, call this files 'tabla_del_n.txt' been n the (0 to 9) numbers with the multiplication tables from (0 to 9)following the format::
for i in range(10):
archivo = open(f'/content/drive/MyDrive/tabla_del_{i}.txt', 'w')
archivo.write(f'Tabla del {i}')
for x in range(10):
archivo.write(f'\n{i} x {x} = {i*x}')
tablas()
| _____no_output_____ | MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
On the same file system, make an algorithm that asks the user for a number n and a number m, so that it shows the user of the file table_del_n.txt, the multiplication 'm'. | def tabla_request(n,m):
archivo = open(f'/content/drive/MyDrive/tabla_del_{n}.txt', 'r')
linea = archivo.readlines()
print(linea[m+1])
tabla_request(6,6) | 6 x 6 = 36
| MIT | lab2_grupo4.ipynb | StifhBarrage/Porgramacion_2022-hbarraganl |
Copyright 2018 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
Image Classification using tf.keras Run in Google Colab View source on GitHub In this Colab you will classify images of flowers. You will build an image classifier using `tf.keras.Sequential` model and load data using `tf.keras.preprocessing.image.ImageDataGenerator`. Importing Packages Let's start by ... | import os
import numpy as np
import glob
import shutil
import matplotlib.pyplot as plt | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Import TensorFlow and Keras LayersIn the cell below, import Tensorflow and the Keras layers and models you will use to build your CNN. Also, import the `ImageDataGenerator` from Keras so that you can perform image augmentation. | import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from tensorflow.keras.preprocessing.image import ImageDataGenerator | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
Data Loading In order to build our image classifier, we can begin by downloading the flowers dataset. We first need to download the archive version of the dataset and after the download we are storing it to "/tmp/" directory. After downloading the dataset, we need to extract its contents. | _URL = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
zip_file = tf.keras.utils.get_file(origin=_URL,
fname="flower_photos.tgz",
extract=True)
base_dir = os.path.join(os.path.dirname(zip_file), 'flower_pho... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
The dataset we downloaded contains images of 5 types of flowers:1. Rose2. Daisy3. Dandelion4. Sunflowers5. TulipsSo, let's create the labels for these 5 classes: | classes = ['roses', 'daisy', 'dandelion', 'sunflowers', 'tulips'] | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
Also, the dataset we have downloaded has following directory structure. nflower_photos|__ daisy|__ dandelion|__ roses|__ sunflowers|__ tulipsAs you can see there are no folders containing training and validation data. Therefore, we will have to create our own training and validation set. Let's write some code that will... | for cl in classes:
img_path = os.path.join(base_dir, cl)
images = glob.glob(img_path + '/*.jpg')
print("{}: {} Images".format(cl, len(images)))
num_train = int(round(len(images)*0.8))
train, val = images[:num_train], images[num_train:]
for t in train:
if not os.path.exists(os.path.join(base_dir, 'train... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
For convenience, let us set up the path for the training and validation sets | train_dir = os.path.join(base_dir, 'train')
val_dir = os.path.join(base_dir, 'val') | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
Data Augmentation Overfitting generally occurs when we have small number of training examples. One way to fix this problem is to augment our dataset so that it has sufficient number of training examples. Data augmentation takes the approach of generating more training data from existing training samples, by augmenting... | batch_size = 100
IMG_SHAPE = 150 | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Apply Random Horizontal FlipIn the cell below, use ImageDataGenerator to create a transformation that rescales the images by 255 and then applies a random horizontal flip. Then use the `.flow_from_directory` method to apply the above transformation to the images in our training set. Make sure you indicate the ba... | image_gen = ImageDataGenerator(rescale=1./255, horizontal_flip=True)
train_data_gen = image_gen.flow_from_directory(
batch_size=batch_size,
directory=train_dir,
shuffle=True,
... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
Let's take 1 sample image from our training examples and repeat it 5 times so that the augmentation can be applied to the same image 5 times over randomly, to see the augmentation in action. | # This function will plot images in the form of a grid with 1 row and 5 columns where images are placed in each column.
def plotImages(images_arr):
fig, axes = plt.subplots(1, 5, figsize=(20,20))
axes = axes.flatten()
for img, ax in zip( images_arr, axes):
ax.imshow(img)
plt.tight_layout()
p... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Apply Random RotationIn the cell below, use ImageDataGenerator to create a transformation that rescales the images by 255 and then applies a random 45 degree rotation. Then use the `.flow_from_directory` method to apply the above transformation to the images in our training set. Make sure you indicate the batch ... | image_gen = ImageDataGenerator(rescale=1./255, rotation_range=45)
train_data_gen = image_gen.flow_from_directory(batch_size=batch_size,
directory=train_dir,
shuffle=True,
target_... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
Let's take 1 sample image from our training examples and repeat it 5 times so that the augmentation can be applied to the same image 5 times over randomly, to see the augmentation in action. | augmented_images = [train_data_gen[0][0][0] for i in range(5)]
plotImages(augmented_images) | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Apply Random ZoomIn the cell below, use ImageDataGenerator to create a transformation that rescales the images by 255 and then applies a random zoom of up to 50%. Then use the `.flow_from_directory` method to apply the above transformation to the images in our training set. Make sure you indicate the batch size,... | image_gen = ImageDataGenerator(rescale=1./255, zoom_range=0.5)
train_data_gen = image_gen.flow_from_directory(
batch_size=batch_size,
directory=train_dir,
shuffle=True,
... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
Let's take 1 sample image from our training examples and repeat it 5 times so that the augmentation can be applied to the same image 5 times over randomly, to see the augmentation in action. | augmented_images = [train_data_gen[0][0][0] for i in range(5)]
plotImages(augmented_images) | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Put It All TogetherIn the cell below, use ImageDataGenerator to create a transformation that rescales the images by 255 and that applies:- random 45 degree rotation- random zoom of up to 50%- random horizontal flip- width shift of 0.15- height shift of 0.15Then use the `.flow_from_directory` method to apply the ... | image_gen_train = ImageDataGenerator(
rescale=1./255,
rotation_range=45,
width_shift_range=.15,
height_shift_range=.15,
horizontal_flip=True,
zoom_range=0.5
)
train_data_gen = im... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
Let's visualize how a single image would look like 5 different times, when we pass these augmentations randomly to our dataset. | augmented_images = [train_data_gen[0][0][0] for i in range(5)]
plotImages(augmented_images) | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Create a Data Generator for the Validation SetGenerally, we only apply data augmentation to our training examples. So, in the cell below, use ImageDataGenerator to create a transformation that only rescales the images by 255. Then use the `.flow_from_directory` method to apply the above transformation to the ima... | image_gen_val = ImageDataGenerator(rescale=1./255)
val_data_gen = image_gen_val.flow_from_directory(batch_size=batch_size,
directory=val_dir,
target_size=(IMG_SHAPE, IMG_SHAPE),
... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Create the CNNIn the cell below, create a convolutional neural network that consists of 3 convolution blocks. Each convolutional block contains a `Conv2D` layer followed by a max pool layer. The first convolutional block should have 16 filters, the second one should have 32 filters, and the third one should have... | model = Sequential()
model.add(Conv2D(16, 3, padding='same', activation='relu', input_shape=(IMG_SHAPE,IMG_SHAPE, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(32, 3, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, 3, padding='same', activation='re... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Compile the ModelIn the cell below, compile your model using the ADAM optimizer, the sparse cross entropy function as a loss function. We would also like to look at training and validation accuracy on each epoch as we train our network, so make sure you also pass the metrics argument. | model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy']) | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Train the ModelIn the cell below, train your model using the **fit_generator** function instead of the usual **fit** function. We have to use the `fit_generator` function because we are using the **ImageDataGenerator** class to generate batches of training and validation data for our model. Train the model for 8... | epochs = 80
history = model.fit_generator(
train_data_gen,
steps_per_epoch=int(np.ceil(train_data_gen.n / float(batch_size))),
epochs=epochs,
validation_data=val_data_gen,
validation_steps=int(np.ceil(val_data_gen.n / float(batch_size)))
) | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
TODO: Plot Training and Validation Graphs.In the cell below, plot the training and validation accuracy/loss graphs. | acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(epochs)
plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='... | _____no_output_____ | Apache-2.0 | courses/udacity_intro_to_tensorflow_for_deep_learning/l05c04_exercise_flowers_with_data_augmentation_solution.ipynb | riyaj5246/skin-cancer-with-tflite |
Equilibrium analysis Chemical reactionNumber (code) of assignment: 2N4Description of activity:Report on behalf of:name : Pieter van Halemstudent number : 4597591name : Dennis Danestudent number :4592239Data of student taking the role of contact person:name :email address : | import numpy as np
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Computerprogrameren TUDelft/Practicum nummeriek/Deel 1/Phase 2 practicum 1 v4 (einde dag 31-5-2017).ipynb | Pietervanhalem/Pieters-Personal-Repository |
Function definitons:In the following block the function that are used for the numerical analysis are definend. These are functions for calculation the various time steps, functions for plotting tables ands functions for plotting graphs. | def f(t,y,a,b,i):
if (t>round(i,2)):
a = 0
du = a-(b+1)*y[0,0]+y[0,0]**2*y[0,1]
dv = b*y[0,0]-y[0,0]**2*y[0,1]
return np.matrix([du,dv])
def FE(t,y,h,a,b,i):
f1 = f(t,y,a,b,i)
pred = y + f1*h
corr = y + (h/2)*(f(t,pred,a,b,i) + f1)
return corr
def Integrate(y0, t0, tend, N,... | _____no_output_____ | MIT | Computerprogrameren TUDelft/Practicum nummeriek/Deel 1/Phase 2 practicum 1 v4 (einde dag 31-5-2017).ipynb | Pietervanhalem/Pieters-Personal-Repository |
Assignment 2.9Integrate the system with Modified Euler and time step h = 0.15. Make a table of u and v on the time interval 0 ≤ t ≤ 1.5. The table needs to give u and v in an 8-digit floating-point format. | y0 = np.matrix([0.0,0.0])
t0 = 0.0
tend = 1.5
N = 10
t_array, w_array = Integrate(y0, t0, tend, N,2,4.5,11)
print("The integrated system using Modified Euler with time step h = 0.15 is shown in the following table: \n")
PrintTable(t_array, w_array)
| The integrated system using Modified Euler with time step h = 0.15 is shown in the following table:
index t: u(t) v(t)
0 0.00: 0.0000000e+00 0.0000000e+00
1 0.15: 1.7625000e-01 1.0125000e-01
2 0.30: 2.6892423e-01 2.7050835e-01
3 0.45:... | MIT | Computerprogrameren TUDelft/Practicum nummeriek/Deel 1/Phase 2 practicum 1 v4 (einde dag 31-5-2017).ipynb | Pietervanhalem/Pieters-Personal-Repository |
Assignmet 2.10Integrate the system with Modified Euler and time step h = 0.05 for the interval [0,20]. Make plots of u and v as functions of t (put them in one figure). Also make a plot of u and v in the phase plane (u,v-plane). Do your plots correspond to your results of part 2? | y0 = np.matrix([0.0,0.0])
t0 = 0.0
tend = 20
N = 400
t_array, w_array = Integrate(y0, t0, tend, N,2,4.5, 25)
print("In this assignment the system has to be integrated using Modified Euler with a time step of h = 0.05 on \na interval of [0,20].")
print("The first graph is u(t) and v(t) against time (t).")
PlotGraphs(t... | In this assignment the system has to be integrated using Modified Euler with a time step of h = 0.05 on
a interval of [0,20].
The first graph is u(t) and v(t) against time (t).
| MIT | Computerprogrameren TUDelft/Practicum nummeriek/Deel 1/Phase 2 practicum 1 v4 (einde dag 31-5-2017).ipynb | Pietervanhalem/Pieters-Personal-Repository |
Assignment 2.11Using the formula derived in question 7, estimate the accuracy of u and v computed with h = 0.05 at t = 8. Hence, integrate once more with time step h = 0.1. The error can be estimated with Richardsons methode. were we use α = 1/3 found in assignment 7. here the estimated error is: E ≈ α( w(h) - w(2h) )... | y0 = np.matrix([0.0,0.0])
t0 = 0.0
tend = 20
N = 400
t_array, w_array = Integrate(y0, t0, tend, N, 2, 4.5,25)
y0 = np.matrix([0.0,0.0])
t0 = 0.0
tend = 20
N = 200
t_array2, w_array2 = Integrate(y0, t0, tend, N, 2, 4.5, 25)
print("The value for u and v at t = 8 with h = 0.05 is:",t_array[160], w_array[:,160])
print(... | The estimated acuracy for u is: 0.0035890365757
The estimated acuracy for v is: -0.00396565753436
| MIT | Computerprogrameren TUDelft/Practicum nummeriek/Deel 1/Phase 2 practicum 1 v4 (einde dag 31-5-2017).ipynb | Pietervanhalem/Pieters-Personal-Repository |
Assignment 2.12Apply Modified Euler with h = 0.05. For 0 ≤ t ≤ t1 it holds that a = 2. At t = t1 the supply of materials A fails, and therefore a = 0 for t > t1. Take t1 = 4.0. Make plot of u and v as a function of t on the intervals [0, 10] in one figure and a plot of u and v in the uv-plane. Evaluate your results by... | y0 = np.matrix([0.0,0.0])
t0 = 0.0
tend = 10.0
N = 200
t_array, w_array = Integrate(y0, t0, tend, N, 2, 4.5, 4)
PlotGraphs(t_array, w_array) | _____no_output_____ | MIT | Computerprogrameren TUDelft/Practicum nummeriek/Deel 1/Phase 2 practicum 1 v4 (einde dag 31-5-2017).ipynb | Pietervanhalem/Pieters-Personal-Repository |
The first plot shows that u and v indeed converges to a certain value, as predicted in assignment 8. The phase plane shows that uv goes to a point on the u-axis. This was as well predicted in assignment 8.The first plot shows a corner in the u and v graph (a discontinuity in the first derivative). This does not contrad... | for i in np.arange(3.0,6.5,0.50):
t0 = 0.0
tend = 10.0
N = 200
t_array2, w_array2 = Integrate(y0, t0, tend, N, 2.0, 4.5,i)
indices = np.nonzero(w_array2[0,:] >= 0.01)
index = np.max(indices[0])
t_tilde = t_array2[index+1]
v_tilde = w_array2[1,N]
if i == 3:
print("%6s %17s: %... | t1 t_tilde: v_tilde
3.00 3.95 4.6881922e+00
3.50 4.60 5.2621261e+00
4.00 6.20 3.1598768e+00
4.50 6.30 3.0999928e+00
5.00 6.60 3.1165068e+00
5.50 6.95 3.1994637e+00
6.00 ... | MIT | Computerprogrameren TUDelft/Practicum nummeriek/Deel 1/Phase 2 practicum 1 v4 (einde dag 31-5-2017).ipynb | Pietervanhalem/Pieters-Personal-Repository |
Creating a simple PDE model In the [previous notebook](./1-an-ode-model.ipynb) we show how to create, discretise and solve an ODE model in pybamm. In this notebook we show how to create and solve a PDE problem, which will require meshing of the spatial domain.As an example, we consider the problem of linear diffusion ... | %pip install pybamm -q # install PyBaMM if it is not installed
import pybamm
import numpy as np
import matplotlib.pyplot as plt | Note: you may need to restart the kernel to use updated packages.
| BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
Setting up the model As in the previous example, we start with a `pybamm.BaseModel` object and define our model variables. Since we are now solving a PDE we need to tell pybamm the domain each variable belongs to so that it can be discretised in space in the correct way. This is done by passing the keyword argument `d... | model = pybamm.BaseModel()
c = pybamm.Variable("Concentration", domain="negative particle") | _____no_output_____ | BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
Note that we have given our variable the (useful) name "Concentration", but the symbol representing this variable is simply `c`. We then state out governing equations. Sometime it is useful to define intermediate quantities in order to express the governing equations more easily. In this example we define the flux, the... | N = -pybamm.grad(c) # define the flux
dcdt = -pybamm.div(N) # define the rhs equation
model.rhs = {c: dcdt} # add the equation to rhs dictionary | _____no_output_____ | BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
Unlike ODE models, PDE models require both initial and boundary conditions. Similar to initial conditions, boundary conditions can be added using the dictionary `model.boundary_conditions`. Boundary conditions for each variable are provided as a dictionary of the form `{side: (value, type)`, where, in 1D, side can be "... | # initial conditions
model.initial_conditions = {c: pybamm.Scalar(1)}
# boundary conditions
lbc = pybamm.Scalar(0)
rbc = pybamm.Scalar(2)
model.boundary_conditions = {c: {"left": (lbc, "Neumann"), "right": (rbc, "Neumann")}} | _____no_output_____ | BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
Note that in our example the boundary conditions take constant values, but the value can be any valid pybamm expression.Finally, we add any variables of interest to the dictionary `model.variables` | model.variables = {"Concentration": c, "Flux": N} | _____no_output_____ | BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
Using the model Now the model is now completely defined all that remains is to discretise and solve. Since this model is a PDE we need to define the geometry on which it will be solved, and choose how to mesh the geometry and discretise in space. Defining a geometry and meshWe can define spatial variables in a simila... | # define geometry
r = pybamm.SpatialVariable(
"r", domain=["negative particle"], coord_sys="spherical polar"
)
geometry = {"negative particle": {r: {"min": pybamm.Scalar(0), "max": pybamm.Scalar(1)}}} | _____no_output_____ | BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
We then create a mesh using the `pybamm.MeshGenerator` class. As inputs this class takes the type of mesh and any parameters required by the mesh. In this case we choose a uniform one-dimensional mesh which doesn't require any parameters. | # mesh and discretise
submesh_types = {"negative particle": pybamm.MeshGenerator(pybamm.Uniform1DSubMesh)}
var_pts = {r: 20}
mesh = pybamm.Mesh(geometry, submesh_types, var_pts) | _____no_output_____ | BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
Example of meshes that do require parameters include the `pybamm.Exponential1DSubMesh` which clusters points close to one or both boundaries using an exponential rule. It takes a parameter which sets how closely the points are clustered together, and also lets the users select the side on which more points should be cl... | spatial_methods = {"negative particle": pybamm.FiniteVolume()}
disc = pybamm.Discretisation(mesh, spatial_methods)
disc.process_model(model); | _____no_output_____ | BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
Now that the model has been discretised we are ready to solve. Solving the model As before, we choose a solver and times at which we want the solution returned. We then solve, extract the variables we are interested in, and plot the result. | # solve
solver = pybamm.ScipySolver()
t = np.linspace(0, 1, 100)
solution = solver.solve(model, t)
# post-process, so that the solution can be called at any time t or space r
# (using interpolation)
c = solution["Concentration"]
# plot
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(13, 4))
ax1.plot(solution.t, c(solu... | 2021-01-24 19:28:37,091 - [WARNING] processed_variable.get_spatial_scale(518): No length scale set for negative particle. Using default of 1 [m].
| BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
In the [next notebook](./3-negative-particle-problem.ipynb) we build on the example here to to solve the problem of diffusion in the negative electrode particle within the single particle model. In doing so we will also cover how to include parameters in a model. ReferencesThe relevant papers for this notebook are: | pybamm.print_citations() | [1] Joel A. E. Andersson, Joris Gillis, Greg Horn, James B. Rawlings, and Moritz Diehl. CasADi – A software framework for nonlinear optimization and optimal control. Mathematical Programming Computation, 11(1):1–36, 2019. doi:10.1007/s12532-018-0139-4.
[2] Charles R. Harris, K. Jarrod Millman, Stéfan J. van der Walt, R... | BSD-3-Clause | examples/notebooks/Creating Models/2-a-pde-model.ipynb | YannickNoelStephanKuhn/PyBaMM |
Writing FunctionsThis lecture discusses the mechanics of writing functions and how to encapsulate scripts as functions. | # Example: We're going to use Pandas dataframes to create a gradebook for this course
import pandas as pd
# Student Rosters:
students = ['Hao', 'Jennifer', 'Alex']
# Gradebook columns:
columns = ['raw_grade', 'did_extra_credit', 'final_grade']
# Let's create two dataframes, one for each class section
gradebook = pd... | Gradebook:
raw_grade did_extra_credit final_grade
Hao 80 True NaN
Jennifer 98 False NaN
Alex 85 True NaN
| BSD-2-Clause | 02b_Procedural_Python/python_functions.ipynb | martaw22/LectureNotes |
Copying and pasting code can introduce bugs: You might forget to change a variable name. If you later make a change (like making extra credit worth 10 points instead of 5), you need to remember to change it in multiple places.If we put the code in a function, we can avoid these problems! | # Let's put our extra credit code in a function!
def add_final_grades(student, grade):
print("in add_final_grades")
gradebook.loc[student, 'final_grade'] = grade
add_final_grades('Jennifer', 99)
print(gradebook) | in add_final_grades
raw_grade did_extra_credit final_grade
Hao 80 True NaN
Jennifer 98 False 99
Alex 85 True 90
| BSD-2-Clause | 02b_Procedural_Python/python_functions.ipynb | martaw22/LectureNotes |
Why write functions?1. Easily reuse code (without introducing bugs)2. Easy testing of components Later in the course we will learn about writing unit tests. You will create a set of input values for a function representing potential scenarios, and will test that the function is generating the expected output. ... |
def example_addition_function(num_1, num_2):
"""
This function adds two numbers.
example_addition_function is the function name
Parameters:
num_1: This is the first formal parameter
num_2: This is the second formal parameter
Returns:
sum of num_1 and num_2
""... | _____no_output_____ | BSD-2-Clause | 02b_Procedural_Python/python_functions.ipynb | martaw22/LectureNotes |
Variable names and scopeIn Python, variables have a scope (a context in which they are valid). Variables created in a function cannot be referenced outside of a function | # Let's put our extra credit code in a function!
section = "Section 1"
def add_final_grades(student, grade):
print("in add_final_grades %s" % section)
gradebook.loc[student, 'final_grade'] = grade
add_final_grades('Jennifer', 99)
print(gradebook)
# Let's put our extra credit code in a function!
section = "Sect... | _____no_output_____ | BSD-2-Clause | 02b_Procedural_Python/python_functions.ipynb | martaw22/LectureNotes |
If you modify an object (like a list or a dataframe) inside of a function, the modifications will affect its value outside of the function | def add_name_to_list(name_list, new_name):
name_list.append(new_name)
teachers = ["Bernease", "Dave", "Joe"]
print(teachers)
add_name_to_list(teachers, "Colin")
print(teachers) | _____no_output_____ | BSD-2-Clause | 02b_Procedural_Python/python_functions.ipynb | martaw22/LectureNotes |
Exercise: Write a function to determine if a number is primeBelow is some code that checks if a number is prime. The code has a bug in it! |
# Determine if num is prime
# This code has a bug. What is it?
# Also, the efficiency of the code can be improved. How?
num = 3
is_prime = True
for integer in range(1, num):
if num % integer == 0:
# The "==" operator checks for equality and returns True or False.
# Note the difference between "... | _____no_output_____ | BSD-2-Clause | 02b_Procedural_Python/python_functions.ipynb | martaw22/LectureNotes |
Identificando y modelando relaciones entre pares de variables> En la sesión anterior introdujimos el lenguaje de programación Python, y la librería de análisis de datos para Python **Pandas**. Con Pandas, aprendimos a: - Cargar datos desde archivos.... | # Importar numpy
import numpy as np
# Importar pyplot
import matplotlib.pyplot as plt | _____no_output_____ | MIT | Sesion2/1relaciones_2variables.ipynb | esjimenezro/pda_course |
- Una correlación positiva $\rho_{xy}>0$ indica que los movimientos relativos entre las variables $x,y$ van en la misma dirección. | # Variables con correlación positiva
x = np.random.rand(100)
y = x + 0.5 * np.random.rand(100)
plt.scatter(x, y)
plt.xlabel('x')
plt.ylabel('y')
# Correlación
np.corrcoef(x, y) | _____no_output_____ | MIT | Sesion2/1relaciones_2variables.ipynb | esjimenezro/pda_course |
- Una correlación negativa $\rho_{xy}<0$ indica que los movimientos relativos entre las variables $x,y$ van en direcciones opuestas. | # Variables con correlación negativa
x = np.random.rand(100)
y = 1 - x + 0.5 * np.random.rand(100)
plt.scatter(x, y)
plt.xlabel('x')
plt.ylabel('y')
# Correlación
np.corrcoef(x, y) | _____no_output_____ | MIT | Sesion2/1relaciones_2variables.ipynb | esjimenezro/pda_course |
- Una correlación nula $\rho_{xy}=0$ indica que no hay una relación aparente entre las variables $x, y$. | # Variables con correlación nula
x = np.random.rand(100)
y = 0.5 * np.random.rand(100)
plt.scatter(x, y)
plt.xlabel('x')
plt.ylabel('y')
# Correlación
np.corrcoef(x, y) | _____no_output_____ | MIT | Sesion2/1relaciones_2variables.ipynb | esjimenezro/pda_course |
Ya que entendimos el coeficiente de correlación, utilicémoslo para descubrir la relación que hay entre el precio de las casas y su tamaño: | # Importar pandas
import pandas as pd
# Cargamos datos de las casas
data = pd.read_csv("house_pricing.csv")
# Gráfico precio vs. tamaño
plt.scatter(data['size'], data['price'])
plt.xlabel('Tamaño ($ft^2$)')
plt.ylabel('Precio (USD)')
# Correlación
np.corrcoef(data['size'], data['price']) | _____no_output_____ | MIT | Sesion2/1relaciones_2variables.ipynb | esjimenezro/pda_course |
2. Regresión lineal con una variableUna vez hemos identificado la relación entre dos variables, ¿Cómo podemos modelar esta relación?La respuesta es: **regresión lineal**. En términos simples, el objetivo de la regresión lineal es encontrar un modelo de una recta:$$y = m x + b$$que **"mejor" (en el sentido de mínimos c... | # Importar sklearn.linear_model.LinearRegression
from sklearn.linear_model import LinearRegression
# Ajustar la mejor recta a los datos de tamaños y precios
model = LinearRegression().fit(data[['size']], data['price'])
# Obtener parámetros ajustados
m = model.coef_
b = model.intercept_
m, b
# Gráfico de datos y de mode... | _____no_output_____ | MIT | Sesion2/1relaciones_2variables.ipynb | esjimenezro/pda_course |
¿Y esto para qué nos sirve? Sistema automático de avalúosSupongamos que un amigo nuestro tiene una casa de $2000$ pies cuadrados en Portland, y desea saber a qué precio la podría vender. Se acaba de enterar que justo acabamos de generar un sistema automático que determina el precio de las casas de Portland usando el t... | # Determinar el precio
model.predict([[2000]])
# Gráfico
plt.plot(data['size'], model.predict(data[['size']]))
plt.plot(2000, model.predict([[2000]]), '*r', ms=10)
plt.scatter(data['size'], data['price'])
plt.xlabel('Tamaño ($ft^2$)')
plt.ylabel('Precio (USD)') | _____no_output_____ | MIT | Sesion2/1relaciones_2variables.ipynb | esjimenezro/pda_course |
线性回归:label:`sec_linear_regression`*回归*(regression)是能为一个或多个自变量与因变量之间关系建模的一类方法。在自然科学和社会科学领域,回归经常用来表示输入和输出之间的关系。在机器学习领域中的大多数任务通常都与*预测*(prediction)有关。当我们想预测一个数值时,就会涉及到回归问题。常见的例子包括:预测价格(房屋、股票等)、预测住院时间(针对住院病人等)、预测需求(零售销量等)。但不是所有的*预测*都是回归问题。在后面的章节中,我们将介绍分类问题。分类问题的目标是预测数据属于一组类别中的哪一个。 线性回归的基本元素*线性回归*(linear regression)可以追溯到19世... | %matplotlib inline
import math
import time
import numpy as np
import tensorflow as tf
from d2l import tensorflow as d2l | _____no_output_____ | Apache-2.0 | d2l/tensorflow/chapter_linear-networks/linear-regression.ipynb | 541979210/xdf |
为了说明矢量化为什么如此重要,我们考虑(**对向量相加的两种方法**)。我们实例化两个全为1的10000维向量。在一种方法中,我们将使用Python的for循环遍历向量;在另一种方法中,我们将依赖对`+`的调用。 | n = 10000
a = tf.ones(n)
b = tf.ones(n) | _____no_output_____ | Apache-2.0 | d2l/tensorflow/chapter_linear-networks/linear-regression.ipynb | 541979210/xdf |
由于在本书中我们将频繁地进行运行时间的基准测试,所以[**我们定义一个计时器**]: | class Timer: #@save
"""记录多次运行时间"""
def __init__(self):
self.times = []
self.start()
def start(self):
"""启动计时器"""
self.tik = time.time()
def stop(self):
"""停止计时器并将时间记录在列表中"""
self.times.append(time.time() - self.tik)
return self.times[-1]
de... | _____no_output_____ | Apache-2.0 | d2l/tensorflow/chapter_linear-networks/linear-regression.ipynb | 541979210/xdf |
现在我们可以对工作负载进行基准测试。首先,[**我们使用for循环,每次执行一位的加法**]。 | c = tf.Variable(tf.zeros(n))
timer = Timer()
for i in range(n):
c[i].assign(a[i] + b[i])
f'{timer.stop():.5f} sec' | _____no_output_____ | Apache-2.0 | d2l/tensorflow/chapter_linear-networks/linear-regression.ipynb | 541979210/xdf |
(**或者,我们使用重载的`+`运算符来计算按元素的和**)。 | timer.start()
d = a + b
f'{timer.stop():.5f} sec' | _____no_output_____ | Apache-2.0 | d2l/tensorflow/chapter_linear-networks/linear-regression.ipynb | 541979210/xdf |
结果很明显,第二种方法比第一种方法快得多。矢量化代码通常会带来数量级的加速。另外,我们将更多的数学运算放到库中,而无须自己编写那么多的计算,从而减少了出错的可能性。 正态分布与平方损失:label:`subsec_normal_distribution_and_squared_loss`接下来,我们通过对噪声分布的假设来解读平方损失目标函数。正态分布和线性回归之间的关系很密切。正态分布(normal distribution),也称为*高斯分布*(Gaussian distribution),最早由德国数学家高斯(Gauss)应用于天文学研究。简单的说,若随机变量$x$具有均值$\mu$和方差$\sigma^2$(标准差$\sigm... | def normal(x, mu, sigma):
p = 1 / math.sqrt(2 * math.pi * sigma**2)
return p * np.exp(-0.5 / sigma**2 * (x - mu)**2) | _____no_output_____ | Apache-2.0 | d2l/tensorflow/chapter_linear-networks/linear-regression.ipynb | 541979210/xdf |
我们现在(**可视化正态分布**)。 | # 再次使用numpy进行可视化
x = np.arange(-7, 7, 0.01)
# 均值和标准差对
params = [(0, 1), (0, 2), (3, 1)]
d2l.plot(x, [normal(x, mu, sigma) for mu, sigma in params], xlabel='x',
ylabel='p(x)', figsize=(4.5, 2.5),
legend=[f'mean {mu}, std {sigma}' for mu, sigma in params]) | _____no_output_____ | Apache-2.0 | d2l/tensorflow/chapter_linear-networks/linear-regression.ipynb | 541979210/xdf |
Project SubmissionContinuous Control for the Udacity Ud893 Deep Reinforcement Learning Nanodegree (DRLND) Imports and Dependencies | import sys
sys.path.append("../python")
import random
import numpy as np
import torch
from collections import deque
import matplotlib.pyplot as plt
from datetime import datetime
from unityagents import UnityEnvironment
%matplotlib inline | _____no_output_____ | Apache-2.0 | P2.ipynb | irvlust/DRLND-Continuous-Control |
Unity EnvironmentNote that if your operating system is Windows (64-bit), the Unity environment is included and you can run the below environment instantiation cell. However, if you're using a different operating system, download the file you require from one of the following links:- Linux: [click here](https://s3-us-... | env = UnityEnvironment(file_name="Reacher_20_Windows_x86_64/Reacher.exe") | INFO:unityagents:
'Academy' started successfully!
Unity Academy name: Academy
Number of Brains: 1
Number of External Brains : 1
Lesson number : 0
Reset Parameters :
goal_size -> 5.0
goal_speed -> 1.0
Unity brain name: ReacherBrain
Number of Visual Observations (per agent): 0
... | Apache-2.0 | P2.ipynb | irvlust/DRLND-Continuous-Control |
Get Default Brain | # get the default brain
brain_name = env.brain_names[0]
brain = env.brains[brain_name] | _____no_output_____ | Apache-2.0 | P2.ipynb | irvlust/DRLND-Continuous-Control |
Main Training Loop Function | def training_loop_20(agent, actor_model_filename='ckpnt_actor_20.pth', critic_model_filename='ckpnt_critic_20.pth', n_episodes=1000, max_t=3000):
"""DDPG Training Loop
Params
======
agent (function): agent function
n_episodes (int): maximum number of training episodes
max_t (int): ... | _____no_output_____ | Apache-2.0 | P2.ipynb | irvlust/DRLND-Continuous-Control |
DDPG Agent | from ddpg_agent_20 import Agent
agent = Agent(state_size=33, action_size=4, random_seed=15, lr_a=1e-4, lr_c=1e-3,weight_decay=0, fc1_units=400, fc2_units=300)
start = datetime.now()
scores = training_loop_20(agent)
end = datetime.now()
time_taken = end - start
print('Time: ',time_taken)
# plot the scores
plt.plot(n... | Agent Parameters:
lr_a: 0.0001
lr_c: 0.001
weight decay: 0
fc1_units: 400
fc2_units: 300
Episode 1 Average Score: 0.23 Time: 0:01:15.565206
Episode 2 Average Score: 0.24 Time: 0:02:38.972181
Episode 3 Average Score: 0.22 Time: 0:04:01.302709
Episode 4 Average Score: 0.29 Time: 0:05:24.917069
Episode 5 Average Score: 0.... | Apache-2.0 | P2.ipynb | irvlust/DRLND-Continuous-Control |
Run Smart Agent | from ddpg_agent_20 import Agent
env_info = env.reset(train_mode=True)[brain_name]
agent = Agent(state_size=33, action_size=4, random_seed=15, lr_a=1e-4, lr_c=1e-3,weight_decay=0, fc1_units=400, fc2_units=300)
agent.actor_local.load_state_dict(torch.load('ckpnt_actor_20.pth')) # load weights from file
agent.critic_loc... | Agent Parameters:
lr_a: 0.0001
lr_c: 0.001
weight decay: 0
fc1_units: 400
fc2_units: 300
Episode: 1 Step: 816 Score: 30.03999932855367745
| Apache-2.0 | P2.ipynb | irvlust/DRLND-Continuous-Control |
Load Model, plain 2D Conv | import os
os.chdir("../..")
os.getcwd()
import numpy as np
import torch
import json
from distributed.model_util import choose_model, choose_old_model, load_model, extend_model_config
from distributed.util import q_value_index_to_action
import matplotlib.pyplot as plt
model_name = "conv2d"
model_config_path = "src/confi... | 10
| MIT | src/analysis/output_activation.ipynb | mbecker12/surface-rl-decoder |
Prepare States | all_states = []
state = torch.zeros((stack_depth, syndrome_size, syndrome_size), dtype=torch.float32)
state[-2:, 1, 2] = 1
all_states.append(state)
state = torch.zeros((stack_depth, syndrome_size, syndrome_size), dtype=torch.float32)
state[-1, 1, 2] = 1
state[-1, 2, 3] = 1
all_states.append(state)
state = torch.zer... | _____no_output_____ | MIT | src/analysis/output_activation.ipynb | mbecker12/surface-rl-decoder |
Do the plotting | k = 1
# stack_depth = 5
# syndrome_size = 5
from matplotlib import colors
plt.rcParams.update({"font.size": 15})
fig, ax = plt.subplots(1, 3, figsize=(18, 8), gridspec_kw={"width_ratios": [4, 4, 8], "wspace": 0.02, "hspace": 0.0},)
plot_colors = ["#ffffff", "#404E5C", "#F76C5E", "#E9B44C", "#7F95D1", "#CF1259", "#669... | ind=array([17, 18, 19])
ind=array([32, 33, 34])
ind=array([74, 75, 75])
ind=array([32, 33, 34])
ind=array([32, 33, 34])
ind=array([32, 33, 34])
['(1, 2)', '(1, 2)', '(1, 2)', '(1, 2)', '(1, 2)', '(1, 2)', '(2, 3)', '(2, 3)', '(2, 3)', '(2, 3)', '(2, 3)', '(2, 3)']
| MIT | src/analysis/output_activation.ipynb | mbecker12/surface-rl-decoder |
3D Conv | model_name = "conv3d"
model_config_path_3d = "src/config/model_spec/conv_agents_slim.json"
trained_model_path_3d = "threshold_networks/5/69312/conv3d_5_69312.pt"
with open(model_config_path_3d, "r") as jsonfile:
model_config_3d = json.load(jsonfile)[model_name]
code_size, stack_depth = 5, 5
syndrome_size = code_si... | _____no_output_____ | MIT | src/analysis/output_activation.ipynb | mbecker12/surface-rl-decoder |
Anyway, under a gigabyte. So, nothing to worry about even if we have 24 cores. | # But what symbol is that?
max_sym = None
max_rows = 0
for sym, rows in rec_counts.items():
if rows > max_rows:
max_rows = rows
max_sym = sym
max_sym, max_rows | _____no_output_____ | BSD-2-Clause | tests/Basic HDF5 Operations.ipynb | dlab-projects/marketflow |
Interesting... the S&P 500 ETF | # Most symbols also have way less rows - note this is log xvals
plt.hist(list(rec_counts.values()), bins=50, log=True)
plt.show() | _____no_output_____ | BSD-2-Clause | tests/Basic HDF5 Operations.ipynb | dlab-projects/marketflow |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.