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
**Step 2:** Compute the Jacobians for the firm block around the stationary equilibrium (analytical).
sol.jac_r_K[:] = 0 sol.jac_w_K[:] = 0 sol.jac_r_Z[:] = 0 sol.jac_w_Z[:] = 0 for s in range(par.path_T): for t in range(par.path_T): if t == s+1: sol.jac_r_K[t,s] = par.alpha*(par.alpha-1)*par.Z*par.K_ss**(par.alpha-2) sol.jac_w_K[t,s] = (1-par.alpha)*par.alpha*par.Z*par.K_ss**(par...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Step 3:** Use the chain rule and solve for $G$.
H_K = sol.jac_curlyK_r @ sol.jac_r_K + sol.jac_curlyK_w @ sol.jac_w_K - np.eye(par.path_T) H_Z = sol.jac_curlyK_r @ sol.jac_r_Z + sol.jac_curlyK_w @ sol.jac_w_Z G_K_Z = -np.linalg.solve(H_K, H_Z) # H_K^(-1)H_Z
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Step 4:** Find effect on prices and other outcomes than $K$.
G_r_Z = sol.jac_r_Z + sol.jac_r_K@G_K_Z G_w_Z = sol.jac_w_Z + sol.jac_w_K@G_K_Z G_C_Z = sol.jac_C_r@G_r_Z + sol.jac_C_w@G_w_Z
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Step 5:** Plot impulse-responses. **Example I:** News shock (i.e. in a single period) vs. persistent shock where $ dZ_t = \rho dZ_{t-1} $ and $dZ_0$ is the initial shock.
fig = plt.figure(figsize=(12,4)) T_fig = 50 # left: news shock ax = fig.add_subplot(1,2,1) for s in [5,10,15,20,25]: dZ = (1+par.Z_sigma)*par.Z*(np.arange(par.path_T) == s) dK = G_K_Z@dZ ax.plot(np.arange(T_fig),dK[:T_fig],'-o',ms=2,label=f'$s={s}$') ax.legend(frameon=True) ax.set_title(r'1% TFP news ...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Example II:** Further effects of persistent shock.
fig = plt.figure(figsize=(12,8)) T_fig = 50 ax_K = fig.add_subplot(2,2,1) ax_r = fig.add_subplot(2,2,2) ax_w = fig.add_subplot(2,2,3) ax_C = fig.add_subplot(2,2,4) ax_K.set_title('$K_t-K_{ss}$ after 1% TFP shock') ax_K.set_xlim([0,T_fig]) ax_r.set_title('$r_t-r_{ss}$ after 1% TFP shock') ax_r.set_xlim([0,T_fig]) ...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
Non-linear transition path Use the Jacobian to speed-up solving for the non-linear transition path using a quasi-Newton method. **1. Solver**
def broyden_solver(f,x0,jac,tol=1e-8,max_iter=100,backtrack_fac=0.5,max_backtrack=30,do_print=False): """ numerical solver using the broyden method """ # a. initial x = x0.ravel() y = f(x) # b. iterate for it in range(max_iter): # i. current difference abs_diff = np.ma...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**2. Target function** $$\boldsymbol{H}(\boldsymbol{K},\boldsymbol{Z},D_{ss}) = \mathcal{K}_{t}(\{r(Z_{s},K_{s-1}),w(Z_{s},K_{s-1})\}_{s\geq0},D_{ss})-K_{t}=0$$
def target(path_K,path_Z,model,D0,full_output=False): par = model.par sim = model.sim path_r = np.zeros(path_K.size) path_w = np.zeros(path_K.size) # a. implied prices K0lag = np.sum(par.a_grid[np.newaxis,:]*D0) path_Klag = np.insert(path_K,0,K0lag) for t in range(par.path_T)...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**3. Solve**
path_Z = model.get_path_Z() f = lambda x: target(x,path_Z,model,sim.D) t0 = time.time() path_K = broyden_solver(f,x0=np.repeat(par.K_ss,par.path_T),jac=H_K,do_print=True) path_r,path_w = target(path_K,path_Z,model,sim.D,full_output=True) print(f'\nIRF found in {elapsed(t0)}')
it = 0 -> max. abs. error = 0.05898269 it = 1 -> max. abs. error = 0.00026075 it = 2 -> max. abs. error = 0.00000163 it = 3 -> max. abs. error = 0.00000000 IRF found in 2.1 secs
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**4. Plot**
fig = plt.figure(figsize=(12,4)) ax = fig.add_subplot(1,2,1) ax.set_title('capital, $K_t$') dK = G_K_Z@(path_Z-par.Z) ax.plot(np.arange(T_fig),dK[:T_fig] + par.K_ss,'-o',ms=2,label=f'linear') ax.plot(np.arange(T_fig),path_K[:T_fig],'-o',ms=2,label=f'non-linear') if DO_TP_RELAX: ax.plot(np.arange(T_fig),path_K_rela...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
Covariances Assume that $Z_t$ is stochastic and follows$$ d\tilde{Z}_t = \rho d\tilde{Z}_{t-1} + \sigma\epsilon_t,\,\,\, \epsilon_t \sim \mathcal{N}(0,1) $$The covariances between all outcomes can be calculated as follows.
# a. choose parameter rho = 0.90 sigma = 0.10 # b. find change in outputs dZ = rho**(np.arange(par.path_T)) dC = G_C_Z@dZ dK = G_K_Z@dZ # c. covariance of consumption print('auto-covariance of consumption:\n') for k in range(5): if k == 0: autocov_C = sigma**2*np.sum(dC*dC) else: autocov_C = s...
auto-covariance of consumption: k = 0: 0.0445 k = 1: 0.0431 k = 2: 0.0415 k = 3: 0.0399 k = 4: 0.0382 covariance of consumption and capital: 0.2117
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
Extra: No idiosyncratic uncertainty This section solve for the transition path in the case without idiosyncratic uncertainty. **Analytical solution for steady state:**
r_ss_pf = (1/par.beta-1) # from euler-equation w_ss_pf = model.implied_w(r_ss_pf,par.Z) K_ss_pf = model.firm_demand(r_ss_pf,par.Z) Y_ss_pf = model.firm_production(K_ss_pf,par.Z) C_ss_pf = Y_ss_pf-par.delta*K_ss_pf print(f'r: {r_ss_pf:.6f}') print(f'w: {w_ss_pf:.6f}') print(f'Y: {Y_ss_pf:.6f}') print(f'C: {C_ss_pf:.6f}...
r: 0.018330 w: 0.998613 Y: 1.122037 C: 1.050826 K/Y: 2.538660
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Function for finding consumption and capital paths given paths of interest rates and wages:**It can be shown that$$ C_{0}=\frac{(1+r_{0})a_{-1}+\sum_{t=0}^{\infty}\frac{1}{\mathcal{R}_{t}}w_{t}}{\sum_{t=0}^{\infty}\beta^{t/\rho}\mathcal{R}_{t}^{\frac{1-\rho}{\rho}}} $$where $$ \mathcal{R}_{t} =\begin{cases} 1 & \text...
def path_CK_func(K0,path_r,path_w,r_ss,w_ss,model): par = model.par # a. initialize wealth = (1+path_r[0])*K0 inv_MPC = 0 # b. solve RT = 1 max_iter = 5000 t = 0 while True and t < max_iter: # i. prices padded with steady state r = path_r[t] i...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Test with steady state prices:**
path_r_pf = np.repeat(r_ss_pf,par.path_T) path_w_pf = np.repeat(w_ss_pf,par.path_T) path_K_pf,path_C_pf = path_CK_func(K_ss_pf,path_r_pf,path_w_pf,r_ss_pf,w_ss_pf,model) print(f'C_ss: {C_ss_pf:.6f}') print(f'C[0]: {path_C_pf[0]:.6f}') print(f'C[-1]: {path_C_pf[-1]:.6f}') assert np.isclose(C_ss_pf,path_C_pf[0])
C_ss: 1.050826 C[0]: 1.050826 C[-1]: 1.050826
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Shock paths** where interest rate deviate in one period:
dr = 1e-4 ts = np.array([0,20,40]) path_C_pf_shock = np.empty((ts.size,par.path_T)) path_K_pf_shock = np.empty((ts.size,par.path_T)) for i,t in enumerate(ts): path_r_pf_shock = path_r_pf.copy() path_r_pf_shock[t] += dr K,C = path_CK_func(K_ss_pf,path_r_pf_shock,path_w_pf,r_ss_pf,w_ss_pf,model) ...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Plot paths:**
fig = plt.figure(figsize=(12,4)) ax = fig.add_subplot(1,2,1) ax.plot(np.arange(par.path_T),path_C_pf,'-o',ms=2,label=f'$r_t = r^{{\\ast}}$') for i,t in enumerate(ts): ax.plot(np.arange(par.path_T),path_C_pf_shock[i],'-o',ms=2,label=f'shock to $r_{{{t}}}$') ax.set_xlim([0,50]) ax.set_xlabel('periods') ax.set_y...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Find transition path with shooting algorithm:**
# a. allocate dT = 200 path_C_pf = np.empty(par.path_T) path_K_pf = np.empty(par.path_T) path_r_pf = np.empty(par.path_T) path_w_pf = np.empty(par.path_T) # b. settings C_min = C_ss_pf C_max = C_ss_pf + K_ss_pf K_min = 1.5 # guess on lower consumption if below this K_max = 3 # guess on higher consumption if above thi...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
**Plot deviations from steady state:**
fig = plt.figure(figsize=(12,8)) ax = fig.add_subplot(2,2,1) ax.plot(np.arange(par.path_T),path_Z,'-o',ms=2) ax.set_xlim([0,200]) ax.set_title('technology, $Z_t$') ax = fig.add_subplot(2,2,2) ax.plot(np.arange(par.path_T),path_K-model.par.kd_ss,'-o',ms=2,label='$\sigma_e = 0.5$') ax.plot(np.arange(par.path_T),path_K_...
_____no_output_____
MIT
00. DynamicProgramming/05. General Equilibrium.ipynb
JMSundram/ConsumptionSavingNotebooks
LeNet Lab![LeNet Architecture](lenet.png)Source: Yan LeCun Load DataLoad the MNIST data, which comes pre-loaded with TensorFlow.You do not need to modify this section.
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", reshape=False) X_train, y_train = mnist.train.images, mnist.train.labels X_validation, y_validation = mnist.validation.images, mnist.validation.labels X_test, y_test = mnist.test.images, mn...
/Users/Kornet-Mac-1/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converte...
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
The MNIST data that TensorFlow pre-loads comes as 28x28x1 images.However, the LeNet architecture only accepts 32x32xC images, where C is the number of color channels.In order to reformat the MNIST data into a shape that LeNet will accept, we pad the data with two rows of zeros on the top and bottom, and two columns of ...
import numpy as np # Pad images with 0s X_train = np.pad(X_train, ((0,0),(2,2),(2,2),(0,0)), 'constant') X_validation = np.pad(X_validation, ((0,0),(2,2),(2,2),(0,0)), 'constant') X_test = np.pad(X_test, ((0,0),(2,2),(2,2),(0,0)), 'constant') print("Updated Image Shape: {}".format(X_train[0].shape))
Updated Image Shape: (32, 32, 1)
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
Visualize DataView a sample from the dataset.You do not need to modify this section.
import random import numpy as np import matplotlib.pyplot as plt %matplotlib inline index = random.randint(0, len(X_train)) image = X_train[index].squeeze() plt.figure(figsize=(1,1)) plt.imshow(image, cmap="gray") print(y_train[index])
6
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
Preprocess DataShuffle the training data.You do not need to modify this section.
from sklearn.utils import shuffle X_train, y_train = shuffle(X_train, y_train)
_____no_output_____
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
Setup TensorFlowThe `EPOCH` and `BATCH_SIZE` values affect the training speed and model accuracy.You do not need to modify this section.
import tensorflow as tf EPOCHS = 10 BATCH_SIZE = 128
_____no_output_____
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
TODO: Implement LeNet-5Implement the [LeNet-5](http://yann.lecun.com/exdb/lenet/) neural network architecture.This is the only cell you need to edit. InputThe LeNet architecture accepts a 32x32xC image as input, where C is the number of color channels. Since MNIST images are grayscale, C is 1 in this case. Architectur...
from tensorflow.contrib.layers import flatten def LeNet(x): # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer mu = 0 sigma = 0.1 # TODO: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6. conv1_W = tf.Variable(tf.truncate...
_____no_output_____
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
Features and LabelsTrain LeNet to classify [MNIST](http://yann.lecun.com/exdb/mnist/) data.`x` is a placeholder for a batch of input images.`y` is a placeholder for a batch of output labels.You do not need to modify this section.
x = tf.placeholder(tf.float32, (None, 32, 32, 1)) y = tf.placeholder(tf.int32, (None)) one_hot_y = tf.one_hot(y, 10)
_____no_output_____
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
Training PipelineCreate a training pipeline that uses the model to classify MNIST data.You do not need to modify this section.
rate = 0.001 logits = LeNet(x) cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits) loss_operation = tf.reduce_mean(cross_entropy) optimizer = tf.train.AdamOptimizer(learning_rate = rate) training_operation = optimizer.minimize(loss_operation)
_____no_output_____
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
Model EvaluationEvaluate how well the loss and accuracy of the model for a given dataset.You do not need to modify this section.
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) saver = tf.train.Saver() def evaluate(X_data, y_data): num_examples = len(X_data) total_accuracy = 0 sess = tf.get_default_session() for offset in ra...
_____no_output_____
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
Train the ModelRun the training data through the training pipeline to train the model.Before each epoch, shuffle the training set.After each epoch, measure the loss and accuracy of the validation set.Save the model after training.You do not need to modify this section.
with tf.Session() as sess: sess.run(tf.global_variables_initializer()) num_examples = len(X_train) print("Training...") print() for i in range(EPOCHS): X_train, y_train = shuffle(X_train, y_train) for offset in range(0, num_examples, BATCH_SIZE): end = offset + BATCH...
Training... EPOCH 1 ... Validation Accuracy = 0.972 EPOCH 2 ... Validation Accuracy = 0.978 EPOCH 3 ... Validation Accuracy = 0.984 EPOCH 4 ... Validation Accuracy = 0.986 EPOCH 5 ... Validation Accuracy = 0.989 EPOCH 6 ... Validation Accuracy = 0.987 EPOCH 7 ... Validation Accuracy = 0.990 EPOCH 8 ... Validati...
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
Evaluate the ModelOnce you are completely satisfied with your model, evaluate the performance of the model on the test set.Be sure to only do this once!If you were to measure the performance of your trained model on the test set, then improve your model, and then measure the performance of your model on the test set a...
with tf.Session() as sess: saver.restore(sess, tf.train.latest_checkpoint('.')) test_accuracy = evaluate(X_test, y_test) print("Test Accuracy = {:.3f}".format(test_accuracy))
INFO:tensorflow:Restoring parameters from ./lenet Test Accuracy = 0.990
MIT
LeNet-Lab.ipynb
dumebi/-Udasity-CarND-LeNet-Lab
Praca domowa 3 Ładowanie podstawowych pakietów
import pandas as pd import numpy as np import sklearn import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score from sklearn.model_selection import StratifiedKFold # used in crossvalidation from sklearn.model_selection import KFold i...
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Krótki wstęp Celem zadania jest by bazujac na danych meteorologicznych z australi sprawdzić i wytrenowac 3 różne modele. Równie ważnym celem zadania jest przejrzenie oraz zmiana tzn. hiperparamterów z każdego nich. Załadowanie danych
data = pd.read_csv("../../australia.csv")
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Przyjrzenie się danym
data.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 56420 entries, 0 to 56419 Data columns (total 18 columns): MinTemp 56420 non-null float64 MaxTemp 56420 non-null float64 Rainfall 56420 non-null float64 Evaporation 56420 non-null float64 Sunshine 56420 non-null float64 WindGustSpe...
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Nie ma w danych żadnych braków, oraz są one przygotowane idealnie do uczenia maszynowego. Przyjżyjmy się jednak jak wygląda ramka.
data.head()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Random Forest **Załadowanie potrzebnych bibliotek**
from sklearn.ensemble import RandomForestClassifier
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Inicjalizowanie modelu**
rf_default = RandomForestClassifier()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Hiperparametry**
params = rf_default.get_params() params
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Zmiana kilku hiperparametrów**
params['n_estimators']=150 params['max_depth']=6 params['min_samples_leaf']=4 params['n_jobs']=4 params['random_state']=0 rf_modified = RandomForestClassifier() rf_modified.set_params(**params)
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Extreme Gradient Boosting **Załadowanie potrzebnych bibliotek**
from xgboost import XGBClassifier
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Inicjalizowanie modelu**
xgb_default = XGBClassifier()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Hiperparametry**
params = xgb_default.get_params() params
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Zmiana kilku hiperparametrów**
params['n_estimators']=150 params['max_depth']=6 params['n_jobs']=4 params['random_state']=0 xgb_modified = XGBClassifier() xgb_modified.set_params(**params)
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Support Vector Machines **Załadowanie potrzebnych bibliotek**
from sklearn.svm import SVC
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Inicjalizowanie modelu**
svc_default = SVC()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Hiperparametry**
params = svc_default.get_params() params
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Zmiana kilku hiperparametrów**
params['degree']=3 params['tol']=0.001 params['random_state']=0 svc_modified = SVC() svc_modified.set_params(**params)
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
KomentarzW tym momencie otrzymaliśmy 3 modele z zmienionymi hiperparametrami, oraz ich domyślne odpowiedniki. Zobaczmy teraz jak zmieniły się rezultaty osiągane przez te modele i chociaż nie był to cel tego zadania, zobaczmy czy może udało nam się poprawić jakiś model. Porównanie **Załadowanie potrzebnych bibliotek**...
from sklearn.metrics import f1_score from sklearn.metrics import accuracy_score from sklearn.metrics import balanced_accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import average_precision_score from sklearn.metrics import roc_auc_score
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Funkcje pomocnicze
def cv_classifier(classifier,kfolds = 10, X = data.drop("RainTomorrow", axis = 1), y = data.RainTomorrow): start_time = time() scores ={} scores["f1"]=[] scores["accuracy"]=[] scores["balanced_accuracy"]=[] scores["precision"]=[] scores["average_precision"]=[] scores["roc_auc"]=[] ...
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
WynikiPoniżej zamieszczam wyniki predykcji pokazanych wcześniej modeli. Dla kontrastu nauczyłem zmodyfikowane wersję klasyfikatorów jak i również te domyślne. Ze smutkiem muszę stwierdzić, że nie jestem najlepszy w strzelaniu, ponieważ parametry, które dobrałem znacznie pogarszają skutecznść każdego z modeli. Niemniej...
scores_rf_default = cv_classifier(rf_default) scores_rf_modified = cv_classifier(rf_modified) mean_scores_rf_default = get_mean_scores(scores_rf_default) mean_scores_rf_modified = get_mean_scores(scores_rf_modified)
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Random forest default**
print_mean_scores(mean_scores_rf_default,precision=2)
Mean f1 score is 62.85% Mean accuracy score is 86.09% Mean balanced_accuracy score is 74.38% Mean precision score is 76.32% Mean average_precision score is 51.05% Mean roc_auc score is 74.38%
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Random forest modified**
print_mean_scores(mean_scores_rf_modified,precision=2)
Mean f1 score is 56.74% Mean accuracy score is 84.97% Mean balanced_accuracy score is 70.54% Mean precision score is 77.55% Mean average_precision score is 46.88% Mean roc_auc score is 70.54%
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Extreme Gradient Boosting Kroswalidacja modeli
scores_xgb_default = cv_classifier(xgb_default) scores_xgb_modified = cv_classifier(xgb_modified) mean_scores_xgb_default = get_mean_scores(scores_xgb_default) mean_scores_xgb_modified = get_mean_scores(scores_xgb_modified)
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**XGBoost default**
print_mean_scores(mean_scores_xgb_default,precision=2)
Mean f1 score is 63.79% Mean accuracy score is 85.92% Mean balanced_accuracy score is 75.3% Mean precision score is 73.56% Mean average_precision score is 51.06% Mean roc_auc score is 75.3%
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**XGBoost modified**
print_mean_scores(mean_scores_xgb_modified,precision=2)
Mean f1 score is 63.93% Mean accuracy score is 85.89% Mean balanced_accuracy score is 75.44% Mean precision score is 73.18% Mean average_precision score is 51.07% Mean roc_auc score is 75.44%
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Support Vector Machines Kroswalidacja modeli **warning this takes a while**
scores_svc_default = cv_classifier(svc_default) scores_svc_modified = cv_classifier(svc_modified) mean_scores_svc_default = get_mean_scores(scores_svc_default) mean_scores_svc_modified = get_mean_scores(scores_svc_modified)
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**SVM default**
print_mean_scores(mean_scores_svc_default,precision=2)
Mean f1 score is 51.52% Mean accuracy score is 84.38% Mean balanced_accuracy score is 67.63% Mean precision score is 81.47% Mean average_precision score is 44.44% Mean roc_auc score is 67.63%
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**SVM modified**
print_mean_scores(mean_scores_svc_modified,precision=2)
Mean f1 score is 51.52% Mean accuracy score is 84.38% Mean balanced_accuracy score is 67.63% Mean precision score is 81.47% Mean average_precision score is 44.44% Mean roc_auc score is 67.63%
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Podsumowanie Wyniki random forest oraz xgboost były dośyć zbliżone i szczerze mówiąc dosyć słabe. Jeszcze gorzej wypadł SVM, co pewnie wielu nie zdziwi. Ma okropnie długi czas uczenia, ponad minuta na model. Wypada dużo gorzej niż pozostałe algorytmy, gdzie 10 modeli xgboost zostało wyszkolone w 41s. Natomiast wyniki ...
data2 = pd.read_csv('allegro-api-transactions.csv') data2 = data2.drop(['lp','date'], axis = 1) data2.head()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Dane są prawie gotowe do procesu czenia, trzeba jedynie poprawić `it_location` w którym mogą pojawić się powtórki w stylu *Warszawa* i *warszawa*, a następnie zakodować zmienne kategoryczne
data2.it_location = data2.it_location.str.lower() data2.head() encoding_columns = ['categories','seller','it_location','main_category']
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Kodowanie zmiennych kategorycznych
import category_encoders from sklearn.preprocessing import OneHotEncoder
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Podział danych Nie wykonam standardowego podziału na dane test i train, ponieważ w dalszej części dokumentu do oceny skutecznosci użytych kodowań posłużę się kroswalidacją. Pragnę zaznaczyć, ze prawdopodbnie najlepszą metodą tutaj byłoby rozbicie kategorii `categories` na 26 kolumn, zero-jedynkowych, jednak znacznie b...
X = data2.drop('price', axis = 1) y = data2.price
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Target encoding
te = category_encoders.target_encoder.TargetEncoder(data2, cols = encoding_columns) target_encoded = te.fit_transform(X,y) target_encoded
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
James-Stein Encoding
js = category_encoders.james_stein.JamesSteinEncoder(cols = encoding_columns) encoded_js = js.fit_transform(X,y) encoded_js
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Cat Boost Encoding
cb = category_encoders.cat_boost.CatBoostEncoder(cols = encoding_columns) encoded_cb = cb.fit_transform(X,y) encoded_cb
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Testowanie
from sklearn.metrics import r2_score, mean_squared_error from sklearn import linear_model def cv_encoding(model,kfolds = 10, X = data.drop("RainTomorrow", axis = 1), y = data.RainTomorrow): start_time = time() scores ={} scores["r2_score"] = [] scores['RMSE'] = [] # Standard k-fold cv ...
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Mierzenie skutecznosci kodowańZdecydowałem isę skorzystać z modelu regresji liniowej `Lasso` początkowo chciałem skorzystać z `Elastic Net`, ale jak się okazało zmienne nie sa ze sobą zbytnio powiązane, a to miał być główny powód do jego użycia.
corr=data2.corr() fig, ax=plt.subplots(figsize=(9,6)) ax=sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns, annot=True, cmap="PiYG", center=0, vmin=-1, vmax=1) ax.set_title('Korelacje zmiennych') plt.show();
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Wybór modelu liniowegoOkreślam go w tym miejscu, ponieważ w dalszych częściach dokumentu będę z niego wielokrotnie korzystał przy kroswalidacji
lasso = linear_model.Lasso()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Wyniki target encodingu
target_encoding_scores = cv_encoding(model = lasso,kfolds=20, X = target_encoded, y = y) target_encoding_scores_mean = get_mean_scores(target_encoding_scores) target_encoding_scores_mean
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Wyniki James-Stein Encodingu
js_encoding_scores = cv_encoding(lasso, 20, encoded_js, y) js_encoding_scores_mean = get_mean_scores(js_encoding_scores) js_encoding_scores_mean
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Wyniki Cat Boost Encodingu
cb_encoding_scores = cv_encoding(lasso, 20 ,encoded_cb, y) cb_encoding_scores_mean = get_mean_scores(cb_encoding_scores) cb_encoding_scores_mean
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
Porównanie Wyniki metryki r2
r2_data = [target_encoding_scores["r2_score"], js_encoding_scores["r2_score"], cb_encoding_scores["r2_score"]] labels = ["Target", " James-Stein", "Cat Boost"] fig, ax = plt.subplots(figsize = (12,9)) ax.set_title('Wyniki r2') ax.boxplot(r2_data, labels = labels) plt.show()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
**Komentarz** Widać, że użycie kodowania Jamesa-Steina pozwoliło modelowi dużo lepiej się dopasować do danych, jednak stwarza to ewentaulny problem nadmiernego dopasowania się do danych. Warto by było sprawdzić czy przez ten sposób kodowania nie dochodzi do dużo silniejszego overfittingu. Wynikii metryki RMSE
rmse_data = [target_encoding_scores["RMSE"], js_encoding_scores["RMSE"], cb_encoding_scores["RMSE"]] labels = ["Target", " James-Stein", "Cat Boost"] fig, ax = plt.subplots(figsize = (12,9)) ax.set_title('Wyniki RMSE w skali logarytmicznej') ax.set_yscale('log') ax.boxplot(rmse_data, labels = labels) plt.show()
_____no_output_____
Apache-2.0
Prace_domowe/Praca_domowa3/Grupa1/EljasiakBartlomiej/pd3.ipynb
niladrem/2020L-WUM
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). Challenge Notebook Problem: Implement depth-first traversals (in-order, pre-order, post-order) on a binary tree.* [Constraints](Constraint...
# %load ../bst/bst.py class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None self.parent = None def __repr__(self): return str(self.data) class Bst(object): def __init__(self, root=None): self.root = root de...
_____no_output_____
Apache-2.0
graphs_trees/tree_dfs/dfs_challenge.ipynb
hanbf/interactive-coding-challenges
Unit Test
%run ../utils/results.py # %load test_dfs.py from nose.tools import assert_equal class TestDfs(object): def __init__(self): self.results = Results() def test_dfs(self): bst = BstDfs(Node(5)) bst.insert(2) bst.insert(8) bst.insert(1) bst.insert(3) bst....
Success: test_dfs
Apache-2.0
graphs_trees/tree_dfs/dfs_challenge.ipynb
hanbf/interactive-coding-challenges
Generative Adversarial NetworksThroughout most of this book, we've talked about how to make predictions.In some form or another, we used deep neural networks learned mappings from data points to labels.This kind of learning is called discriminative learning,as in, we'd like to be able to discriminate between photos ca...
from __future__ import print_function import matplotlib as mpl from matplotlib import pyplot as plt import mxnet as mx from mxnet import gluon, autograd, nd from mxnet.gluon import nn import numpy as np ctx = mx.cpu()
_____no_output_____
Apache-2.0
chapter14_generative-adversarial-networks/gan-intro.ipynb
vishaalkapoor/mxnet-the-straight-dope
Generate some 'real' dataSince this is going to be the world's lamest example, we simply generate data drawn from a Gaussian. And let's also set a context where we'll do most of the computation.
X = nd.random_normal(shape=(1000, 2)) A = nd.array([[1, 2], [-0.1, 0.5]]) b = nd.array([1, 2]) X = nd.dot(X, A) + b Y = nd.ones(shape=(1000, 1)) # and stick them into an iterator batch_size = 4 train_data = mx.io.NDArrayIter(X, Y, batch_size, shuffle=True)
_____no_output_____
Apache-2.0
chapter14_generative-adversarial-networks/gan-intro.ipynb
vishaalkapoor/mxnet-the-straight-dope
Let's see what we got. This should be a Gaussian shifted in some rather arbitrary way with mean $b$ and covariance matrix $A^\top A$.
plt.scatter(X[:,0].asnumpy(), X[:,1].asnumpy()) plt.show() print("The covariance matrix is") print(nd.dot(A.T, A))
_____no_output_____
Apache-2.0
chapter14_generative-adversarial-networks/gan-intro.ipynb
vishaalkapoor/mxnet-the-straight-dope
Defining the networksNext we need to define how to fake data. Our generator network will be the simplest network possible - a single layer linear model. This is since we'll be driving that linear network with a Gaussian data generator. Hence, it literally only needs to learn the parameters to fake things perfectly. Fo...
# build the generator netG = nn.Sequential() with netG.name_scope(): netG.add(nn.Dense(2)) # build the discriminator (with 5 and 3 hidden units respectively) netD = nn.Sequential() with netD.name_scope(): netD.add(nn.Dense(5, activation='tanh')) netD.add(nn.Dense(3, activation='tanh')) netD.add(nn.Dens...
_____no_output_____
Apache-2.0
chapter14_generative-adversarial-networks/gan-intro.ipynb
vishaalkapoor/mxnet-the-straight-dope
Setting up the training loopWe are going to iterate over the data a few times. To make life simpler we need a few variables
real_label = mx.nd.ones((batch_size,), ctx=ctx) fake_label = mx.nd.zeros((batch_size,), ctx=ctx) metric = mx.metric.Accuracy() # set up logging from datetime import datetime import os import time
_____no_output_____
Apache-2.0
chapter14_generative-adversarial-networks/gan-intro.ipynb
vishaalkapoor/mxnet-the-straight-dope
Training loop
stamp = datetime.now().strftime('%Y_%m_%d-%H_%M') for epoch in range(10): tic = time.time() train_data.reset() for i, batch in enumerate(train_data): ############################ # (1) Update D network: maximize log(D(x)) + log(1 - D(G(z))) ########################### # trai...
binary training acc at epoch 0: accuracy=0.764500 time: 5.838877
Apache-2.0
chapter14_generative-adversarial-networks/gan-intro.ipynb
vishaalkapoor/mxnet-the-straight-dope
Checking the outcomeLet's now generate some fake data and check whether it looks real.
noise = mx.nd.random_normal(shape=(100, 2), ctx=ctx) fake = netG(noise) plt.scatter(X[:,0].asnumpy(), X[:,1].asnumpy()) plt.scatter(fake[:,0].asnumpy(), fake[:,1].asnumpy()) plt.show()
_____no_output_____
Apache-2.0
chapter14_generative-adversarial-networks/gan-intro.ipynb
vishaalkapoor/mxnet-the-straight-dope
*This notebook is part of course materials for CS 345: Machine Learning Foundations and Practice at Colorado State University.Original versions were created by Asa Ben-Hur.The content is availabe [on GitHub](https://github.com/asabenhur/CS345).**The text is released under the [CC BY-SA license](https://creativecommons...
import numpy as np import matplotlib.pyplot as plt %matplotlib inline %autosave 0
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
Evaluating classifiers: cross validation Learning curvesIntuitively, the more data we have available, the more accurate our classifiers become. To demonstrate this, let's read in some data and evaluate a k-nearest neighbor classifier on a fixed test set with increasing number of training examples. The resulting cu...
from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier X, y = load_digits(return_X_y=True) training_sizes = [20, 40, 100, 200, 400, 600, 800, 1000, 1200] # note the use of the stratify keyword: it makes it so that each # class...
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
It's also instructive to look at the numbers themselves:
print ("# training examples\t accuracy") for i in range(len(accuracy)) : print ("\t{:d}\t\t {:f}".format(training_sizes[i], accuracy[i]))
# training examples accuracy 20 0.636516 40 0.889447 100 0.914573 200 0.953099 400 0.966499 600 0.979899 800 0.983250 1000 0.983250 1200 0.983250
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
Exercise* What can you conclude from this plot? * Why would you want to compute a learning curve on your data? Making better use of our data with cross validationThe discussion above demonstrates that it is best to have as large of a training set as possible. We also need to have a large enough test set, so that th...
from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_validate from sklearn.model_selection import cross_val_score from sklearn import metrics
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
Let's use the scikit-learn breast cancer dataset to demonstrate the use of cross-validation.
from sklearn.datasets import load_breast_cancer data = load_breast_cancer()
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
A scikit-learn data object is container object with whose interesting attributes are: * ‘data’, the data to learn, * ‘target’, the classification labels, * ‘target_names’, the meaning of the labels, * ‘feature_names’, the meaning of the features, and * ‘DESCR’, the full description of the dataset.
X = data.data y = data.target print('number of examples ', len(y)) print('number of features ', len(X[0])) print(data.target_names) print(data.feature_names) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=0) classifier = KNeigh...
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
Let's compute the accuracy of our predictions:
np.mean(y_pred==y_test)
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
We can do the same using scikit-learn:
metrics.accuracy_score(y_test, y_pred)
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
Now let's compute accuracy using [cross_validate](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_validate.html) instead:
accuracy = cross_val_score(classifier, X, y, cv=5, scoring='accuracy') print(accuracy)
[0.87719298 0.92105263 0.94736842 0.93859649 0.91150442]
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
This yields an array containing the accuracy values for each fold.When reporting your results, you will typically show the mean:
np.mean(accuracy)
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
The arguments of `cross_val_score`:* A classifier (anything that satisfies the scikit-learn classifier API)* data (features/labels)* `cv` : an integer that specifies the number of folds (can be used in more sophisticated ways as we will see below).* `scoring`: this determines which accuracy measure is evaluated for eac...
accuracy = cross_val_score(classifier, X, y, cv=5, scoring='balanced_accuracy') np.mean(accuracy)
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
`cross_val_score` is somewhat limited, in that it simply returns a list of accuracy scores. In practice, we often want to have more information about what happened during training, and also to compute multiple accuracy measures.`cross_validate` will provide you with that information:
results = cross_validate(classifier, X, y, cv=5, scoring='accuracy', return_estimator=True) print(results)
{'fit_time': array([0.0010581 , 0.00099397, 0.00085902, 0.00093985, 0.00105977]), 'score_time': array([0.00650811, 0.00734997, 0.01043916, 0.00643301, 0.00529218]), 'estimator': (KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=None, n_neighbors=3,...
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
The object returned by `cross_validate` is a Python dictionary as the output suggests. To extract a specific piece of data from this object, simply access the dictionary with the appropriate key:
results['test_score']
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
If you would like to know the predictions made for each training example during cross-validation use [cross_val_predict](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_predict.html) instead:
from sklearn.model_selection import cross_val_predict y_pred = cross_val_predict(classifier, X, y, cv=5) metrics.accuracy_score(y, y_pred)
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
The above way of performing cross-validation doesn't always give us enough control on the process: we usually want our machine learning experiments be reproducible, and to be able to use the same cross-validation splits with multiple algorithms. The scikit-learn `KFold` and `StratifiedKFold` cross-validation generato...
from sklearn.model_selection import StratifiedKFold, KFold X_toy = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9,10], [11, 12]]) y_toy = np.array([0, 0, 1, 1, 1, 1]) cv = KFold(n_splits=2, random_state=3, shuffle=True) for train_idx, test_idx in cv.split(X_toy, y_toy): print("train:", train_idx, "test:", test_idx) ...
train: [0 1 2] test: [3 4 5] [0 0 1] train: [3 4 5] test: [0 1 2] [1 1 1]
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
`StratifiedKFold` addresses this issue by making sure that each class is represented in each fold in proportion to its overall fraction in the data. This is particularly important when one or more of the classes have few examples.`StratifiedKFold` and `KFold` generate folds that can be used in conjunction with the cro...
cv = StratifiedKFold(n_splits=5, random_state=1, shuffle=True) accuracy = cross_val_score(classifier, X, y, cv=cv, scoring='accuracy') np.mean(accuracy)
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
For classification problems, `StratifiedKFold` is the preferred strategy. However, for regression problems `KFold` is the way to go. QuestionWhy is `KFold` used in regression probelms rather than `StratifiedKFold`? To clarify the distinction between the different methods of generating cross-validation folds and their ...
# the code for the figure is adapted from # https://scikit-learn.org/stable/auto_examples/model_selection/plot_cv_indices.html np.random.seed(42) cmap_data = plt.cm.Paired cmap_cv = plt.cm.coolwarm n_folds = 4 # Generate the data X = np.random.randn(100, 10) # generate labels - classes 0,1,2 and 10,30,60 examples, r...
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
Let's visualize the results of using `KFold` for fold generation:
fig, ax = plt.subplots() cv = KFold(n_folds) plot_cv_indices(cv, X, y, ax, n_folds);
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
As you can see, this naive way of using `KFold` can lead to highly undesirable splits into cross-validation folds.Using `StratifiedKFold` addresses this to some extent:
fig, ax = plt.subplots() cv = StratifiedKFold(n_folds) plot_cv_indices(cv, X, y, ax, n_folds);
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
Using `StratifiedKFold` with shuffling of the examples is the preferred way of splitting the data into folds:
fig, ax = plt.subplots() cv = StratifiedKFold(n_folds, shuffle=True) plot_cv_indices(cv, X, y, ax, n_folds);
_____no_output_____
MIT
notebooks/module05_01_cross_validation.ipynb
lottieandrews/CS345
Lecture 3.3: Anomaly Detection[**Lecture Slides**](https://docs.google.com/presentation/d/1_0Z5Pc5yHA8MyEBE8Fedq44a-DcNPoQM1WhJN93p-TI/edit?usp=sharing)This lecture, we are going to use gaussian distributions to detect anomalies in our emoji faces dataset**Learning goals:**- Introduce an anomaly detection problem- Imp...
from PIL import Image import glob paths = glob.glob('emoji_faces/*.png') images = [Image.open(path) for path in paths] len(images)
_____no_output_____
CC-BY-4.0
data_analysis/3.3_anomaly_detection/anomaly_detection.ipynb
camille-vanhoffelen/modern-ML-engineer