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 |
|---|---|---|---|---|---|
Registering your model with Azure ML | model_dir = "emotion_ferplus" # replace this with the location of your model files
# leave as is if it's in the same folder as this notebook
from azureml.core.model import Model
model = Model.register(model_path = model_dir + "/" + "model.onnx",
model_name = "onnx_emotion",
... | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
Optional: Displaying your registered modelsThis step is not required, so feel free to skip it. | models = ws.models()
for m in models:
print("Name:", m.name,"\tVersion:", m.version, "\tDescription:", m.description, m.tags) | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
ONNX FER+ Model MethodologyThe image classification model we are using is pre-trained using Microsoft's deep learning cognitive toolkit, [CNTK](https://github.com/Microsoft/CNTK), from the [ONNX model zoo](http://github.com/onnx/models). The model zoo has many other models that can be deployed on cloud providers like ... | # for images and plots in this notebook
import matplotlib.pyplot as plt
from IPython.display import Image
# display images inline
%matplotlib inline | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
Model DescriptionThe FER+ model from the ONNX Model Zoo is summarized by the graphic below. You can see the entire workflow of our pre-trained model in the following image from Barsoum et. al's paper ["Training Deep Networks for Facial Expression Recognitionwith Crowd-Sourced Label Distribution"](https://arxiv.org/pdf... | %%writefile score.py
import json
import numpy as np
import onnxruntime
import sys
import os
from azureml.core.model import Model
import time
def init():
global session
model = Model.get_model_path(model_name = 'onnx_emotion')
session = onnxruntime.InferenceSession(model, None)
def run(input_data):
... | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
Write Environment File | from azureml.core.conda_dependencies import CondaDependencies
myenv = CondaDependencies()
myenv.add_pip_package("numpy")
myenv.add_pip_package("azureml-core")
myenv.add_pip_package("onnxruntime-gpu")
with open("myenv.yml","w") as f:
f.write(myenv.serialize_to_string()) | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
Create the Container ImageThis step will likely take a few minutes. | from azureml.core.image import ContainerImage
# enable_gpu = True to install CUDA 9.1 and cuDNN 7.0
image_config = ContainerImage.image_configuration(execution_script = "score.py",
runtime = "python",
conda_file = "mye... | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
DebuggingIn case you need to debug your code, the next line of code accesses the log file. | print(image.image_build_log_uri) | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
We're all set! Let's get our model chugging. Deploy the container image | from azureml.core.webservice import AciWebservice
aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1,
memory_gb = 1,
tags = {'demo': 'onnx'},
description = 'ONNX for... | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
The following cell will likely take a few minutes to run as well. | from azureml.core.webservice import Webservice
aci_service_name = 'onnx-emotion-demo'
print("Service", aci_service_name)
aci_service = Webservice.deploy_from_image(deployment_config = aciconfig,
image = image,
name = aci_service_nam... | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
Success!If you've made it this far, you've deployed a working VM with a facial emotion recognition model running in the cloud using Azure ML. Congratulations!Let's see how well our model deals with our test images. Testing and Evaluation Useful Helper FunctionsWe preprocess and postprocess our data (see score.py fil... | def preprocess(img):
"""Convert image to the write format to be passed into the model"""
input_shape = (1, 64, 64)
img = np.reshape(img, input_shape)
img = np.expand_dims(img, axis=0)
return img
# to manipulate our arrays
import numpy as np
# read in test data protobuf files included with the mode... | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
Show some sample imagesWe use `matplotlib` to plot 3 images from the dataset with their labels over them. | plt.figure(figsize = (20, 20))
for test_image in np.arange(3):
test_inputs[test_image].reshape(1, 64, 64)
plt.subplot(1, 8, test_image+1)
plt.axhline('')
plt.axvline('')
plt.text(x = 10, y = -10, s = test_outputs[test_image][0], fontsize = 18)
plt.imshow(test_inputs[test_image].reshape(64, 64))
... | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
Run evaluation / prediction | plt.figure(figsize = (16, 6), frameon=False)
plt.subplot(1, 8, 1)
plt.text(x = 0, y = -30, s = "True Label: ", fontsize = 13, color = 'black')
plt.text(x = 0, y = -20, s = "Result: ", fontsize = 13, color = 'black')
plt.text(x = 0, y = -10, s = "Inference Time: ", fontsize = 13, color = 'black')
plt.text(x = 3, y = 14... | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
Try classifying your own images! | # Replace the following string with your own path/test image
# Make sure the dimensions are 28 * 28 pixels
# Any PNG or JPG image file should work
# Make sure to include the entire path with // instead of /
# e.g. your_test_image = "C://Users//vinitra.swamy//Pictures//emotion_test_images//img_1.jpg"
your_test_image ... | _____no_output_____ | MIT | onnx/onnx-inference-emotion-recognition.ipynb | sxusx/MachineLearningNotebooks |
2d. Distributed training and monitoring In this notebook, we refactor to call ```train_and_evaluate``` instead of hand-coding our ML pipeline. This allows us to carry out evaluation as part of our training loop instead of as a separate step. It also adds in failure-handling that is necessary for distributed training c... | from google.cloud import bigquery
import tensorflow as tf
import numpy as np
import shutil
print(tf.__version__) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst |
Input Read data created in Lab1a, but this time make it more general, so that we are reading in batches. Instead of using Pandas, we will use add a filename queue to the TensorFlow graph. | CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key']
LABEL_COLUMN = 'fare_amount'
DEFAULTS = [[0.0], [-74.0], [40.0], [-74.0], [40.7], [1.0], ['nokey']]
def read_dataset(filename, mode, batch_size = 512):
def decode_csv(value_column):
columns = tf.decode_csv(value_... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst |
Create features out of input data For now, pass these through. (same as previous lab) | INPUT_COLUMNS = [
tf.feature_column.numeric_column('pickuplon'),
tf.feature_column.numeric_column('pickuplat'),
tf.feature_column.numeric_column('dropofflat'),
tf.feature_column.numeric_column('dropofflon'),
tf.feature_column.numeric_column('passengers'),
]
def add_more_features(feats):
# Nothing... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst |
Serving input function Defines the expected shape of the JSON feed that the modelwill receive once deployed behind a REST API in production. | ## TODO: Create serving input function
def serving_input_fn():
#ADD CODE HERE
return tf.estimator.export.ServingInputReceiver(features, json_feature_placeholders) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst |
tf.estimator.train_and_evaluate | ## TODO: Create train and evaluate function using tf.estimator
def train_and_evaluate(output_dir, num_train_steps):
#ADD CODE HERE
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst |
Monitoring with TensorBoard Start the TensorBoard by opening up a new Launcher (File > New Launcher) and selecting TensorBoard. | OUTDIR = './taxi_trained' | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst |
Run training | # Run training
shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time
tf.summary.FileWriterCache.clear() # ensure filewriter cache is clear for TensorBoard events file
train_and_evaluate(OUTDIR, num_train_steps = 2000) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive/03_tensorflow/labs/d_traineval.ipynb | jonesevan007/training-data-analyst |
DescriptionResnet from scratch tutorial from medium post: https://towardsdatascience.com/building-a-resnet-in-keras-e8f1322a49baNet structure: - Input with shape (32, 32, 3) - 1 Conv2D layer, with 64 filters - 2, 5, 5, 2 residual blocks with 64, 128, 256, and 512 filters - AveragePooling2D layer with pool size = ... | from tensorflow import Tensor
from tensorflow.keras.layers import Input, Conv2D, ReLU, BatchNormalization,\
Add, AveragePooling2D, Flatten, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.callbacks import ModelCheckp... | _____no_output_____ | MIT | tutorial_resnet.ipynb | ElHouas/cnn-deep-learning |
Function definitions | def relu_bn(inputs: Tensor) -> Tensor: # Specifying return type
relu = ReLU()(inputs)
bn = BatchNormalization()(relu)
return bn
def residual_block(x: Tensor, downsample: bool, filters: int, kernel_size: int = 3) -> Tensor:
y = Conv2D(kernel_size=kernel_size,
... | _____no_output_____ | MIT | tutorial_resnet.ipynb | ElHouas/cnn-deep-learning |
Main function | (x_train, y_train), (x_test, y_test) = cifar10.load_data()
model = create_res_net()
model.summary
timestr= datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
name = 'cifar-10_res_net_30-'+timestr # or 'cifar-10_plain_net_30-'+timestr
checkpoint_path = "checkpoints/"+name+"/cp-{epoch:04d}.ckpt"
checkpoint_dir = os.path.... | Epoch 1/20
1/391 [..............................] - ETA: 0s - loss: 2.3458 - accuracy: 0.0938WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/summary_ops_v2.py:1277: stop (from tensorflow.python.eager.profiler) is deprecated and will be removed after 2020-07-01.
Instructions for up... | MIT | tutorial_resnet.ipynb | ElHouas/cnn-deep-learning |
Quiz 1 : Sifat ListJawab Pertanyaan di bawah ini :Jenis data apa saja yang bisa ada di dalam List? list, ada numerik, string, boolean, dan sebagainya Quiz 2 : Akses ListLengkapi kode untuk menghasilkan suatu output yang di harapkan | a = ['1', '13b', 'aa1', 1.32, 22.1, 2.34]
# slicing list
print(a[1:5]) | ['13b', 'aa1', 1.32, 22.1]
| MIT | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode |
Expected Output :[ '13b', 'aa1', 1.32, 22.1 ] Quiz 3 : Nested ListLengkapi kode untuk menghasilkan suatu output yang di harapkan | a = [1.32, 22.1, 2.34]
b = ['1', '13b', 'aa1']
c = [3, 40, 100]
# combine list
d = [a, c, b]
print(d) | [[1.32, 22.1, 2.34], [3, 40, 100], ['1', '13b', 'aa1']]
| MIT | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode |
Expected Output :[ [1.32, 22.1, 2.34], [3, 40, 100], ['1', '13b', 'aa1'] ] Quiz 4 : Akses Nested ListLengkapi kode untuk menghasilkan suatu output yang di harapkan | a = [
[5, 9, 8],
[0, 0, 6]
]
# subsetting list
print(a[1][1:3]) | [0, 6]
| MIT | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode |
Expected Output :[0, 6] Quiz 5 : Built in Function ListLengkapi kode untuk menghasilkan suatu output yang di harapkan | p = [0, 5, 2, 10, 4, 9]
# ordered list
print(sorted(p, reverse=False))
# get max value of list
print(max(p)) | [0, 2, 4, 5, 9, 10]
10
| MIT | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode |
Expected Output :[0, 2, 4, 5, 9, 10]10 Quiz 6 : List OperationLengkapi kode untuk menghasilkan suatu output yang di harapkan | a = [1, 3, 5]
b = [5, 1, 3]
# combine list
c = b + a
print(c) | [5, 1, 3, 1, 3, 5]
| MIT | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode |
Expected Output :[5, 1, 3, 1, 3, 5] Quiz 7 : List ManipulationLengkapi kode untuk menghasilkan suatu output yang di harapkan | a = [
[5, 9, 8],
[0, 0, 6]
]
# change list value
a[0][2] = 10
# change list value
a[1][0] = 11
print(a) | [[5, 9, 10], [11, 0, 6]]
| MIT | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode |
Expected Output :[ [5, 9, 10], [11, 0, 6] ] Quiz 8 : Delete Element ListLengkapi kode untuk menghasilkan suatu output yang di harapkan | areas = ["hallway", 11.25, "kitchen", 18.0,
"chill zone", 20.0, "bedroom", 10.75,
"bathroom", 10.50, "poolhouse", 24.5,
"garage", 15.45]
# Hilangkan elemen yang bernilai "bathroom" dan 10.50 dalam satu statement code
del(areas[8], areas[8])
print(areas) | ['hallway', 11.25, 'kitchen', 18.0, 'chill zone', 20.0, 'bedroom', 10.75, 'poolhouse', 24.5, 'garage', 15.45]
| MIT | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode |
Expected Output :['hallway', 11.25, 'kitchen', 18.0, 'chill zone', 20.0, 'bedroom', 10.75, 'poolhouse', 24.5, 'garage', 15.45] | _____no_output_____ | MIT | Learn/Week 1 Basic Python/Week_1_Day_2.ipynb | mazharrasyad/Data-Science-SanberCode | |
Welcome to the walkthrough for the updated Python SDK for libsimba.py-platformTo use the Python SDK for SEP, there are two steps the user/developer takes. These two steps assume that you have already created a contract, and an app that uses that contract, on SEP.1. Instantiate a SimbaHintedContract object. Instantiati... | from libsimba.simba_hinted_contract import SimbaHintedContract
app_name = "TestSimbaHinted"
contract_name = "TestSimbaHinted"
base_api_url = 'https://api.sep.dev.simbachain.com/'
output_file = "test_simba_hinted.py"
contract_class_name = "TestSimbaHinted" | _____no_output_____ | MIT | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform |
Next, we instantiate our SimbaHintedContract object: | sch = SimbaHintedContract(
app_name,
contract_name,
contract_class_name=contract_class_name,
base_api_url=base_api_url,
output_file=output_file) | _____no_output_____ | MIT | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform |
Instantiating that object will write our class-based smart contract to "test_simba_hinted.py", since that is the name we specified for our output fileIn this output, solidity structs from our smart contract are represented as subclasses (Addr, Person, AddressPerson). Also note that our contract methods are now represe... | from libsimba.simba import Simba
from typing import List, Tuple, Dict, Any, Optional
from libsimba.class_converter import ClassToDictConverter, convert_classes
from libsimba.file_handler import open_files, close_files
class TestSimbaHinted:
def __init__(self):
self.app_name = "TestSimbaHinted"
self... | _____no_output_____ | MIT | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform |
Here we will instantiate an instance of our contract class. You could do that from a separate file, by importing your contract class, but since we're using a notebook here, we'll just instantiate an object in the same file: | tsh = TestSimbaHinted() | _____no_output_____ | MIT | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform |
Now we will call one of our smart contract's methods by invoking a method of our contract class object. We will call our method two_arrs, which simply takes two arrays as parameters. | arr1 = [2, 4, 20, 10, 3, 3]
arr2 = [1,3,5]
r = tsh.two_arrs(arr1, arr2) | _____no_output_____ | MIT | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform |
We can inspect the response from this submission to check it has succeeded: | assert (200 <= r.status_code <= 299)
print(r.json()) | _____no_output_____ | MIT | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform |
Now let's invoke structTest_5, which is a method that accepts files, and also takes a nested struct as a parameter. First we need to assign our file path and file name, as well as specify the read_mode for our file. if read_mode is not specified here, then it defaults to 'r' (see file_handler.py for documentation on t... | file_name = 'test_file'
file_path = '../tests/data/file1.txt'
files = [(file_name, file_path, 'r')] | _____no_output_____ | MIT | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform |
Now we will need to instantiate Person and Addr objects. Person takes an Addr object as one of its initialization parameters. | name = "Charlie"
age = 99
street = "rogers street"
number = 123
town = "new york"
addr = TestSimbaHinted.Addr(street, number, town)
p = TestSimbaHinted.Person(name, age, addr)
| _____no_output_____ | MIT | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform |
Now we will invoke structTest_5 with parameters p, and files. |
r = tsh.structTest_5(p, files)
if 200 <= r.status_code <= 299:
print(r.json()) | _____no_output_____ | MIT | notebooks/examples.ipynb | SIMBAChain/libsimba.py-platform |
**Movie Recommendation Model** | import numpy as np
import pandas as pd
movies = pd.read_csv("/Users/sarang/Documents/Movie-Reccomendation/content/tmdb_5000_movies.csv")
credits = pd.read_csv("/Users/sarang/Documents/Movie-Reccomendation/content/tmdb_5000_credits.csv")
movies = movies.merge(credits,on='title')
movies = movies[['movie_id','title','over... | _____no_output_____ | MIT | Movie-Recommendation.ipynb | Git-Sarang/Movie-Recommender |
Machine Learning Section | from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=5000,stop_words='english')
vector = cv.fit_transform(new['tag']).toarray()
vector.shape
from sklearn.metrics.pairwise import cosine_similarity
similarity = cosine_similarity(vector)
type(similarity)
new[new['title']=='The Lego... | _____no_output_____ | MIT | Movie-Recommendation.ipynb | Git-Sarang/Movie-Recommender |
Hypothesis test power from scratch with Python Calculating power of hypothesis tests.The code is from the [Data Science from Scratch](https://www.oreilly.com/library/view/data-science-from/9781492041122/) book. Libraries and helper functions | from typing import Tuple
import math as m
def calc_normal_cdf(x: float, mu: float = 0, sigma: float = 1) -> float:
return (1 + m.erf((x - mu) / m.sqrt(2) / sigma)) / 2
normal_probability_below = calc_normal_cdf
def normal_probability_between(lo: float, hi: float, mu: float = 0, sigma: float = 1) -> float:
retu... | _____no_output_____ | Apache-2.0 | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog |
Type 1 Error and Tolerance Let's make our null hypothesis ($H_0$) that the probability of head is 0.5 | mu_0, sigma_0 = normal_approximation_to_binomial(1000, 0.5)
mu_0, sigma_0 | _____no_output_____ | Apache-2.0 | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog |
We define our tolerance at 5%. That is, we accept our model to produce 'type 1' errors (false positive) in 5% of the time. With the coin flipping example, we expect to receive 5% of the results to fall outsied of our defined interval. | lo, hi = normal_two_sided_bounds(0.95, mu_0, sigma_0)
lo, hi | _____no_output_____ | Apache-2.0 | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog |
Type 2 Error and Power At type 2 error we consider false negatives, that is, those cases where we fail to reject our null hypothesis even though we should. Let's assume that contra $H_0$ the actual probability is 0.55. | mu_1, sigma_1 = normal_approximation_to_binomial(1000, 0.55)
mu_1, sigma_1 | _____no_output_____ | Apache-2.0 | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog |
In this case we get our Type 2 probability as the overlapping of the real distribution and the 95% probability region of $H_0$. In this particular case, in 11% of the cases we will wrongly fail to reject our null hypothesis. | type_2_probability = normal_probability_between(lo, hi, mu_1, sigma_1)
type_2_probability | _____no_output_____ | Apache-2.0 | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog |
The power of the test is then the probability of rightly rejecting the $H_0$ | power = 1 - type_2_probability
power | _____no_output_____ | Apache-2.0 | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog |
Now, let's redefine our null hypothesis so that we expect the probability of head to be less than or equal to 0.5.In this case we have a one-sided test. | hi = normal_upper_bound(0.95, mu_0, sigma_0)
hi | _____no_output_____ | Apache-2.0 | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog |
Because this is a less strict hypothesis than our previus one, it has a smaller T2 probability and a greater power. | type_2_probability = normal_probability_below(hi, mu_1, sigma_1)
type_2_probability
power = 1 - type_2_probability
power | _____no_output_____ | Apache-2.0 | _notebooks/2020-10-12-hypothesis-test-power.ipynb | nocibambi/ds_blog |
Carry signals by Gustavo SoaresIn this notebook you will apply a few things you learned in our Python lecture [FinanceHub's Python lectures](https://github.com/Finance-Hub/FinanceHubMaterials/tree/master/Python%20Lectures):* You will use and manipulate different kinds of variables in Python such as text variables, boo... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from bloomberg import BBG
bbg = BBG() # because BBG is a class, we need to create an instance of the BBG class wihtin this notebook, here deonted by bbg | _____no_output_____ | MIT | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials |
CarryThe concept of carry arised in currency markets but it can be applied to any asset. Any security or derivative expected return can be decomposed into its “carry” – an ex-ante and model-free characteristic – and its expected price appreciation. So, "carry" can be understood as the expected return of a security or ... | ref_date = '2019-12-04'
tickers = [
'BCDRC BDSR Curncy', # BRL 3M deposit rate
'USDRC BDSR Curncy', # USD 3M deposit rate
'USDBRL Curncy', # USDBRL spot exchange rate
'BCN+3M BGN Curncy', # USDBRL 3M forward contract
'USDBRLV3M BGN Curncy', # USDBRL 3M ATM implied volatility
]
bbg_d... | _____no_output_____ | MIT | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials |
Given the data above, let's calculate carry in both ways: | dr_carry = (1+bbg_data.iloc[-1,1]/100)/(1+bbg_data.iloc[-1,0]/100)-1
print('Deposit rate 3M ann. carry for USDBRL on %s is: %s'% (ref_date,dr_carry))
fwd_carry = ((1+bbg_data.iloc[-1,2])/(1+bbg_data.iloc[-1,3]))**(12/3)-1
print('Forward contract 3M ann. carry for USDBRL on %s is: %s'% (ref_date,fwd_carry))
vol_adj_carr... | Deposit rate 3M ann. carry for USDBRL on 2019-12-04 is: -0.016833325297719526
Forward contract 3M ann. carry for USDBRL on 2019-12-04 is: -0.013180395716221094
Vol-adjusted forward contract 3M ann. carry for USDBRL on 2019-12-04 is: -0.11723201739945827
| MIT | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials |
Carry in commodity futuresCalculating carry for commodity futures, or for any futures contract follows pretty much the same lines as calculating carry for forward FX contract. Again, by a no-arbitrage argument any futures contract on an underlying $i$, maturing in $T$ years, should be priced by:$$F_{i}^{T} = S_{i} \ti... | tickers = ['NG' + str(i) + ' Comdty' for i in range(1,13)]
bbg_data = bbg.fetch_series(securities=tickers,
fields='PX_LAST',
startdate=ref_date,
enddate=ref_date)
bbg_data.columns = [int(x.replace('NG','').replace(' Comdty',''... | _____no_output_____ | MIT | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials |
In order to avoid the definition of carry moving up and down seasonally, carry strategies in commodities often look at $T$ and $T_{0}$ exactly one year apart. However, this not always true. Some people may argue that you want carry to move up and down seasonally because the underlying spot markets do so. Carry in rates... | # get spot 10Y rates tickers
spot_IRS = pd.Series({
'USD':'USSW10 Curncy',
'EUR':'EUSA10 Curncy',
'JPY':'JYSW10 Curncy',
'GBP':'BPSW10 Curncy',
'AUD':'ADSW10Q Curncy',
'CAD':'CDSW10 Curncy',
'SEK':'SKSW10 Curncy',
'CHF':'SFSW10 Curncy',
'NOK':'NKSW10 Curncy',
'NZD':'NDSWAP10 Cur... | _____no_output_____ | MIT | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials |
Carry in equity indicesFor equities, we can also use the same arguemnt we used for FX forward contracts. The no-arbitrage price of a futures contract, $F_{t}$ depends on the current equity value $S_{t}$, the expected future dividend payment $D_{t+1}$ computed under the risk-neutral measure and the risk-free interest r... | front_month = bbg.fetch_contract_parameter(securities='SP1 Comdty', field='FUT_CUR_GEN_TICKER')
expiry = bbg.fetch_contract_parameter(securities=front_month.iloc[0,0] + ' Index', field='FUT_NOTICE_FIRST')
h = (pd.to_datetime(expiry.iloc[0,0]) - pd.to_datetime('today')).days/365.25
bbg_data = bbg.fetch_series(securitie... | On 28-Jan-20, the carry on the front month S&P future is: 0.0007568960130031055
| MIT | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials |
Carry in bond futuresCalculating carry for bond futures is similar to calculating carry for any futures contract and it follows pretty much the same lines as calculating carry for forward FX contract. The tricky part about bond futures is that the underlying $i$ keeps changing. At any one point in time, the bond under... | front_month_ticker = bbg.fetch_contract_parameter(securities='TY1 Comdty', field='FUT_CUR_GEN_TICKER')
front_month_ticker = front_month_ticker.iloc[0,0] + ' Comdty'
expiry = bbg.fetch_contract_parameter(securities=front_month_ticker, field='LAST_TRADEABLE_DT')
h = (pd.to_datetime(expiry.iloc[0,0])-pd.to_datetime('today... | On 28-Jan-20, the carry on the front month 10Y UST future is: -0.001715206652355361
| MIT | Quantitative Finance Lectures/carry.ipynb | antoniosalomao/FinanceHubMaterials |
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
x = np.arange(1, 15)
x
y = x * 5
y
plt.plot(x, y)
plt.axis([0, 16, -20, 100])
plt.show()
def f(m):
y = x * m
plt.plot(x, y)
plt.axis([0, 16... | _____no_output_____ | CC0-1.0 | notebooks/ea_Interactive_controls.ipynb | lmcanavals/analytics_visualization | |
Regression in Python***This is a very quick run-through of some basic statistical concepts, adapted from [Lab 4 in Harvard's CS109](https://github.com/cs109/2015lab4) course. Please feel free to try the original lab if you're feeling ambitious :-) The CS109 git repository also has the solutions if you're stuck.* Linea... | # special IPython command to prepare the notebook for matplotlib and other libraries
%matplotlib inline
import numpy as np
import pandas as pd
import scipy.stats as stats
import matplotlib.pyplot as plt
import sklearn
import collections
import seaborn as sns
# special matplotlib argument for improved plots
from mat... | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
*** Part 1: Introduction to Linear Regression Purpose of linear regression*** Given a dataset containing predictor variables $X$ and outcome/response variable $Y$, linear regression can be used to: Build a predictive model to predict future values of $\hat{Y}$, using new data $X^*$ where $Y$ is unknown. Model the ... | from sklearn.datasets import load_boston
import pandas as pd
boston = load_boston()
boston.keys()
boston.data.shape
# Print column names
print(boston.feature_names)
# Print description of Boston housing data set
print(boston.DESCR) | Boston House Prices dataset
===========================
Notes
------
Data Set Characteristics:
:Number of Instances: 506
:Number of Attributes: 13 numeric/categorical predictive
:Median Value (attribute 14) is usually the target
:Attribute Information (in order):
- CRIM per capit... | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Now let's explore the data set itself. | bos = pd.DataFrame(boston.data)
bos.head() | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
There are no column names in the DataFrame. Let's add those. | bos.columns = boston.feature_names
bos.head() | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Now we have a pandas DataFrame called `bos` containing all the data we want to use to predict Boston Housing prices. Let's create a variable called `PRICE` which will contain the prices. This information is contained in the `target` data. | print(boston.target.shape)
bos['PRICE'] = boston.target
bos.head() | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
EDA and Summary Statistics***Let's explore this data set. First we use `describe()` to get basic summary statistics for each of the columns. | bos.describe() | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Scatterplots***Let's look at some scatter plots for three variables: 'CRIM' (per capita crime rate), 'RM' (number of rooms) and 'PTRATIO' (pupil-to-teacher ratio in schools). | plt.scatter(bos.CRIM, bos.PRICE)
plt.xlabel("Per capita crime rate by town (CRIM)")
plt.ylabel("Housing Price")
plt.title("Relationship between CRIM and Price")
#Describe relationship
sns.regplot(x=bos.CRIM, y=bos.PRICE, data=bos, fit_reg = True)
stats.linregress(bos.CRIM,bos.PRICE)
plt.xlabel("Per capita crime rate by... | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
The relationship between housing price and crime rate is negative. There are a few outliers, an unusual high crime rate for a same price and a higher crime rate at a high housing price. | #scatter plot between *RM* and *PRICE*
sns.regplot(x=bos.RM, y=bos.PRICE, data=bos, fit_reg = True)
stats.linregress(bos.RM,bos.PRICE)
plt.xlabel("average number of rooms per dwelling")
plt.ylabel("Housing Price")
plt.title("Relationship between CRIM and Price")
#Scatter plot between *PTRATIO* and *PRICE*
sns.regplot(x... | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Scatterplots using Seaborn***[Seaborn](https://stanford.edu/~mwaskom/software/seaborn/) is a cool Python plotting library built on top of matplotlib. It provides convenient syntax and shortcuts for many common types of plots, along with better-looking defaults.We can also use [seaborn regplot](https://stanford.edu/~mw... | sns.regplot(y="PRICE", x="RM", data=bos, fit_reg = True)
plt.xlabel("average number of rooms per dwelling")
plt.ylabel("Housing Price") | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Histograms*** | plt.hist(np.log(bos.CRIM))
plt.title("CRIM")
plt.xlabel("Crime rate per capita")
plt.ylabel("Frequencey")
plt.show() | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Exercise: Plot the histogram for *RM* and *PTRATIO* against each other, along with the two variables you picked in the previous section. We are looking for correlations in predictors here. | plt.hist(bos.CRIM)
plt.title("CRIM")
plt.xlabel("Crime rate per capita")
plt.ylabel("Frequencey")
plt.show() | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
The first histogram was created by taking the logarithm of the crime rate per capita. In comparison, the histogram above was created using the original data. Taking the log transforms the skewed data to approximately conform to normality. The transformation shows a bimodal type of distribution. | plt.hist(bos.RM)
plt.hist(bos.PTRATIO) | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Part 3: Linear Regression with Boston Housing Data Example***Here, $Y$ = boston housing prices (called "target" data in python, and referred to as the dependent variable or response variable)and$X$ = all the other features (or independent variables, predictors or explanatory variables)which we will use to fit a linear... | # Import regression modules
import statsmodels.api as sm
from statsmodels.formula.api import ols
# statsmodels works nicely with pandas dataframes
# The thing inside the "quotes" is called a formula, a bit on that below
m = ols('PRICE ~ RM',bos).fit()
print(m.summary()) | OLS Regression Results
==============================================================================
Dep. Variable: PRICE R-squared: 0.484
Model: OLS Adj. R-squared: 0.483
Meth... | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Interpreting coefficientsThere is a ton of information in this output. But we'll concentrate on the coefficient table (middle table). We can interpret the `RM` coefficient (9.1021) by first noticing that the p-value (under `P>|t|`) is so small, basically zero. This means that the number of rooms, `RM`, is a statistica... | sns.regplot(bos.PRICE, m.fittedvalues)
stats.linregress(bos.PRICE, m.fittedvalues)
plt.ylabel("Predicted Values")
plt.xlabel("Actual Values")
plt.title("Comparing Predicted Values to the Actual Values") | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
The majority of the predicted value match the actual values. However, the outliers that were incorrectly predicted range from 10 to 40 prices. Fitting Linear Regression using `sklearn` | from sklearn.linear_model import LinearRegression
X = bos.drop('PRICE', axis = 1)
lm = LinearRegression()
lm | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
What can you do with a LinearRegression object? ***Check out the scikit-learn [docs here](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html). We have listed the main functions here. Most machine learning models in scikit-learn follow this same API of fitting a model with `fit`... | lm.predict | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Output | Description--- | --- `lm.coef_` | Estimated coefficients`lm.intercept_` | Estimated intercept Fit a linear model***The `lm.fit()` function estimates the coefficients the linear regression using least squares. | # Use all 13 predictors to fit linear regression model
lm.fit(X, bos.PRICE)
lm.fit_intercept = True
lm.fit(X, bos.PRICE) | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Determining whether an intercept is important or not requires looking at t-test. Estimated intercept and coefficientsLet's look at the estimated coefficients from the linear model using `1m.intercept_` and `lm.coef_`. After we have fit our linear regression model using the least squares method, we want to see what ar... | print('Estimated intercept coefficient: {}'.format(lm.intercept_))
print('Number of coefficients: {}'.format(len(lm.coef_)))
pd.DataFrame({'features': X.columns, 'estimatedCoefficients': lm.coef_})[['features', 'estimatedCoefficients']] | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Predict Prices We can calculate the predicted prices ($\hat{Y}_i$) using `lm.predict`. $$ \hat{Y}_i = \hat{\beta}_0 + \hat{\beta}_1 X_1 + \ldots \hat{\beta}_{13} X_{13} $$ | # first five predicted prices
lm.predict(X)[0:5]
#Plot a histogram of all the predicted prices.
plt.hist(lm.predict(X))
plt.xlabel('Predict Values')
plt.ylabel('Frequency')
plt.show()
print('Predicted Average:', lm.predict(X).mean())
print('Predicted Variance:', np.var(lm.predict(X)))
print(collections.Counter(lm.predi... | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
The histogram is approximately a normal distribution. The center is 22.5328063241 and the variance is 62.5217769385, suggesting that outliers do exist; the plot above shows the outliers. Evaluating the Model: Sum-of-SquaresThe partitioning of the sum-of-squares shows the variance in the predictions explained by the mo... | print(np.sum((bos.PRICE - lm.predict(X)) ** 2)) | 11080.2762841
| MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Explained Sum-of-Squares (aka $ESS$)The explained sum-of-squares measures the variance explained by the regression model.$$ESS = \sum_{i=1}^N \left( \hat{y}_i - \bar{y} \right)^2 = \sum_{i=1}^N \left( \left( \hat{\beta}_0 + \hat{\beta}_1 x_i \right) - \bar{y} \right)^2$$ | print(np.sum(lm.predict(X) - np.mean(bos.PRICE)) ** 2) | 8.69056631064e-23
| MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Evaluating the Model: The Coefficient of Determination ($R^2$)The coefficient of determination, $R^2$, tells us the percentage of the variance in the response variable $Y$ that can be explained by the linear regression model.$$ R^2 = \frac{ESS}{TSS} $$The $R^2$ value is one of the most common metrics that people use i... | lm = LinearRegression()
lm.fit(X[['CRIM','RM','PTRATIO']],bos.PRICE)
mseCRP = np.mean((bos.PRICE - lm.predict(X[['CRIM','RM','PTRATIO']])) ** 2)
msy = np.mean((bos.PRICE - np.mean(bos.PRICE)) ** 2)
RsquareCRP = 1 - mseCRP/msy
print(mseCRP, RsquareCRP)
plt.scatter(bos.PRICE, lm.predict(X[['CRIM','RM','PTRATIO']]))
plt.x... | _____no_output_____ | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Part 4: Comparing Models During modeling, there will be times when we want to compare models to see which one is more predictive or fits the data better. There are many ways to compare models, but we will focus on two. The $F$-Statistic RevisitedThe $F$-statistic can also be used to compare two *nested* models, that ... | # ols - ordinary least squares
import statsmodels.api as sm
from statsmodels.api import OLS
m = sm.OLS(bos.PRICE, bos.RM).fit()
print(m.summary()) | OLS Regression Results
==============================================================================
Dep. Variable: PRICE R-squared: 0.901
Model: OLS Adj. R-squared: 0.901
Meth... | MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Part 5: Evaluating the Model via Model Assumptions and Other Issues***Linear regression makes several assumptions. It is always best to check that these assumptions are valid after fitting a linear regression model. **Linearity**. The dependent variable $Y$ is a linear combination of the regression coefficients and t... | from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn.linear_model import LinearRegression
lm = LinearRegression()
Rsquared = cross_val_score(estimator =lm, X=bos.iloc[:,:-1], y = bos.PRICE,cv=5)
print('Rsquared:', Rsquared) | ('Rsquared:', array([ 0.63861069, 0.71334432, 0.58645134, 0.07842495, -0.26312455]))
| MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Interesting. I got a R^2 that is negative, meaning that this model fits worse than a horizontal line. | np.mean(Rsquares)
from sklearn.model_selection import KFold
Y=bos.PRICE
kf=KFold(n_splits=4)
for train, test in kf.split(X):
X_train, X_test= X.iloc[train], X.iloc[test]
for train, test in kf.split(Y):
Y_train, Y_test = Y.iloc[train], Y.iloc[test]
lm.fit(X_train, Y_train)
lm.predict(X_test)
print('Testing Set ... | ('Testing Set MSE:', 61.59301573238758, 'Training Set MSE :', 21.198414282847672)
| MIT | linear_regression/Mini_Project_Linear_Regression.ipynb | sdf94/Springboard |
Getting started in scikit-learn with the famous iris dataset Objectives- What is the famous iris dataset, and how does it relate to machine learning?- How do we load the iris dataset into scikit-learn?- How do we describe a dataset using machine learning terminology?- What are scikit-learn's four key requirements fo... | from IPython.display import IFrame
IFrame('http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', width=300, height=200) | _____no_output_____ | MIT | 03_getting_started_with_iris.ipynb | ArkoMukherjee25/Machine-Learning |
Machine learning on the iris dataset- Framed as a **supervised learning** problem: Predict the species of an iris using the measurements- Famous dataset for machine learning because prediction is **easy** Loading the iris dataset into scikit-learn | # import load_iris function from datasets module
from sklearn.datasets import load_iris
# save "bunch" object containing iris dataset and its attributes
iris = load_iris()
type(iris)
# print the iris data
print(iris.data) | [[5.1 3.5 1.4 0.2]
[4.9 3. 1.4 0.2]
[4.7 3.2 1.3 0.2]
[4.6 3.1 1.5 0.2]
[5. 3.6 1.4 0.2]
[5.4 3.9 1.7 0.4]
[4.6 3.4 1.4 0.3]
[5. 3.4 1.5 0.2]
[4.4 2.9 1.4 0.2]
[4.9 3.1 1.5 0.1]
[5.4 3.7 1.5 0.2]
[4.8 3.4 1.6 0.2]
[4.8 3. 1.4 0.1]
[4.3 3. 1.1 0.1]
[5.8 4. 1.2 0.2]
[5.7 4.4 1.5 0.4]
[5.4 3.9 1.3 0.... | MIT | 03_getting_started_with_iris.ipynb | ArkoMukherjee25/Machine-Learning |
Machine learning terminology- Each row is an **observation** (also known as: sample, example, instance, record)- Each column is a **feature** (also known as: predictor, attribute, independent variable, input, regressor, covariate) | # print the names of the four features
print(iris.feature_names)
# print integers representing the species of each observation
print(iris.target)
# print the encoding scheme for species: 0 = setosa, 1 = versicolor, 2 = virginica
print(iris.target_names) | ['setosa' 'versicolor' 'virginica']
| MIT | 03_getting_started_with_iris.ipynb | ArkoMukherjee25/Machine-Learning |
- Each value we are predicting is the **response** (also known as: target, outcome, label, dependent variable)- **Classification** is supervised learning in which the response is categorical- **Regression** is supervised learning in which the response is ordered and continuous Requirements for working with data in sci... | # check the types of the features and response
print(type(iris.data))
print(type(iris.target))
# check the shape of the features (first dimension = number of observations, second dimensions = number of features)
print(iris.data.shape)
# check the shape of the response (single dimension matching the number of observatio... | _____no_output_____ | MIT | 03_getting_started_with_iris.ipynb | ArkoMukherjee25/Machine-Learning |
PYTHON OBJECTS AND CLASSES Welcome!Objects in programming are like objects in real life. Like life, there are different classes of objects. In this notebook, we will create two classes called Circle and Rectangle. By the end of this notebook, you will have a better idea about :-what a class is-what an attribute is-wha... | import matplotlib.pyplot as plt
%matplotlib inline
| _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
The first step in creating your own class is to use the **class** keyword, then the name of the class. In this course the class parent will always be object: The next step is a special method called a constructor **__init__**, which is used to initialize the object. The input are data attributes. The term **self** co... | class Circle(object):
def __init__(self,radius=3,color='blue'):
self.radius=radius
self.color=color
def add_radius(self,r):
self.radius=self.radius+r
return(self.radius)
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0),... | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
Creating an instance of a class Circle Let’s create the object **RedCircle** of type Circle to do the following: | RedCircle=Circle(10,'red') | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
We can use the **dir** command to get a list of the object's methods. Many of them are default Python methods. | dir(RedCircle) | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
We can look at the data attributes of the object: | RedCircle.radius
RedCircle.color | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
We can change the object's data attributes: | RedCircle.radius=1
RedCircle.radius | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
We can draw the object by using the method **drawCircle()**: | RedCircle.drawCircle() | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
We can increase the radius of the circle by applying the method **add_radius()**. Let increases the radius by 2 and then by 5: | print('Radius of object:',RedCircle.radius)
RedCircle.add_radius(2)
print('Radius of object of after applying the method add_radius(2):',RedCircle.radius)
RedCircle.add_radius(5)
print('Radius of object of after applying the method add_radius(5):',RedCircle.radius) | Radius of object: 1
Radius of object of after applying the method add_radius(2): 3
Radius of object of after applying the method add_radius(5): 8
| MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
Let’s create a blue circle. As the default colour is blue, all we have to do is specify what the radius is: | BlueCircle=Circle(radius=100) | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
As before we can access the attributes of the instance of the class by using the dot notation: | BlueCircle.radius
BlueCircle.color | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
We can draw the object by using the method **drawCircle()**: | BlueCircle.drawCircle() | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
Compare the x and y axis of the figure to the figure for **RedCircle**; they are different. The Rectangle Class Let's create a class rectangle with the attributes of height, width and colour. We will only add the method to draw the rectangle object: | class Rectangle(object):
def __init__(self,width=2,height =3,color='r'):
self.height=height
self.width=width
self.color=color
def drawRectangle(self):
import matplotlib.pyplot as plt
plt.gca().add_patch(plt.Rectangle((0, 0),self.width, self.height ,fc=self.colo... | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
Let’s create the object **SkinnyBlueRectangle** of type Rectangle. Its width will be 2 and height will be 3, and the colour will be blue: | SkinnyBlueRectangle= Rectangle(2,10,'blue') | _____no_output_____ | MIT | Basics of Python/Notebooks/Python_Objects_and_Classes.ipynb | VNSST/Hands_on_Machine_Learning_using_Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.