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 |
|---|---|---|---|---|---|
Building decision tree classifier using entropy criteria (c5.o) | model = DecisionTreeClassifier(criterion = 'entropy',max_depth = 3)
model.fit(x_train,y_train) | _____no_output_____ | MIT | Decision_tree_C5.O_CART.ipynb | anagha0397/Decision-Tree |
Plotting the decision tree | tree.plot_tree(model);
model.get_n_leaves()
## As this tree is not visible so we will display it with some another technique
# we will extract the feature names, class names and we will define the figure size so that our tree will be visible in a better way
fn = ['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'Petal... | precision recall f1-score support
0 1.00 1.00 1.00 8
1 1.00 0.92 0.96 13
2 0.90 1.00 0.95 9
accuracy 0.97 30
macro avg 0.97 0.97 0.97 ... | MIT | Decision_tree_C5.O_CART.ipynb | anagha0397/Decision-Tree |
Building a decision tree using CART method (Classifier model) | model_1 = DecisionTreeClassifier(criterion = 'gini',max_depth = 3)
model_1.fit(x_train,y_train)
tree.plot_tree(model_1);
# predicting the values on xtest data
preds = model_1.predict(x_test)
preds
pd.Series(preds).value_counts()
# calculating accuracy of the model using the actual values
np.mean(preds==y_test) | _____no_output_____ | MIT | Decision_tree_C5.O_CART.ipynb | anagha0397/Decision-Tree |
Decision tree Regressor using CART | from sklearn.tree import DecisionTreeRegressor
# Just converting the iris data into the following way as I want my Y to be numeric
X = iris.iloc[:,0:3]
Y = iris.iloc[:,3]
X_train,X_test,Y_train,Y_test = train_test_split(X,Y, test_size = 0.33, random_state = 1)
model_reg = DecisionTreeRegressor()
model_reg.fit(X_train,... | _____no_output_____ | MIT | Decision_tree_C5.O_CART.ipynb | anagha0397/Decision-Tree |
Homework | import matplotlib.pyplot as plt
%matplotlib inline
import random
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from plotting import overfittingDemo, plot_multiple_linear_regression, overlay_simple_linear_model,plot_simple_residuals
from scipy.optimize import curve_fit | _____no_output_____ | MIT | Lectures/Lecture6/Intro to Machine Learning Homework.ipynb | alaymodi/Spring-2019-Career-Exploration-master |
**Exercise 1:** What are the two "specialities" of machine learning? Pick one and in your own words, explain what it means. ` Your Answer Here **Exercise 2:** What is the difference between a regression task and a classification task? Your Answer Here **Exercise 3:** 1. What is parametric fitting in your understanding?... | bestplot = 'Put your letter answer between these quotes' | _____no_output_____ | MIT | Lectures/Lecture6/Intro to Machine Learning Homework.ipynb | alaymodi/Spring-2019-Career-Exploration-master |
**Exercise 5:** Observe the following graphs. Assign each graph variable to one of the following strings: 'overfitting', 'underfitting', or 'bestfit'. | graph1 = "Put answer here"
graph2 = "Put answer here"
graph3 = "Put answer here" | _____no_output_____ | MIT | Lectures/Lecture6/Intro to Machine Learning Homework.ipynb | alaymodi/Spring-2019-Career-Exploration-master |
**Exercise 6:** What are the 3 sets we split our initial data set into? Your Answer Here **Exercise 7:** Refer to the graphs below when answering the following questions (Exercise 6 and 7).As we increase the degree of our model, what happens to the training error and what happens to the test error? Your Answer Here **... | import pandas as pd
mpg = pd.read_csv("./mpg_category.csv", index_col="name")
#exercise part 1
mpg['Old?'] = ...
#exercise part 2
mpg_train, mpg_test = ..., ...
#exercise part 3
from sklearn.linear_model import LogisticRegression
softmax_reg = LogisticRegression(multi_class="multinomial",solver="lbfgs", C=10)
X = ... | _____no_output_____ | MIT | Lectures/Lecture6/Intro to Machine Learning Homework.ipynb | alaymodi/Spring-2019-Career-Exploration-master |
2. create the test data set and make the prediction on test dataset | X_test = ...
Y_test = ...
pred = softmax_reg.predict(...) | _____no_output_____ | MIT | Lectures/Lecture6/Intro to Machine Learning Homework.ipynb | alaymodi/Spring-2019-Career-Exploration-master |
3. Make the confusion matrix and tell me how you interpret each of the cell in the confusion matrix. What does different depth of blue means. You can just run the cell below, assumed what you did above is correct. You just have to answer your understanding. | from sklearn.metrics import confusion_matrix
confusion_matrix = confusion_matrix(Y_test, pred)
X_label = ['old', 'new']
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(l... | _____no_output_____ | MIT | Lectures/Lecture6/Intro to Machine Learning Homework.ipynb | alaymodi/Spring-2019-Career-Exploration-master |
Your Answer Here | # be sure to hit save (File > Save and Checkpoint) or Ctrl/Command-S before you run the cell!
from submit import create_and_submit
create_and_submit(['Intro to Machine Learning Homework.ipynb'], verbose=True) | Parsed Intro to Machine Learning Homework.ipynb
Enter your Berkeley email address: xinyiren@berkeley.edu
Posting answers for Intro to Machine Learning Homework
Your submission: {'exercise-1': 'Your Answer Here', 'exercise-1_output': None, 'exercise-2': 'Your Answer Here', 'exercise-2_output': None, 'exercise-3': 'Your ... | MIT | Lectures/Lecture6/Intro to Machine Learning Homework.ipynb | alaymodi/Spring-2019-Career-Exploration-master |
Copyright 2020 Google LLC.Licensed under the Apache License, Version 2.0 (the "License"); | #@title License header
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | _____no_output_____ | Apache-2.0 | colab/resnet.ipynb | WindQAQ/iree |
ResNet[ResNet](https://arxiv.org/abs/1512.03385) is a deep neural network architecture for image recognition.This notebook* Constructs a [ResNet50](https://www.tensorflow.org/api_docs/python/tf/keras/applications/ResNet50) model using `tf.keras`, with weights pretrained using the[ImageNet](http://www.image-net.org/) d... | #@title Imports and common setup
from pyiree import rt as ireert
from pyiree.tf import compiler as ireec
from pyiree.tf.support import tf_utils
import tensorflow as tf
from matplotlib import pyplot as plt
#@title Construct a pretrained ResNet model with ImageNet weights
tf.keras.backend.set_learning_phase(False)
# ... | IREE prediction:
[('n02091244', 'Ibizan_hound', 0.12879075), ('n02099712', 'Labrador_retriever', 0.1263297), ('n02091831', 'Saluki', 0.09625255)]
| Apache-2.0 | colab/resnet.ipynb | WindQAQ/iree |
ART for TensorFlow v2 - Keras API This notebook demonstrate applying ART with the new TensorFlow v2 using the Keras API. The code follows and extends the examples on www.tensorflow.org. | import warnings
warnings.filterwarnings('ignore')
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
import numpy as np
from matplotlib import pyplot as plt
from art.estimators.classification import KerasClassifier
from art.attacks.evasion import FastGradientMethod, CarliniLInfMethod
if tf.__version__[0] !... | _____no_output_____ | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Load MNIST dataset | (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_test = x_test[0:100]
y_test = y_test[0:100] | _____no_output_____ | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
TensorFlow with Keras API Create a model using Keras API. Here we use the Keras Sequential model and add a sequence of layers. Afterwards the model is compiles with optimizer, loss function and metrics. | model = tf.keras.models.Sequential([
tf.keras.layers.InputLayer(input_shape=(28, 28)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='spars... | _____no_output_____ | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Fit the model on training data. | model.fit(x_train, y_train, epochs=3); | Train on 60000 samples
Epoch 1/3
60000/60000 [==============================] - 3s 46us/sample - loss: 0.2968 - accuracy: 0.9131
Epoch 2/3
60000/60000 [==============================] - 3s 46us/sample - loss: 0.1435 - accuracy: 0.9575
Epoch 3/3
60000/60000 [==============================] - 3s 46us/sample - loss: 0.110... | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Evaluate model accuracy on test data. | loss_test, accuracy_test = model.evaluate(x_test, y_test)
print('Accuracy on test data: {:4.2f}%'.format(accuracy_test * 100)) | Accuracy on test data: 100.00%
| MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Create a ART Keras classifier for the TensorFlow Keras model. | classifier = KerasClassifier(model=model, clip_values=(0, 1)) | _____no_output_____ | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Fast Gradient Sign Method attack Create a ART Fast Gradient Sign Method attack. | attack_fgsm = FastGradientMethod(estimator=classifier, eps=0.3) | _____no_output_____ | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Generate adversarial test data. | x_test_adv = attack_fgsm.generate(x_test) | _____no_output_____ | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Evaluate accuracy on adversarial test data and calculate average perturbation. | loss_test, accuracy_test = model.evaluate(x_test_adv, y_test)
perturbation = np.mean(np.abs((x_test_adv - x_test)))
print('Accuracy on adversarial test data: {:4.2f}%'.format(accuracy_test * 100))
print('Average perturbation: {:4.2f}'.format(perturbation)) | Accuracy on adversarial test data: 0.00%
Average perturbation: 0.18
| MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Visualise the first adversarial test sample. | plt.matshow(x_test_adv[0])
plt.show() | _____no_output_____ | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Carlini&Wagner Infinity-norm attack Create a ART Carlini&Wagner Infinity-norm attack. | attack_cw = CarliniLInfMethod(classifier=classifier, eps=0.3, max_iter=100, learning_rate=0.01) | _____no_output_____ | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Generate adversarial test data. | x_test_adv = attack_cw.generate(x_test) | C&W L_inf: 100%|██████████| 1/1 [00:04<00:00, 4.23s/it]
| MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Evaluate accuracy on adversarial test data and calculate average perturbation. | loss_test, accuracy_test = model.evaluate(x_test_adv, y_test)
perturbation = np.mean(np.abs((x_test_adv - x_test)))
print('Accuracy on adversarial test data: {:4.2f}%'.format(accuracy_test * 100))
print('Average perturbation: {:4.2f}'.format(perturbation)) | Accuracy on adversarial test data: 10.00%
Average perturbation: 0.03
| MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Visualise the first adversarial test sample. | plt.matshow(x_test_adv[0, :, :])
plt.show() | _____no_output_____ | MIT | notebooks/art-for-tensorflow-v2-keras.ipynb | changx03/adversarial-robustness-toolbox |
Prophet Time serie forecasting using ProphetOfficial documentation: https://facebook.github.io/prophet/docs/quick_start.html Procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. It is released by Facebook... | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from fbprophet import Prophet
from sklearn.metrics import mean_squared_error, mean_absolute_error
plt.style.use('fivethirtyeight') # For plots
dataset_path = './data/hourly-energy-consumption/PJME_hourly.csv'
df = pd.read_csv(d... | _____no_output_____ | MIT | English/9_time_series_prediction/Prophet.ipynb | JeyDi/DataScienceCourse |
Train and Test Split We use a temporal split, keeping old data and use only new period to do the prediction | split_date = '01-Jan-2015'
pjme_train = df.loc[df.index <= split_date].copy()
pjme_test = df.loc[df.index > split_date].copy()
# Plot train and test so you can see where we have split
pjme_test \
.rename(columns={'PJME_MW': 'TEST SET'}) \
.join(pjme_train.rename(columns={'PJME_MW': 'TRAINING SET'}),
h... | _____no_output_____ | MIT | English/9_time_series_prediction/Prophet.ipynb | JeyDi/DataScienceCourse |
To use prophet you need to correctly rename features and label to correctly pass the input to the engine. | # Format data for prophet model using ds and y
pjme_train.reset_index() \
.rename(columns={'Datetime':'ds',
'PJME_MW':'y'})
print(pjme_train.columns)
pjme_train.head(5) | Index(['PJME_MW'], dtype='object')
| MIT | English/9_time_series_prediction/Prophet.ipynb | JeyDi/DataScienceCourse |
Create and train the model | # Setup and train model and fit
model = Prophet()
model.fit(pjme_train.reset_index() \
.rename(columns={'Datetime':'ds',
'PJME_MW':'y'}))
# Predict on training set with model
pjme_test_fcst = model.predict(df=pjme_test.reset_index() \
.ren... | _____no_output_____ | MIT | English/9_time_series_prediction/Prophet.ipynb | JeyDi/DataScienceCourse |
Plot the results and forecast | # Plot the forecast
f, ax = plt.subplots(1)
f.set_figheight(5)
f.set_figwidth(15)
fig = model.plot(pjme_test_fcst,
ax=ax)
plt.show()
# Plot the components of the model
fig = model.plot_components(pjme_test_fcst) | _____no_output_____ | MIT | English/9_time_series_prediction/Prophet.ipynb | JeyDi/DataScienceCourse |
Frequency rangeThe first first step needed to simulate an electrochemical impedance spectra is to generate a frequency domain, to do so, use to build-in freq_gen() function, as follows | f_range = freq_gen(f_start=10**10, f_stop=0.1, pts_decade=7)
# print(f_range[0]) #First 5 points in the freq. array
print()
# print(f_range[1]) #First 5 points in the angular freq.array | MIT | examples/nyquist_plots_examples.ipynb | EISy-as-Py/EISy-as-Py | |
Note that all functions included are described, to access these descriptions stay within () and press shift+tab. The freq_gen(), returns both the frequency, which is log seperated based on points/decade between f_start to f_stop, and the angular frequency. This function is quite useful and will be used through this tut... | cir_RC
cir_RQ
cir_RsRQ
cir_RsRQRQ
cir_Randles
cir_Randles_simplified
cir_C_RC_C
cir_Q_RQ_Q
cir_RCRCZD
cir_RsTLsQ
cir_RsRQTLsQ
cir_RsTLs
cir_RsRQTLs
cir_RsTLQ
cir_RsRQTLQ
cir_RsTL
cir_RsRQTL
cir_RsTL_1Dsolid
cir_RsRQTL_1Dsolid | _____no_output_____ | MIT | examples/nyquist_plots_examples.ipynb | EISy-as-Py/EISy-as-Py |
Simulation of -(RC)- Input Parameters:- w = Angular frequency [1/s]- R = Resistance [Ohm]- C = Capacitance [F]- fs = summit frequency of RC circuit [Hz] | RC_example = EIS_sim(frange=f_range[0], circuit=cir_RC(w=f_range[1], R=70, C=10**-6), legend='on') | _____no_output_____ | MIT | examples/nyquist_plots_examples.ipynb | EISy-as-Py/EISy-as-Py |
Simulation of -Rs-(RQ)- Input parameters:- w = Angular frequency [1/s]- Rs = Series resistance [Ohm]- R = Resistance [Ohm]- Q = Constant phase element [s^n/ohm]- n = Constant phase elelment exponent [-]- fs = summit frequency of RQ circuit [Hz] | RsRQ_example = EIS_sim(frange=f_range[0], circuit=cir_RsRQ(w=f_range[1], Rs=70, R=200, n=.8, Q=10**-5), legend='on')
RsRC_example = EIS_sim(frange=f_range[0], circuit=cir_RsRC(w=f_range[1], Rs=80, R=100, C=10**-5), legend='on') | _____no_output_____ | MIT | examples/nyquist_plots_examples.ipynb | EISy-as-Py/EISy-as-Py |
Simulation of -Rs-(RQ)-(RQ)- Input parameters:- w = Angular frequency [1/s]- Rs = Series Resistance [Ohm]- R = Resistance [Ohm]- Q = Constant phase element [s^n/ohm]- n = Constant phase element exponent [-]- fs = summit frequency of RQ circuit [Hz]- R2 = Resistance [Ohm]- Q2 = Constant phase element [s^n/ohm]- n2 = Co... | RsRQRQ_example = EIS_sim(frange=f_range[0], circuit=cir_RsRQRQ(w=f_range[1], Rs=200, R=150, n=.872, Q=10**-4, R2=50, n2=.853, Q2=10**-6), legend='on') | _____no_output_____ | MIT | examples/nyquist_plots_examples.ipynb | EISy-as-Py/EISy-as-Py |
Simulation of -Rs-(Q(RW))- (Randles-circuit)This circuit is often used for an experimental setup with a macrodisk working electrode with an outer-sphere heterogeneous charge transfer. This, classical, warburg element is controlled by semi-infinite linear diffusion, which is given by the geometry of the working electro... | Randles = cir_Randles_simplified(w=f_range[1], Rs=100, R=1000, n=1, sigma=300, Q=10**-5)
Randles_example = EIS_sim(frange=f_range[0], circuit=Randles, legend='off')
Randles_example = EIS_sim(frange=f_range[0], circuit=cir_Randles_simplified(w=f_range[1], Rs=100, R=1000, n=1, sigma=300, Q='none', fs=10**3.3), legend='of... | _____no_output_____ | MIT | examples/nyquist_plots_examples.ipynb | EISy-as-Py/EISy-as-Py |
In the following, the Randles circuit with the Warburg constant (sigma) defined is simulated where:- D$_{red}$/D$_{ox}$ = 10$^{-6}$ cm$^2$/s- C$_{red}$/C$_{ox}$ = 10 mM- n_electron = 1- T = 25 $^o$CThis function is a great tool to simulate expected impedance responses prior to starting experiments as it allows for eval... | Randles_example = EIS_sim(frange=f_range[0], circuit=cir_Randles(w=f_range[1], Rs=100, Rct=1000, Q=10**-7, n=1, T=298.15, D_ox=10**-9, D_red=10**-9, C_ox=10**-5, C_red=10**-5, n_electron=1, E=0, A=1), legend='off') | _____no_output_____ | MIT | examples/nyquist_plots_examples.ipynb | EISy-as-Py/EISy-as-Py |
Complex Dummy Experiment Manager> Dummy experiment manager with features that allow additional functionality | #export
from hpsearch.examples.dummy_experiment_manager import DummyExperimentManager, FakeModel
import hpsearch
import os
import shutil
import os
import hpsearch.examples.dummy_experiment_manager as dummy_em
from hpsearch.visualization import plot_utils
#for tests
import pytest
from block_types.utils.nbdev_utils imp... | _____no_output_____ | MIT | nbs/examples/complex_dummy_experiment_manager.ipynb | Jaume-JCI/hpsearch |
ComplexDummyExperimentManager | #export
class ComplexDummyExperimentManager (DummyExperimentManager):
def __init__ (self, model_file_name='model_weights.pk', **kwargs):
super().__init__ (model_file_name=model_file_name, **kwargs)
self.raise_error_if_run = False
def run_experiment (self, parameters={}, path_results='./res... | _____no_output_____ | MIT | nbs/examples/complex_dummy_experiment_manager.ipynb | Jaume-JCI/hpsearch |
Usage | #exports tests.examples.test_complex_dummy_experiment_manager
def test_complex_dummy_experiment_manager ():
#em = generate_data ('complex_dummy_experiment_manager')
md (
'''
Extend previous experiment by using a larger number of epochs
We see how to create a experiment that is the same as a previous exper... | running test_complex_dummy_experiment_manager
| MIT | nbs/examples/complex_dummy_experiment_manager.ipynb | Jaume-JCI/hpsearch |
Running experiments and removing experiments | # export
def run_multiple_experiments (**kwargs):
dummy_em.run_multiple_experiments (EM=ComplexDummyExperimentManager, **kwargs)
def remove_previous_experiments ():
dummy_em.remove_previous_experiments (EM=ComplexDummyExperimentManager)
#export
def generate_data (name_folder):
em = ComplexDummyExperimentMa... | _____no_output_____ | MIT | nbs/examples/complex_dummy_experiment_manager.ipynb | Jaume-JCI/hpsearch |
Workshop 13 _Object-oriented programming._ Classes and Objects | class MyClass:
pass
obj1 = MyClass()
obj2 = MyClass()
print(obj1)
print(type(obj1))
print(obj2)
print(type(obj2))
| _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Constructor and destructor | class Employee:
def __init__(self):
print('Employee created.')
def __del__(self):
print('Destructor called, Employee deleted.')
obj = Employee()
del obj
| _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Attributes and methods | class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __str__(self):
return '{' + self.name + ': ' + str(self.grade) + '}'
def learn(self):
print('My name is %s. I am learning Python! My grade is %d.' % (self.name, self.grade))
students ... | _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Class and instance attributes | class Person:
# class variable shared by all instances
status = 'student'
def __init__(self, name):
# instance variable unique to each instance
self.name = name
a = Person('Steve')
b = Person('Mark')
print('')
print(a.name + ' : ' + a.status)
print(b.name + ' : ' + b.status)
Person.sta... | _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Class and static methods | class Env:
os = 'Windows'
@classmethod
def print_os(self):
print(self.os)
@staticmethod
def print_user():
print('guest')
Env.print_os()
Env.print_user()
| _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Encapsulation | class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return 'My name is ' + self.name
person = Person('Steve')
print(person.name)
person.name = 'Said'
print(person.name)
class Identity:
def __init__(self, name):
self.__name = name
def __str__(self)... | _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Operator overloading | class Number:
def __init__(self, value):
self.__value = value
def __del__(self):
pass
def __str__(self):
return str(self.__value)
def __int__(self):
return self.__value
def __eq__(self, other):
return self.__value == other.__value
def __ne__(self, ot... | _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Inheritance and polymorphism | class Creature:
def say(self):
pass
class Dog(Creature):
def say(self):
print('Woof!')
class Cat(Creature):
def say(self):
print("Meow!")
class Lion(Creature):
def say(self):
print("Roar!")
animals = [Creature(), Dog(), Cat(), Lion()]
for animal in animal... | _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Multiple inheritance | class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, grade):
super().__init__(name)
self.grade = grade
class Employee:
def __init__(self, salary):
self.salary = salary
class Teacher(Person, Employee):
def __init__(... | _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Function _isinstance_ | x = 10
print('')
print(isinstance(x, int))
print(isinstance(x, float))
print(isinstance(x, str))
y = 3.14
print('')
print(isinstance(y, int))
print(isinstance(y, float))
print(isinstance(y, str))
z = 'Hello world'
print('')
print(isinstance(z, int))
print(isinstance(z, float))
print(isinstance(z, str))
class A:
... | _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Composition | class Teacher:
pass
class Student:
pass
class ClassRoom:
def __init__(self, teacher, students):
self.teacher = teacher
self.students = students
cl = ClassRoom(Teacher(), [Student(), Student(), Student()])
class Set:
def __init__(self, values=None):
self.dict = {}
i... | _____no_output_____ | Apache-2.0 | lessons/Workshop_13_OOP.ipynb | andrewt0301/python-problems |
Scalable GP Classification in 1D (w/ KISS-GP)This example shows how to use grid interpolation based variational classification with an `ApproximateGP` using a `GridInterpolationVariationalStrategy` module. This classification module is designed for when the inputs of the function you're modeling are one-dimensional.Th... | import math
import torch
import gpytorch
from matplotlib import pyplot as plt
from math import exp
%matplotlib inline
%load_ext autoreload
%autoreload 2
train_x = torch.linspace(0, 1, 26)
train_y = torch.sign(torch.cos(train_x * (2 * math.pi))).add(1).div(2)
from gpytorch.models import ApproximateGP
from gpytorch.vari... | _____no_output_____ | MIT | examples/06_Scalable_GP_Classification_1D/KISSGP_Classification_1D.ipynb | phumm/gpytorch |
np.savetxt('/nfs/slac/g/ki/ki18/des/swmclau2/AB_tests/sham_vpeak_wp.npy', sham_wp)np.savetxt('/nfs/slac/g/ki/ki18/des/swmclau2/AB_tests/sham_vpeak_nd.npy', np.array([len(galaxy_catalog)/((cat.Lbox*cat.h)**3)])) np.savetxt('/nfs/slac/g/ki/ki18/des/swmclau2/AB_tests/rp_bins_split.npy',rp_bins ) | plt.figure(figsize=(10,8))
for p, mock_wp in zip(split, mock_wps):
plt.plot(bin_centers, mock_wp, label = p)
#plt.plot(bin_centers, sham_wp, ls='--', label = 'SHAM')
plt.plot(bin_centers, noab_wp, ls=':', label = 'No AB')
plt.loglog()
plt.legend(loc='best',fontsize = 15)
plt.xlim([1e-1, 30e0]);
#plt.ylim([1,... | _____no_output_____ | MIT | notebooks/AB_tests/Understand Splitting Fraction.ipynb | mclaughlin6464/pearce |
cens_occ = cat.model._input_model_dictionary['centrals_occupation']cens_occ._split_ordinates = [0.1] | print sats_occ
baseline_lower_bound, baseline_upper_bound = 0,np.inf
prim_haloprop = cat.model.mock.halo_table['halo_mvir']
sec_haloprop = cat.model.mock.halo_table['halo_nfw_conc']
from halotools.utils.table_utils import compute_conditional_percentile_values
split = sats_occ.percentile_splitting_function(prim_haloprop... | _____no_output_____ | MIT | notebooks/AB_tests/Understand Splitting Fraction.ipynb | mclaughlin6464/pearce |
percentiles = compute_conditional_percentiles( prim_haloprop=prim_haloprop, sec_haloprop=sec_haloprop )no_edge_percentiles = percentiles[no_edge_mask]type1_mask = no_edge_percentiles > no_edge_splitperturbation = sats_occ._galprop_perturbation(prim_ha... | from halotools.utils.table_utils import compute_conditional_averages
strength = sats_occ.assembias_strength(prim_haloprop[no_edge_mask])
slope = sats_occ.assembias_slope(prim_haloprop[no_edge_mask])
# the average displacement acts as a normalization we need.
max_displacement = sats_occ._disp_func(sec_haloprop=pv_sub_s... | _____no_output_____ | MIT | notebooks/AB_tests/Understand Splitting Fraction.ipynb | mclaughlin6464/pearce |
Showing uncertainty> Uncertainty occurs everywhere in data science, but it's frequently left out of visualizations where it should be included. Here, we review what a confidence interval is and how to visualize them for both single estimates and continuous functions. Additionally, we discuss the bootstrap resampling t... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams['figure.figsize'] = (10, 5) | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
Point estimate intervals- When is uncertainty important? - Estimates from sample - Average of a subset - Linear model coefficients- Why is uncertainty important? - Helps inform confidence in estimate - Neccessary for decision making - Acknowledges limitations of data Basic confidence interva... | average_ests = pd.read_csv('./dataset/average_ests.csv', index_col=0)
average_ests
# Construct CI bounds for averages
average_ests['lower'] = average_ests['mean'] - 1.96 * average_ests['std_err']
average_ests['upper'] = average_ests['mean'] + 1.96 * average_ests['std_err']
# Setup a grid of plots, with non-shared x ax... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
This simple visualization shows that all the observed values fall well within the confidence intervals for all the pollutants except for $O_3$. Annotating confidence intervalsYour data science work with pollution data is legendary, and you are now weighing job offers in both Cincinnati, Ohio and Indianapolis, Indiana.... | diffs_by_year = pd.read_csv('./dataset/diffs_by_year.csv', index_col=0)
diffs_by_year
# Set start and ends according to intervals
# Make intervals thicker
plt.hlines(y='year', xmin='lower', xmax='upper',
linewidth=5, color='steelblue', alpha=0.7,
data=diffs_by_year);
# Point estimates
plt.plot('me... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
By looking at the confidence intervals you can see that the difference flipped from generally positive (more pollution in Cincinnati) in 2013 to negative (more pollution in Indianapolis) in 2014 and 2015. Given that every year's confidence interval contains the null value of zero, no P-Value would be significant, and a... | vandenberg_NO2 = pd.read_csv('./dataset/vandenberg_NO2.csv', index_col=0)
vandenberg_NO2.head()
# Draw 99% interval bands for average NO2
vandenberg_NO2['lower'] = vandenberg_NO2['mean'] - 2.58 * vandenberg_NO2['std_err']
vandenberg_NO2['upper'] = vandenberg_NO2['mean'] + 2.58 * vandenberg_NO2['std_err']
# Plot mean e... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
This plot shows that the middle of the year's $NO_2$ values are not only lower than the beginning and end of the year but also are less noisy. If just the moving average line were plotted, then this potentially interesting observation would be completely missed. (Can you think of what may cause reduced variance at the ... | eastern_SO2 = pd.read_csv('./dataset/eastern_SO2.csv', index_col=0)
eastern_SO2.head()
# setup a grid of plots with columns divided by location
g = sns.FacetGrid(eastern_SO2, col='city', col_wrap=2);
# Map interval plots to each cities data with coral colored ribbons
g.map(plt.fill_between, 'day', 'lower', 'upper', co... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
By separating each band into its own plot you can investigate each city with ease. Here, you see that Des Moines and Houston on average have lower SO2 values for the entire year than the two cities in the Midwest. Cincinnati has a high and variable peak near the beginning of the year but is generally more stable and lo... | SO2_compare = pd.read_csv('./dataset/SO2_compare.csv', index_col=0)
SO2_compare.head()
for city, color in [('Denver', '#66c2a5'), ('Long Beach', '#fc8d62')]:
# Filter data to desired city
city_data = SO2_compare[SO2_compare.city == city]
# Set city interval color to desired and lower opacity
plt.fi... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
From these two curves you can see that during the first half of the year Long Beach generally has a higher average SO2 value than Denver, in the middle of the year they are very close, and at the end of the year Denver seems to have higher averages. However, by showing the confidence intervals, you can see however that... | from statsmodels.formula.api import ols
pollution = pd.read_csv('./dataset/pollution_wide.csv')
pollution = pollution.query("city == 'Fairbanks' & year == 2014 & month == 11")
pollution_model = ols(formula='SO2 ~ CO + NO2 + O3 + day', data=pollution)
res = pollution_model.fit()
# Add interval percent widths
alphas = [ ... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
90 and 95% bandsYou are looking at a 40-day rolling average of the $NO_2$ pollution levels for the city of Cincinnati in 2013. To provide as detailed a picture of the uncertainty in the trend you want to look at both the 90 and 99% intervals around this rolling estimate.To do this, set up your two interval sizes and a... | cinci_13_no2 = pd.read_csv('./dataset/cinci_13_no2.csv', index_col=0);
cinci_13_no2.head()
int_widths = ['90%', '99%']
z_scores = [1.67, 2.58]
colors = ['#fc8d59', '#fee08b']
for percent, Z, color in zip(int_widths, z_scores, colors):
# Pass lower and upper confidence bounds and lower opacity
plt.fill_bet... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
This plot shows us that throughout 2013, the average NO2 values in Cincinnati followed a cyclical pattern with the seasons. However, the uncertainty bands show that for most of the year you can't be sure this pattern is not noise at both a 90 and 99% confidence level. Using band thickness instead of coloringYou are a ... | rocket_model = pd.read_csv('./dataset/rocket_model.csv', index_col=0)
rocket_model
# Decrase interval thickness as interval widens
sizes = [ 15, 10, 5]
int_widths = ['90% CI', '95%', '99%']
z_scores = [ 1.67, 1.96, 2.58]
for percent, Z, size in zip(int_widths, z_scores, sizes):
plt.hlines(y = rock... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
While less elegant than using color to differentiate interval sizes, this plot still clearly allows the reader to access the effect each pollutant has on rocket visibility. You can see that of all the pollutants, O3 has the largest effect and also the tightest confidence bounds Visualizing the bootstrap The bootstrap... | # Perform bootstrapped mean on a vector
def bootstrap(data, n_boots):
return [np.mean(np.random.choice(data,len(data))) for _ in range(n_boots) ]
pollution = pd.read_csv('./dataset/pollution_wide.csv')
cinci_may_NO2 = pollution.query("city == 'Cincinnati' & month == 5").NO2
# Generate bootstrap samples
boot_me... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
Your bootstrap histogram looks stable and uniform. You're now confident that the average NO2 levels in Cincinnati during your vacation should be in the range of 16 to 23. Bootstrapped regressionsWhile working for the Long Beach parks and recreation department investigating the relationship between $NO_2$ and $SO_2$ yo... | no2_so2 = pd.read_csv('./dataset/no2_so2.csv', index_col=0)
no2_so2_boot = pd.read_csv('./dataset/no2_so2_boot.csv', index_col=0)
sns.lmplot('NO2', 'SO2', data = no2_so2_boot,
# Tell seaborn to a regression line for each sample
hue = 'sample',
# Make lines blue and transparent
... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
The outliers appear to drag down the regression lines as evidenced by the cluster of lines with more severe slopes than average. In a single plot, you have not only gotten a good idea of the variability of your correlation estimate but also the potential effects of outliers. Lots of bootstraps with beeswarmsAs a curre... | pollution_may = pollution.query("month == 5")
pollution_may
# Initialize a holder DataFrame for bootstrap results
city_boots = pd.DataFrame()
for city in ['Cincinnati', 'Des Moines', 'Indianapolis', 'Houston']:
# Filter to city
city_NO2 = pollution_may[pollution_may.city == city].NO2
# Bootstrap city dat... | _____no_output_____ | Apache-2.0 | _notebooks/2020-06-29-01-Showing-uncertainty.ipynb | AntonovMikhail/chans_jupyter |
Define our search parameters and send to the USGS Use a dict, with same names as used by the USGS web call.Send a query to the web server. The result is a list of events also in a dict format. | search_params = {
'starttime': "2018-05-01",
'endtime': "2018-05-17",
'minmagnitude': 6.8,
'maxmagnitude': 10.0,
'mindepth': 0.0,
'maxdepth': 50.0,
'minlongitude': -180.0,
'maxlongitude': -97.0,
'minlatitude': 0.0,
'maxlatitude': 45.0,
'limit': 50,
'producttype': 'sha... | Sending query to get events...
Parsing...
...1 events returned (limit of 50)
70116556 : M 6.9 - 19km SSW of Leilani Estates, Hawaii
| MIT | notebooks/find_a_shakemap.ipynb | iwbailey/shakemap_lookup |
Check the metadata Display metadata including number of earthquakes returned and what url was used for the query | for k, v in events['metadata'].items():
print(k,":", v) | generated : 1575582197000
url : https://earthquake.usgs.gov/fdsnws/event/1/query?starttime=2018-05-01&endtime=2018-05-17&minmagnitude=6.8&maxmagnitude=10.0&mindepth=0.0&maxdepth=50.0&minlongitude=-180.0&maxlongitude=-97.0&minlatitude=0.0&maxlatitude=45.0&limit=50&producttype=shakemap&format=geojson&jsonerror=true
title... | MIT | notebooks/find_a_shakemap.ipynb | iwbailey/shakemap_lookup |
Selection of event from candidates | my_event = usgs_web.choose_event(events)
my_event |
USER SELECTION OF EVENT:
========================
0: M 6.9 - 19km SSW of Leilani Estates, Hawaii (70116556)
None: First on list
-1: Exit
Choice:
... selected M 6.9 - 19km SSW of Leilani Estates, Hawaii (70116556)
| MIT | notebooks/find_a_shakemap.ipynb | iwbailey/shakemap_lookup |
Select which ShakeMap for the selected event | smDetail = usgs_web.query_shakemapdetail(my_event['properties']) | Querying detailed event info for eventId=70116556...
...2 shakemaps found
USER SELECTION OF SHAKEMAP:
===========================
Option 0:
eventsourcecode: 70116556
version: 1
process-timestamp: 2018-09-08T02:52:24Z
Option 1:
eventsourcecode: 1000dyad
version: 11
process-timestamp... | MIT | notebooks/find_a_shakemap.ipynb | iwbailey/shakemap_lookup |
Display available content for the ShakeMap | print("Available Content\n=================")
for k, v in smDetail['contents'].items():
print("{:32s}: {} [{}]".format(k, v['contentType'], v['length'])) | Available Content
=================
about_formats.html : text/html [28820]
contents.xml : application/xml [9187]
download/70116556.kml : application/vnd.google-earth.kml+xml [1032]
download/cont_mi.json : application/json [79388]
download/cont_mi.kmz : appl... | MIT | notebooks/find_a_shakemap.ipynb | iwbailey/shakemap_lookup |
Get download linksClick on the link to download | # Extract the shakemap grid urls and version from the detail
grid = smDetail['contents']['download/grid.xml.zip']
print(grid['url'])
grid = smDetail['contents']['download/uncertainty.xml.zip']
print(grid['url']) | https://earthquake.usgs.gov/archive/product/shakemap/hv70116556/us/1536375199192/download/uncertainty.xml.zip
| MIT | notebooks/find_a_shakemap.ipynb | iwbailey/shakemap_lookup |
Lambda School Data Science*Unit 2, Sprint 3, Module 3*--- Permutation & Boosting- Get **permutation importances** for model interpretation and feature selection- Use xgboost for **gradient boosting** SetupRun the code cell below. You can work locally (follow the [local setup instructions](https://lambdaschool.github... | %%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'
!pip install category_encoders==2.*
!pip install eli5
# If you're working locally:
else:
DATA_PATH = '../data/' | _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | mariokart345/DS-Unit-2-Applied-Modeling |
We'll go back to Tanzania Waterpumps for this lesson. | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
# Merge train_features.csv & train_labels.csv
train = pd.merge(pd.read_csv(DATA_PATH+'waterpumps/train_features.csv'),
pd.read_csv(DATA_PATH+'waterpumps/train_labels.csv'))
# Read test_features.csv & sample_s... | /usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
import pandas.util.testing as tm
| MIT | module3-permutation-boosting/LS_DS_233.ipynb | mariokart345/DS-Unit-2-Applied-Modeling |
Get permutation importances for model interpretation and feature selection Overview Default Feature Importances are fast, but Permutation Importances may be more accurate.These links go deeper with explanations and examples:- Permutation Importances - [Kaggle / Dan Becker: Machine Learning Explainability](https://ww... | # Get feature importances
rf = pipeline.named_steps['randomforestclassifier']
importances = pd.Series(rf.feature_importances_, X_train.columns)
# Plot feature importances
%matplotlib inline
import matplotlib.pyplot as plt
n = 20
plt.figure(figsize=(10,n/2))
plt.title(f'Top {n} features')
importances.sort_values()[-n:... | _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | mariokart345/DS-Unit-2-Applied-Modeling |
2. Drop-Column ImportanceThe best in theory, but too slow in practice | column = 'wpt_name'
# Fit without column
pipeline = make_pipeline(
ce.OrdinalEncoder(),
SimpleImputer(strategy='median'),
RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
)
pipeline.fit(X_train.drop(columns=column), y_train)
score_without = pipeline.score(X_val.drop(columns=column), ... | Validation Accuracy without wpt_name: 0.8087542087542088
Validation Accuracy with wpt_name: 0.8135521885521886
Drop-Column Importance for wpt_name: 0.004797979797979801
| MIT | module3-permutation-boosting/LS_DS_233.ipynb | mariokart345/DS-Unit-2-Applied-Modeling |
3. Permutation ImportancePermutation Importance is a good compromise between Feature Importance based on impurity reduction (which is the fastest) and Drop Column Importance (which is the "best.")[The ELI5 library documentation explains,](https://eli5.readthedocs.io/en/latest/blackbox/permutation_importance.html)> Imp... | #lets see how permutation works first
nevi_array = [1,2,3,4,5]
nevi_permuted = np.random.permutation(nevi_array)
nevi_permuted
#BEFORE : sequence of the feature to be permuted
feature = 'quantity'
X_val[feature].head()
#BEFORE: distribution
X_val[feature].value_counts()
#PERMUTE
X_val_permuted = X_val.copy(... | _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | mariokart345/DS-Unit-2-Applied-Modeling |
With eli5 libraryFor more documentation on using this library, see:- [eli5.sklearn.PermutationImportance](https://eli5.readthedocs.io/en/latest/autodocs/sklearn.htmleli5.sklearn.permutation_importance.PermutationImportance)- [eli5.show_weights](https://eli5.readthedocs.io/en/latest/autodocs/eli5.htmleli5.show_weights)... | # Ignore warnings
transformers = make_pipeline(
ce.OrdinalEncoder(),
SimpleImputer(strategy='median')
)
X_train_transformed = transformers.fit_transform(X_train)
X_val_transformed = transformers.transform(X_val)
model = RandomForestClassifier(n_estimators=50, random_state=42, n_jobs=-1)
model.fit(X_trai... | _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | mariokart345/DS-Unit-2-Applied-Modeling |
We can use importances for feature selectionFor example, we can remove features with zero importance. The model trains faster and the score does not decrease. | print('Shape before removing feature ', X_train.shape)
#remove features with feature importance <0
minimum_importance = 0
mask=permuter.feature_importances_ > minimum_importance
features = X_train.columns[mask]
X_train=X_train[features]
print('Shape AFTER removing feature ', X_train.shape)
X_val=X_val[features]
... | Validation accuracy 0.8066498316498316
| MIT | module3-permutation-boosting/LS_DS_233.ipynb | mariokart345/DS-Unit-2-Applied-Modeling |
Use xgboost for gradient boosting Overview In the Random Forest lesson, you learned this advice: Try Tree Ensembles when you do machine learning with labeled, tabular data- "Tree Ensembles" means Random Forest or **Gradient Boosting** models. - [Tree Ensembles often have the best predictive accuracy](https://arxiv.or... | from xgboost import XGBClassifier
pipeline = make_pipeline(
ce.OrdinalEncoder(),
XGBClassifier(n_estimators=100, random_state=42, n_jobs=-1)
)
pipeline.fit(X_train, y_train)
from sklearn.metrics import accuracy_score
y_pred=pipeline.predict(X_val)
print('Validation score', accuracy_score(y_val, y_p... | Validation score 0.7453703703703703
| MIT | module3-permutation-boosting/LS_DS_233.ipynb | mariokart345/DS-Unit-2-Applied-Modeling |
[Avoid Overfitting By Early Stopping With XGBoost In Python](https://machinelearningmastery.com/avoid-overfitting-by-early-stopping-with-xgboost-in-python/)Why is early stopping better than a For loop, or GridSearchCV, to optimize `n_estimators`?With early stopping, if `n_iterations` is our number of iterations, then ... | encoder = ce.OrdinalEncoder()
X_train_encoded = encoder.fit_transform(X_train)
X_val_encoded = encoder.transform(X_val)
model = XGBClassifier(
n_estimators=1000, # <= 1000 trees, depend on early stopping
max_depth=7, # try deeper trees because of high cardinality categoricals
learning_rate=0.5... | _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | mariokart345/DS-Unit-2-Applied-Modeling |
Introductory Data Analysis Workflow https://xkcd.com/2054 An example machine learning notebook* Original Notebook by [Randal S. Olson](http://www.randalolson.com/)* Supported by [Jason H. Moore](http://www.epistasis.org/)* [University of Pennsylvania Instit... | # text 17.04.2019
import datetime
print(datetime.datetime.now())
print('hello') | 2019-06-13 16:12:23.662194
hello
| MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Table of contents1. [Introduction](Introduction)2. [License](License)3. [Required libraries](Required-libraries)4. [The problem domain](The-problem-domain)5. [Step 1: Answering the question](Step-1:-Answering-the-question)6. [Step 2: Checking the data](Step-2:-Checking-the-data)7. [Step 3: Tidying the data](Step-3:-Ti... | import pandas as pd
iris_data = pd.read_csv('../data/iris-data.csv')
# Resources for loading data from nonlocal sources
# Pandas Can generally handle most common formats
# https://pandas.pydata.org/pandas-docs/stable/io.html
# SQL https://stackoverflow.com/questions/39149243/how-do-i-connect-to-a-sql-server-database... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
We're in luck! The data seems to be in a usable format.The first row in the data file defines the column headers, and the headers are descriptive enough for us to understand what each column represents. The headers even give us the units that the measurements were recorded in, just in case we needed to know at a later ... | iris_data.shape
iris_data.info()
iris_data.describe()
iris_data = pd.read_csv('../data/iris-data.csv', na_values=['NA', 'N/A']) | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Voilà! Now pandas knows to treat rows with 'NA' as missing values. Next, it's always a good idea to look at the distribution of our data — especially the outliers.Let's start by printing out some summary statistics about the data set. | iris_data.describe() | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
We can see several useful values from this table. For example, we see that five `petal_width_cm` entries are missing.If you ask me, though, tables like this are rarely useful unless we know that our data should fall in a particular range. It's usually better to visualize the data in some way. Visualization makes outlie... | # This line tells the notebook to show plots inside of the notebook
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sb | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Next, let's create a **scatterplot matrix**. Scatterplot matrices plot the distribution of each column along the diagonal, and then plot a scatterplot matrix for the combination of each variable. They make for an efficient tool to look for errors in our data.We can even have the plotting package color each entry by its... | # We have to temporarily drop the rows with 'NA' values
# because the Seaborn plotting function does not know
# what to do with them
sb.pairplot(iris_data.dropna(), hue='class')
| C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\_methods.py:140: RuntimeWarning: Degrees of freedom <= 0 for slice
keepdims=keepdims)
C:\ProgramData\Anaconda3\lib\site-packages\numpy\core\_methods.py:132: RuntimeWarning: invalid value encountered in double_scalars
ret = ret.dtype.type(ret / rcount)
| MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
From the scatterplot matrix, we can already see some issues with the data set:1. There are five classes when there should only be three, meaning there were some coding errors.2. There are some clear outliers in the measurements that may be erroneous: one `sepal_width_cm` entry for `Iris-setosa` falls well outside its n... | iris_data['class'].unique()
# Copy and Replace
iris_data.loc[iris_data['class'] == 'versicolor', 'class'] = 'Iris-versicolor'
iris_data['class'].unique()
# So we take a row where a specific column('class' here) matches our bad values
# and change them to good values
iris_data.loc[iris_data['class'] == 'Iris-setossa'... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Much better! Now we only have three class types. Imagine how embarrassing it would've been to create a model that used the wrong classes.>There are some clear outliers in the measurements that may be erroneous: one `sepal_width_cm` entry for `Iris-setosa` falls well outside its normal range, and several `sepal_length_c... | smallpetals = iris_data.loc[(iris_data['sepal_width_cm'] < 2.5) & (iris_data['class'] == 'Iris-setosa')]
smallpetals
iris_data.loc[iris_data['class'] == 'Iris-setosa', 'sepal_width_cm'].hist()
# This line drops any 'Iris-setosa' rows with a separal width less than 2.5 cm
# Let's go over this command in class
iris_data ... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Excellent! Now all of our `Iris-setosa` rows have a sepal width greater than 2.5.The next data issue to address is the several near-zero sepal lengths for the `Iris-versicolor` rows. Let's take a look at those rows. | iris_data.loc[(iris_data['class'] == 'Iris-versicolor') &
(iris_data['sepal_length_cm'] < 1.0)] | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
How about that? All of these near-zero `sepal_length_cm` entries seem to be off by two orders of magnitude, as if they had been recorded in meters instead of centimeters.After some brief correspondence with the field researchers, we find that one of them forgot to convert those measurements to centimeters. Let's do tha... | iris_data.loc[iris_data['class'] == 'Iris-versicolor', 'sepal_length_cm'].hist()
iris_data['sepal_length_cm'].hist()
# Here we fix the wrong units
iris_data.loc[(iris_data['class'] == 'Iris-versicolor') &
(iris_data['sepal_length_cm'] < 1.0),
'sepal_length_cm'] *= 100.0
iris_data.loc[iris_... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Phew! Good thing we fixed those outliers. They could've really thrown our analysis off.>We had to drop those rows with missing values.Let's take a look at the rows with missing values: | iris_data.loc[(iris_data['sepal_length_cm'].isnull()) |
(iris_data['sepal_width_cm'].isnull()) |
(iris_data['petal_length_cm'].isnull()) |
(iris_data['petal_width_cm'].isnull())] | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
It's not ideal that we had to drop those rows, especially considering they're all `Iris-setosa` entries. Since it seems like the missing data is systematic — all of the missing values are in the same column for the same *Iris* type — this error could potentially bias our analysis.One way to deal with missing data is **... | iris_data.loc[iris_data['class'] == 'Iris-setosa', 'petal_width_cm'].hist()
| _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Most of the petal widths for `Iris-setosa` fall within the 0.2-0.3 range, so let's fill in these entries with the average measured petal width. | iris_data.loc[iris_data['class'] == 'Iris-setosa', 'petal_width_cm'].mean()
average_petal_width = iris_data.loc[iris_data['class'] == 'Iris-setosa', 'petal_width_cm'].mean()
print(average_petal_width)
iris_data.loc[(iris_data['class'] == 'Iris-setosa') &
(iris_data['petal_width_cm'].isnull()),
... | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Great! Now we've recovered those rows and no longer have missing data in our data set.**Note:** If you don't feel comfortable imputing your data, you can drop all rows with missing data with the `dropna()` call: iris_data.dropna(inplace=True)After all this hard work, we don't want to repeat this process every time w... | iris_data.to_json('../data/iris-clean.json')
iris_data.to_csv('../data/iris-data-clean.csv', index=False)
cleanedframe = iris_data.dropna()
iris_data_clean = pd.read_csv('../data/iris-data-clean.csv') | _____no_output_____ | MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Now, let's take a look at the scatterplot matrix now that we've tidied the data. | myplot = sb.pairplot(iris_data_clean, hue='class')
myplot.savefig('irises.png')
import scipy.stats as stats
iris_data = pd.read_csv('../data/iris-data.csv')
iris_data.columns.unique()
stats.entropy(iris_data_clean['sepal_length_cm'])
iris_data.columns[:-1]
# we go through list of column names except last one and get en... | Entropy for: sepal_length_cm 4.96909746125432
Entropy for: sepal_width_cm 5.000701325982732
Entropy for: petal_length_cm 4.888113822938816
Entropy for: petal_width_cm 4.754264731532864
| MIT | Irises_ML_Intro/Irises Data Analysis Workflow_06_2019.ipynb | ValRCS/RCS_Data_Analysis_Python_2019_July |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.