0%

Coursera | Applied Machine Learning in Python(University of Michigan)| Assignment1

   所有quiz和assignment链接:
  Coursera | Applied Machine Learning in Python(University of Michigan)| Quiz
  Coursera | Applied Machine Learning in Python(University of Michigan)| Assignment1
  Coursera | Applied Machine Learning in Python(University of Michigan)| Assignment2
  Coursera | Applied Machine Learning in Python(University of Michigan)| Assignment3
  Coursera | Applied Machine Learning in Python(University of Michigan)| Assignment4


You are currently looking at version 1.1 of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the Jupyter Notebook FAQ course resource.


Assignment 1 - Introduction to Machine Learning

For this assignment, you will be using the Breast Cancer Wisconsin (Diagnostic) Database to create a classifier that can help diagnose patients. First, read through the description of the dataset (below).

1
2
3
4
5
6
7
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer

cancer = load_breast_cancer()

#print(cancer.DESCR) # Print the data set description

The object returned by load_breast_cancer() is a scikit-learn Bunch object, which is similar to a dictionary.

1
cancer.keys()
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename'])

Question 0 (Example)

How many features does the breast cancer dataset have?

This function should return an integer.

1
2
3
4
5
6
7
8
9
10
# You should write your whole answer within the function provided. The autograder will call
# this function and compare the return value against the correct solution value
def answer_zero():
# This function returns the number of features of the breast cancer dataset, which is an integer.
# The assignment question description will tell you the general format the autograder is expecting
return len(cancer['feature_names'])

# You can examine what your function returns by calling it in the cell. If you have questions
# about the assignment formats, check out the discussion forums for any FAQs
answer_zero()
30

Question 1

Scikit-learn works with lists, numpy arrays, scipy-sparse matrices, and pandas DataFrames, so converting the dataset to a DataFrame is not necessary for training this model. Using a DataFrame does however help make many things easier such as munging data, so let’s practice creating a classifier with a pandas DataFrame.

Convert the sklearn.dataset cancer to a DataFrame.

*This function should return a (569, 31) DataFrame with *

*columns = *

['mean radius', 'mean texture', 'mean perimeter', 'mean area',
'mean smoothness', 'mean compactness', 'mean concavity',
'mean concave points', 'mean symmetry', 'mean fractal dimension',
'radius error', 'texture error', 'perimeter error', 'area error',
'smoothness error', 'compactness error', 'concavity error',
'concave points error', 'symmetry error', 'fractal dimension error',
'worst radius', 'worst texture', 'worst perimeter', 'worst area',
'worst smoothness', 'worst compactness', 'worst concavity',
'worst concave points', 'worst symmetry', 'worst fractal dimension',
'target']

*and index = *

RangeIndex(start=0, stop=569, step=1)
1
2
3
4
5
6
7
8
9
def answer_one():

df = pd.DataFrame(cancer.data, columns=cancer.feature_names)
df['target'] = cancer.target

return df


answer_one()

mean radiusmean texturemean perimetermean areamean smoothnessmean compactnessmean concavitymean concave pointsmean symmetrymean fractal dimension...worst textureworst perimeterworst areaworst smoothnessworst compactnessworst concavityworst concave pointsworst symmetryworst fractal dimensiontarget
017.9910.38122.801001.00.118400.277600.300100.147100.24190.07871...17.33184.602019.00.162200.665600.71190.26540.46010.118900
120.5717.77132.901326.00.084740.078640.086900.070170.18120.05667...23.41158.801956.00.123800.186600.24160.18600.27500.089020
219.6921.25130.001203.00.109600.159900.197400.127900.20690.05999...25.53152.501709.00.144400.424500.45040.24300.36130.087580
311.4220.3877.58386.10.142500.283900.241400.105200.25970.09744...26.5098.87567.70.209800.866300.68690.25750.66380.173000
420.2914.34135.101297.00.100300.132800.198000.104300.18090.05883...16.67152.201575.00.137400.205000.40000.16250.23640.076780
..................................................................
56421.5622.39142.001479.00.111000.115900.243900.138900.17260.05623...26.40166.102027.00.141000.211300.41070.22160.20600.071150
56520.1328.25131.201261.00.097800.103400.144000.097910.17520.05533...38.25155.001731.00.116600.192200.32150.16280.25720.066370
56616.6028.08108.30858.10.084550.102300.092510.053020.15900.05648...34.12126.701124.00.113900.309400.34030.14180.22180.078200
56720.6029.33140.101265.00.117800.277000.351400.152000.23970.07016...39.42184.601821.00.165000.868100.93870.26500.40870.124000
5687.7624.5447.92181.00.052630.043620.000000.000000.15870.05884...30.3759.16268.60.089960.064440.00000.00000.28710.070391

569 rows × 31 columns

Question 2

What is the class distribution? (i.e. how many instances of malignant (encoded 0) and how many benign (encoded 1)?)

This function should return a Series named target of length 2 with integer values and index = ['malignant', 'benign']

1
2
3
4
5
6
7
8
9
10
11
12
def answer_two():
cancerdf = answer_one()

malignant = cancerdf[cancerdf['target'] == 0]
benign = cancerdf[cancerdf['target'] == 1]



return pd.Series({'malignant': len(malignant), 'benign': len(benign)})


