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
- 11![](../Photo/52.png)
a = input('请输入一个3位数: ') b = a[2]+a[1]+a[0] if a == b: print('是回文数') else: print('不是回文数')
请输入一个3位数: 123 不是回文数
Apache-2.0
7.18.ipynb
dimong/dimongg
- 12![](../Photo/53.png)
a,b,c =eval(input('输入三边:')) if a+b>c and a-b<c: d=a+b+c print(d) else: print('输入非法')
输入三边:4,6,10 输入非法
Apache-2.0
7.18.ipynb
dimong/dimongg
LOGISTIC REGRESSION WITH MNIST
import numpy as np # import tensorflow as tf import tensorflow.compat.v1 as tf import matplotlib.pyplot as plt # tf.disable_eager_execution() # tf.enable_eager_execution() print ("PACKAGES LOADED")
PACKAGES LOADED
MIT
notebooks/logistic_regression_mnist.ipynb
smwgf/Tensorflow-101
DOWNLOAD AND EXTRACT MNIST DATASET
def OnehotEncoding(target): from sklearn.preprocessing import OneHotEncoder target_re = target.reshape(-1,1) enc = OneHotEncoder() enc.fit(target_re) return enc.transform(target_re).toarray() def SuffleWithNumpy(data_x, data_y): idx = np.random.permutation(len(data_x)) x,y = data_x[idx], dat...
_____no_output_____
MIT
notebooks/logistic_regression_mnist.ipynb
smwgf/Tensorflow-101
download with keras dataset
print ("Download and Extract MNIST dataset") # mnist = input_data.read_data_sets('data/', one_hot=True) mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 print print (" tpye of 'mnist' is %s" % (type(mnist))) print (" number of t...
Download and Extract MNIST dataset tpye of 'mnist' is <class 'tensorflow.python.util.module_wrapper.TFModuleWrapper'> number of train data is 60000 number of test data is 10000 MNIST loaded
MIT
notebooks/logistic_regression_mnist.ipynb
smwgf/Tensorflow-101
Download with tfds
import tensorflow_datasets as tfds print ("Batch Learning? ") tf.enable_eager_execution() dataset, metadata = tfds.load('mnist', as_supervised=True, with_info=True) train_dataset, test_dataset = dataset['train'], dataset['test'] num_train_examples = metadata.splits['train'].num_examples num_test_examples = metadata.sp...
Batch Learning? Number of training examples: 60000 Number of test examples: 10000
MIT
notebooks/logistic_regression_mnist.ipynb
smwgf/Tensorflow-101
CREATE TENSOR GRAPH FOR LOGISTIC REGRESSION
x = tf.placeholder(tf.float32, shape = (None, 784)) y = tf.placeholder(tf.float32, shape = (None, 10)) # None is for infinite W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) # LOGISTIC REGRESSION MODEL actv = tf.nn.softmax(tf.matmul(x, W) + b) # COST FUNCTION cost = tf.reduce_mean(-tf.reduce_sum...
_____no_output_____
MIT
notebooks/logistic_regression_mnist.ipynb
smwgf/Tensorflow-101
PREDICTION AND ACCURACY
# PREDICTION pred = tf.equal(tf.argmax(actv, 1), tf.argmax(y, 1)) # ACCURACY accr = tf.reduce_mean(tf.cast(pred, "float")) # INITIALIZER initializer = tf.global_variables_initializer()
_____no_output_____
MIT
notebooks/logistic_regression_mnist.ipynb
smwgf/Tensorflow-101
TRAIN MODEL
training_epochs = 50 batch_size = 100 display_step = 5 # SESSION sess = tf.Session() sess.run(initializer) # MINI-BATCH LEARNING for epoch in range(training_epochs): avg_cost = 0. num_batch = int(num_train_data/batch_size) for i in range(num_batch): batch_xs=trainimg[i*batch_size:(i...
Epoch: 000/050 cost: 1.137559623 train_acc: 0.830 test_acc: 0.856 Epoch: 005/050 cost: 0.429877024 train_acc: 0.870 test_acc: 0.896 Epoch: 010/050 cost: 0.375152144 train_acc: 0.950 test_acc: 0.905 Epoch: 015/050 cost: 0.350435106 train_acc: 0.920 test_acc: 0.909 Epoch: 020/050 cost: 0.335372693 train_acc: 0.890 test_a...
MIT
notebooks/logistic_regression_mnist.ipynb
smwgf/Tensorflow-101
[View in Colaboratory](https://colab.research.google.com/github/anaurora/WineClassification/blob/master/WineClassification.ipynb) Wine Type Prediction (Multi-class Classification)This data set is taken from the UCI repository (link [here](https://archive.ics.uci.edu/ml/datasets/wine)). I have done some basic pre-proces...
!pip3 install -U -q PyDrive #Only if you are loading your data from Google Drive from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive from google.colab import auth from oauth2client.client import GoogleCredentials import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn...
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
Authorize Google Drive (if your data is stored in Drive)
%%capture auth.authenticate_user() gauth = GoogleAuth() gauth.credentials = GoogleCredentials.get_application_default() drive = GoogleDrive(gauth)
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
Data IngestionI have saved the file in my personal drive storage and read it from there into a pandas data frame. Please modify the following cells to read the CSV files into a Pandas dataframe as per your storage location.
%%capture downloaded = drive.CreateFile({'id':'1Tghlhn7nTZv_WOV7typp9fFZil4TjZ_9'}) # replace the id with id of file you want to access downloaded.GetContentFile('Winelab.csv') winedata = pd.read_csv('Winelab.csv')
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
Let's take a sneak peek at the data
winedata.head() winedata.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 178 entries, 0 to 177 Data columns (total 14 columns): Wine_Class 178 non-null int64 Alcohol 178 non-null float64 Malic_acid 178 non-null float64 Ash 178 non-null float64 Alkalinity_ash 178 non-null ...
MIT
WineClassification.ipynb
anaurora/WineClassification
As we can see, we have 13 attributes for each wine with one class label (*Wine_Class*). Data Preparation To prepare the data for analysis, we need to convert our Wine Class feature to a categorical one and scale the features, to prepare for dimensionality reduction using Principal Component Analysis (PCA).
winedata['Wine_Class']=winedata['Wine_Class'].astype('category')
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
In the previous section, we noticed that all 13 attributes of each wine are measured on completely different scales. To run PCA, and most machine learning algorithms, we need to focus on keeping the data around the same scale, so that no one feature can overpower the others with pure magnitude.
scaler = StandardScaler() winedatapc=winedata.copy() scaler.fit(winedatapc.iloc[:,1:]) winedatapc.iloc[:,1:]=scaler.transform(winedatapc.iloc[:,1:])
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
Now, one can see that all data has been scaled i.e. each feature (except the class label, of course) has been centered and scaled to unit variance (Z scores).
winedatapc.head()
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
Dimension Reduction (using PCA) We are going to generate all possible Principal Components for our dataset (13), plot them to see how well segregated the classes are, and decide on the number of components we are going to use for our prediction algorithm. The following lines of code generate the Principal Component sco...
pca = PCA(n_components=13,random_state=0) PCAscores=pd.DataFrame(pca.fit_transform(winedatapc.iloc[:,1:])) PCAscores=PCAscores.rename('PC{}'.format, axis='columns') PCAscores['Wine_Class']=winedatapc.Wine_Class PCAscores.head()
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
To see what these Principal Components mean, we create a loadings dataframe for each attribute of the dataframe (columns), for each Principal Component (index)
load=pd.DataFrame(pca.components_,columns=winedatapc.iloc[:,1:].columns) load=load.rename('PC{}'.format, axis='index') load
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
To interpret the above table, we take an example of the first row (PC0 i.e. the first Principal Component). The highest dependence of this PC is on *Flavanoids* and the dependence is positive. This implies that the higher the amount of Flavanoids in this wine, the higher the score of the first principal component. The ...
PC=sns.pairplot(x_vars=['PC0'], y_vars=['PC1'], data=PCAscores, hue="Wine_Class", size=8) plt.xlabel('Principal Component 0') plt.ylabel('Principal Component 1') plt.title('Visual Representation of all observations') plt.show()
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
We can see that the 3 categories of wine, are pretty well segregated. This is good, as we have distinct features for each type of wine. This will improve the accuracy of our prediction algorithm. The next task is to use these Principal Components to reduce the dimension of the problem. To see how many Principal Compone...
scree=plt.plot(pca.explained_variance_,'o-') plt.title('Scree Plot') plt.ylabel('Eigen Values') plt.xlabel('Component/Dimension') plt.xticks(range(0,13)) plt.show() var1=np.cumsum(np.round(pca.explained_variance_ratio_, decimals=4)*100) cumsum=plt.plot(var1,'o-') plt.xlabel('Component/Dimension') plt.ylabel('Percentage...
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
According to Kaiser's Rule, we should select the number of components that have eigen values greater than 1, and according to the variance rule, we should select the number of components that explain 95% of the variance in the data.From Kaiser's Rule, we should select approximately 3 components (scree plot), and from t...
X=PCAscores.iloc[:,:5].copy() X=X.values y=PCAscores.Wine_Class.astype(np.int64).values
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
Prediction Split Data: Training and Testing **We split the data to use 70% of it for training our machine learning models, and the remaining 30% for testing.**
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
Class distribution **A large part of how we decide which Machine Learning model to choose will depend on the class distribution. **
unique, counts = np.unique(y, return_counts=True) print(np.asarray((unique, counts)).T)
[[ 1 59] [ 2 71] [ 3 48]]
MIT
WineClassification.ipynb
anaurora/WineClassification
**So we have a noticeably uneven class distribution. This skew can introduce a bias in our model, and hence we need to be careful with our scoring method.****We chose the F1 micro score as a measure of model performance as we have an uneven class distribution (we have more ones than zeros in our class labels). For a mo...
def knn_param_selection(X, y, nfolds): n_neighborss = [3,4,5,6,7,8,9,10,11,12,13,14,15] metrics=['minkowski','euclidean','manhattan'] param_grid = {'n_neighbors': n_neighborss,'metric':metrics} grid_search = GridSearchCV(KNeighborsClassifier(), param_grid, cv=nfolds,scoring='f1_micro') grid_search.fit(X, y) ...
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
**The grid search reveals that we should use the *minkowski* distance metric and the *5 nearest neighbours* to maximize the F1 (micro) score. Since we have a class imbalance, we have used the F1 Micro score.** Model Fitting and Analysis
knnclass = KNeighborsClassifier(n_neighbors=5,metric='minkowski') knnclass.fit(X_train, y_train) y_pred = knnclass.predict(X_test) print('K-Nearest Neighbors predicts the correct class label with a',str(round(accuracy_score(y_test, y_pred)*100,2)),'% accuracy.') kfold=KFold(n_splits=10, random_state=0) modelCV = K...
10-fold average cross validation average F1 micro score: 0.950
MIT
WineClassification.ipynb
anaurora/WineClassification
Method 2: Logistic Regression Hyperparameter Tuning **We tune the regularization parameter (*C*) for logistic regression using a 10 fold cross validated Grid Search, using our training set. Notice, that we have set the grid search to maximize the F1 micro score for our model. **
def lgr_param_selection(X, y, nfolds): Cs = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.5,2,2.5,3] param_grid = {'C': Cs} grid_search = GridSearchCV(LogisticRegression(max_iter=1000,solver='sag',penalty='l2',random_state=0), param_grid, cv=nfolds,scoring='f1_micro') grid_search.fit(X, y) grid_search.best_params_...
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
**The Grid Search has yielded a regularization parameter (C) of 0.5. Note that we have used the L2 norm penalty, as L1/Elastic Net would perform automatic feature selection for us, which we have already done in the previous section.****We now apply this parameter to create a logistic regression model for analysis, and ...
logreg = LogisticRegression(max_iter=1000,solver='sag',penalty='l2',C=0.5,random_state=0) logreg.fit(X_train, y_train) y_pred = logreg.predict(X_test) print('Logistic Regression predicts the correct class label with a',str(round(accuracy_score(y_test, y_pred)*100,2)),'% accuracy.') kfold=KFold(n_splits=10, random_state...
10-fold average cross validation average F1 micro score: 0.933
MIT
WineClassification.ipynb
anaurora/WineClassification
Method 3: Support Vector Classifier with Linear Kernel Hyperparameter Tuning
def linsvc_param_selection(X, y, nfolds): Cs = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.5,2,2.5,3] param_grid = {'C': Cs} grid_search = GridSearchCV(LinearSVC(random_state=0), param_grid, cv=nfolds,scoring='f1_micro') grid_search.fit(X, y) grid_search.best_params_ return grid_search.best_params_ linsvc_para...
_____no_output_____
MIT
WineClassification.ipynb
anaurora/WineClassification
Model Fitting and Analysis
clf = LinearSVC(C=0.1,random_state=0) linsvc = CalibratedClassifierCV(clf) linsvc.fit(X_train, y_train) y_pred=linsvc.predict(X_test) print('Linear SVC predicts the correct class label with a',str(round(accuracy_score(y_test, y_pred)*100,2)),'% accuracy.') kfold=KFold(n_splits=10, random_state=0) modelCV = Calibrated...
10-fold average cross validation average F1 micro score: 0.944
MIT
WineClassification.ipynb
anaurora/WineClassification
Benchmark FRESA.CAD BSWIMS final Script This algorithm implementation uses R code and a Python library (rpy2) to connect with it, in order to run the following it is necesary to have installed both on your computer:- R (you can download in https://www.r-project.org/) - install rpy2 by pip install rpy2
import numpy as np import pandas as pd import sys from pathlib import Path import tadpole_algorithms from tadpole_algorithms.models import BenchmarkSVM_R from tadpole_algorithms.preprocessing.split import split_test_train_tadpole #rpy2 libs and funcs import rpy2.robjects.packages as rpackages from rpy2.robjects.vectors...
[[76 10 0] [20 69 3] [ 2 11 19]] mAUC (multiclass Area Under Curve): 0.8905512475700299 bca (balanced classification accuracy): 0.894263287696832 adasMAE (ADAS13 Mean Aboslute Error): 9.700607599015592 ventsMAE (Ventricles Mean Aboslute Error): 0.014373537870395907 adasWES (ADAS13 Weighted Error Score): 8.243242488...
Apache-2.0
benchmarking_FRESA-CAD.ipynb
88vikram/jupyter
Initialize pandarallel
pandarallel.initialize()
_____no_output_____
BSD-3-Clause
docs/examples.ipynb
asterist/pandarallel
DataFrame.apply
df_size = int(5e6) df = pd.DataFrame(dict(a=np.random.randint(1, 8, df_size), b=np.random.rand(df_size))) def func(x): return math.sin(x.a**2) + math.sin(x.b**2) %%time res = df.apply(func, axis=1) %%time res_parallel = df.parallel_apply(func, axis=1) res.equals(res_parallel)
_____no_output_____
BSD-3-Clause
docs/examples.ipynb
asterist/pandarallel
DataFrame.applymap
df_size = int(1e7) df = pd.DataFrame(dict(a=np.random.randint(1, 8, df_size), b=np.random.rand(df_size))) def func(x): return math.sin(x**2) - math.cos(x**2) %%time res = df.applymap(func) %%time res_parallel = df.parallel_applymap(func) res.equals(res_parallel)
_____no_output_____
BSD-3-Clause
docs/examples.ipynb
asterist/pandarallel
DataFrame.groupby.apply
df_size = int(3e7) df = pd.DataFrame(dict(a=np.random.randint(1, 1000, df_size), b=np.random.rand(df_size))) def func(df): dum = 0 for item in df.b: dum += math.log10(math.sqrt(math.exp(item**2))) return dum / len(df.b) %%time res = df.groupby("a").apply(func) %%time ...
_____no_output_____
BSD-3-Clause
docs/examples.ipynb
asterist/pandarallel
DataFrame.groupby.rolling.apply
df_size = int(1e6) df = pd.DataFrame(dict(a=np.random.randint(1, 300, df_size), b=np.random.rand(df_size))) def func(x): return x.iloc[0] + x.iloc[1] ** 2 + x.iloc[2] ** 3 + x.iloc[3] ** 4 %%time res = df.groupby('a').b.rolling(4).apply(func, raw=False) %%time res_parallel = df.groupby('a').b...
_____no_output_____
BSD-3-Clause
docs/examples.ipynb
asterist/pandarallel
DataFrame.groupby.expanding.apply
df_size = int(1e6) df = pd.DataFrame(dict(a=np.random.randint(1, 300, df_size), b=np.random.rand(df_size))) def func(x): return x.iloc[0] + x.iloc[1] ** 2 + x.iloc[2] ** 3 + x.iloc[3] ** 4 %%time res = df.groupby('a').b.expanding(4).apply(func, raw=False) %%time res_parallel = df.groupby('a')...
_____no_output_____
BSD-3-Clause
docs/examples.ipynb
asterist/pandarallel
Series.map
df_size = int(5e7) df = pd.DataFrame(dict(a=np.random.rand(df_size) + 1)) def func(x): return math.log10(math.sqrt(math.exp(x**2))) %%time res = df.a.map(func) %%time res_parallel = df.a.parallel_map(func) res.equals(res_parallel)
_____no_output_____
BSD-3-Clause
docs/examples.ipynb
asterist/pandarallel
Series.apply
df_size = int(3.5e7) df = pd.DataFrame(dict(a=np.random.rand(df_size) + 1)) def func(x, power, bias=0): return math.log10(math.sqrt(math.exp(x**power))) + bias %%time res = df.a.apply(func, args=(2,), bias=3) %%time res_parallel = df.a.parallel_apply(func, args=(2,), bias=3) res.equals(res_parallel)
_____no_output_____
BSD-3-Clause
docs/examples.ipynb
asterist/pandarallel
Series.rolling.apply
df_size = int(1e6) df = pd.DataFrame(dict(a=np.random.randint(1, 8, df_size), b=list(range(df_size)))) def func(x): return x.iloc[0] + x.iloc[1] ** 2 + x.iloc[2] ** 3 + x.iloc[3] ** 4 %%time res = df.b.rolling(4).apply(func, raw=False) %%time res_parallel = df.b.rolling(4).parallel_apply(func...
_____no_output_____
BSD-3-Clause
docs/examples.ipynb
asterist/pandarallel
What is the most popular start station and most popular end station?
#one import csv from pprint import pprint """This takes the file and returns dict of values. """ with open('chicago.csv', newline='') as csv_file: reader = [{key: value for key, value in row.items()} #list comprehimsion or one liners {} its s dictionary for row in csv.DictReader(csv_file, skipinitialspac...
_____no_output_____
MIT
other/popular_station.ipynb
chrisdmell/Project_Bikeshare
SVM (Support Vector Machines) In this notebook, you will use SVM (Support Vector Machines) to build and train a model using human cell records, and classify cells to whether the samples are benign or malignant.SVM works by mapping data to a high-dimensional feature space so that data points can be categorized, even wh...
import pandas as pd import pylab as pl import numpy as np import scipy.optimize as opt from sklearn import preprocessing from sklearn.model_selection import train_test_split %matplotlib inline import matplotlib.pyplot as plt
_____no_output_____
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
Load the Cancer dataThe example is based on a dataset that is publicly available from the UCI Machine Learning Repository (Asuncion and Newman, 2007)[http://mlearn.ics.uci.edu/MLRepository.html]. The dataset consists of several hundred human cell sample records, each of which contains the values of a set of cell charac...
#Click here and press Shift+Enter !wget -O cell_samples.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/cell_samples.csv
--2019-12-25 19:08:27-- https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/cell_samples.csv Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 67.228.254.196 Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-...
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
Load Data From CSV File
cell_df = pd.read_csv("cell_samples.csv") cell_df.head() cell_df.describe
_____no_output_____
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
The ID field contains the patient identifiers. The characteristics of the cell samples from each patient are contained in fields Clump to Mit. The values are graded from 1 to 10, with 1 being the closest to benign.The Class field contains the diagnosis, as confirmed by separate medical procedures, as to whether the sam...
ax = cell_df[cell_df['Class'] == 4][0:50].plot(kind='scatter', x='Clump', y='UnifSize', color='DarkBlue', label='malignant'); cell_df[cell_df['Class'] == 2][0:50].plot(kind='scatter', x='Clump', y='UnifSize', color='Yellow', label='benign', ax=ax); plt.show()
_____no_output_____
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
Data pre-processing and selection Lets first look at columns data types:
cell_df.dtypes
_____no_output_____
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
It looks like the __BareNuc__ column includes some values that are not numerical. We can drop those rows:
cell_df = cell_df[pd.to_numeric(cell_df['BareNuc'], errors='coerce').notnull()] cell_df['BareNuc'] = cell_df['BareNuc'].astype('int') cell_df.dtypes feature_df = cell_df[['Clump', 'UnifSize', 'UnifShape', 'MargAdh', 'SingEpiSize', 'BareNuc', 'BlandChrom', 'NormNucl', 'Mit']] X = np.asarray(feature_df) X[0:5]
_____no_output_____
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
We want the model to predict the value of Class (that is, benign (=2) or malignant (=4)). As this field can have one of only two possible values, we need to change its measurement level to reflect this.
cell_df['Class'] = cell_df['Class'].astype('int') y = np.asarray(cell_df['Class']) y [0:5]
/home/jupyterlab/conda/envs/python/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/u...
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
Train/Test dataset Okay, we split our dataset into train and test set:
X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4) print ('Train set:', X_train.shape, y_train.shape) print ('Test set:', X_test.shape, y_test.shape)
Train set: (546, 9) (546,) Test set: (137, 9) (137,)
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
Modeling (SVM with Scikit-learn) The SVM algorithm offers a choice of kernel functions for performing its processing. Basically, mapping data into a higher dimensional space is called kernelling. The mathematical function used for the transformation is known as the kernel function, and can be of different types, such a...
from sklearn import svm clf = svm.SVC(kernel='rbf') clf.fit(X_train, y_train)
/home/jupyterlab/conda/envs/python/lib/python3.6/site-packages/sklearn/svm/base.py:196: FutureWarning: The default value of gamma will change from 'auto' to 'scale' in version 0.22 to account better for unscaled features. Set gamma explicitly to 'auto' or 'scale' to avoid this warning. "avoid this warning.", FutureWa...
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
After being fitted, the model can then be used to predict new values:
yhat = clf.predict(X_test) yhat [0:5]
_____no_output_____
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
Evaluation
from sklearn.metrics import classification_report, confusion_matrix import itertools def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusio...
precision recall f1-score support 2 1.00 0.94 0.97 90 4 0.90 1.00 0.95 47 micro avg 0.96 0.96 0.96 137 macro avg 0.95 0.97 0.96 137 weighted avg 0.97 0.96 0.96 ...
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
You can also easily use the __f1_score__ from sklearn library:
from sklearn.metrics import f1_score f1_score(y_test, yhat, average='weighted')
_____no_output_____
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
Lets try jaccard index for accuracy:
from sklearn.metrics import jaccard_similarity_score jaccard_similarity_score(y_test, yhat)
_____no_output_____
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
PracticeCan you rebuild the model, but this time with a __linear__ kernel? You can use __kernel='linear'__ option, when you define the svm. How the accuracy changes with the new kernel function?
# write your code here
_____no_output_____
MIT
python/coursera_python/ML_WITH_PYTHON_IBM/.ipynb_checkpoints/ML0101EN-Clas-SVM-cancer-py-v1-checkpoint.ipynb
SayanGhoshBDA/code-backup
Iteration **CS1302 Introduction to Computer Programming**___
%reload_ext mytutor from ipywidgets import interact
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
Motivation Many tasks are repetitive:- To print from 1 up to a user-specified number *arbitrarily large*.- To compute the maximum of a sequence of numbers *arbitrarily long*.- To get user input *repeatedly until* it is within a certain range. **How to write code to perform repetitive tasks?** E.g., can you complete th...
%%mytutor -h 400 num = int(input(">")) if 1 <= num: print(1) if 2 <= num: print(2) if 3 <= num: print(3) # YOUR CODE HERE
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
*Code duplication* is not good because: - Duplicate code is hard to read/write/maintain. (Imagine what you need to do to change some code.)- The number of repetitions may not be known before runtime. Instead, programmers write a *loop* which specifies a piece of code to be executed iteratively. For Loop Iterate o...
%%mytutor -h 300 for i in 1, 2, 3, 4: print(i)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
- `i` is automatically assigned to each element in the sequence `1, 2, 3, 4` one-by-one from left to right.- After each assignment, the body `print(i)` is executed. N.b., if `i` is defined before the for loop, its value will be overwritten. The assignment is not restricted to integers and can also be a tuple assignme...
tuples = (0, "l"), (1, "o"), (2, "o"), (3, "p") for i, c in tuples: print(i, c)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
An even shorter code...
for i, c in enumerate("loop"): print(i, c)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
Iterate over a range **How to print up to a user-specified number?** We can use [`range`](https://docs.python.org/3/library/stdtypes.htmlrange):
%%mytutor -h 300 stop = int(input(">")) + 1 for i in range(stop): print(i)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
**Why add 1 to the user input number?** `range(stop)` generates a sequence of integers from `0` up to *but excluding* `stop`. **How to start from a number different from `0`?**
for i in range(1, 5): print(i)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
**What about a step size different from `1`?**
for i in range(0, 5, 2): print(i) # starting number must also be specified. Why?
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
**Exercise** How to count down from 4 to 0? Try doing it without addition or subtraction.
# YOUR CODE HERE raise NotImplementedError()
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
**Exercise** Print from `0` to a user-specified number but in steps of `0.5`. E.g., if the user inputs `2`, the program should print:```0.00.51.01.52.0```*Note:* `range` only accepts integer arguments.
%%mytutor -h 300 num = int(input(">")) # YOUR CODE HERE raise NotImplementedError()
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
**Exercise** How to print the character `'*'` repeatedly for `m` rows and `n` columns? Try using a *nested for loop*: Write a for loop (*inner loop*) inside the body of another for loop (*outer loop*).
@interact(m=(0, 10), n=(0, 10)) def draw_rectangle(m=5, n=5): # YOUR CODE HERE raise NotImplementedError()
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
Iterate over a string **What does the following do?**
%%mytutor -h 300 for character in "loop": print(character)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
`str` is a [sequence type](https://docs.python.org/3/library/stdtypes.htmltextseq) because a string is regarded as a sequence of characters.- The function [`len`](https://docs.python.org/3/library/functions.htmllen) can return the length of a string.- The indexing operator `[]` can return the character of a string at a...
message = "loop" print("length:", len(message)) print("characters:", message[0], message[1], message[2], message[3])
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
We can also iterate over a string as follows although it is less elegant:
for i in range(len("loop")): print("loop"[i])
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
**Exercise** Print a string assigned to `message` in reverse. E.g., `'loop'` should be printed as `'pool'`. Try using the for loop and indexing operator.
@interact(message="loop") def reverse_print(message): # YOUR CODE HERE raise NotImplementedError()
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
While Loop **How to ensure user input is non-empty?** Python provides the [`while` statement](https://docs.python.org/3/reference/compound_stmts.htmlwhile) to loop until a specified condition is false.
%%mytutor -h 300 while not input("Input something please:"): pass
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
As long as the condition after `while` is true, the body gets executed repeatedly. In the above example,- if user inputs nothing, - `input` returns an empty string `''`, which is [regarded as `False`](https://docs.python.org/3/reference/expressions.htmlbooleans), and so- the looping condition `not input('...')` is `Tru...
i = 0 while i <= 4: print(i) i += 1
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
- A while loop may not be as elegant, c.f., ```Python for i in range(5): print(i) ```- but it can be as efficient. **Should we just use while loop?** Consider using the following while loop to print from `0` to a user-specified value.
%%mytutor -h 310 num = int(input(">")) i = 0 while i != num + 1: print(i) i += 1
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
**Exercise** Is the above while loop doing the same thing as the for loop below?
%%mytutor -h 300 for i in range(int(input(">")) + 1): print(i)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
YOUR ANSWER HERE We have to be careful not to create unintended *infinite loops*. The computer can't always detect whether there is an infinite loop. ([Why not?](https://en.wikipedia.org/wiki/Halting_problem)) Break/Continue/Else Constructs of a Loop Breaking out of a loop **Is the following an infinite loop?**
%%mytutor -h 310 while True: message = input("Input something please:") if message: break print("You entered:", message)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
The loop is terminated by the [`break` statement](https://docs.python.org/3/tutorial/controlflow.htmlbreak-and-continue-statements-and-else-clauses-on-loops) when user input is non-empty. **Why is the `break` statement useful?** Recall the earlier `while` loop:
%%mytutor -h 300 while not input("Input something please:"): pass
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
This while loop is not useful because it does not store the user input. **Is the `break` statement strictly necessary?** - We can use the assignment expression but it is not supported by Python version <3.8. - We can avoid `break` statement by using *flags*, which are boolean variables for flow control:
%%mytutor -h 350 has_no_input = True while has_no_input: message = input("Input something please:") if message: has_no_input = False print("You entered:", message)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
Using flags makes the program more readable, and we can use multiple flags for more complicated behavior. The variable names for flags are often `is_...`, `has_...`, etc. Continue to Next Iteration **What does the following program do? Is it an infinite loop?**
%%mytutor -h 310 while True: message = input("Input something please:") if not message: continue print("You entered:", message)
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
- The program repeatedly asks the user for input.- If the input is empty, the `continue` statement will skip to the next iteration.- The loop can only be terminated by interrupting the kernel.- Such an infinite loop can be useful. E.g., your computer clock continuously updates the current time. **Exercise** Is the `con...
%%mytutor -h 350 while True: message = input("Input something please:") # YOUR CODE HERE raise NotImplementedError()
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
Else construct for a loop The following program checks whether a number is composite, namely, - a positive integer that is- a product of two strictly smaller positive integers.
@interact(num="1") def check_composite(num): if num.isdigit(): num = int(num) for divisor in range(2, num): # why starts from 2 instead of 1 if num % divisor: continue # where will this go? else: print("It is composite.") break...
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
**Exercise** There are three else claues in the earlier code. Which one is for the loop? - The second else clause that `print('It is not composite.')`.- The clause is called when there is no divisor found in the range from `2` to `num`. If program flow is confusing, try stepping through executation:
%%mytutor -h 520 def check_composite(num): if num.isdigit(): num = int(num) for divisor in range(2, num): if num % divisor: continue else: print("It is composite.") break else: print("It is not composite.") ...
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
- In addition to using `continue` and `break` in an elegant way, - the code also uses an else clause that is executed only when the loop terminates *normally* not by `break`. **Exercise** Convert the for loop to a while loop. Try to make the code as efficient as possible with less computation and storage.
@interact(num="1") def check_composite(num): if num.isdigit(): num = int(num) # YOUR CODE HERE raise NotImplementedError() else: print("Not a positive integer.")
_____no_output_____
MIT
Lecture3/Iteration.ipynb
ccha23/CS1302
Use Spark to predict credit risk with `ibm-watson-machine-learning` This notebook introduces commands for model persistance to Watson Machine Learning repository, model deployment, and scoring.Some familiarity with Python is helpful. This notebook uses Python 3.6 and Apache® Spark 2.4.You will use **German Credit Risk...
username = 'PASTE YOUR USERNAME HERE' password = 'PASTE YOUR PASSWORD HERE' url = 'PASTE THE PLATFORM URL HERE' wml_credentials = { "username": username, "password": password, "url": url, "instance_id": 'openshift', "version": '3.5' }
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
Install and import the `ibm-watson-machine-learning` package**Note:** `ibm-watson-machine-learning` documentation can be found here.
!pip install -U ibm-watson-machine-learning from ibm_watson_machine_learning import APIClient client = APIClient(wml_credentials)
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
Working with spacesFirst of all, you need to create a space that will be used for your work. If you do not have space already created, you can use `{PLATFORM_URL}/ml-runtime/spaces?context=icp4data` to create one.- Click New Deployment Space- Create an empty space- Go to space `Settings` tab- Copy `space_id` and paste...
space_id = 'PASTE YOUR SPACE ID HERE'
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
You can use `list` method to print all existing spaces.
client.spaces.list(limit=10)
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
To be able to interact with all resources available in Watson Machine Learning, you need to set **space** which you will be using.
client.set.default_space(space_id)
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
Test Spark
try: from pyspark.sql import SparkSession except: print('Error: Spark runtime is missing. If you are using Watson Studio change the notebook runtime to Spark.') raise
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
2. Load and explore data In this section you will load the data as an Apache® Spark DataFrame and perform a basic exploration. The csv file for German Credit Risk is available on the same repository as this notebook. Load the file to Apache® Spark DataFrame using code below.
import os from wget import download sample_dir = 'spark_sample_model' if not os.path.isdir(sample_dir): os.mkdir(sample_dir) filename = os.path.join(sample_dir, 'credit_risk_training.csv') if not os.path.isfile(filename): filename = download('https://github.com/IBM/watson-machine-learning-samples/raw/mast...
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
Explore the loaded data by using the following Apache® Spark DataFrame methods:- print schema- print top ten records- count all records
df_data.printSchema()
root |-- CheckingStatus: string (nullable = true) |-- LoanDuration: integer (nullable = true) |-- CreditHistory: string (nullable = true) |-- LoanPurpose: string (nullable = true) |-- LoanAmount: integer (nullable = true) |-- ExistingSavings: string (nullable = true) |-- EmploymentDuration: string (nullable = tr...
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
As you can see, the data contains 21 fields. Risk field is the one we would like to predict (label).
df_data.show(n=5, truncate=False, vertical=True) print("Number of records: " + str(df_data.count()))
Number of records: 5000
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
As you can see, the data set contains 5000 records. 2.1 Prepare dataIn this subsection you will split your data into: train, test and predict datasets.
splitted_data = df_data.randomSplit([0.8, 0.18, 0.02], 24) train_data = splitted_data[0] test_data = splitted_data[1] predict_data = splitted_data[2] print("Number of training records: " + str(train_data.count())) print("Number of testing records : " + str(test_data.count())) print("Number of prediction records : " + ...
Number of training records: 4016 Number of testing records : 881 Number of prediction records : 103
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
As you can see our data has been successfully split into three datasets: - The train data set, which is the largest group, is used for training.- The test data set will be used for model evaluation and is used to test the assumptions of the model.- The predict data set will be used for prediction. 3. Persist model ...
import os from wget import download sample_dir = 'spark_sample_model' if not os.path.isdir(sample_dir): os.mkdir(sample_dir) pipeline_filename = os.path.join(sample_dir, 'credit_risk_spark_pipeline.tar.gz') if not os.path.isfile(pipeline_filename): pipeline_filename = download('https://github.com/IBM/wats...
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
**Store piepline and model** To be able to store your Spark model, you need to provide a training data reference, this will allow to read the model schema automatically.
training_data_references = [ { "type": "fs", "connection": {}, "location": {}, "schema": { "id": "training_schema", "fields": [ { "metadat...
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
Get saved model metadata from Watson Machine Learning. **Tip**: Use `client.repository.ModelMetaNames.show()` to get the list of available props.
client.repository.ModelMetaNames.show()
------------------------ ---- -------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------...
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
3.2: Load model In this subsection you will learn how to load back saved model from specified instance of Watson Machine Learning.
loaded_model = client.repository.load(model_uid)
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
You can print for example model name to make sure that model has been loaded correctly.
print(type(loaded_model))
<class 'pyspark.ml.pipeline.PipelineModel'>
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
4. Predict locally In this section you will learn how to score test data using loaded model. 4.1: Make local prediction using previously loaded model and test data In this subsection you will score *predict_data* data set.
predictions = loaded_model.transform(predict_data)
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
Preview the results by calling the *show()* method on the predictions DataFrame.
predictions.show(5)
+--------------+------------+--------------------+-----------+----------+---------------+------------------+------------------+------+------------+------------------------+------------+---+----------------+-------+--------------------+----------+----------+---------+-------------+-------+-----------------+-------------...
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
By tabulating a count, you can see which product line is the most popular.
predictions.select("predictedLabel").groupBy("predictedLabel").count().show(truncate=False)
+--------------+-----+ |predictedLabel|count| +--------------+-----+ |No Risk |82 | |Risk |21 | +--------------+-----+
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
5. Deploy and score In this section you will learn how to create online scoring and to score a new data record using `ibm-watson-machine-learning`. **Note:** You can also use REST API to deploy and score.For more information about REST APIs, see the [Swagger Documentation](https://watson-ml-v4-api.mybluemix.net/wml-re...
deployment_details = client.deployments.create( model_uid, meta_props={ client.deployments.ConfigurationMetaNames.NAME: "Credit Risk model deployment", client.deployments.ConfigurationMetaNames.ONLINE: {} } ) deployment_details
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples