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
Install the [Category Encoders](https://github.com/scikit-learn-contrib/categorical-encoding) libraryIf you're running on Google Colab:```!pip install category_encoders```If you're running locally with Anaconda:```!conda install -c conda-forge category_encoders```
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Baseline with cross-validation + independent test setA complete example, as an alternative to Train/Validate/Test scikit-learn documentation- [`sklearn.model_selection.cross_val_score`](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html)- [ The `scoring` parameter: defining ...
# Imports %matplotlib inline import warnings import category_encoders as ce import matplotlib.pyplot as plt import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score from sklearn.pipeline import make_pipeline from sklearn.exceptions import DataConversion...
[Parallel(n_jobs=-1)]: Using backend LokyBackend with 2 concurrent workers. [Parallel(n_jobs=-1)]: Done 1 tasks | elapsed: 3.9s [Parallel(n_jobs=-1)]: Done 4 tasks | elapsed: 6.7s [Parallel(n_jobs=-1)]: Done 10 out of 10 | elapsed: 12.8s finished
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
This is the baseline score that more sophisticated models must beat.
print('Cross-Validation ROC AUC scores:', scores) print('Average:', scores.mean())
Cross-Validation ROC AUC scores: [0.82042478 0.79227573 0.79162088 0.762977 0.78662274 0.78877613 0.76414311 0.79607284 0.80670867 0.77968487] Average: 0.7889306746390174
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Is more effort justified? It depends. The blogpost ["Always start with a stupid model"](https://blog.insightdatascience.com/always-start-with-a-stupid-model-no-exceptions-3a22314b9aaa) explains,> Here is a very common story: a team wants to implement a model to predict something like the probability of a user clicking ...
# (Re)fit on training data pipeline.fit(X_train, y_train) # Visualize coefficients plt.figure(figsize=(10,30)) plt.title('Coefficients') coefficients = pipeline.named_steps['logisticregression'].coef_[0] feature_names = pipeline.named_steps['onehotencoder'].transform(X_train).columns pd.Series(coefficients, feature_na...
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Kubeflow pipelines**Learning Objectives:** 1. Learn how to deploy a Kubeflow cluster on GCP 1. Learn how to create a experiment in Kubeflow 1. Learn how to package you code into a Kubeflow pipeline 1. Learn how to run a Kubeflow pipeline in a repeatable and traceable way IntroductionIn this notebook, we will first...
!pip3 install --user kfp --upgrade
Requirement already satisfied: kfp in /home/jupyter/.local/lib/python3.7/site-packages (1.7.2) Requirement already satisfied: google-auth<2,>=1.6.1 in /opt/conda/lib/python3.7/site-packages (from kfp) (1.34.0) Requirement already satisfied: jsonschema<4,>=3.0.1 in /opt/conda/lib/python3.7/site-packages (from kfp) (3.2....
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Restart the kernelAfter you install the additional packages, you need to restart the notebook kernel so it can find the packages. Import libraries and define constants
from os import path import kfp import kfp.compiler as compiler import kfp.components as comp import kfp.dsl as dsl import kfp.gcp as gcp import kfp.notebook
_____no_output_____
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Setup a Kubeflow cluster on GCP **TODO 1** To deploy a [Kubeflow](https://www.kubeflow.org/) clusterin your GCP project, use the [AI Platform pipelines](https://console.cloud.google.com/ai-platform/pipelines):1. Go to [AI Platform Pipelines](https://console.cloud.google.com/ai-platform/pipelines) in the GCP Console.1....
HOST = "" # TODO: fill in the HOST information for the cluster
_____no_output_____
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Authenticate your KFP cluster with a Kubernetes secretIf you run pipelines that requires calling any GCP services, you need to set the application default credential to a pipeline step by mounting the proper GCP service account token as a Kubernetes secret.First point your kubectl current context to your cluster. Go ...
# Change below if necessary PROJECT = !gcloud config get-value project # noqa: E999 PROJECT = PROJECT[0] BUCKET = PROJECT # change if needed CLUSTER = "cluster-1" # change if needed ZONE = "us-central1-a" # change if needed NAMESPACE = "default" # change if needed %env PROJECT=$PROJECT %env CLUSTER=$CLUSTER %env ...
Fetching cluster endpoint and auth data. kubeconfig entry generated for cluster-1.
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
We'll create a service account called `kfpdemo` with the necessary IAM permissions for our cluster secret. We'll give this service account permissions for any GCP services it might need. This `taxifare` pipeline needs access to Cloud Storage, so we'll give it the `storage.admin` role and `ml.admin`. Open a Cloud Shell ...
%%bash gcloud iam service-accounts keys create application_default_credentials.json \ --iam-account kfpdemo@$PROJECT.iam.gserviceaccount.com # Check that the key was downloaded correctly. !ls application_default_credentials.json # Create a k8s secret. If already exists, override. !kubectl create secret generic user-g...
secret/user-gcp-sa configured
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Create an experiment **TODO 2** We will start by creating a Kubeflow client to pilot the Kubeflow cluster:
client = kfp.Client(host=HOST)
_____no_output_____
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Let's look at the experiments that are running on this cluster. Since you just launched it, you should see only a single "Default" experiment:
client.list_experiments()
_____no_output_____
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Now let's create a 'taxifare' experiment where we could look at all the various runs of our taxifare pipeline:
exp = client.create_experiment(name="taxifare")
_____no_output_____
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Let's make sure the experiment has been created correctly:
client.list_experiments()
_____no_output_____
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Packaging your code into Kubeflow components We have packaged our taxifare ml pipeline into three components:* `./components/bq2gcs` that creates the training and evaluation data from BigQuery and exports it to GCS* `./components/trainjob` that launches the training container on AI-platform and exports the model* `./c...
# Builds the taxifare trainer container in case you skipped the optional part # of lab 1 !taxifare/scripts/build.sh # Pushes the taxifare trainer container to gcr/io !taxifare/scripts/push.sh # Builds the KF component containers and push them to gcr/io !cd pipelines && make components
make[1]: Entering directory '/home/jupyter/asl-ml-immersion/notebooks/building_production_ml_systems/solutions/pipelines/components/bq2gcs' rm: cannot remove './venv': No such file or directory OK Sending build context to Docker daemon 21.5kB Step 1/6 : FROM google/cloud-sdk:latest ---> 915a516535e8 Step 2/6 : RUN a...
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Now that the container images are pushed to the [registry in your project](https://console.cloud.google.com/gcr), we need to create yaml files describing to Kubeflow how to use these containers. It boils down essentially to* describing what arguments Kubeflow needs to pass to the containers when it runs them* telling K...
%%writefile bq2gcs.yaml name: bq2gcs description: | This component creates the training and validation datasets as BiqQuery tables and export them into a Google Cloud Storage bucket at gs://qwiklabs-gcp-00-568a75dfa3e1/taxifare/data. inputs: - {name: Input Bucket , type: String, descr...
Overwriting deploymodel.yaml
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
Create a Kubeflow pipeline The code below creates a kubeflow pipeline by decorating a regular function with the`@dsl.pipeline` decorator. Now the arguments of this decorated function will bethe input parameters of the Kubeflow pipeline.Inside the function, we describe the pipeline by* loading the yaml component files ...
# TODO 3 PIPELINE_TAR = "taxifare.tar.gz" BQ2GCS_YAML = "./bq2gcs.yaml" TRAINJOB_YAML = "./trainjob.yaml" DEPLOYMODEL_YAML = "./deploymodel.yaml" @dsl.pipeline( name="Taxifare", description="Train a ml model to predict the taxi fare in NY", ) def pipeline(gcs_bucket_name="<bucket where data and model will be ...
_____no_output_____
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
The pipeline function above is then used by the Kubeflow compiler to create a Kubeflow pipeline artifact that can be either uploaded to the Kubeflow cluster from the UI, or programatically, as we will do below:
compiler.Compiler().compile(pipeline, PIPELINE_TAR) ls $PIPELINE_TAR
taxifare.tar.gz
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
If you untar and uzip this pipeline artifact, you'll see that the compiler has transformed thePython description of the pipeline into yaml description!Now let's feed Kubeflow with our pipeline and run it using our client:
# TODO 4 run = client.run_pipeline( experiment_id=exp.id, job_name="taxifare", pipeline_package_path="taxifare.tar.gz", params={ "gcs_bucket_name": BUCKET, }, )
_____no_output_____
Apache-2.0
notebooks/building_production_ml_systems/solutions/3_kubeflow_pipelines.ipynb
Jonathanpro/asl-ml-immersion
**Setup**
%reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.vision import *
_____no_output_____
Apache-2.0
planet_experimental2.ipynb
amittal27/course-v3
**Configure data**
path = Path.cwd()/'planet' path.mkdir(parents=True, exist_ok=True) path
_____no_output_____
Apache-2.0
planet_experimental2.ipynb
amittal27/course-v3
**Multiclassification**
# read the csv file using the pandas library (popular way of dealing with tabular data in python), print the first five rows df = pd.read_csv(path/'train_classes.csv') df.head() # data augmentation tfms = get_transforms(flip_vert=True, max_lighting=0.1, max_zoom=1.05, max_warp=0) # do not want warp on the satellite ima...
_____no_output_____
Apache-2.0
planet_experimental2.ipynb
amittal27/course-v3
**Metrics**metrics to print out during training (NOTE: they do not impact how our model trains); just shows us how we're doing
# however, instead of picking just one of the classes in len(data.classes) as our prediction label, we want to pick out n of those classes # anything higher than a desired threshold will be assumed to be a label for the input image # accuracy uses argmax to find the category with the maximum probability of being repres...
_____no_output_____
Apache-2.0
planet_experimental2.ipynb
amittal27/course-v3
**Now, create a whole "new" dataset where the images are 256 x 256 to hopefully increase our fbeta metric score**no concern of overfitting then
# create new databunch with 256 x 256 images (higher res images) data = (src.transform(tfms, size=256), # same transforms as before .databunch.normalize(imagenet_stats)) # start with our pre-trained model learn.data = data # replace learner data with new databunch data.train_ds[0][0].shape # freeze to just trai...
_____no_output_____
Apache-2.0
planet_experimental2.ipynb
amittal27/course-v3
Convolutional Neural Networks: Step by StepWelcome to Course 4's first assignment! In this assignment, you will implement convolutional (CONV) and pooling (POOL) layers in numpy, including both forward propagation and (optionally) backward propagation. By the end of this notebook, you'll be able to: * Explain the conv...
import numpy as np import h5py import matplotlib.pyplot as plt from public_tests import * %matplotlib inline plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' %load_ext autoreload %autoreload 2 np.random.seed(1)
_____no_output_____
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
2 - Outline of the AssignmentYou will be implementing the building blocks of a convolutional neural network! Each function you will implement will have detailed instructions to walk you through the steps:- Convolution functions, including: - Zero Padding - Convolve window - Convolution forward - Convoluti...
# GRADED FUNCTION: zero_pad def zero_pad(X, pad): """ Pad with zeros all images of the dataset X. The padding is applied to the height and width of an image, as illustrated in Figure 1. Argument: X -- python numpy array of shape (m, n_H, n_W, n_C) representing a batch of m images pad -- i...
x.shape = (4, 3, 3, 2) x_pad.shape = (4, 9, 9, 2) x[1,1] = [[ 0.90085595 -0.68372786] [-0.12289023 -0.93576943] [-0.26788808 0.53035547]] x_pad[1,1] = [[0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.] [0. 0.]] [[0. 0. 0. 0. 0. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 0. 0.]]  All tests pas...
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
3.2 - Single Step of Convolution In this part, implement a single step of convolution, in which you apply the filter to a single position of the input. This will be used to build a convolutional unit, which: - Takes an input volume - Applies a filter at every position of the input- Outputs another volume (usually of d...
# GRADED FUNCTION: conv_single_step def conv_single_step(a_slice_prev, W, b): """ Apply one filter defined by parameters W on a single slice (a_slice_prev) of the output activation of the previous layer. Arguments: a_slice_prev -- slice of input data of shape (f, f, n_C_prev) W -- Weight ...
Z = -6.999089450680221  All tests passed.
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
3.3 - Convolutional Neural Networks - Forward PassIn the forward pass, you will take many filters and convolve them on the input. Each 'convolution' gives you a 2D matrix output. You will then stack these outputs to get a 3D volume: Exercise 3 - conv_forwardImplement the function below to convolve the filters `W` on...
# GRADED FUNCTION: conv_forward def conv_forward(A_prev, W, b, hparameters): ''' Implements the forward propagation for a convolution function Arguments: A_prev -- output activations of the previous layer, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) W -- Weights, numpy arra...
Z's mean = 0.5511276474566768 Z[0,2,1] = [-2.17796037 8.07171329 -0.5772704 3.36286738 4.48113645 -2.89198428 10.99288867 3.03171932] cache_conv[0][1][2][3] = [-1.1191154 1.9560789 -0.3264995 -1.34267579] (2, 13, 15, 8)  All tests passed.
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
Finally, a CONV layer should also contain an activation, in which case you would add the following line of code:```python Convolve the window to get back one output neuronZ[i, h, w, c] = ... Apply activationA[i, h, w, c] = activation(Z[i, h, w, c])```You don't need to do it here, however. 4 - Pooling Layer The poolin...
# GRADED FUNCTION: pool_forward def pool_forward(A_prev, hparameters, mode = "max"): """ Implements the forward pass of the pooling layer Arguments: A_prev -- Input data, numpy array of shape (m, n_H_prev, n_W_prev, n_C_prev) hparameters -- python dictionary containing "f" and "stride" mod...
mode = max A.shape = (2, 3, 3, 3) A[1, 1] = [[1.96710175 0.84616065 1.27375593] [1.96710175 0.84616065 1.23616403] [1.62765075 1.12141771 1.2245077 ]] mode = average A.shape = (2, 3, 3, 3) A[1, 1] = [[ 0.44497696 -0.00261695 -0.31040307] [ 0.50811474 -0.23493734 -0.23961183] [ 0.11872677 0.17255229 -0.22112197]...
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
**Expected output**```mode = maxA.shape = (2, 3, 3, 3)A[1, 1] = [[1.96710175 0.84616065 1.27375593] [1.96710175 0.84616065 1.23616403] [1.62765075 1.12141771 1.2245077 ]]mode = averageA.shape = (2, 3, 3, 3)A[1, 1] = [[ 0.44497696 -0.00261695 -0.31040307] [ 0.50811474 -0.23493734 -0.23961183] [ 0.11872677 0.17255229 -0...
# Case 2: stride of 2 np.random.seed(1) A_prev = np.random.randn(2, 5, 5, 3) hparameters = {"stride" : 2, "f": 3} A, cache = pool_forward(A_prev, hparameters) print("mode = max") print("A.shape = " + str(A.shape)) print("A[0] =\n", A[0]) print() A, cache = pool_forward(A_prev, hparameters, mode = "average") print("mo...
mode = max A.shape = (2, 2, 2, 3) A[0] = [[[1.74481176 0.90159072 1.65980218] [1.74481176 1.6924546 1.65980218]] [[1.13162939 1.51981682 2.18557541] [1.13162939 1.6924546 2.18557541]]] mode = average A.shape = (2, 2, 2, 3) A[1] = [[[-0.17313416 0.32377198 -0.34317572] [ 0.02030094 0.14141479 -0.01231585]...
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
**Expected Output:** ```mode = maxA.shape = (2, 2, 2, 3)A[0] = [[[1.74481176 0.90159072 1.65980218] [1.74481176 1.6924546 1.65980218]] [[1.13162939 1.51981682 2.18557541] [1.13162939 1.6924546 2.18557541]]]mode = averageA.shape = (2, 2, 2, 3)A[1] = [[[-0.17313416 0.32377198 -0.34317572] [ 0.02030094 0.1414147...
def conv_backward(dZ, cache): """ Implement the backward propagation for a convolution function Arguments: dZ -- gradient of the cost with respect to the output of the conv layer (Z), numpy array of shape (m, n_H, n_W, n_C) cache -- cache of values needed for the conv_backward(), output of conv...
dA_mean = 1.4524377775388075 dW_mean = 1.7269914583139097 db_mean = 7.839232564616838  All tests passed.
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
**Expected Output**: dA_mean 1.45243777754 dW_mean 1.72699145831 db_mean 7.83923256462 5.2 Pooling Layer - Backward PassNext, let's i...
def create_mask_from_window(x): """ Creates a mask from an input matrix x, to identify the max entry of x. Arguments: x -- Array of shape (f, f) Returns: mask -- Array of the same shape as window, contains a True at the position corresponding to the max entry of x. """ # (≈...
x = [[ 1.62434536 -0.61175641 -0.52817175] [-1.07296862 0.86540763 -2.3015387 ]] mask = [[ True False False] [False False False]]  All tests passed.
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
**Expected Output:** **x =**[[ 1.62434536 -0.61175641 -0.52817175] [-1.07296862 0.86540763 -2.3015387 ]] mask =[[ True False False] [False False False]] Why keep track of the position of the max? It's because this is the input value that ultimately influenced the output, and therefore the cost. Backprop is compu...
def distribute_value(dz, shape): """ Distributes the input value in the matrix of dimension shape Arguments: dz -- input scalar shape -- the shape (n_H, n_W) of the output matrix for which we want to distribute the value of dz Returns: a -- Array of size (n_H, n_W) for which we dis...
distributed value = [[0.5 0.5] [0.5 0.5]]  All tests passed.
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
**Expected Output**: distributed_value =[[ 0.5 0.5] [ 0.5 0.5]] 5.2.3 Putting it Together: Pooling Backward You now have everything you need to compute backward propagation on a pooling layer. Exercise 8 - pool_backwardImplement the `pool_backward` function in both modes (`"max"` and `"average"`). You will once ag...
def pool_backward(dA, cache, mode = "max"): """ Implements the backward pass of the pooling layer Arguments: dA -- gradient of cost with respect to the output of the pooling layer, same shape as A cache -- cache output from the forward pass of the pooling layer, contains the layer's input and h...
(5, 4, 2, 2) (5, 5, 3, 2) mode = max mean of dA = 0.14571390272918056 dA_prev1[1,1] = [[ 0. 0. ] [ 5.05844394 -1.68282702] [ 0. 0. ]] mode = average mean of dA = 0.14571390272918056 dA_prev2[1,1] = [[ 0.08485462 0.2787552 ] [ 1.26461098 -0.25749373] [ 1.17975636 -0.53624893]] ...
MIT
Convolution_model_Step_by_Step_v1.ipynb
rahul23aug/DeepLearning
Beginning Programming with Python===========================Session 1: Getting Started--------------------------* The Zen of Python* Variables* Comments* Strings* Numbers* Booleans* String Methods* Using Variables in Strings* Numerical Operations* Working with Numerical Data* Using the Math library* Setting up Anaconda...
2 + 5 import this
_____no_output_____
MIT
april-2019/1-getting-started.ipynb
dogweather/beginning-programming-with-python
Variables---------
phoebe = 8 print(phoebe) print(id(phoebe)) maru = 7 id(maru) 4fun = 3 fun4 = 3 m = 7 phoebe_age_in_years = 8 dog_name = "Phoebe" print(dog_name) type(dog_name) type(phoebe) dog_name + phoebe dog_name + " is a dog"
_____no_output_____
MIT
april-2019/1-getting-started.ipynb
dogweather/beginning-programming-with-python
Comments--------
# I'm attempting to calculate dog years for humans dog = 1222 # Here's something # ... And etc. # and more... """Calculate the age very simply. I'm using the standard algorithm... """ age = 10
_____no_output_____
MIT
april-2019/1-getting-started.ipynb
dogweather/beginning-programming-with-python
Strings-------
4 + 4 "4" + "4" len("robb") dir("robb") "robb".endswith('b') "robb".endswith('x') "Phoebe".lower() "Here's a meanlingless sentence.".split() "phoebe" print("hey") name = "Ramona" f"{name} said thanks!" name + " said thanks!" "%s said thanks!", name "{} said thanks! {}".format(name, "hey")
_____no_output_____
MIT
april-2019/1-getting-started.ipynb
dogweather/beginning-programming-with-python
Numbers-------
type(5) type(5.5) account_balance = 100.1111111 5.5 + 5 5.5 + "5" 5.5 + float("5") float("0") type(0.0) float("x") int("0") int("x") "x" x x = 1 x id(x) "x"
_____no_output_____
MIT
april-2019/1-getting-started.ipynb
dogweather/beginning-programming-with-python
Booleans--------
1, -1, 0 type(1) False True 1 == 2 1 == 1 not (1 == 1) not (True and False) (not True) or (not False) if 1 == 2: print("The world's gone mad") if 1 == 1: print("No problem with that") phoebe_is_old = phoebe > 12 phoebe_is_old if phoebe_is_old: print("old") phoebe o = phoebe > 12 O = maru > 12 Math.PI impo...
_____no_output_____
MIT
april-2019/1-getting-started.ipynb
dogweather/beginning-programming-with-python
Numerical Data and the Math Library-----------------------------------
round(1.23456) round(1.5) round(1.4) help(round) round(1.23456, 2) 1.23 * 1.07 round(1.23 * 1.07, 2) round('x' + 'y', 2) abs(3) abs(-3) 2 % 3 3 % 2 3 % 2 == 0 10 % 2 == 0 10 % 3 == 0 15 % 3 == 0 not(10 % 2 == 0) 10 % 7 != 0
_____no_output_____
MIT
april-2019/1-getting-started.ipynb
dogweather/beginning-programming-with-python
Using the Math Library----------------------
import math x math dir(math) math pi math.pi math.factorial(4) math.factorial(10) help(math.ceil) math.ceil(1.1) math.ceil type(math.ceil)
_____no_output_____
MIT
april-2019/1-getting-started.ipynb
dogweather/beginning-programming-with-python
`concurrent.futures`This lesson has a strange name. `concurrent.futures` is the name of a (relative) modern package in the Python standard library. It's a package with a beautiful and Pythonic API that abstracts us from the low level mechanisms of concurrency.**`concurrent.futures` should be your default choice for co...
def check_price(exchange, symbol, date): base_url = "http://localhost:5000" resp = requests.get(f"{base_url}/price/{exchange}/{symbol}/{date}") return resp.json() with ThreadPoolExecutor(max_workers=10) as ex: future = ex.submit(check_price, 'bitstamp', 'btc', '2020-04-01') print(f"Price: ${future.r...
Price: $6421.14
MIT
7. concurrent.futures.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
This is the beauty of `cf`: we're using the same logic with two completely different executors; the API is the same. FuturesAs you can see from the the examples above, the `submit` method returns immediately a `Future` object. These objects are an abstraction of a task that is being processed. They have multiple useful...
with ThreadPoolExecutor(max_workers=10) as ex: future = ex.submit(check_price, 'bitstamp', 'btc', '2020-04-01') print(future.done()) print(f"Price: ${future.result()['close']}") print(future.done())
False Price: $6421.14 True
MIT
7. concurrent.futures.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
The `map` methodExecutors have a `map` method that is similar to `mp.Pool.map`, it's convenient as there are no futures to work with, but it's limited as only one parameter can be passed:
EXCHANGES = ['bitfinex', 'bitstamp', 'kraken'] def check_price_tuple(arg): exchange, symbol, date = arg base_url = "http://localhost:5000" resp = requests.get(f"{base_url}/price/{exchange}/{symbol}/{date}") return resp.json() with ThreadPoolExecutor(max_workers=10) as ex: results = ex.map(check_pric...
_____no_output_____
MIT
7. concurrent.futures.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
As you can see, we had to define a new special function that works by receiving a tuple instead of the individual elements. `submit` & `as_completed` patternTo overcome the limitation of `Executor.map`, we can use a common pattern of creating multiple futures with `Executor.submit` and waiting for them to complete with...
with ThreadPoolExecutor(max_workers=10) as ex: futures = { ex.submit(check_price, exchange, 'btc', '2020-04-01'): exchange for exchange in EXCHANGES } for future in cf.as_completed(futures): exchange = futures[future] print(f"{exchange.title()}: ${future.result()['close']}")
Kraken: $6401.9 Bitfinex: $6409.8 Bitstamp: $6421.14
MIT
7. concurrent.futures.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
Producer/Consumer with `concurrent.futures`I'll show you an example of the producer/consumer pattern using the `cf` module. There are multiple ways to create this pattern, I'll stick to the basics.
BASE_URL = "http://localhost:5000" resp = requests.get(f"{BASE_URL}/exchanges") EXCHANGES = resp.json() EXCHANGES[:3] START_DATE = datetime(2020, 3, 1) DATES = [(START_DATE + timedelta(days=i)).strftime('%Y-%m-%d') for i in range(31)] DATES[:3] resp = requests.get(f"{BASE_URL}/symbols") SYMBOLS = resp.json() SYMBOLS
_____no_output_____
MIT
7. concurrent.futures.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
Queues:
work_to_do = Queue() work_done = SimpleQueue() for exchange in EXCHANGES: for date in DATES: for symbol in SYMBOLS: task = { 'exchange': exchange, 'symbol': symbol, 'date': date, } work_to_do.put(task) work_to_do.qsize() def...
_____no_output_____
MIT
7. concurrent.futures.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
Basic Ensemble Learinng : Hard/Soft Voting/Bagging - OOB/bootstraps/bootstrap_features
##----------------- ## Copyright in private ## Modify History : ## 2018 - 9 - 24 ## Purpose: ## 1. 集成学习分类器 构建 - 集成多个子模型来投票,提供准确率,理论上子模型越多,整体模型的准确率将很高! ## 2. Hard(少数服从多数) and Soft voting classifier ## ## 3. 为提高每个子模型的差异性。希望每个子模型只看一部分的数据样本。 在看样本的形式上可以分为:放回取样(bagging)和不放回取样方法(pasting) ##...
_____no_output_____
MIT
6_Ensemble Learing_HardandSoft_VotingClasaifier_OOB_Boostrap_Features.ipynb
Yazooliu/Ai_Lab_
1. EnsembleLearning Classifier
from sklearn.linear_model import LogisticRegression # Logistic Regression log_clf = LogisticRegression() log_clf.fit(X_train,y_train) #log_clf.score(X_test,y_test) # 0.83 # SVM from sklearn.svm import SVC svc_clf = SVC() svc_clf.fit(X_train,y_train) #svc_clf.score(X_test,y_test) #0.98 # Decision Tree from sklearn....
_____no_output_____
MIT
6_Ensemble Learing_HardandSoft_VotingClasaifier_OOB_Boostrap_Features.ipynb
Yazooliu/Ai_Lab_
1.1 Ensemble Leaning 1.1.1集成学习的效果- 人多力量大,明显比单个分类器的分类结果准确率要高
predict_1 = log_clf.predict(X_test) predict_2 = svc_clf.predict(X_test) predict_3 = dt_clf.predict(X_test) # predict_y = np.array((predict_1 + predict_2 + predict_3) >=2 ,dtype = 'int') predict_y[:10] from sklearn.metrics import accuracy_score accuracy_score(y_test,predict_y)
_____no_output_____
MIT
6_Ensemble Learing_HardandSoft_VotingClasaifier_OOB_Boostrap_Features.ipynb
Yazooliu/Ai_Lab_
2. Voting Classifier - Hard Voting - 少数服从多数准则
# Harding voting - 少数服从多数 from sklearn.ensemble import VotingClassifier voting_clf_hard = VotingClassifier(estimators = [ ('log_clf',LogisticRegression()), ('svm_clf',SVC()), ('dt_clf',DecisionTreeClassifier(random_state = 200))], voting = 'hard') # test score by hard voting classifier voting_clf_hard.f...
c:\users\h155809\appdata\local\programs\python\python36\lib\site-packages\sklearn\preprocessing\label.py:151: DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use `array.size > 0` to check that an array is not empty. if diff:
MIT
6_Ensemble Learing_HardandSoft_VotingClasaifier_OOB_Boostrap_Features.ipynb
Yazooliu/Ai_Lab_
3. Voting Classifier - Soft Voting -考虑以分类的概率作为权值 来分类
from sklearn.ensemble import VotingClassifier voting_clf_soft = VotingClassifier(estimators = [ ('log_clf', LogisticRegression()), ('svc_clf',SVC(probability=True)), ('dt_clf', DecisionTreeClassifier(random_state = 200))],voting = 'soft') voting_clf_soft.fit(X_train,y_train) voting_clf_soft.score(X_test,y...
c:\users\h155809\appdata\local\programs\python\python36\lib\site-packages\sklearn\preprocessing\label.py:151: DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use `array.size > 0` to check that an array is not empty. if diff:
MIT
6_Ensemble Learing_HardandSoft_VotingClasaifier_OOB_Boostrap_Features.ipynb
Yazooliu/Ai_Lab_
4. 放回的取样方法 - Bagging
# 提高子模型的差异可以提高整体模型的准确率,并且可以让模型看不同数量的样本数量。 # 在取样本时,分为放回取样方法- Bagging and 不放回取样 pasting from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier # 以DecisionTree 为例 # n_estimators : 集成多少个分类器模型 # max_sample: 分类器一次看多少数据 # bootstrap = True: 可放回取样 bagging_clf = BaggingClassifier( De...
_____no_output_____
MIT
6_Ensemble Learing_HardandSoft_VotingClasaifier_OOB_Boostrap_Features.ipynb
Yazooliu/Ai_Lab_
4.1 放回取样方法Bagging - Out of Bag(OOB) 有大约30%的数据取不到
# 有放回的取样本,并通过 oob_score = True 来确定标记没有被取到的样本数量。并将这些样本用于测试样本准确度 bagging_clf = BaggingClassifier( DecisionTreeClassifier(), n_estimators = 100,max_samples = 100, bootstrap = True,oob_score = True ) bagging_clf.fit(X_train,y_train) bagging_clf.score(X_test,y_test) # test model on out of bag data bagging_clf.oob_s...
_____no_output_____
MIT
6_Ensemble Learing_HardandSoft_VotingClasaifier_OOB_Boostrap_Features.ipynb
Yazooliu/Ai_Lab_
4.2 放回取样方法Bagging - Out of Bag(OOB) - 基于样本特征的取样方法 - bootstrap_features
## 有放回的取样本 , 基于样本特征的取样方法,并标记最大取样特征数量max_features ## from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import BaggingClassifier # max_features - 每次取样特征数量 # bootstrap_features = True 基于特征的取样方法 bagging_clf_features = BaggingClassifier( DecisionTreeClassifier(), n_estimators = 100,max_samples...
_____no_output_____
MIT
6_Ensemble Learing_HardandSoft_VotingClasaifier_OOB_Boostrap_Features.ipynb
Yazooliu/Ai_Lab_
here true says is is stopped and we can say drone is hit something and stopped we can say
env.step(0)
_____no_output_____
Apache-2.0
RL1.ipynb
bsivavenu/Google_Colab_Notebooks
multiarmbandit
env = MultiArmedBandit()
_____no_output_____
Apache-2.0
RL1.ipynb
bsivavenu/Google_Colab_Notebooks
Stay classification: MBC evaluation**31.08.2020**
import numpy as np import pandas as pd import os, sys sys.path.append('/home/sandm/Notebooks/stay_classification/src/') %matplotlib inline import matplotlib.pyplot as plt from synthetic_data.trajectory_class import get_pickle_trajectory from synthetic_data.trajectory import get_stay_segs, get_adjusted_stays from stay_c...
_____no_output_____
MIT
notebooks/classifiers_playground/metric_box_classifier/classifier_1D__metric_box_classifier__3stays_illustrate_metrics.ipynb
m-salewski/stay_classification
Batch data evaluation
dsec = 1/3600.0 t_total = np.arange(0,24,dsec) time_thresh = 1/6 dist_thresh=0.25 nr_stays = 3 data_dir = os.path.abspath('../../')+f"/classifiers_playground/metric_box_classifier/testdata_training_set__canonical_{nr_stays}stays/" os.path.isdir(data_dir) import glob #data_dir = os.path.abspath('../../')+f"/testdata/te...
_____no_output_____
MIT
notebooks/classifiers_playground/metric_box_classifier/classifier_1D__metric_box_classifier__3stays_illustrate_metrics.ipynb
m-salewski/stay_classification
Load, Classify, Measure
# For the correct nr of stays lens3 = [] precs3, a_precs3, w_precs3 = [], [], [] recs3, a_recs3, w_recs3 = [], [], [] errs3, a_errs3, w_errs3 = [], [], [] # For the incorrect nr of stays lens = [] precs, a_precs, w_precs = [], [], [] recs, a_recs, w_recs = [], [], [] errs, a_errs, w_errs = [], [], [] bad_list = [] ...
* correct number of stays, 0.796 * prec.: 0.956 * rec.: 0.994 * incorrect number of stays, 0.204 * prec.: 0.856 * rec.: 0.95
MIT
notebooks/classifiers_playground/metric_box_classifier/classifier_1D__metric_box_classifier__3stays_illustrate_metrics.ipynb
m-salewski/stay_classification
Visualizations
from stay_classification.metrics_plotting import plot_scores_stats, plot_errs_stats, plot_scores_stats_cominbed os.mkdir('./visualizations/metrics_new/')
_____no_output_____
MIT
notebooks/classifiers_playground/metric_box_classifier/classifier_1D__metric_box_classifier__3stays_illustrate_metrics.ipynb
m-salewski/stay_classification
Prec/rec score distributions Total scores
title = f"Tot. scores: correct stays, {correct_frac:6.3f}; incorrect stays, {incorrect_frac:6.3f}" fig, axs = plot_scores_stats(precs3, recs3, precs, recs, title) fig.savefig("./visualizations/metrics_new/" + f"metrics__{nr_stays}stays.png") title = f"Total scores: correct stays, {correct_frac:6.3f}; incorrect stays,...
_____no_output_____
MIT
notebooks/classifiers_playground/metric_box_classifier/classifier_1D__metric_box_classifier__3stays_illustrate_metrics.ipynb
m-salewski/stay_classification
Segment-averaged score distributions
title = f"Avg. scores: correct stays, {correct_frac:6.3f}; incorrect stays, {incorrect_frac:6.3f}" fig, axs = plot_scores_stats(a_precs3, a_recs3, a_precs, a_recs, title) fig.savefig("./visualizations/metrics_new/" + f"metrics__{nr_stays}stays_seg_scores_avg.png") title = f"Avg. Scores: correct stays, {correct_frac:6...
_____no_output_____
MIT
notebooks/classifiers_playground/metric_box_classifier/classifier_1D__metric_box_classifier__3stays_illustrate_metrics.ipynb
m-salewski/stay_classification
Segment, weighted-averaged score distributions
title = f"W-avg. scores: correct stays, {correct_frac:6.3f}; incorrect stays, {incorrect_frac:6.3f}" fig, axs = plot_scores_stats(w_precs3, w_recs3, w_precs, w_recs, title) fig.savefig("./visualizations/metrics_new/" + f"metrics__{nr_stays}stays_seg_scores_wavg.png") title = f"W-avg. Scores: correct stays, {correct_f...
_____no_output_____
MIT
notebooks/classifiers_playground/metric_box_classifier/classifier_1D__metric_box_classifier__3stays_illustrate_metrics.ipynb
m-salewski/stay_classification
Error stats
title = f"Avg. Error: correct stays, {correct_frac:6.3f}; incorrect stays, {incorrect_frac:6.3f}" fig, ax = plot_errs_stats(w_errs3, w_errs, title) fig.savefig("./visualizations/metrics_new/" + f"metrics__{nr_stays}stays_seg_errs_avg.png") title = f"W-avg. Error: correct stays, {correct_frac:6.3f}; incorrect stays, {...
_____no_output_____
MIT
notebooks/classifiers_playground/metric_box_classifier/classifier_1D__metric_box_classifier__3stays_illustrate_metrics.ipynb
m-salewski/stay_classification
Capturer un texte saisi par l'utilisateurNous nous proposons d'écrire un programme qui demande et stocke le nom de l'utilisateur, l'âge de l'utilisateur et stocke une valeur qui renseigne si l'utilisateur est majeur ou non. Par la suite nous afficherons un message de salutation à cet utilisateur, son âge ainsi que sa m...
nom = input("Veuillez saisir votre nom: ") age = int(input("Veuillez saisir votre age: ")) estMajeur = age >= 18 print(f'Bonjour {nom}') print(f'vous avez {age} ans') print(f'Etes-vous majeur? {estMajeur}')
Veuillez saisir votre nom: Hippo Veuillez saisir votre age: 15
MIT
Jour 2/chap02-04-saisie-utilisateur.ipynb
bellash13/SmartAcademyPython
Repaso de ciclos, cadenas, tuplas y listas Cobra MosmasAl ver los precios y los anuncios del almacén Cobra Mosmas, un cliente lepide crear un programa de computador que le permita ingresar el precioindividual de tres productos y el precio de la promoción en combo de lostres productos anunciada por el almacen y determ...
#piense aquí la solución
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Solución
def comprar(p1,p2,p3,pc): if pc <= p1+p2+p3: return 'Combo' else: return 'Por separado' a=float(input('Precio primer producto?')) b=float(input('Precio segundo producto?')) c=float(input('Precio tercer producto?')) d=float(input('Precio combo?')) print("Comprar",comprar(a,b,c,d))
Precio primer producto?1 Precio segundo producto?2 Precio tercer producto?3 Precio combo?4 Comprar Combo
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
La cercaUn campesino de la región le pide crear un programa de computador quele permita determinar cual de dos opciones (madera o alambre) es la mejoropción (menor costo) para encerrar un terreno rectangular de 𝑛 ∗ 𝑚 metroscuadrados, sabiendo el costo de un metro lineal de alambre, el costo de unmetro de madera y la...
def en_madera(n,m,w,p): return (2*n+2*m)*w*p def en_alambre(n,m,h,a): return (2*n+2*m)*h*a def usar(n,m,h,a,w,p): if en_madera(n,m,w,p) <= en_alambre(n,m,h,a): return 'Madera' else: return 'Alambre' n=float(input('Largo terreno?')) m=float(input('Ancho terreno?')) a=float(input('C...
Largo terreno?2 Ancho terreno?4 Costo metro alambre?4 Hilos de alambre?3 Costo metro madera?2 Hileras de madera?2 Usar Madera
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Lista EscolarUnos padres de familia desesperados por determinar el dinero que debenpedir prestado para pagar los útiles escolares de su hijo, le han pedido crearun programa de computador que a partir de una lista de los precios de cada útil escolar y de la cantidad de cada útil escolar en la lista, determineel precio ...
def costo(precio, cantidad): costo = 0 for i in range(0,len(precio)): costo = costo + precio[i] * cantidad[i] return costo precio = [] cantidad = [] while input('Ingresar otro útil?').upper()=='S': precio.append(float(input('Precio útil?'))) cantidad.append(float(input('Cantidad?'))) print(...
Ingresar otro útil?S Precio útil?3999 Cantidad?1 Ingresar otro útil?N La lista cuesta 3999.0
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
ADNEn la última edición de la revista científica ”ADN al día” se indica que laspruebas de relación entre individuos a partir de código genético se definede la siguiente manera: Si las dos cadenas se diferencian en menos de𝑝letras, existe una relación de padre-hijo, si se diferencian en menos de𝑓 > 𝑝letras, existe u...
def diferencia(a,b): cuenta = 0 for i in range(0,len(a)): if a[i] != b[i]: cuenta = cuenta + 1 return cuenta def relacion(a,b,p,f): d = diferencia(a,b) if d <= p: return 'Padre-Hijo' elif d <= f: return 'Familia' else: ...
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Extraer nombres de universidades ColombianasDada una lista de Universidades Colombianas, obtener el nombre del sitio web. Se asume que un nombre de universidad está entre los caracteres www. y edu.co. Por ejemplo de www.unal.edu.co se obtiene unal.*Entrada:*Un numero n indicando la cantidad de nombres de sitios web a...
#escriba aquí la solución
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Solucion:
def process(uni): return uni.split(".")[1] def main(): n = int(input()) for i in range(n): uni = input() print(process(uni)) main()
www.k.edu.co
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Leer información de estudiantes y calcular el promedio de notas Se tienen que procesar algunos comandos para realizar el procesamiento de notas de una Universidad. Se tiene una lista de estudiantes - Comando 1: Agregar estudiante y nota `1&nombre_estudiante&nota`- Comando 2: Calcular promedio de los estudiantes en un ...
#ingrese aquí la solución
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Para poder resolver el problema se pueden identificar varias partes a resolver que pueden modelarse como funciones:- Definir la lista de estudiantes.- agregar un estudiante dada la información- calcular el promedio de notas de los estudiantes en un momento dado- ordenar estudiantes agregados por nombre- consultar la no...
# definir la lista de estudiantes un estudiante puede ser modelado como una tupla (por ahora) def agregar_estudiante(estudiantes, est): estudiantes.append(est) def promedio(estudiantes): prom = 0 #print(estudiantes) for estudiante in estudiantes: prom += float(estudiante[1]) print("El ...
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Entendiendo los sentimientos de GrootEl lenguaje de Groot es muy complicado para expresar sentimientos. Los sentimientos tienen n capas.Si n = 1, el sentimiento será "I hate it", si n = 2 es "I hate that I love it", y si n = 3 es "I hate that I love that I hate it" y así sucesivamente.*Entrada:*La cantidad n de capas...
#piense aquí la solución en caso de no plantear ninguna abra la siguiente celda
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Una posible opción para grootUna posible opción puede ser construir una tupla ó lista con dos elementos:
emocion = ["I hate", "I love"]
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Puede ir alternando entre posiciones de la lista el ciclo así:
salida = [] n = int(input()) for i in range(n): salida.append(emocion[i%2]) print(salida)
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Se puede usar join con that...
res = " that ".join(salida)
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Agregue it:
res += " it " print(res)
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Es posible generar esta solución con una lista creada por comprensión?
#intentelo aquí
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Solución
emocion = ["I hate", "I love"] salida = " that ".join([emocion[i % 2] for i in range(n)])+" it" print(salida)
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
Simplificador de FraccionesUtilizando funciones recursivas, elabore un programa que simplifique una fracción escrita de la forma a/b.Ejemplo: EntradaSalida 6/43/2
_____no_output_____
MIT
Cycle_1/Week_4/Session_16/12_Ejercicios_de_Repaso.ipynb
htrismicristo/MisionTIC_2022
King-County-House-Price-Prediction
# Importing libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import sklearn from sklearn.metrics import mean_absolute_error, mean_squared_error,r2_score from sklearn.preprocessing import MinMaxScaler, StandardScaler # Ignore warnings import warnings warnings....
_____no_output_____
Apache-2.0
King-County-House-Price-Prediction.ipynb
norochalise/House-Price-Prediction-to-Deoployment
1. Loading Dataset and Explore
df = pd.read_csv('/content/dataset/kc_house_data.csv') df.head() df.shape df.info() # Delete Unwanted columns df.drop(['id', 'date'], axis=1, inplace=True) # Display missing values information df.isna().sum().sort_values(ascending=False) df.describe().T
_____no_output_____
Apache-2.0
King-County-House-Price-Prediction.ipynb
norochalise/House-Price-Prediction-to-Deoployment
2. EDA
# classification cat_col and num_col for plotting cat_col = [] num_col = [] col_name = df.columns for idx, value in enumerate(col_name): con = df[value].nunique() if(con<20): cat_col.append(value) else: num_col.append(value) def bar_plot(data, categorical_features): """Bar plot for categorical fetures ...
_____no_output_____
Apache-2.0
King-County-House-Price-Prediction.ipynb
norochalise/House-Price-Prediction-to-Deoployment
3. Split dataset
# create function for Split data def split_data(data, target_col): # Remove rows with missing target, seprate target from predictors data_copy = data.copy() data_copy.dropna(axis=0, subset=[target_col], inplace=True) y = data_copy[target_col] data_copy.drop([target_col], axis=1, inplace=True) # Break o...
_____no_output_____
Apache-2.0
King-County-House-Price-Prediction.ipynb
norochalise/House-Price-Prediction-to-Deoployment
4. Model train Create column classification function for pipeline
def col_classification(data, num=20): # Select categorical columns cat_cols = [cname for cname in data.columns if data[cname].nunique() < num and data[cname].dtype =='object'] # Select numerical columns num_cols = [cname for cname in data.columns if dat...
_____no_output_____
Apache-2.0
King-County-House-Price-Prediction.ipynb
norochalise/House-Price-Prediction-to-Deoployment
Create model evaluation function
def evaluation_model(X_test, y_test, title="Target price prediction"): """Evaluation Model for regression problem, We need to use model name is clf""" # Evaluate the model using the test data preds = reg.predict(X_test) mse = mean_squared_error(y_test, preds) print("MSE:", mse) rmse = np.sqrt(mse) print(...
_____no_output_____
Apache-2.0
King-County-House-Price-Prediction.ipynb
norochalise/House-Price-Prediction-to-Deoployment
Try some of the linear regression model and evaluation their performance in our dataset
from sklearn.linear_model import LinearRegression from sklearn.linear_model import Ridge from sklearn.linear_model import Lasso from sklearn.linear_model import ElasticNet from sklearn.ensemble import GradientBoostingRegressor from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegre...
####################################################################### Linear Regression: MSE: 39200213360.80082 Mae: 126368.12273608406 RMSE: 197990.43754888978 R2: 0.6969193739897344
Apache-2.0
King-County-House-Price-Prediction.ipynb
norochalise/House-Price-Prediction-to-Deoployment
After the evaluation Gradient Boosting Regressor works well in our dataset so we will use it. **Model train with Gradient Boosting Regressor using sklearn pipeline**
from sklearn.compose import ColumnTransformer from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import mean_absolute_error from sklearn.preprocessing import StandardScaler from sklearn.ensemble import GradientBoostingRegre...
MSE: 13811738810.108906 Mae: 66634.5069623637 RMSE: 117523.35431780743 R2: 0.8932130698797662
Apache-2.0
King-County-House-Price-Prediction.ipynb
norochalise/House-Price-Prediction-to-Deoployment
5. Save Model, Load and Prediction
import pickle !mkdir 'model_save' pickle.dump(reg, open("model_save/model.pkl","wb")) # Load the model from the file loaded_model = pickle.load(open('model_save/model.pkl', 'rb')) X_new = pd.read_csv('dataset/user_input.csv') X_new result = loaded_model.predict(X_new) print('Prediction: {:.0f} price'.format(np.round(re...
Prediction: 562858 price
Apache-2.0
King-County-House-Price-Prediction.ipynb
norochalise/House-Price-Prediction-to-Deoployment
Table of Contents 1&nbsp;&nbsp;Testing lolviz1.1&nbsp;&nbsp;Testing naively1.2&nbsp;&nbsp;Testing from within a Jupyter notebook1.2.1&nbsp;&nbsp;List1.2.2&nbsp;&nbsp;List of lists1.2.3&nbsp;&nbsp;List of lists of lists???1.2.4&nbsp;&nbsp;Tree1.2.5&nbsp;&nbsp;Objects1.2.6&nbsp;&nbsp;Calls1.2.7&nbsp;&nbsp;String1.3&nbsp...
%load_ext watermark %watermark -v -m -p lolviz from lolviz import *
_____no_output_____
MIT
Testing_the_lolviz_Python_module.ipynb
doc22940/notebooks-2
Testing naively
data = ['hi', 'mom', {3, 4}, {"parrt": "user"}] g = listviz(data) print(g.source) # if you want to see the graphviz source g.view() # render and show graphviz.files.Source object
digraph G { nodesep=.05; node [penwidth="0.5", width=.1,height=.1]; node139621679300936 [shape="box", space="0.0", margin="0.01", fontcolor="#444443", fontname="Helvetica", label=<<table BORDER="0" CELLBORDER="0" CELLSPACING="0"> <tr> <td cellspacing="0" cellpadding="0" bgcolor="#fefecd" border...
MIT
Testing_the_lolviz_Python_module.ipynb
doc22940/notebooks-2
It opened a window showing me this image: Testing from within a Jupyter notebookI test here all [the features of lolviz](https://github.com/parrt/lolvizfunctionality) : List
squares = [ i**2 for i in range(10) ] squares listviz(squares)
_____no_output_____
MIT
Testing_the_lolviz_Python_module.ipynb
doc22940/notebooks-2
List of lists
n, m = 3, 4 example_matrix = [[0 if i != j else 1 for i in range(n)] for j in range(m)] example_matrix lolviz(example_matrix)
_____no_output_____
MIT
Testing_the_lolviz_Python_module.ipynb
doc22940/notebooks-2
List of lists of lists???
n, m, o = 2, 3, 4 example_3D_matrix = [[[ 1 if i < j < k else 0 for i in range(n)] for j in range(m)] for k in range(o)] example_3D_matrix lolviz(example_3D_matrix)
_____no_output_____
MIT
Testing_the_lolviz_Python_module.ipynb
doc22940/notebooks-2
It works, even if it is not as pretty. TreeOnly for binary trees, apparently. Let's try with a dictionary that looks like a binary tree:
anakin = { "name": "Anakin Skywalker", "son": { "name": "Luke Skywalker", }, "daughter": { "name": "Leia Skywalker", }, } from pprint import pprint pprint(anakin) treeviz(anakin, leftfield='son', rightfield='daugther')
_____no_output_____
MIT
Testing_the_lolviz_Python_module.ipynb
doc22940/notebooks-2
It doesn't work out of the box for dictionaries, sadly.Let's check another example:
class Tree: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right root = Tree('parrt', Tree('mary', Tree('jim', Tree('srinivasan'), Tree('april'))), ...
_____no_output_____
MIT
Testing_the_lolviz_Python_module.ipynb
doc22940/notebooks-2
Objects
objviz(anakin) objviz(anakin.values()) objviz(anakin.items())
_____no_output_____
MIT
Testing_the_lolviz_Python_module.ipynb
doc22940/notebooks-2