answer_two()
malignant    212
benign       357
dtype: int64

Question 3

Split the DataFrame into X (the data) and y (the labels).

This function should return a tuple of length 2: (X, y), where

  • X has shape (569, 30)
  • y has shape (569,).
1
2
3
4
5
6
7
def answer_three():
cancerdf = answer_one()

X = cancerdf[cancer['feature_names']]
y = cancerdf['target']

return X, y
1
2
3
X, y = answer_three()
print(X.shape)
print(y.shape)
(569, 30)
(569,)

Question 4

Using train_test_split, split X and y into training and test sets (X_train, X_test, y_train, and y_test).

Set the random number generator state to 0 using random_state=0 to make sure your results match the autograder!

This function should return a tuple of length 4: (X_train, X_test, y_train, y_test), where

  • X_train has shape (426, 30)
  • X_test has shape (143, 30)
  • y_train has shape (426,)
  • y_test has shape (143,)
1
2
3
4
5
6
7
8
from sklearn.model_selection import train_test_split

def answer_four():
X, y = answer_three()

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0)

return X_train, X_test, y_train, y_test
1
2
3
4
5
X_train, X_test, y_train, y_test=answer_four()
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
(426, 30)
(143, 30)
(426,)
(143,)

Question 5

Using KNeighborsClassifier, fit a k-nearest neighbors (knn) classifier with X_train, y_train and using one nearest neighbor (n_neighbors = 1).

*This function should return a * sklearn.neighbors.classification.KNeighborsClassifier.

1
2
3
4
5
6
7
8
from sklearn.neighbors import KNeighborsClassifier

def answer_five():
X_train, X_test, y_train, y_test = answer_four()
knn = KNeighborsClassifier(n_neighbors = 1)
knn.fit(X_train, y_train)

return knn

Question 6

Using your knn classifier, predict the class label using the mean value for each feature.

Hint: You can use cancerdf.mean()[:-1].values.reshape(1, -1) which gets the mean value for each feature, ignores the target column, and reshapes the data from 1 dimension to 2 (necessary for the precict method of KNeighborsClassifier).

This function should return a numpy array either array([ 0.]) or array([ 1.])

1
2
3
4
5
6
7
8
9
def answer_six():
cancerdf = answer_one()
means = cancerdf.mean()[:-1].values.reshape(1, -1)

knn = answer_five()

predict_ = knn.predict(means)

return predict_
1
answer_six()
array([1])

Question 7

Using your knn classifier, predict the class labels for the test set X_test.

This function should return a numpy array with shape (143,) and values either 0.0 or 1.0.

1
2
3
4
5
6
7
def answer_seven():
X_train, X_test, y_train, y_test = answer_four()
knn = answer_five()

predict_ = knn.predict(X_test)

return predict_
1
2
3
predict_X_test=answer_seven()
print(predict_X_test.shape)
set(predict_X_test)
(143,)

{0, 1}

Question 8

Find the score (mean accuracy) of your knn classifier using X_test and y_test.

This function should return a float between 0 and 1

1
2
3
4
5
6
7
def answer_eight():
X_train, X_test, y_train, y_test = answer_four()
knn = answer_five()

score = knn.score(X_test, y_test)

return score
1
answer_eight()
0.916083916083916

Optional plot

Try using the plotting function below to visualize the differet predicition scores between training and test sets, as well as malignant and benign cells.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def accuracy_plot():
import matplotlib.pyplot as plt

%matplotlib notebook

X_train, X_test, y_train, y_test = answer_four()

# Find the training and testing accuracies by target value (i.e. malignant, benign)
mal_train_X = X_train[y_train==0]
mal_train_y = y_train[y_train==0]
ben_train_X = X_train[y_train==1]
ben_train_y = y_train[y_train==1]

mal_test_X = X_test[y_test==0]
mal_test_y = y_test[y_test==0]
ben_test_X = X_test[y_test==1]
ben_test_y = y_test[y_test==1]

knn = answer_five()

scores = [knn.score(mal_train_X, mal_train_y), knn.score(ben_train_X, ben_train_y),
knn.score(mal_test_X, mal_test_y), knn.score(ben_test_X, ben_test_y)]


plt.figure()

# Plot the scores as a bar chart
bars = plt.bar(np.arange(4), scores, color=['#4c72b0','#4c72b0','#55a868','#55a868'])

# directly label the score onto the bars
for bar in bars:
height = bar.get_height()
plt.gca().text(bar.get_x() + bar.get_width()/2, height*.90, '{0:.{1}f}'.format(height, 2),
ha='center', color='w', fontsize=11)

# remove all the ticks (both axes), and tick labels on the Y axis
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

# remove the frame of the chart
for spine in plt.gca().spines.values():
spine.set_visible(False)

plt.xticks([0,1,2,3], ['Malignant\nTraining', 'Benign\nTraining', 'Malignant\nTest', 'Benign\nTest'], alpha=0.8);
plt.title('Training and Test Accuracies for Malignant and Benign Cells', alpha=0.8)
1
2
3
4
# Uncomment the plotting function to see the visualization, 
# Comment out the plotting function when submitting your notebook for grading

accuracy_plot()

------------------   The End    Thanks for reading   ------------------