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 |
|---|---|---|---|---|---|
Now we can pass these sets into a series of different training & testing algorithms and compare their results. ___ Train a Logistic Regression classifierOne of the simplest multi-class classification tools is [logistic regression](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression... | from sklearn.linear_model import LogisticRegression
lr_model = LogisticRegression(solver='lbfgs')
lr_model.fit(X_train, y_train) | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
Test the Accuracy of the Model | from sklearn import metrics
# Create a prediction set:
predictions = lr_model.predict(X_test)
# Print a confusion matrix
print(metrics.confusion_matrix(y_test,predictions))
# You can make the confusion matrix less confusing by adding labels:
df = pd.DataFrame(metrics.confusion_matrix(y_test,predictions), index=['ham'... | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
These results are terrible! More spam messages were confused as ham (241) than correctly identified as spam (5), although a relatively small number of ham messages (46) were confused as spam. | # Print a classification report
print(metrics.classification_report(y_test,predictions))
# Print the overall accuracy
print(metrics.accuracy_score(y_test,predictions)) | 0.84393692224
| Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
This model performed *worse* than a classifier that assigned all messages as "ham" would have! ___ Train a naïve Bayes classifier:One of the most common - and successful - classifiers is [naïve Bayes](http://scikit-learn.org/stable/modules/naive_bayes.htmlnaive-bayes). | from sklearn.naive_bayes import MultinomialNB
nb_model = MultinomialNB()
nb_model.fit(X_train, y_train) | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
Run predictions and report on metrics | predictions = nb_model.predict(X_test)
print(metrics.confusion_matrix(y_test,predictions)) | [[1583 10]
[ 246 0]]
| Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
The total number of confusions dropped from **287** to **256**. [241+46=287, 246+10=256] | print(metrics.classification_report(y_test,predictions))
print(metrics.accuracy_score(y_test,predictions)) | 0.860793909734
| Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
Better, but still less accurate than 86.6% ___ Train a support vector machine (SVM) classifierAmong the SVM options available, we'll use [C-Support Vector Classification (SVC)](https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.htmlsklearn.svm.SVC) | from sklearn.svm import SVC
svc_model = SVC(gamma='auto')
svc_model.fit(X_train,y_train) | _____no_output_____ | Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
Run predictions and report on metrics | predictions = svc_model.predict(X_test)
print(metrics.confusion_matrix(y_test,predictions)) | [[1515 78]
[ 131 115]]
| Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
The total number of confusions dropped even further to **209**. | print(metrics.classification_report(y_test,predictions))
print(metrics.accuracy_score(y_test,predictions)) | 0.886351277868
| Apache-2.0 | nlp/UPDATED_NLP_COURSE/03-Text-Classification/00-SciKit-Learn-Primer.ipynb | rishuatgithub/MLPy |
View source on GitHub Notebook Viewer Run in binder Run in Google Colab Install Earth Engine APIInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](http... | # %%capture
# !pip install earthengine-api
# !pip install geehydro | _____no_output_____ | MIT | Gena/map_center_object.ipynb | guy1ziv2/earthengine-py-notebooks |
Import libraries | import ee
import folium
import geehydro | _____no_output_____ | MIT | Gena/map_center_object.ipynb | guy1ziv2/earthengine-py-notebooks |
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()` if you are running this notebook for this first time or if you are getting an authentication error. | # ee.Authenticate()
ee.Initialize() | _____no_output_____ | MIT | Gena/map_center_object.ipynb | guy1ziv2/earthengine-py-notebooks |
Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `... | Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID') | _____no_output_____ | MIT | Gena/map_center_object.ipynb | guy1ziv2/earthengine-py-notebooks |
Add Earth Engine Python script | # get a single feature
countries = ee.FeatureCollection("USDOS/LSIB_SIMPLE/2017")
country = countries.filter(ee.Filter.eq('country_na', 'Ukraine'))
Map.addLayer(country, { 'color': 'orange' }, 'feature collection layer')
# TEST: center feature on a map
Map.centerObject(country, 6)
| _____no_output_____ | MIT | Gena/map_center_object.ipynb | guy1ziv2/earthengine-py-notebooks |
Display Earth Engine data layers | Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map | _____no_output_____ | MIT | Gena/map_center_object.ipynb | guy1ziv2/earthengine-py-notebooks |
Examples for the AbsComponent Class (v1.1) | %matplotlib inline
# suppress warnings for these examples
import warnings
warnings.filterwarnings('ignore')
# import
try:
import seaborn as sns; sns.set_style("white")
except:
pass
import numpy as np
from astropy.table import QTable
import astropy.units as u
from linetools.spectralline import AbsLine
from line... | _____no_output_____ | BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
Instantiate Standard | abscomp = AbsComponent((10.0*u.deg, 45*u.deg), (14,2), 1.0, [-300,300]*u.km/u.s)
abscomp | _____no_output_____ | BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
From AbsLines From one line | lya = AbsLine(1215.670*u.AA, z=2.92939)
lya.limits.set([-300.,300.]*u.km/u.s) # vlim
abscomp = AbsComponent.from_abslines([lya])
print(abscomp)
abscomp._abslines | <AbsComponent: 00:00:00 +00:00:00, Name=HI_z2.92939, Zion=(1,1), Ej=0 1 / cm, z=2.92939, vlim=-300 km / s,300 km / s>
| BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
From multiple | lyb = AbsLine(1025.7222*u.AA, z=lya.z)
lyb.limits.set([-300.,300.]*u.km/u.s) # vlim
abscomp = AbsComponent.from_abslines([lya,lyb])
print(abscomp)
abscomp._abslines
#### Define from QTable and make an spectrum model
# We first create a QTable with the most relevant information for defining AbsComponents
tab = QTable(... | Loading abundances from Asplund2009
Abundances are relative by number on a logarithmic scale with H=12
| BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
Methods Generate a Component Table | lya.attrib['logN'] = 14.1
lya.attrib['sig_logN'] = 0.15
lya.attrib['flag_N'] = 1
laa.linear_clm(lya.attrib)
lyb.attrib['logN'] = 14.15
lyb.attrib['sig_logN'] = 0.19
lyb.attrib['flag_N'] = 1
laa.linear_clm(lyb.attrib)
abscomp = AbsComponent.from_abslines([lya,lyb])
comp_tbl = abscomp.build_table()
comp_tbl | _____no_output_____ | BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
Synthesize multiple components | SiIItrans = ['SiII 1260', 'SiII 1304', 'SiII 1526']
SiIIlines = []
for trans in SiIItrans:
iline = AbsLine(trans, z=2.92939)
iline.attrib['logN'] = 12.8 + np.random.rand()
iline.attrib['sig_logN'] = 0.15
iline.attrib['flag_N'] = 1
iline.limits.set([-300.,50.]*u.km/u.s) # vlim
_,_ = laa.linear_c... | _____no_output_____ | BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
Generate multiple components from abslines | comps = ltiu.build_components_from_abslines([lya,lyb,SiIIlines[0],SiIIlines[1]])
comps | _____no_output_____ | BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
Generate an Ion Table | tbl = ltiu.iontable_from_components([abscomp,SiIIcomp,SiIIcomp2])
tbl | _____no_output_____ | BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
Stack plot Load a spectrum | xspec = lsio.readspec(lt_path+'/spectra/tests/files/UM184_nF.fits')
lya.analy['spec'] = xspec
lyb.analy['spec'] = xspec | _____no_output_____ | BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
Show | abscomp = AbsComponent.from_abslines([lya,lyb])
abscomp.stack_plot()
| _____no_output_____ | BSD-3-Clause | docs/examples/AbsComponent_examples.ipynb | marijana777/linetools |
Notice: This notebook is not optimized for memory nor performance yet. Please use it with caution when handling large datasets. Notice: Please ignore Feature engineering part if you are using a ready dataset Feature engineering This notebook is for BDSE12_03G_HomeCredit_V2.csv processing for bear LGBM final Prepare... | # Pandas for managing datasets
import numpy as np
import pandas as pd
np.__version__, pd.__version__
# math for operating numbers
import math
import gc
# Change pd displayg format for float
pd.options.display.float_format = '{:,.4f}'.format
# Matplotlib for additional customization
from matplotlib import pyplot as plt
... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Read & combine datasets | appl_all_df = pd.read_csv('../..//datasets/homecdt_fteng/BDSE12_03G_HomeCredit_V2.csv',index_col=0)
appl_all_df.info() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 356255 entries, 0 to 356254
Columns: 797 entries, AMT_ANNUITY to GOODS_PRICE_PREV%
dtypes: float64(741), int64(42), object(14)
memory usage: 2.1+ GB
| MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- | # appl_all_df.apply(lambda x:x.unique().size).describe()
appl_all_df['TARGET'].unique(), \
appl_all_df['TARGET'].unique().size
appl_all_df['TARGET'].value_counts()
appl_all_df['TARGET'].isnull().sum(), \
appl_all_df['TARGET'].size, \
(appl_all_df['TARGET'].isnull().sum()/appl_all_df['TARGET'].size).round(4)
# Make sure... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Randomized sampleing: If the dataset is too large, consider following randomized sampling from original dataset to facilitate development and testing | # Randomized sampling from original dataset.
# This is just for simplifying the development process
# After coding is complete, should replace all df-->df, and remove this cell
# Reference: https://yiidtw.github.io/blog/2018-05-29-how-to-shuffle-dataframe-in-pandas/
# df= appl_all_df.sample(n = 1000).reset_index(drop=... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Tool: Get numerical/ categorical variables(columns) from a dataframe | def get_num_df (data_df, unique_value_threshold: int):
"""
Output: a new dataframe with columns of numerical variables from the input dataframe.
Input:
data_df: original dataframe,
unique_value_threshold(int): number of unique values of each column
e.g. If we define a column with > 3 ... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Splitting id_target_df, cat_df, num_df | # Separate id and target columns before any further processing
id_target_df = appl_all_df.loc[:, ['SK_ID_CURR','TARGET']]
# Get the operating appl_all_df by removing id and target columns
appl_all_df_opr = appl_all_df.drop(['SK_ID_CURR','TARGET'], axis=1)
# A quick check of their shapes
appl_all_df.shape, id_target_d... | <class 'pandas.core.frame.DataFrame'>
Int64Index: 356255 entries, 0 to 356254
Columns: 795 entries, AMT_ANNUITY to GOODS_PRICE_PREV%
dtypes: float64(740), int64(41), object(14)
memory usage: 2.1+ GB
<class 'pandas.core.frame.DataFrame'>
Int64Index: 356255 entries, 0 to 356254
Columns: 797 entries, AMT_ANNUITY to GOODS_... | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Dealing with categorical variables Transform to String (i.e., python object) and fill nan with String 'nan' | cat_df_obj = cat_df.astype(str)
assert np.all(cat_df_obj.dtypes) == object
# There are no NA left
assert all(cat_df_obj.isnull().sum())==0
# The float nan will be tranformed to String 'nan'
# Use this assertion carefully when dealing with extra-large datasets
assert cat_df.isnull().equals(cat_df_obj.isin({'nan'})) | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
Dealing with special columns Replace 'nan' with 'not specified' in column 'FONDKAPREMONT_MODE' | # Do the replacement and re-assign the modified column back to the original dataframe
cat_df_obj['FONDKAPREMONT_MODE'] = cat_df_obj['FONDKAPREMONT_MODE'].replace('nan','not specified')
# check again the unique value, it should be 1 less than the original cat_df
assert cat_df['FONDKAPREMONT_MODE'].unique().size == cat_d... | <class 'pandas.core.frame.DataFrame'>
Int64Index: 356255 entries, 0 to 356254
Columns: 250 entries, AMT_REQ_CREDIT_BUREAU_DAY to AMT_REQ_CREDIT_BUREAU_MON/QRT
dtypes: float64(198), int64(38), object(14)
memory usage: 682.2+ MB
| MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
Do one-hot encoding Check the input dataframe (i.e., cat_df_obj) | cat_df_obj.shape
cat_df_obj.apply(lambda x:x.unique().size).sum()
# ?pd.get_dummies
# pd.get_dummies() method deals only with categorical variables.
# Although it has a built-in argument 'dummy_na' to manage the na value,
# our na value has already been converted to string object which are not recognized by the method... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Dealing with numerial variables Get na flags | num_df.shape
# How many columns contain na value.
num_df.isna().any().sum()
num_isna_df = num_df[num_df.columns[num_df.isna().any()]]
num_notna_df = num_df[num_df.columns[num_df.notna().all()]]
assert num_isna_df.shape[1] + num_notna_df.shape[1] == num_df.shape[1]
assert num_isna_df.shape[0] == num_notna_df.shape[0] =... | <class 'pandas.core.frame.DataFrame'>
Int64Index: 356255 entries, 0 to 356254
Columns: 528 entries, APARTMENTS_AVG_na to GOODS_PRICE_PREV%_na
dtypes: uint8(528)
memory usage: 182.1 MB
| MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
replace na with zero | num_isna_df = num_isna_df.fillna(0)
num_isna_df.shape
# How many columns contain na value.
num_isna_df.isna().any().sum()
num_isna_df.info()
assert num_isna_df.shape == num_naFlag_df.shape
num_df = pd.concat([num_notna_df,num_isna_df,num_naFlag_df], axis = 'columns')
assert num_notna_df.shape[1] + num_isna_df.shape[1] ... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Normalization (DO LATER!!) Generally, in tree-based models, the scale of the features does not matter.https://scikit-learn.org/stable/modules/preprocessing.htmlnormalizationhttps://datascience.stackexchange.com/questions/22036/how-does-lightgbm-deal-with-value-scale --- Combine to a complete, processed dataset | frames = np.array([id_target_df, cat_df_obj_ohe, num_df])
id_target_df.shape, cat_df_obj_ohe.shape, num_df.shape
appl_all_processed_df = pd.concat(frames, axis ='columns')
appl_all_processed_df.shape
assert appl_all_processed_df.shape[1] == id_target_df.shape[1] + cat_df_obj_ohe.shape[1] + num_df.shape[1]
appl_all_proc... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Export to CSV | # Export the dataframe to csv for future use
appl_all_processed_df.to_csv('../../datasets/homecdt_fteng/ss_fteng_fromBDSE12_03G_HomeCredit_V2_20200204a.csv', index = False)
# Export the dtypes Series to csv for future use
appl_all_processed_df.dtypes.to_csv('../../datasets/homecdt_fteng/ss_fteng_fromBDSE12_03G_HomeCred... | C:\Users\Student\.conda\envs\homecdt\lib\site-packages\ipykernel_launcher.py:2: FutureWarning: The signature of `Series.to_csv` was aligned to that of `DataFrame.to_csv`, and argument 'header' will change its default value from False to True: please pass an explicit value to suppress this warning.
| MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Interface connecting fteng & model parts | # Assign appl_all_processed_df to final_df for follow-up modeling
final_df = appl_all_processed_df
# Apply the following gc if memory is running slow
del appl_all_processed_df
gc.collect()
final_df.columns = ["".join (c if c.isalnum() else "_" for c in str(x)) for x in final_df.columns]
final_df.info() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 356255 entries, 0 to 356254
Columns: 4081 entries, SK_ID_CURR to GOODS_PRICE_PREV__na
dtypes: float64(543), int64(4), uint8(3534)
memory usage: 2.6 GB
| MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Modeling part. If using a ready dataset, please start here | # Reading the saved dtypes Series
final_df_dtypes = \
pd.read_csv('../../datasets/homecdt_fteng/ss_fteng_fromBDSE12_03G_HomeCredit_V2_20200204a_dtypes_series.csv'\
, header=None, index_col=0, squeeze=True)
del final_df_dtypes.index.name
final_df_dtypes = final_df_dtypes.to_dict()
final_df = \
pd.read_csv('.... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 356255 entries, 0 to 356254
Columns: 4081 entries, SK_ID_CURR to GOODS_PRICE_PREV__na
dtypes: float64(543), int64(4), uint8(3534)
memory usage: 2.6 GB
| MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
This following is based on 'bear_Final_model' released 2020/01/23 | # Forked from excellent kernel : https://www.kaggle.com/jsaguiar/updated-0-792-lb-lightgbm-with-simple-features
# From Kaggler : https://www.kaggle.com/jsaguiar
# Just added a few features so I thought I had to make release it as well...
import numpy as np
import pandas as pd
import gc
import time
from contextlib impo... | 48744 float64
| MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
LightGBM 模型 | def timer(title):
t0 = time.time()
yield
print("{} - done in {:.0f}s".format(title, time.time() - t0))
def kfold_lightgbm(df, num_folds = 5, stratified = True, debug= False, boosting_type= 'goss', epoch=20000, early_stop=200):
# Divide in training/validation and test data
train_df = df[df['TARGET']... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
boosting_type:goss | init_time = time.time()
kfold_lightgbm(final_df,10)
print("Elapsed time={:5.2f} sec.".format(time.time() - init_time))
init_time = time.time()
kfold_lightgbm(final_df,10)
print("Elapsed time={:5.2f} sec.".format(time.time() - init_time)) | Starting LightGBM goss. Train shape: (307511, 4081), test shape: (48744, 4081)
Training until validation scores don't improve for 200 rounds
Early stopping, best iteration is:
[1773] training's auc: 0.860105 valid_1's auc: 0.793118
Fold 1 AUC : 0.793118
Training until validation scores don't improve for 200 rounds
[20... | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
boosting_type:gbdt | # init_time = time.time()
# kfold_lightgbm(final_df, 10, boosting_type= 'gbdt')
# print("Elapsed time={:5.2f} sec.".format(time.time() - init_time)) | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
boosting_type:dart | # init_time = time.time()
# kfold_lightgbm(final_df,10, boosting_type= 'dart')
# print("Elapsed time={:5.2f} sec.".format(time.time() - init_time)) | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
boosting_type:rf | # init_time = time.time()
# kfold_lightgbm(final_df,10,boosting_type= 'rf')
# print("Elapsed time={:5.2f} sec.".format(time.time() - init_time)) | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
XGBoost 模型 | from numba import cuda
cuda.select_device(0)
cuda.close()
import numpy as np
import pandas as pd
import gc
import time
from contextlib import contextmanager
from xgboost import XGBClassifier
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import KFold, StratifiedKFold
import matplotlib... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- Below not executed Balance the 'TARGET' column | appl_all_processed_df['TARGET'].value_counts()
balanceFactor = ((appl_all_processed_df['TARGET'].value_counts()[0])/(appl_all_processed_df['TARGET'].value_counts()[1])).round(0).astype(int)
balanceFactor
# appl_all_processed_df['TARGET'].value_counts()[0]
# appl_all_processed_df['TARGET'].value_counts()[1]
default_df =... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- --- Todo Todo:* cleaning: * num_df: normalize with z-score* feature engineering: * make reciprocol, polynomial columns of the existing columns. 1/x, x^x. * multiplying each columns, two columns at a time. * asset items, income items, willingness(history + misc profile) items, loading(principle + intere... | numcol = df['CNT_FAM_MEMBERS']
numcol.describe(), \
numcol.isnull().sum(), \
numcol.size
numcol.value_counts(sort=True), numcol.unique().size
# numcol_toYear = pd.to_numeric(\
# ((numcol.abs() / 365) \
# .round(0)) \
# ,downcast=... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
Quick check for categorical columns | catcol = df['HOUR_APPR_PROCESS_START']
catcol.unique(), \
catcol.unique().size
catcol.value_counts(sort=True)
catcol.isnull().sum(), \
catcol.size
catcol.isnull().sum(), \
catcol.size | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
Appendix Tool: Getting summary dataframe | # might not be very useful at this point
def summary_df (data_df):
"""
Output: a new dataframe with summary info from the input dataframe.
Input: data_df, the original dataframe
"""
summary_df = pd.concat([(data_df.describe(include='all')), \
(data_df.dtypes.to_frame(name='dtypes').T), \... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- .nunique() function | # nunique() function excludes NaN
# i.e. it does not consider NaN as a "value", therefore NaN is not counted as a "unique value"
df.nunique()
df.nunique() == df.apply(lambda x:x.unique().shape[0])
df['AMT_REQ_CREDIT_BUREAU_YEAR'].unique().shape[0]
df['AMT_REQ_CREDIT_BUREAU_YEAR'].nunique()
df['AMT_REQ_CREDIT_BUREAU_YE... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
.value_counts() function | # .value_counts() function has similar viewpoint towards NaN.
# i.e. it does not consider null as a value, therefore not counted in .value_counts()
df['NAME_TYPE_SUITE'].value_counts()
df['AMT_REQ_CREDIT_BUREAU_YEAR'].isnull().sum()
df['AMT_REQ_CREDIT_BUREAU_YEAR'].size
df['AMT_REQ_CREDIT_BUREAU_YEAR'].value_counts().s... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
重複值 | # Counting unique values (cf. .nunique() function, see above section)
# This code was retrieved from HT
df.apply(lambda x:x.unique().shape[0])
# It is the same if you write (df.apply(lambda x:x.unique().size))
assert (df.apply(lambda x:x.unique().shape[0])==df.apply(lambda x:x.unique().size)).all
# # %timeit showed th... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
空值 | # 含空值欄位占比
print(f"{df.isnull().any().sum()} in {df.shape[1]} columns (ratio: {(df.isnull().any().sum()/df.shape[1]).round(2)}) has empty value(s)")
| _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
--- re-casting to reduce memory use (beta) | # np.isfinite(num_df).all().value_counts()
# num_df_finite = num_df[num_df.columns[np.isfinite(num_df).all()]]
# num_df_infinite = num_df[num_df.columns[np.isfinite(num_df).all() == False]]
# num_df_finite.shape, num_df_infinite.shape
# assert num_df_finite.shape[0] == num_df_infinite.shape[0] == num_df.shape[0]
# asse... | _____no_output_____ | MIT | notebooks/homecdt_model/.ipynb_checkpoints/ss_fteng_model_fromBDSE12_03G_HomeCredit_V2_20200204b-checkpoint.ipynb | ss9202150/Project_1 |
Batch Prediction 1. Download demo data```cd PhaseNetwget https://github.com/wayneweiqiang/PhaseNet/releases/download/test_data/test_data.zipunzip test_data.zip``` 2. Run batch prediction PhaseNet currently supports three data formats: numpy, hdf5, and mseed- For numpy format:~~~bashpython phasenet/predict.py --model=m... | import pandas as pd
import json
import os
PROJECT_ROOT = os.path.realpath(os.path.join(os.path.abspath(''), ".."))
picks_csv = pd.read_csv(os.path.join(PROJECT_ROOT, "results/picks.csv"), sep="\t")
picks_csv.loc[:, 'p_idx'] = picks_csv["p_idx"].apply(lambda x: x.strip("[]").split(","))
picks_csv.loc[:, 'p_prob'] = pick... | {'id': 'NC.MCV..EH.0361339.npz', 'timestamp': '1970-01-01T00:01:30.150', 'prob': 0.9811667799949646, 'type': 'p'}
{'id': 'NC.MCV..EH.0361339.npz', 'timestamp': '1970-01-01T00:00:59.990', 'prob': 0.9872905611991882, 'type': 'p'}
| MIT | docs/example_batch_prediction.ipynb | javak87/phasenet_chile-subduction-zone |
Multithreading and MultiprocessingRecall the phrase "many hands make light work". This is as true in programming as anywhere else.What if you could engineer your Python program to do four things at once? What would normally take an hour could (almost) take one fourth the time.\*This is the idea behind parallel process... | from random import random # perform this import outside the function
def find_pi(n):
"""
Function to estimate the value of Pi
"""
inside=0
for i in range(0,n):
x=random()
y=random()
if (x*x+y*y)**(0.5)<=1: # if i falls inside the circle
inside+=1
pi=4*ins... | _____no_output_____ | MIT | 22-Parallel Processing/01-Multithreading and Multiprocessing.ipynb | Pankaj-Ra/Complete-Python3-Bootcamp-master |
Let's test `find_pi` on 5,000 points: | find_pi(5000) | _____no_output_____ | MIT | 22-Parallel Processing/01-Multithreading and Multiprocessing.ipynb | Pankaj-Ra/Complete-Python3-Bootcamp-master |
This ran very quickly, but the results are not very accurate!Next we'll write a script that sets up a pool of workers, and lets us time the results against varying sized pools. We'll set up two arguments to represent *processes* and *total_iterations*. Inside the script, we'll break *total_iterations* down into the num... | %%writefile test.py
from random import random
from multiprocessing import Pool
import timeit
def find_pi(n):
"""
Function to estimate the value of Pi
"""
inside=0
for i in range(0,n):
x=random()
y=random()
if (x*x+y*y)**(0.5)<=1: # if i falls inside the circle
... | 3.1466800
3.1364400
3.1470400
3.1370400
3.1256400
3.1398400
3.1395200
3.1363600
3.1437200
3.1334400
0.2370227286270967
100000 total iterations with 5 processes
| MIT | 22-Parallel Processing/01-Multithreading and Multiprocessing.ipynb | Pankaj-Ra/Complete-Python3-Bootcamp-master |
Great! The above test took under a second on our computer.Now that we know our script works, let's increase the number of iterations, and compare two different pools. Sit back, this may take awhile! | %%writefile test.py
from random import random
from multiprocessing import Pool
import timeit
def find_pi(n):
"""
Function to estimate the value of Pi
"""
inside=0
for i in range(0,n):
x=random()
y=random()
if (x*x+y*y)**(0.5)<=1: # if i falls inside the circle
... | 3.1420964
3.1417412
3.1411108
3.1408184
3.1414204
3.1417656
3.1408324
3.1418828
3.1420492
3.1412804
36.03526345242264
10000000 total iterations with 1 processes
3.1424524
3.1418376
3.1415292
3.1410344
3.1422376
3.1418736
3.1420540
3.1411452
3.1421652
3.1410672
17.300921846344366
10000000 total iterations with 5 process... | MIT | 22-Parallel Processing/01-Multithreading and Multiprocessing.ipynb | Pankaj-Ra/Complete-Python3-Bootcamp-master |
Hopefully you saw that with 5 processes our script ran faster! More is Better ...to a point.The gain in speed as you add more parallel processes tends to flatten out at some point. In any collection of tasks, there are going to be one or two that take longer than average, and no amount of added processing can speed th... | %%writefile test2.py
from random import random
from multiprocessing import Pool
import timeit
import sys
N = int(sys.argv[1]) # these arguments are passed in from the command line
P = int(sys.argv[2])
def find_pi(n):
"""
Function to estimate the value of Pi
"""
inside=0
for i in range(0,n):
... | 3.14121
3.14145
3.14178
3.14194
3.14109
3.14201
3.14243
3.14150
3.14203
3.14116
16.871822701405073
10000000 total iterations with 500 processes
| MIT | 22-Parallel Processing/01-Multithreading and Multiprocessing.ipynb | Pankaj-Ra/Complete-Python3-Bootcamp-master |
Define a function to integrate | def func(x):
a = 1.01
b= -3.04
c = 2.07
return a*x**2 + b*x + c | _____no_output_____ | MIT | Integration.ipynb | QuinnPaddock/UCSC-ASTR-119 |
Define it's integral so we know the right answer | def func_integral(x):
a = 1.01
b= -3.04
c = 2.07
return (a*x**3)/3. + (b*x**2)/2. + c*x | _____no_output_____ | MIT | Integration.ipynb | QuinnPaddock/UCSC-ASTR-119 |
Define core of trapezoid method | def trapezoid_core(f,x,h):
return 0.5*h*(f(x*h)+f(x)) | _____no_output_____ | MIT | Integration.ipynb | QuinnPaddock/UCSC-ASTR-119 |
Define the wrapper function to perform the trapezoid method | def trapezoid_method(f,a,b,N):
#f == function to integrate
#a == lower limit of integration
#b == upper limit of integration
#N == number of intervals to use
#define x values to perform the trapezoid rule
x = np.linspace(a,b,N)
h = x[1]-x[0]
#define the value of the integral
... | _____no_output_____ | MIT | Integration.ipynb | QuinnPaddock/UCSC-ASTR-119 |
Define the core of simpson's method | def simpsons_core(f,x,h):
return h*(f(x) + 4*f(x+h) + f(x+2*h))/3 | _____no_output_____ | MIT | Integration.ipynb | QuinnPaddock/UCSC-ASTR-119 |
Define a wrapper for simpson's method | def simpsons_method(f,a,b,N):
#f == function to integrate
#a == lower limit of integration
#b == upper limit of integration
#N == number of intervals to use
x = np.linspace(a,b,N)
h = x[1]-x[0]
#define the value of the integral
Fint = 0.0
#perform the integral usi... | _____no_output_____ | MIT | Integration.ipynb | QuinnPaddock/UCSC-ASTR-119 |
Define Romberg core | def romberg_core(f,a,b,i):
#we need the difference between a and b
h = b-a
#interval betwen function evaluations at refine level i
dh = h/2.**(i)
#we need the cofactor
K = h/2.**(i+1)
#and the function evaluations
M = 0.0
for j in range(2**i):
M += f(a + 0.5*dh... | _____no_output_____ | MIT | Integration.ipynb | QuinnPaddock/UCSC-ASTR-119 |
Define a wrapper function | def romberg_integration(f,a,b,tol):
#define an iteration variable
i=0
#define a max number of iterations
imax = 1000
#define an error estimate
delta = 100.0*np.fabs(tol)
#set an array of integral answers
I = np.zeros(imax,dtype=float)
#fet the zeroth romberg itera... | _____no_output_____ | MIT | Integration.ipynb | QuinnPaddock/UCSC-ASTR-119 |
Check the interages | Answer = func_integral(1) - func_integral(0)
print(Answer)
print("Trapezoidal method")
print(trapezoid_method(func,0,1,10))
print("Simpson's method")
print(simpsons_method(func,0,1,10))
print("Romberg")
tolerance = 1.0e-4
RI = romberg_integration(func,0,1,tolerance)
print(RI, (RI-Answer)/Answer, tolerance) | _____no_output_____ | MIT | Integration.ipynb | QuinnPaddock/UCSC-ASTR-119 |
Tuning an estimator[José C. García Alanis (he/him)](https://github.com/JoseAlanis) Research Fellow - Child and Adolescent Psychology at [Uni Marburg](https://www.uni-marburg.de/de) Member - [RTG 2271 | Breaking Expectations](https://www.uni-marburg.de/en/fb04/rtg-2271), [Brainhack](https://brainhack.org/) &... | import numpy as np
import pandas as pd
# get the data set
data = np.load('MAIN2019_BASC064_subsamp_features.npz')['a']
# get the labels
info = pd.read_csv('participants.csv')
print('There are %s samples and %s features' % (data.shape[0], data.shape[1])) | There are 155 samples and 2016 features
| BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
We'll set `Age` as target- i.e., well look at these from the `regression` perspective | # set age as target
Y_con = info['Age']
Y_con.describe() | _____no_output_____ | BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
Model specificationNow let's bring back the model specifications we used last time | from sklearn.model_selection import train_test_split
# split the data
X_train, X_test, y_train, y_test = train_test_split(data, Y_con, random_state=0)
# use `AgeGroup` for stratification
age_class2 = info.loc[y_train.index,'AgeGroup'] | _____no_output_____ | BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
Normalize the target data¶ | # plot the data
sns.displot(y_train,label='train')
plt.legend()
# create a log transformer function and log transform Y (age)
from sklearn.preprocessing import FunctionTransformer
log_transformer = FunctionTransformer(func = np.log, validate=True)
log_transformer.fit(y_train.values.reshape(-1,1))
y_train_log = log_tra... | _____no_output_____ | BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
Now let's plot the transformed data | import matplotlib.pyplot as plt
import seaborn as sns
sns.displot(y_train_log,label='test log')
plt.legend() | _____no_output_____ | BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
and go on with fitting the model to the log-tranformed data | # split the data
X_train2, X_test, y_train2, y_test = train_test_split(
X_train, # x
y_train, # y
test_size = 0.25, # 75%/25% split
shuffle = True, # shuffle dataset before splitting
stratify = age_class2, # keep distribution of age class consistent
# betw. train & tes... | _____no_output_____ | BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
Alright, seems like a definite improvement, right? We might agree on that.But we can't forget about interpretability? The MAE is much less interpretable now- do you know why? Tweak the hyperparameters¶Many machine learning algorithms have hyperparameters that can be "tuned" to optimize model fitting.Careful parameter ... | SVR? | _____no_output_____ | BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
Now, how do we know what parameter tuning does?- One way is to plot a **Validation Curve**, this will let us view changes in training and validation accuracy of a model as we shift its hyperparameters. We can do this easily with sklearn. We'll fit the same model, but with a range of different values for `C` - The C par... | from sklearn.model_selection import validation_curve
C_range = 10. ** np.arange(-3, 7)
train_scores, valid_scores = validation_curve(lin_svr, X_train, y_train_log,
param_name= "C",
param_range = C_range,
... | _____no_output_____ | BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
It looks like accuracy is better for higher values of `C`, and plateaus somewhere between 0.1 and 1.The default setting is `C=1`, so it looks like we can't really improve much by changing `C`.But our SVR model actually has two hyperparameters, `C` and `epsilon`. Perhaps there is an optimal combination of settings for t... | from sklearn.model_selection import GridSearchCV
C_range = 10. ** np.arange(-3, 8)
epsilon_range = 10. ** np.arange(-3, 8)
param_grid = dict(epsilon=epsilon_range, C=C_range)
grid = GridSearchCV(lin_svr, param_grid=param_grid, cv=10)
grid.fit(X_train, y_train_log) | _____no_output_____ | BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
Now that the grid search has completed, let's find out what was the "best" parameter combination | print(grid.best_params_) | {'C': 0.01, 'epsilon': 0.01}
| BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
And if redo our cross-validation with this parameter set? | y_pred = cross_val_predict(SVR(kernel='linear',
C=grid.best_params_['C'],
epsilon=grid.best_params_['epsilon'],
gamma='auto'),
X_train, y_train_log, cv=10)
# scores
acc = r2_score(y_train_log, y_pr... | _____no_output_____ | BSD-3-Clause | lecture/ML_tuning_biases.ipynb | JoseAlanis/ML-DL_workshop_SynAGE |
Homework 2: classificationData source: http://archive.ics.uci.edu/ml/datasets/Polish+companies+bankruptcy+data**Description:** The goal of this HW is to be familiar with the basic classifiers PML Ch 3.For this HW, we continue to use Polish companies bankruptcy data Data Set from UCI Machine Learning Repository. Downlo... | from scipy.io import arff
import pandas as pd
import numpy as np
data = arff.loadarff('./data/4year.arff')
df = pd.DataFrame(data[0])
df['bankruptcy'] = (df['class']==b'1')
del df['class']
df.columns = ['X{0:02d}'.format(k) for k in range(1,65)] + ['bankruptcy']
df.describe()
sum(df.bankruptcy == True)
from sklearn.im... | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
*A dll load error occured here. Solution recorded in [my blog](https://quoth.win/671.html)* | from sklearn.model_selection import train_test_split
X, y = X_imp[:, :-1], X_imp[:, -1]
X_train, X_test, y_train, y_test =\
train_test_split(X, y,
test_size=0.3,
random_state=0,
stratify=y)
from sklearn.preprocessing import StandardScaler
stdsc = S... | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
1. Find the 2 most important featuresSelect the 2 most important features using LogisticRegression with L1 penalty. **(Adjust C until you see 2 features)** | from sklearn.linear_model import LogisticRegression
C = [1, .1, .01, 0.001]
cdf = pd.DataFrame()
for c in C:
lr = LogisticRegression(penalty='l1', C=c, solver='liblinear', random_state=0)
lr.fit(X_train_std, y_train)
print(f'[C={c}] with {lr.coef_[lr.coef_!=0].shape[0]} features: \n {lr.coef_[lr.coef_!=0... | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
redefine X_train_std and X_test_std | X_train_std = X_train_std[:, lr.coef_[0]!=0]
X_test_std = X_test_std[:, lr.coef_[0]!=0]
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.scatter(x=X_train_std[:,0], y=X_train_std[:,1], c=y_train, cmap='Set1') | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
2. Apply LR / SVM / Decision Tree belowUsing the 2 selected features, apply LR / SVM / decision tree. **Try your own hyperparameters (C, gamma, tree depth, etc)** to maximize the prediction accuracy. (Just try several values. You don't need to show your answer is the maximum.) LR | CLr = np.arange(0.000000000000001, 0.0225, 0.0001)
acrcLr = [] # acurracy
for c in CLr:
lr = LogisticRegression(C=c,penalty='l1',solver='liblinear')
lr.fit(X_train_std, y_train)
acrcLr.append([lr.score(X_train_std, y_train), lr.score(X_test_std, y_test), c])
acrcLr = np.array(acrcLr)
plt.plot(acrcLr[:,2], a... | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
Choose `c=.01` | c = .01
lr = LogisticRegression(C=c,penalty='l1',solver='liblinear')
lr.fit(X_train_std, y_train)
print(f'Accuracy when [c={c}] \nTrain {lr.score(X_train_std, y_train)}\nTest {lr.score(X_test_std, y_test)}') | Accuracy when [c=0.01]
Train 0.9474759264662971
Test 0.9469026548672567
| MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
SVM | from sklearn.svm import SVC
G = np.arange(0.00001, 0.3, 0.005)
acrcSvm = []
for g in G:
svm = SVC(kernel='rbf', gamma=g, C=1.0, random_state=0)
svm.fit(X_train_std, y_train)
acrcSvm.append([svm.score(X_train_std, y_train), svm.score(X_test_std, y_test), g])
acrcSvm = np.array(acrcSvm)
plt.plot(acrcSvm[:,2],... | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
Choose `gamma = 0.2` | g = 0.2
svm = SVC(kernel='rbf', gamma=g, C=1.0, random_state=0)
svm.fit(X_train_std, y_train)
print(f'Accuracy when [gamma={g}] \nTrain {svm.score(X_train_std, y_train)}\nTest {svm.score(X_test_std, y_test)}') | Accuracy when [gamma=0.2]
Train 0.9482054274875985
Test 0.9472430224642614
| MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
Decision Tree | from sklearn.tree import DecisionTreeClassifier
depthTree = range(1, 6)
acrcTree = []
for depth in depthTree:
tree = DecisionTreeClassifier(criterion='gini', max_depth=depth, random_state=0)
tree.fit(X_train_std, y_train)
acrcTree.append([tree.score(X_train_std, y_train), tree.score(X_test_std, y_test), dep... | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
Choose `max_depth=2`: | depth = 2
tree = DecisionTreeClassifier(criterion='gini', max_depth=depth, random_state=0)
tree.fit(X_train_std, y_train)
print(f'Accuracy when [max_depth={depth}] \nTrain {tree.score(X_train_std, y_train)}\nTest {tree.score(X_test_std, y_test)}') | Accuracy when [max_depth=2]
Train 0.9474759264662971
Test 0.9472430224642614
| MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
3. Visualize the classificationVisualize your classifiers using the plot_decision_regions function from PML Ch. 3 | def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
# setup marker generator and color map
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
# plot the decision surface
x1_min, x... | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
LR`test_idx` removed on purpose | plot_decision_regions(X=X_combined_std, y=y_combined,
classifier=lr)
plt.xlabel(cdf.index[0])
plt.ylabel(cdf.index[1])
plt.legend(loc='lower left')
plt.tight_layout()
#plt.savefig('images/03_01.png', dpi=300)
plt.show() | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
Decision Tree | plot_decision_regions(X=X_combined_std, y=y_combined,
classifier=tree)
plt.xlabel(cdf.index[0])
plt.ylabel(cdf.index[1])
plt.legend(loc='lower left')
plt.tight_layout()
#plt.savefig('images/03_01.png', dpi=300)
plt.show() | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
SVM (samples) | # Visualization of all features in a SVM model is too slow
# Because the complexity is very high (sourse:https://scikit-learn.org/stable/modules/svm.html#complexity)
# So use random samples(n=3000) instead
samples = np.random.randint(0, len(X_combined_std), size=3000)
plot_decision_regions(X=X_combined_std[samples], y... | _____no_output_____ | MIT | HW2/Classifiers.ipynb | oyrx/PHBS_MLF_2019 |
TopicsThis notebook covers the following topics -1. Basic Concepts 1. [Basic Syntax](basic-syntax) 2. [Lists](lists) 3. [String Manipulation](string) 4. [Decision making (If statement)](if) 5. Loops 1. [For loop](for) 2. [While loop](while) 6. [Function](func) 7. [Scope](scope) 8.... | #A basic print statement to display given message
print("Hello World!") | Hello World!
| MIT | .ipynb_checkpoints/Python Crash Course-checkpoint.ipynb | rafia37/DSA5113-TA-class-repo |
Basic Operations | #Addition
2 + 10
#Subtraction
2 - 10
#Multiplication
2*10
#Division
3/2
#Integer division
3//2
#Raising to a power
10**3
#Exponentiating - not the same as 10^3
10e3 | _____no_output_____ | MIT | .ipynb_checkpoints/Python Crash Course-checkpoint.ipynb | rafia37/DSA5113-TA-class-repo |
Defining VariablesYou can define variables as `variable_name = value`- Variable names can be alphanumeric though it can't start with a number.- Variable names are case sensitive- The values that you assign to a variable will typically be of these 5 standard data types (In python, you can assign almost anything to a va... | #Numbers
my_num = 5113 #Example of defining an integer
my_float = 3.0 #Example of defining a float
#Strings
truth = "This crash course is just the tip of the iceberg o_O"
#Lists
same_type_list = [1,2,3,4,5] #A simple list of same type of objects - integers
mixed_list = [1,2,"three", my_num, same_type_list] #A list c... | _____no_output_____ | MIT | .ipynb_checkpoints/Python Crash Course-checkpoint.ipynb | rafia37/DSA5113-TA-class-repo |
More print statementsNow we're going to print the variables we defined in the previous cell and look at some more ways to use the print statement | #printing a variable
print(my_float)
#printing the truth!
print(truth)
print(simple_dict)
print(mixed_list) #Notice how the 4th & 5th objects got the value of the variables we defined earlier
#Dynamic printing
print("This is DSA {}".format(my_num)) #The value/variable given inside format replaces the curly braces in th... | Value of pi up to 4 decimal places = 3.1416
| MIT | .ipynb_checkpoints/Python Crash Course-checkpoint.ipynb | rafia37/DSA5113-TA-class-repo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.