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
Learning from Italy, South Korea & Japan Italy, South Korea & Japan are three countries which show different growth rates and how it evolved over time. **South Korea** flattened it's growth after 2 weeks since 100 cases. **Italy** continue to grew after 3rd week.Where does your Country stand today?Click (Shift+ for mu...
#hide_input HTML(f'<small class="float-right">Last Updated on {pd.to_datetime(LAST_DATE).strftime("%B, %d %Y")}</small>') #hide_input chart = make_since_chart() chart #hide_input chart2 = make_since_chart(['Spain', 'Germany']) chart2 #hide_input chart3 = make_since_chart(['US', 'France']) chart3 #hide_input chart4 = ma...
_____no_output_____
MIT
covid19/covid19-compare-country-trajectories.ipynb
aladin002dz/notebooks
Select a country from the drop down list below to toggle the visualization.
#hide_input base = alt.Chart(dff2, width=600).encode( x='Days since 100 cases:Q', y=alt.Y('Confirmed Cases:Q', scale=alt.Scale(type='log')), color=alt.Color('Country:N', scale=alt.Scale(domain=color_domain, range=color_range), legend=None), tooltip=['Country', 'Date', 'Confirmed Cases', 'Days since 100 ...
_____no_output_____
MIT
covid19/covid19-compare-country-trajectories.ipynb
aladin002dz/notebooks
Handwriting Number Recognizer Importing Libraries
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score
_____no_output_____
MIT
Project Handwriting Number Recognizer/Handwriting_Number_Recognizer.ipynb
Nova1323/CodersWeek-ML
Importing Data
trainingdf = pd.read_csv('/content/sample_data/mnist_train_small.csv') testdf = pd.read_csv('/content/sample_data/mnist_test.csv') trainingdf.head()
_____no_output_____
MIT
Project Handwriting Number Recognizer/Handwriting_Number_Recognizer.ipynb
Nova1323/CodersWeek-ML
We can see that the output is in the first column
X_train = trainingdf.iloc[:,1:] y_train = trainingdf.iloc[:,0] y_train.head()
_____no_output_____
MIT
Project Handwriting Number Recognizer/Handwriting_Number_Recognizer.ipynb
Nova1323/CodersWeek-ML
testdf.head
_____no_output_____
MIT
Project Handwriting Number Recognizer/Handwriting_Number_Recognizer.ipynb
Nova1323/CodersWeek-ML
The first 100 rows are taken as the whole set takes time to predict
X_test = testdf.iloc[:100,1:] y_test = testdf.iloc[:100,0]
_____no_output_____
MIT
Project Handwriting Number Recognizer/Handwriting_Number_Recognizer.ipynb
Nova1323/CodersWeek-ML
Classifing the numbers using K-Nearest Neighbors
from sklearn.neighbors import KNeighborsClassifier clf = KNeighborsClassifier(n_neighbors=10).fit(X_train, y_train) clfpredict = clf.predict(X_test)
_____no_output_____
MIT
Project Handwriting Number Recognizer/Handwriting_Number_Recognizer.ipynb
Nova1323/CodersWeek-ML
Accuracy Score
accuracy_score(clfpredict,y_test)
_____no_output_____
MIT
Project Handwriting Number Recognizer/Handwriting_Number_Recognizer.ipynb
Nova1323/CodersWeek-ML
Confusion Matrix
label=y_train.unique() label=np.sort(label) from sklearn.metrics import plot_confusion_matrix cm=plot_confusion_matrix(clf,X_test, y_test,labels=label,cmap=plt.cm.Blues)
_____no_output_____
MIT
Project Handwriting Number Recognizer/Handwriting_Number_Recognizer.ipynb
Nova1323/CodersWeek-ML
Projekt 1 Mateusz Grzyb, Bartłomiej Eljasiak Wczytanie bibliotek
import random import numpy as np import pandas as pd from scipy.stats import uniform from scipy.stats import expon from scipy.stats import randint import matplotlib.pyplot as plt import seaborn as sns import missingno as msno from sklearn.model_selection import train_test_split from xgboost import XGBClassifier fro...
_____no_output_____
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Przygotowanie danych Bazując na wynikach, z poprzednich etapów projektu, surowe dane obrobię w następujący sposób:* Wczytam surowe dane,* wykonam rzutowanie str na bool,* tym razem zostawię kolumny '*_measured', będą informowały o miejsach imputacji,* poprawię jedną, nierealną obserwację zmiennej 'age',* usunę kolumny...
raw_data=pd.read_csv('sick.csv') # kopia surowych danych data=raw_data.copy() # sex (F == 1, M == 0) data.loc[~data['sex'].isnull(), 'sex']=(data.loc[:, 'sex']=='F').astype(int) # Class (Sick == 1, negative == 0) data.loc[~data['Class'].isnull(), 'Class']=(data.loc[:, 'Class']=='sick').astype(int) # pozostałe zmienn...
_____no_output_____
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Przygotowanie modelu i metryki Modelem, którym posłużę się w tej części projektu, jest XGBoost z imputacją mediany. Wybrałem go, ponieważ osiągnął on najlepsze wyniki w poprzedniej części projektu i jest szybki.
xgb=XGBClassifier(n_jobs=-1) mi=SimpleImputer(strategy='median') # pipeline zapewnia brak przecieku danych przy imputacji classifier=make_pipeline(mi, xgb)
_____no_output_____
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Funkcja RandomizedSearchCV pozwala na przekazanie metryki, za pomocą której będzie ona oceniać jakość wartości hiperparametrów. Chciałbym z tej możliwości skorzystać i napisać własną metrykę, bazując na tym artykule naukowym: https://www.sciencedirect.com/science/article/abs/pii/S0957417420302153?via%3Dihub (artykuł zo...
def my_score_func(y_true, y_pred): P=sum(y_true) N=len(y_true)-P TN, FP, FN, TP=confusion_matrix(y_true, y_pred).ravel() w1=N/(P+N) w2=P/(P+N) TPR=TP/(TP+FN) TNR=TN/(TN+FP) score=TPR*w1+TNR*w2 return score # powinno wyjsc 1 (idealna predykcja) my_score...
_____no_output_____
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Strojenie hiperparametrów Posłużę się funkcją RandomizedSearchCV.
# https://xgboost.readthedocs.io/en/latest/parameter.html # https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/ # domyslnie 'gbtree' # "...I’ll consider only tree booster here because it always outperforms the linear booster and thus the later is rarely used." booste...
Fitting 5 folds for each of 1000 candidates, totalling 5000 fits
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Udało się zauważalnie poprawić model, czego dowodem są następujące wyniki.
# sprawdzmy wynik najlepszego modelu print('Weighted TPR-TNR for best tuned model: '+str(round(random_result.best_score_, 3))) # dla porownania wyniki przy domyslnych parametrach classifier.fit(X_train, y_train) print('Weighted TPR-TNR for default model: '+str(round(my_scorer(classifier, X_test, y_test), 3)))
Weighted TPR-TNR for default model: 0.856
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Sprawdźmy jakie parametry modelu dobrał algorytm.
# parametry najlepszego klasyfikatora random_result.best_estimator_.named_steps.xgbclassifier.get_xgb_params()
_____no_output_____
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Wspomniany wcześniej artykuł chwali także miarę "Matthews correlation coefficient (MCC)" przy ocenie klasyfikatorów na zbiorach niezbalansowanych. Jest ona już zaimplementowana w scikit-learn.
bm=random_result.best_estimator_ print('Weighted MCC for best tuned model: '+str(round(matthews_corrcoef(bm.predict(X_test), y_test), 3))) classifier.fit(X_train, y_train) print('Weighted MCC for default model: '+str(round(matthews_corrcoef(classifier.predict(X_test), y_test), 3)))
Weighted MCC for default model: 0.819
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Zawsze warto również spojrzeć na Confusion Matrix.
disp=plot_confusion_matrix(bm, X_test, y_test, cmap=plt.cm.Blues, normalize='true') disp.ax_.set_title('Confusion Matrix\n(normalized along horizontal axis)');
_____no_output_____
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Wyniki są bardzo dobre. Model tylko w 1.7% przypadków fałszywie poinformował o chorobie i jednocześnie wykrył chorobę w 93% przypadków.Model oczywiście nigdy wcześniej nie "widział" tych obserwacji, ponieważ funkcja RandomizedSearchCV została wywołana na zbiorze treningowym, nie ma więc mowy o przecieku danych. Featur...
from xgboost import plot_importance bm.named_steps.xgbclassifier.get_booster().feature_names=list(X.columns) fig, ax=plt.subplots(figsize=(9,6)) plot_importance(bm.named_steps.xgbclassifier, ylabel=None, importance_type='weight', title='Feature importance (weight)', show_values=False, ax=ax);
_____no_output_____
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Gain"A higher **gain** value when compared to another feature implies it is more important for generating a prediction."
fig, ax=plt.subplots(figsize=(9,6)) plot_importance(bm.named_steps.xgbclassifier, ylabel=None, importance_type='gain', title='Feature importance (gain)', show_values=False, ax=ax);
_____no_output_____
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Coverage"The **Coverage** metric means the relative number of observations related to this feature."
fig, ax=plt.subplots(figsize=(9,6)) plot_importance(bm.named_steps.xgbclassifier, ylabel=None, importance_type='cover', title='Feature importance (cover)', show_values=False, ax=ax);
_____no_output_____
Apache-2.0
Projekty/Projekt1/Grupa1/Grzyb_Eljasiak/HT.ipynb
niladrem/2020L-WUM
Data Loading and Preprocessing
# Loads the training and test data sets (X_train, y_train), (X_test, y_test) = mnist.load_data() first_image = X_train[0, :, :] # To interpret the values as a 28x28 image, we need to reshape # the numpy array, which is one dimensional. plt.imshow(first_image, cmap=plt.cm.Greys); num_classes = len(np.unique(y_train)) nu...
_____no_output_____
MIT
notebooks/05_convolutional_neural_net.ipynb
ramhiser/Keras-Tutorials
Convolutional Neural Net (ConvNet)
model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), strides=(1, 1), activation='relu', input_shape=input_shape)) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(Dropout(0.25)) model.add(MaxPooling2D(pool_size=(2, 2))) model...
_____no_output_____
MIT
notebooks/05_convolutional_neural_net.ipynb
ramhiser/Keras-Tutorials
Different Ways to Summarize Model
model.summary() SVG(model_to_dot(model, show_shapes=True).create(prog='dot', format='svg')) import json json.loads(model.to_json())
_____no_output_____
MIT
notebooks/05_convolutional_neural_net.ipynb
ramhiser/Keras-Tutorials
Train Classifier
# Trains the model, iterating on the training data in batches of 128 in 5 epochs. # Using the Adam optimizer. model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(X_train, y_train, batch_size=128, epochs=5, verbose=1)
Epoch 1/5 60000/60000 [==============================] - 94s - loss: 0.3360 - acc: 0.8965 - E Epoch 2/5 60000/60000 [==============================] - 97s - loss: 0.1246 - acc: 0.9627 Epoch 3/5 60000/60000 [==============================] - 97s - loss: 0.0950 - acc: 0.9714 Epoch 4/5 60000/60000 [============...
MIT
notebooks/05_convolutional_neural_net.ipynb
ramhiser/Keras-Tutorials
Model Evaluation
# Test accuracy is ~99%. model.evaluate(X_test, y_test)
9952/10000 [============================>.] - ETA: 0s
MIT
notebooks/05_convolutional_neural_net.ipynb
ramhiser/Keras-Tutorials
Predicting a Couple of Held-Out Images
first_test_image = X_test[0, :] plt.imshow(first_test_image.reshape(28, 28), cmap=plt.cm.Greys); second_test_image = X_test[1, :] plt.imshow(second_test_image.reshape(28, 28), cmap=plt.cm.Greys); model.predict_classes(X_test[[0, 1], :])
2/2 [==============================] - 0s
MIT
notebooks/05_convolutional_neural_net.ipynb
ramhiser/Keras-Tutorials
BL books metadata This notebook contains the code that was used to create a sample of books from the British Library 10th century books collection.
# imports import pandas as pd import json, os, shutil, codecs # read metadata file filename = "extra_metadata.csv" df = pd.read_csv(filename, delimiter=";") df.head(3) df["Language code (008)"].value_counts() df["Genre"].value_counts() df_eng = df[df["Language code (008)"] == "eng"] df_eng["Genre"].value_counts() how...
_____no_output_____
MIT
data/bl_books/BL_sample.ipynb
BL-Labs/ADA-DHOxSS
Assignment 2Before working on this assignment please read these instructions fully. In the submission area, you will notice that you can click the link to **Preview the Grading** for each step of the assignment. This is the criteria that will be used for peer grading. Please familiarize yourself with the criteria befo...
!find ~ | grep -i C2A2_data !head ../../_data/ghcnd-stations.txt import matplotlib.pyplot as plt import mplleaflet import pandas as pd def leaflet_plot_stations(binsize, hashid): df = pd.read_csv('data/C2A2_data/BinSize_d{}.csv'.format(binsize)) station_locations_by_hash = df[df['hash'] == hashid] lons ...
_____no_output_____
MIT
_numpy_pandas/pandas_more3_.ipynb
aixpact/data-science
Loading experiments
ema_logging.log_to_stderr(ema_logging.INFO) from Model_init import vensimModel from ema_workbench import (TimeSeriesOutcome, perform_experiments, RealParameter, CategoricalParameter, ...
[MainProcess/INFO] using 64 bit vensim [MainProcess/INFO] results loaded succesfully from D:\moallemie\EM_analysis\Data\SDG_experiments_ranking_verification_Total Primary Education Graduates Indicator_sc500.tar.gz
BSD-3-Clause
Notebook/.ipynb_checkpoints/Morris_ranking_verification_plot_Total Primary Education Graduates Indicator-checkpoint.ipynb
enayatmoallemi/Moallemi_et_al_SDG_SSP_Assessment
Calculating SA (Morris) metrics
#Sobol indice calculation as a function of number of scenarios and time def make_morris_df(scores, problem, outcome_var, sc, t): scores_filtered = {k:scores[k] for k in ['mu_star','mu_star_conf','mu','sigma']} Si_df = pd.DataFrame(scores_filtered, index=problem['names']) Si_df.sort_values(by=['mu_...
_____no_output_____
BSD-3-Clause
Notebook/.ipynb_checkpoints/Morris_ranking_verification_plot_Total Primary Education Graduates Indicator-checkpoint.ipynb
enayatmoallemi/Moallemi_et_al_SDG_SSP_Assessment
Plotting SA results
# define the ploting function def plot_scores(inds, errs, outcome_var, sc): sns.set_style('white') fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(3, 6)) ind = inds.iloc[:,0] err = errs.iloc[:,0] ind.plot.barh(xerr=err.values.T,ax=ax, color = ['#FCF6F5']*(20-top_factor)+['#C6B5ED']*top_facto...
_____no_output_____
BSD-3-Clause
Notebook/.ipynb_checkpoints/Morris_ranking_verification_plot_Total Primary Education Graduates Indicator-checkpoint.ipynb
enayatmoallemi/Moallemi_et_al_SDG_SSP_Assessment
EDC Sentinel Hub: Data Fusion Example 2: Mapping crop NDVI with Sentinel-1 and Sentinel-2[NDVI](https://www.sentinel-hub.com/eoproducts/ndvi-normalized-difference-vegetation-index) is a widely used vegetation index that uses Near Infra-Red (NIR) and Red wavelengths to measure the photosynthetic capacity of plant canop...
# Request tools imports from oauthlib.oauth2 import BackendApplicationClient from requests_oauthlib import OAuth2Session # Utilities import shapely.geometry import IPython.display %matplotlib inline
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
Setup
# Pass the Sentinel Hub Client ID and Secret to variables to be used in the request. my_client_id = %env SH_CLIENT_ID my_client_secret = %env SH_CLIENT_SECRET # Create an OAuth2 session based on the client ID client = BackendApplicationClient(client_id=my_client_id) oauth = OAuth2Session(client=client)
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
The Sentinel Hub API uses OAuth2 Authentication and requires that you have an [access token](https://docs.sentinel-hub.com/api/latest//API/authentication). These tokens are limited in time, but a new one can be requested with the following command.
# Get a token for the session token = oauth.fetch_token(token_url='https://services.sentinel-hub.com/oauth/token', client_id=my_client_id, client_secret=my_client_secret)
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
Setting an area of interestWe will download Sentinel-1 and Sentinel-2 imagery over cropland located to the west of Dodge City, Kansas. The region is characterised by intensive agriculture, mainly wheat and sorghum cultivated in circular crop fields.The bounding box is in the WGS84 coordinate system, and consists of th...
# Set bounding box coordinates for the area of interest bbox = (-100.9204, 37.5718, -100.4865, 37.8640) # Display the coordinates on a map IPython.display.GeoJSON(shapely.geometry.box(*bbox).__geo_interface__)
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
API requestWe need to specify arguments to send a POST request, more information about all the availaible options [here](https://docs.sentinel-hub.com/api/latest/reference/operation/process):- The access point URL: set it to `https://services.sentinel-hub.com/api/v1/process`- `json` - the contents of the request ...
# 1. Bounds bounds = {"properties":{"crs":"http://www.opengis.net/def/crs/OGC/1.3/CRS84"}, "bbox": bbox} # 2. Data # Following Filgueiras et al. (2019), the Sentinel-1 orthorectified sigma_0 bands are returned. # We also use Atmospherically corrected Sentinel-2 (L2A) data data = [{"id": "s1", "type": "S1GR...
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
Step 2Then set the output options. The default output size of the requested image is 256x256 pixels, so here we will modify the output to be larger. The result will be displayed only, therefore we also set the output format to jpeg.
output_options = {"width": 640, "height": 640, "responses": [{"format": {"type": "image/jpeg", "quality": 90}}]}
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
Step 3The [evalscript](https://docs.sentinel-hub.com/api/latest//Evalscript/) is a piece of javascript code that allows to process the pixels of the images that are returned.In the current example, the S1 and S2 bands needed are called in the `setup` function of the script. To compare the results of the fused NDVI pro...
# 1. Evalscript returning the True Color Visualisation of S2 data tc_evalscript = """ //VERSION=3 function setup (){ return { input: [ {datasource: "s1", bands:["VV", "VH"]}, {datasource: "l2a", bands:["B02", "B03", "B08", "B04", "SCL"], units:["REFLECTANCE", "REFLECTANCE", "REFLECTANCE", "REFLECTANCE...
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
Step 4 (final)The different parts of the request built above are merged together in the `oauth.post` command and the request is posted. If all the elements are correct, the command should return a `200` status.
# Here we call the first evalscript for a True Color visualisation of Sentinel-2. response_tc = oauth.post('https://services.sentinel-hub.com/api/v1/process', json={"input": input_options, "evalscript": tc_evalscript, "output": output_options, }) print("Request status: %s, %s" % (response_tc.status_...
Request status: 200, OK
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
ResultsBelow, the True Color visualisation of the Sentinel-2 image shows the circular crop fields forming the agricultural landscape near Dodge City. The brown colored fields are most likely bare soil (i.e. the crops haven't yet emerged) given the date of the acquisition (26-04-2019). A certain number of fields appear...
IPython.display.Image(response_tc.content)
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
Below, the Sentinel-2 NDVI product clearly highlights the fields in which crop are present (green) with varying NDVI values (represented in different shades of green, the darker the green, the higher the NDVI value). The agricultural plots where no crops are growing are shown in red in the image (NDVI < 0). However, th...
IPython.display.Image(response_s2_ndvi.content)
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
In the image below, the Sentinel-2 NDVI values located in cloud-covered areas were replaced with NDVI calculated from the Sentinel-1 data. The fusion of the two data sources now allows showing the NDVI for the areas that were not resolved simply using Sentinel-2 data. A number of large fields, where crops are growing a...
IPython.display.Image(response_s12_ndvi.content)
_____no_output_____
MIT
notebooks/curated/EDC_SentinelHub_DataFusion_NDVI.ipynb
eurodatacube/notebooks
Ex1 - Filtering and Sorting Data This time we are going to pull data directly from the internet.Special thanks to: https://github.com/justmarkham for sharing the dataset and materials. Step 1. Import the necessary libraries
import pandas as pd
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solution_my.ipynb
karina-rev/pandas_exercises
Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv). Step 3. Assign it to a variable called chipo.
URL = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/chipotle.tsv' chipo = pd.read_csv(URL, sep = '\t') chipo.head()
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solution_my.ipynb
karina-rev/pandas_exercises
Step 4. How many products cost more than $10.00?
chipo['item_price'] = chipo['item_price'].apply(lambda x: float(x[1:-1])) chip = chipo.drop_duplicates(['item_name', 'quantity']) chip[(chip['quantity'] == 1) & (chip['item_price'] > 10.00)]['item_name'].nunique()
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solution_my.ipynb
karina-rev/pandas_exercises
Step 5. What is the price of each item? print a data frame with only two columns item_name and item_price
chipo.drop_duplicates(['item_name', 'quantity'])[chipo['quantity'] == 1][['item_name', 'item_price']].\ sort_values(by='item_price', ascending=False)
/Users/karina/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:1: UserWarning: Boolean Series key will be reindexed to match DataFrame index. """Entry point for launching an IPython kernel.
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solution_my.ipynb
karina-rev/pandas_exercises
Step 6. Sort by the name of the item
chipo.sort_values(by='item_name')
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solution_my.ipynb
karina-rev/pandas_exercises
Step 7. What was the quantity of the most expensive item ordered?
chipo[chipo['item_price'] == chipo['item_price'].max()]['quantity'] chipo.sort_values(by = 'item_price', ascending = False).head(1)
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solution_my.ipynb
karina-rev/pandas_exercises
Step 8. How many times were a Veggie Salad Bowl ordered?
len(chipo[chipo['item_name'] == 'Veggie Salad Bowl'].drop_duplicates('order_id'))
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solution_my.ipynb
karina-rev/pandas_exercises
Step 9. How many times people orderd more than one Canned Soda?
len(chipo[(chipo['item_name'] == 'Canned Soda') & (chipo['quantity'] > 1)])
_____no_output_____
BSD-3-Clause
02_Filtering_&_Sorting/Chipotle/Exercises_with_solution_my.ipynb
karina-rev/pandas_exercises
Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
# Dependencies and Setup import pandas as pd import csv # File to Load(Remember to Change These) file_to_load = "Resources/purchase_data.csv" # Read Purchasing File and store into Pandas data frame purchase_data = pd.read_csv(file_to_load) purchase_data.head()
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Player Count * Display the total number of players
#Calculate the Number of Unique Players player_demographics = purchase_data.loc[:,["Gender","SN","Age"]] player_demographics = player_demographics.drop_duplicates() num_players = player_demographics.count()[0] pd.DataFrame({"Total Players":[num_players]})
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Purchasing Analysis (Total) * Run basic calculations to obtain number of unique items, average price, etc.* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame
#run calc to obtain number of unqiue items average price etc. average_item_price = purchase_data["Price"].mean() total_purchase_value = purchase_data["Price"].sum() purchase_count = purchase_data["Price"].count() item_count = len(purchase_data["Item ID"].unique()) summary_table = pd.DataFrame({"Number of Unique Items"...
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Gender Demographics * Percentage and Count of Male Players* Percentage and Count of Female Players* Percentage and Count of Other / Non-Disclosed
gender_demographics_total = player_demographics["Gender"].value_counts() gender_demographics_percent = gender_demographics_total / num_players gender_demographics = pd.DataFrame({"Total Count": gender_demographics_total, "Percentage of Players": gender_demographics_percent}) gender_de...
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Purchasing Analysis (Gender) * Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary data frame
gender_purchase_total = purchase_data.groupby(["Gender"]).sum()["Price"].rename("Total Purchase Value") gender_purchase_total gender_average = purchase_data.groupby(["Gender"]).mean()["Price"].rename("Average Purchase Price") gender_average gender_counts = purchase_data.groupby(["Gender"]).count()["Price"].rename("Purc...
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Age Demographics * Establish bins for ages* Categorize the existing players using the age bins. Hint: use pd.cut()* Calculate the numbers and percentages by age group* Create a summary data frame to hold the results* Optional: round the percentage column to two decimal points* Display Age Demographics Table
age_bins = [0, 9.90, 14.90, 19.90, 24.90, 29.90, 34.90, 39.90,99999] group_names = ["<10","10-14", "15-19","20-24","25-29","30-34","35-39","40+"] player_demographics["Age Ranges"] = pd.cut(player_demographics["Age"], age_bins, labels = group_names) age_demographics_totals = player_demographics["Age Ranges"].value_coun...
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Purchasing Analysis (Age) * Bin the purchase_data data frame by age* Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below* Create a summary data frame to hold the results* Optional: give the displayed data cleaner formatting* Display the summary d...
purchase_data["Age Ranges"] = pd.cut(purchase_data["Age"], age_bins, labels= group_names) age_purchase_total = purchase_data.groupby (["Age Ranges"]).sum()["Price"].rename("Total Purchase Value") age_average = purchase_data.groupby (["Age Ranges"]).mean()["Price"].rename("Average Purchase Price") age_count = purchase_...
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Top Spenders * Run basic calculations to obtain the results in the table below* Create a summary data frame to hold the results* Sort the total purchase value column in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the summary data frame
user_total = purchase_data.groupby(["SN"]).sum()["Price"].rename("Total Purchase Value") user_average = purchase_data.groupby(["SN"]).mean()["Price"].rename("Avg Purchase Price") user_count = purchase_data.groupby(["SN"]).count()["Price"].rename("Purchase Count") user_data = pd.DataFrame({"Total Purchase Value": user_t...
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Most Popular Items * Retrieve the Item ID, Item Name, and Item Price columns* Group by Item ID and Item Name. Perform calculations to obtain purchase count, average item price, and total purchase value* Create a summary data frame to hold the results* Sort the purchase count column in descending order* Optional: give ...
item_data = purchase_data[["Item ID","Item Name","Price"]] total_item_purchase = item_data.groupby(["Item ID","Item Name"]).sum()["Price"].rename("Total Purchase Price") average_item_purchase = item_data.groupby(["Item ID","Item Name"]).mean()["Price"].rename("Price") item_count = item_data.groupby(["Item ID","Item Na...
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Most Profitable Items * Sort the above table by total purchase value in descending order* Optional: give the displayed data cleaner formatting* Display a preview of the data frame
item_total_purchase = item_data_pd.sort_values("Total Purchase Value", ascending = False) item_total_purchase["Item Price"] = item_total_purchase["Item Price"].map("${:,.2f}".format) item_total_purchase["Purchase Count"] = item_total_purchase["Purchase Count"].map("{:,}".format) item_total_purchase["Total Purchase Valu...
_____no_output_____
MIT
HeroesofPymoli/HeroesOfPymoli_starter.ipynb
estherkim0998/Pandas-Challenge
Equations of motion The EOM for $m_1$ is:$m_1 \ddot{x}_1+c_s \dot{x}_1+k_s x_1 = c_s \dot{x}_2 + k_s x_2$The EOM for $m_2$ is:$m_2 \ddot{x}_2+c_s \dot{x}_2+(k_s +k_t) x_2 = c_s \dot{x}_1 + k_s x_1 + k_t y$ Block diagram Transfer Function Sympy Implementation
m1, m2, kt, ks, cs, s = symbols('m_1 m_2 k_t k_s c_s s') # have python perform the block diagram operations symbolically num1 = cs*s + ks den1 = m1*s**2 + cs*s + ks G1 = TransferFunction(num1, den1, s) num2 = cs*s + ks den2 = m2*s**2 + cs*s + (ks+kt) G2 = TransferFunction(num2,den2, s) num3 = kt den3 = m2*s**2 + cs*...
_____no_output_____
BSD-3-Clause
Jupyter Notebooks/Car_suspension.ipynb
gge0866/MCHE474---Control-Systems
Expanding this TF gives us
TF.expand() # sub in values for the variables TF = TF.subs([(kt,190000),(cs,5000),(ks,20000),(m1,290),(m2,59)]) # Plot the poles and zeros of the TF pole_zero_plot(TF) step_response_plot(TF,grid=False,color='r')
_____no_output_____
BSD-3-Clause
Jupyter Notebooks/Car_suspension.ipynb
gge0866/MCHE474---Control-Systems
Controls Package Implementation
# cs = 5000 # ks = 20000 cs = 10 ks = 5 kt = 190000 m1 = 290 m2 = 59 num1 = [cs, ks] den1 = [m1, cs, ks] G1 = control.tf(num1,den1) num2 = [cs, ks] den2 = [m2, cs, (ks+kt)] G2 = control.tf(num2,den2) num3 = [kt] den3 = [m2, cs, (ks+kt)] G3 = control.tf(num3,den3) G4 = control.feedback(G1,G2,sign=1) G = control.ser...
_____no_output_____
BSD-3-Clause
Jupyter Notebooks/Car_suspension.ipynb
gge0866/MCHE474---Control-Systems
Data Engineering Capstone Project US I94 Immigration Data Lake Project SummaryThis project performs ETL operations on Udacity provided I94 immigration and demographics datasets using Pyspark. It generates a Star Schema in parquet file at the end following Data Lake's schema-on-read semantics.This notebooks performs Ex...
# Check readme for installation and env setup import configparser import logging import pandas as pd from pyspark.sql import SparkSession from pyspark.sql import functions as F from etl import ( get_spark_session, get_immigration_data, get_us_demographics_data, get_i94_countries, get_i94_ports, ...
_____no_output_____
MIT
us_immigration_analysis.ipynb
aitzaz/udacity-DEND-capstone-immigration
Step 1: Scope the Project and Gather Data Scope *Explain what you plan to do in the project in more detail. What data do you use? What is your end solution look like? What tools did you use? etc.*I plan to create a data lake using Pyspark about immigrants destinations in US. To achieve this, I've used I94 immigrations...
# Because the immigration data has 28 columns pd.set_option('display.max_columns', 28) # Read config config = configparser.ConfigParser() config.read_file(open('capstone.cfg')) I94_DATA_FILE_PATH = config['DATA']['I94_DATA_FILE_PATH'] print(I94_DATA_FILE_PATH) # df = pd.read_sas(I94_DATA_FILE_PATH, format='sas7bdat'...
_____no_output_____
MIT
us_immigration_analysis.ipynb
aitzaz/udacity-DEND-capstone-immigration
1.2 Configure Spark session
# spark = SparkSession.builder \ # .appName("Capstone Project - Immigration Dataset") \ # .config("spark.jars.packages","saurfang:spark-sas7bdat:2.0.0-s_2.11") \ # .enableHiveSupport() \ # .getOrCreate() spark = get_spark_session() print("Spark session created")
Spark session created
MIT
us_immigration_analysis.ipynb
aitzaz/udacity-DEND-capstone-immigration
1.3 Show sample immigration dataRead April 2016 file in spark dataframe (same as Pandas df)
# Reading apr sas file in Spark df # immigration_df = spark.read.format('com.github.saurfang.sas.spark').load(I94_DATA_FILE_PATH) immigration_df = get_immigration_data(spark) immigration_df.printSchema() print("Paritions: ", immigration_df.rdd.getNumPartitions()) df_pd = pd.DataFrame(immigration_df.head(10)) df_pd
Paritions: 4
MIT
us_immigration_analysis.ipynb
aitzaz/udacity-DEND-capstone-immigration
Step 2: Explore and Assess the Data 2.1 Explore the Data*Identify data quality issues, like missing values, duplicate data, etc.*
# Read data sets us_demographics_df = get_us_demographics_data(spark) countries_df = get_i94_countries(spark) ports_df = get_i94_ports(spark) states_df = get_i94_states(spark) travel_modes_df = get_i94_travel_modes(spark) visa_categories_df = get_i94_visas(spark) us_demographics_df.select("city").distinct().count()
_____no_output_____
MIT
us_immigration_analysis.ipynb
aitzaz/udacity-DEND-capstone-immigration
2.2 Cleaning StepsDocument steps necessary to clean the dataExplained in readme/etl.py
# Performing cleaning tasks here cleaned_immigration_df = clean_immigration_data(immigration_df) cleaned_us_demographics_df = clean_us_demographics_data(us_demographics_df) cleaned_ports_df = clean_ports_data(ports_df) cleaned_countries_df = clean_countries_data(countries_df) cleaned_states_df = clean_states_data(state...
_____no_output_____
MIT
us_immigration_analysis.ipynb
aitzaz/udacity-DEND-capstone-immigration
Step 3: Define the Data Model 3.1 Conceptual Data Model*Map out the conceptual data model and explain why you chose that model*Added in readme. 3.2 Mapping Out Data Pipelines*List the steps necessary to pipeline the data into the chosen data model*Added in readme. Step 4: Run Pipelines to Model the Data 4.1 Create t...
# Creating immigrations fact immigration_fact_table = create_immigration_fact_table(spark, cleaned_immigration_df, cleaned_countries_df, cleaned_states_df, cleaned_ports_df, visa_categories_df, travel_m...
_____no_output_____
MIT
us_immigration_analysis.ipynb
aitzaz/udacity-DEND-capstone-immigration
4.2 Data Quality ChecksExplain the data quality checks you'll perform to ensure the pipeline ran as expected. These could include: * Integrity constraints on the relational database (e.g., unique key, data type, etc.) * Unit tests for the scripts to ensure they are doing the right thing * Source/Count checks to ensure...
spark.conf.set("spark.sql.shuffle.partitions", 50) # To reduce data shuffling locally # Create tables immigration_fact_table.createOrReplaceTempView("fact_immigrations") city_demographics_table.createOrReplaceTempView("dim_city_demographics") ports_df.createOrReplaceTempView("dim_ports") countries_df.createOrReplaceTem...
root |-- port_code: string (nullable = true) |-- city: string (nullable = true) |-- state_code: string (nullable = true) |-- male_population: long (nullable = true) |-- female_population: long (nullable = true) |-- total_population: long (nullable = true) |-- number_of_veterans: long (nullable = true) |-- num_f...
MIT
us_immigration_analysis.ipynb
aitzaz/udacity-DEND-capstone-immigration
4.3 Data dictionary Create a data dictionary for your data model. For each field, provide a brief description of what the data is and where it came from. You can include the data dictionary in the notebook or in a separate file. Step 5: Complete Project Write Up* Clearly state the rationale for the choice of tools an...
# Which city was most visited in a specific month? # This data is from April file, let's try for it # numeric code for April is 4 spark.sql(""" SELECT tvc.port_code, tvc.immigrant_visits, dcd.city, dcd.state_code, dcd.total_population FROM (SELECT fi...
+-------------------+----------------+------------+--------------------+ |origin_country_code|student_visitors|country_code| country_name| +-------------------+----------------+------------+--------------------+ | 245| 9760| 245| CHINA, PRC| | 213| ...
MIT
us_immigration_analysis.ipynb
aitzaz/udacity-DEND-capstone-immigration
**The goal of our model building is we want to see which functional group or fingerprints are essential for designing a good drug or a potent one.**
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from google.colab import drive drive.mount('/content/gdrive/', force_remount = True) df = pd.read_csv("/content/gdrive/MyDrive/Colab Note...
_____no_output_____
MIT
Acetylcholinesterase_RandomForest.ipynb
kaustubhadixit/BioInformatics
**Features**
# Input Feature X = df.drop('pIC50', axis=1) X # Output Feature Y = df["pIC50"] Y
_____no_output_____
MIT
Acetylcholinesterase_RandomForest.ipynb
kaustubhadixit/BioInformatics
**Removing Features with low variance**
from sklearn.feature_selection import VarianceThreshold selection = VarianceThreshold(threshold=(.85 * (1 - .85))) x = selection.fit_transform(X) x.shape
_____no_output_____
MIT
Acetylcholinesterase_RandomForest.ipynb
kaustubhadixit/BioInformatics
**Test Train Split 70/30**
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.3) X_train.shape, Y_train.shape, X_test.shape, Y_test.shape x_train, x_test, y_train, y_test = train_test_split(x, Y, test_size=0.3) x_train.shape, y_train.shape, x_test.shape, y_test.shape
_____no_output_____
MIT
Acetylcholinesterase_RandomForest.ipynb
kaustubhadixit/BioInformatics
**Random Forest Regression model**
# Low variance features not removed model = RandomForestRegressor(n_estimators=100) model.fit(X_train, Y_train) S = model.score(X_test, Y_test) S # Low varinace features removed model2 = RandomForestRegressor(n_estimators=150) model2.fit(x_train, y_train) s = model2.score(x_test, y_test) s Y_pred = model.predic...
_____no_output_____
MIT
Acetylcholinesterase_RandomForest.ipynb
kaustubhadixit/BioInformatics
**Scatter Plot of Experimental vs Predicted pIC50 Values** **Without reomoving low variance features**
sns.set(color_codes=True) sns.set_style("white") ax = sns.regplot(Y_test, Y_pred, scatter_kws={'alpha':0.4}) ax.set_xlabel('Experimental pIC50', fontsize='large', fontweight='bold') ax.set_ylabel('Predicted pIC50', fontsize='large', fontweight='bold') ax.set_xlim(0, 12) ax.set_ylim(0, 12) ax.figure.set_size_in...
/usr/local/lib/python3.6/dist-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation. FutureWarning...
MIT
Acetylcholinesterase_RandomForest.ipynb
kaustubhadixit/BioInformatics
**After reomoving low variance features**
sns.set(color_codes=True) sns.set_style("white") ax = sns.regplot(y_test, y_pred, scatter_kws={'alpha':0.4}) ax.set_xlabel('Experimental pIC50', fontsize='large', fontweight='bold') ax.set_ylabel('Predicted pIC50', fontsize='large', fontweight='bold') ax.set_xlim(0, 12) ax.set_ylim(0, 12) ax.figure.set_size_in...
/usr/local/lib/python3.6/dist-packages/seaborn/_decorators.py:43: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation. FutureWarning...
MIT
Acetylcholinesterase_RandomForest.ipynb
kaustubhadixit/BioInformatics
The framework and why do we need itIn the previous notebooks, we introduce some concepts regarding theevaluation of predictive models. While this section could be slightlyredundant, we intend to go into details into the cross-validation framework.Before we dive in, let's linger on the reasons for always having trainin...
from sklearn.datasets import fetch_california_housing housing = fetch_california_housing(as_frame=True) data, target = housing.data, housing.target
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
In this dataset, the aim is to predict the median value of houses in an areain California. The features collected are based on general real-estate andgeographical information.Therefore, the task to solve is different from the one shown in the previousnotebook. The target to be predicted is a continuous variable and not...
print(housing.DESCR) data.head()
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
To simplify future visualization, let's transform the prices from thedollar (\\$) range to the thousand dollars (k\\$) range.
target *= 100 target.head()
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
NoteIf you want a deeper overview regarding this dataset, you can refer to theAppendix - Datasets description section at the end of this MOOC. Training error vs testing errorTo solve this regression task, we will use a decision tree regressor.
from sklearn.tree import DecisionTreeRegressor regressor = DecisionTreeRegressor(random_state=0) regressor.fit(data, target)
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
After training the regressor, we would like to know its potential statisticalperformance once deployed in production. For this purpose, we use the meanabsolute error, which gives us an error in the native unit, i.e. k\\$.
from sklearn.metrics import mean_absolute_error target_predicted = regressor.predict(data) score = mean_absolute_error(target, target_predicted) print(f"On average, our regressor makes an error of {score:.2f} k$")
On average, our regressor makes an error of 0.00 k$
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
We get perfect prediction with no error. It is too optimistic and almostalways revealing a methodological problem when doing machine learning.Indeed, we trained and predicted on the same dataset. Since our decision treewas fully grown, every sample in the dataset is stored in a leaf node.Therefore, our decision tree fu...
from sklearn.model_selection import train_test_split data_train, data_test, target_train, target_test = train_test_split( data, target, random_state=0)
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
Then, let's train our model.
regressor.fit(data_train, target_train)
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
Finally, we estimate the different types of errors. Let's start by computingthe training error.
target_predicted = regressor.predict(data_train) score = mean_absolute_error(target_train, target_predicted) print(f"The training error of our model is {score:.2f} k$")
The training error of our model is 0.00 k$
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
We observe the same phenomena as in the previous experiment: our modelmemorized the training set. However, we now compute the testing error.
target_predicted = regressor.predict(data_test) score = mean_absolute_error(target_test, target_predicted) print(f"The testing error of our model is {score:.2f} k$")
The testing error of our model is 47.28 k$
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
This testing error is actually about what we would expect from our model ifit was used in a production environment. Stability of the cross-validation estimatesWhen doing a single train-test split we don't give any indication regardingthe robustness of the evaluation of our predictive model: in particular, ifthe test s...
from sklearn.model_selection import cross_validate from sklearn.model_selection import ShuffleSplit cv = ShuffleSplit(n_splits=40, test_size=0.3, random_state=0) cv_results = cross_validate( regressor, data, target, cv=cv, scoring="neg_mean_absolute_error")
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
The results `cv_results` are stored into a Python dictionary. We will convertit into a pandas dataframe to ease visualization and manipulation.
import pandas as pd cv_results = pd.DataFrame(cv_results) cv_results.head()
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
TipA score is a metric for which higher values mean better results. On thecontrary, an error is a metric for which lower values mean better results.The parameter scoring in cross_validate always expect a function that isa score.To make it easy, all error metrics in scikit-learn, likemean_absolute_error, can be transfor...
cv_results["test_error"] = -cv_results["test_score"]
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
Let's check the results reported by the cross-validation.
cv_results.head(10)
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
We get timing information to fit and predict at each cross-validationiteration. Also, we get the test score, which corresponds to the testingerror on each of the splits.
len(cv_results)
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
We get 40 entries in our resulting dataframe because we performed 40splits. Therefore, we can show the testing error distribution and thus, havean estimate of its variability.
import matplotlib.pyplot as plt cv_results["test_error"].plot.hist(bins=10, edgecolor="black", density=True) plt.xlabel("Mean absolute error (k$)") _ = plt.title("Test error distribution")
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
We observe that the testing error is clustered around 47 k\\$ andranges from 43 k\\$ to 50 k\\$.
print(f"The mean cross-validated testing error is: " f"{cv_results['test_error'].mean():.2f} k$") print(f"The standard deviation of the testing error is: " f"{cv_results['test_error'].std():.2f} k$")
The standard deviation of the testing error is: 1.17 k$
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
Note that the standard deviation is much smaller than the mean: we couldsummarize that our cross-validation estimate of the testing error is46.36 +/- 1.17 k\\$.If we were to train a single model on the full dataset (withoutcross-validation) and then later had access to an unlimited amount of testdata, we would expect i...
target.plot.hist(bins=20, edgecolor="black", density=True) plt.xlabel("Median House Value (k$)") _ = plt.title("Target distribution") print(f"The standard deviation of the target is: {target.std():.2f} k$")
The standard deviation of the target is: 115.40 k$
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
The target variable ranges from close to 0 k\\$ up to 500 k\\$ and, with astandard deviation around 115 k\\$.We notice that the mean estimate of the testing error obtained bycross-validation is a bit smaller than the natural scale of variation of thetarget variable. Furthermore, the standard deviation of the cross vali...
cv_results = cross_validate(regressor, data, target, return_estimator=True) cv_results cv_results["estimator"]
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc
The five decision tree regressors corresponds to the five fitted decisiontrees on the different folds. Having access to these regressors is handybecause it allows to inspect the internal fitted parameters of theseregressors.In the case where you only are interested in the test score, scikit-learnprovide a `cross_val_sc...
from sklearn.model_selection import cross_val_score scores = cross_val_score(regressor, data, target) scores
_____no_output_____
CC-BY-4.0
notebooks/cross_validation_train_test.ipynb
castorfou/scikit-learn-mooc