分类问题

逻辑回归,随机梯度下降

In [1]:
#案例:肿瘤细胞
# 导入pandas与numpy工具包
import pandas as pd
import numpy as np

# 创建特征列表
column_names = ['Sample code number',
                'Clump Thickness',
                'Uniformity of Cell Size',
               'Uniformity of Cell Shape',
               'Marginal Nucleoli',
                'Single Epithelial Cell Size',
                'Bare Nuclei',
                'Bland Chromatin',
                'Normal Nucleoli',
               'Mitoses',
               'Class']

# 从互联网读取指定数据
data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data', 
                   names=column_names)

# 预处理-转换‘?’为缺失值
data = data.replace(to_replace='?', value=np.nan)
# 预处理-丢弃缺失值
data = data.dropna(how='any')
# 检查
data.shape
Out[1]:
(683, 11)
In [2]:
data.head()
Out[2]:
Sample code number Clump Thickness Uniformity of Cell Size Uniformity of Cell Shape Marginal Nucleoli Single Epithelial Cell Size Bare Nuclei Bland Chromatin Normal Nucleoli Mitoses Class
0 1000025 5 1 1 1 2 1 3 1 1 2
1 1002945 5 4 4 5 7 10 3 2 1 2
2 1015425 3 1 1 1 2 2 3 1 1 2
3 1016277 6 8 8 1 3 4 3 7 1 2
4 1017023 4 1 1 3 2 1 3 1 1 2
In [6]:
# 分割训练集和测试集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(data[column_names[1:10]], data[column_names[10]], 
                                                    test_size=0.25, random_state=33)
In [8]:
y_train.value_counts()
Out[8]:
2    344
4    168
Name: Class, dtype: int64
In [9]:
y_test.value_counts()
Out[9]:
2    100
4     71
Name: Class, dtype: int64
In [11]:
# 导入模型库
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
In [13]:
# 标准化数据
ss = StandardScaler()
x_train = ss.fit_transform(x_train)
x_test = ss.transform(x_test)
In [17]:
# 训练和预测
# 逻辑回归模型
lr = LogisticRegression()
lr.fit(x_train, y_train)
lr_y_predict = lr.predict(x_test)

# 随机梯度下降模型
sgdc = SGDClassifier()
sgdc.fit(x_train, y_train)
sgdc_y_predict = sgdc.predict(x_test)
In [18]:
# 性能测评
from sklearn.metrics import classification_report
# LR
print 'Accuracy of LR Classifier:', lr.score(x_test, y_test)
print classification_report(y_test, lr_y_predict, target_names=['Benign', 'Malignant'])
Accuracy of LR Classifier: 0.988304093567
              precision    recall  f1-score   support

      Benign       0.99      0.99      0.99       100
   Malignant       0.99      0.99      0.99        71

   micro avg       0.99      0.99      0.99       171
   macro avg       0.99      0.99      0.99       171
weighted avg       0.99      0.99      0.99       171

In [19]:
# SGD
print 'Accuracy of SGD Classifier is:', sgdc.score(x_test, y_test)
print classification_report(y_test, sgdc_y_predict, target_names=['Benign', 'Malignant'])
Accuracy of SGD Classifier is: 0.93567251462
              precision    recall  f1-score   support

      Benign       0.92      0.98      0.95       100
   Malignant       0.97      0.87      0.92        71

   micro avg       0.94      0.94      0.94       171
   macro avg       0.94      0.93      0.93       171
weighted avg       0.94      0.94      0.94       171

支持向量机

In [24]:
#手写数字识别
# 从数据库里导入手写体数字加载器
from sklearn.datasets import load_digits
digits = load_digits()
digits.data.shape
Out[24]:
(1797L, 64L)
In [25]:
# 分割训练集和测试集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.25, random_state=33)

y_train.shape
Out[25]:
(1347L,)
In [26]:
y_test.shape
Out[26]:
(450L,)
In [27]:
# 调用模型
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC
# 标准化
ss = StandardScaler()
x_train = ss.fit_transform(x_train)
x_test = ss.transform(x_test)

lsvc = LinearSVC()
lsvc.fit(x_train, y_train)
y_predict = lsvc.predict(x_test)
In [29]:
# 性能测评
print 'The Accuracy of Linear SVC is:', lsvc.score(x_test, y_test)

from sklearn.metrics import classification_report
print classification_report(y_test, y_predict, target_names=digits.target_names.astype(str))
The Accuracy of Linear SVC is: 0.953333333333
              precision    recall  f1-score   support

           0       0.92      1.00      0.96        35
           1       0.96      0.98      0.97        54
           2       0.98      1.00      0.99        44
           3       0.93      0.93      0.93        46
           4       0.97      1.00      0.99        35
           5       0.94      0.94      0.94        48
           6       0.96      0.98      0.97        51
           7       0.92      1.00      0.96        35
           8       0.98      0.84      0.91        58
           9       0.95      0.91      0.93        44

   micro avg       0.95      0.95      0.95       450
   macro avg       0.95      0.96      0.95       450
weighted avg       0.95      0.95      0.95       450

朴素贝叶斯

In [30]:
#新闻文本分类
# 从数据库里导入新闻数据抓取器
from sklearn.datasets import fetch_20newsgroups
news=fetch_20newsgroups(subset='all')
print len(news.data)
print news.data[0]
Downloading 20news dataset. This may take a few minutes.
Downloading dataset from https://ndownloader.figshare.com/files/5975967 (14 MB)
18846
From: Mamatha Devineni Ratnam <mr47+@andrew.cmu.edu>
Subject: Pens fans reactions
Organization: Post Office, Carnegie Mellon, Pittsburgh, PA
Lines: 12
NNTP-Posting-Host: po4.andrew.cmu.edu



I am sure some bashers of Pens fans are pretty confused about the lack
of any kind of posts about the recent Pens massacre of the Devils. Actually,
I am  bit puzzled too and a bit relieved. However, I am going to put an end
to non-PIttsburghers' relief with a bit of praise for the Pens. Man, they
are killing those Devils worse than I thought. Jagr just showed you why
he is much better than his regular season stats. He is also a lot
fo fun to watch in the playoffs. Bowman should let JAgr have a lot of
fun in the next couple of games since the Pens are going to beat the pulp out of Jersey anyway. I was very disappointed not to see the Islanders lose the final
regular season game.          PENS RULE!!!


In [41]:
# 查看数据说明
print digits.DESCR
.. _digits_dataset:

Optical recognition of handwritten digits dataset
--------------------------------------------------

**Data Set Characteristics:**

    :Number of Instances: 5620
    :Number of Attributes: 64
    :Attribute Information: 8x8 image of integer pixels in the range 0..16.
    :Missing Attribute Values: None
    :Creator: E. Alpaydin (alpaydin '@' boun.edu.tr)
    :Date: July; 1998

This is a copy of the test set of the UCI ML hand-written digits datasets
http://archive.ics.uci.edu/ml/datasets/Optical+Recognition+of+Handwritten+Digits

The data set contains images of hand-written digits: 10 classes where
each class refers to a digit.

Preprocessing programs made available by NIST were used to extract
normalized bitmaps of handwritten digits from a preprinted form. From a
total of 43 people, 30 contributed to the training set and different 13
to the test set. 32x32 bitmaps are divided into nonoverlapping blocks of
4x4 and the number of on pixels are counted in each block. This generates
an input matrix of 8x8 where each element is an integer in the range
0..16. This reduces dimensionality and gives invariance to small
distortions.

For info on NIST preprocessing routines, see M. D. Garris, J. L. Blue, G.
T. Candela, D. L. Dimmick, J. Geist, P. J. Grother, S. A. Janet, and C.
L. Wilson, NIST Form-Based Handprint Recognition System, NISTIR 5469,
1994.

.. topic:: References

  - C. Kaynak (1995) Methods of Combining Multiple Classifiers and Their
    Applications to Handwritten Digit Recognition, MSc Thesis, Institute of
    Graduate Studies in Science and Engineering, Bogazici University.
  - E. Alpaydin, C. Kaynak (1998) Cascading Classifiers, Kybernetika.
  - Ken Tang and Ponnuthurai N. Suganthan and Xi Yao and A. Kai Qin.
    Linear dimensionalityreduction using relevance weighted LDA. School of
    Electrical and Electronic Engineering Nanyang Technological University.
    2005.
  - Claudio Gentile. A New Approximate Maximal Margin Classification
    Algorithm. NIPS. 2000.
In [33]:
# 分割为训练集和测试集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(news.data, news.target, test_size=0.25, random_state=33)
In [34]:
# 预处理-文本转向量
from sklearn.feature_extraction.text import CountVectorizer
vec = CountVectorizer()
x_train = vec.fit_transform(x_train)
x_test = vec.transform(x_test)
In [36]:
# 调用模型
from sklearn.naive_bayes import MultinomialNB
mnb = MultinomialNB()
mnb.fit(x_train, y_train)
y_predict = mnb.predict(x_test)
In [38]:
# 性能测评
from sklearn.metrics import classification_report
print 'The accruracy of Naive Bayes Classifier is', mnb.score(x_test, y_test)
print classification_report(y_test, y_predict, target_names=news.target_names)
The accruracy of Naive Bayes Classifier is 0.839770797963
                          precision    recall  f1-score   support

             alt.atheism       0.86      0.86      0.86       201
           comp.graphics       0.59      0.86      0.70       250
 comp.os.ms-windows.misc       0.89      0.10      0.17       248
comp.sys.ibm.pc.hardware       0.60      0.88      0.72       240
   comp.sys.mac.hardware       0.93      0.78      0.85       242
          comp.windows.x       0.82      0.84      0.83       263
            misc.forsale       0.91      0.70      0.79       257
               rec.autos       0.89      0.89      0.89       238
         rec.motorcycles       0.98      0.92      0.95       276
      rec.sport.baseball       0.98      0.91      0.95       251
        rec.sport.hockey       0.93      0.99      0.96       233
               sci.crypt       0.86      0.98      0.91       238
         sci.electronics       0.85      0.88      0.86       249
                 sci.med       0.92      0.94      0.93       245
               sci.space       0.89      0.96      0.92       221
  soc.religion.christian       0.78      0.96      0.86       232
      talk.politics.guns       0.88      0.96      0.92       251
   talk.politics.mideast       0.90      0.98      0.94       231
      talk.politics.misc       0.79      0.89      0.84       188
      talk.religion.misc       0.93      0.44      0.60       158

               micro avg       0.84      0.84      0.84      4712
               macro avg       0.86      0.84      0.82      4712
            weighted avg       0.86      0.84      0.82      4712

K邻近(分类)

In [1]:
# 植物分类
# 导入数据加载器
from sklearn.datasets import load_iris
iris = load_iris()
iris.data.shape
Out[1]:
(150L, 4L)
In [2]:
print iris.DESCR
.. _iris_dataset:

Iris plants dataset
--------------------

**Data Set Characteristics:**

    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class
    :Attribute Information:
        - sepal length in cm
        - sepal width in cm
        - petal length in cm
        - petal width in cm
        - class:
                - Iris-Setosa
                - Iris-Versicolour
                - Iris-Virginica
                
    :Summary Statistics:

    ============== ==== ==== ======= ===== ====================
                    Min  Max   Mean    SD   Class Correlation
    ============== ==== ==== ======= ===== ====================
    sepal length:   4.3  7.9   5.84   0.83    0.7826
    sepal width:    2.0  4.4   3.05   0.43   -0.4194
    petal length:   1.0  6.9   3.76   1.76    0.9490  (high!)
    petal width:    0.1  2.5   1.20   0.76    0.9565  (high!)
    ============== ==== ==== ======= ===== ====================

    :Missing Attribute Values: None
    :Class Distribution: 33.3% for each of 3 classes.
    :Creator: R.A. Fisher
    :Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
    :Date: July, 1988

The famous Iris database, first used by Sir R.A. Fisher. The dataset is taken
from Fisher's paper. Note that it's the same as in R, but not as in the UCI
Machine Learning Repository, which has two wrong data points.

This is perhaps the best known database to be found in the
pattern recognition literature.  Fisher's paper is a classic in the field and
is referenced frequently to this day.  (See Duda & Hart, for example.)  The
data set contains 3 classes of 50 instances each, where each class refers to a
type of iris plant.  One class is linearly separable from the other 2; the
latter are NOT linearly separable from each other.

.. topic:: References

   - Fisher, R.A. "The use of multiple measurements in taxonomic problems"
     Annual Eugenics, 7, Part II, 179-188 (1936); also in "Contributions to
     Mathematical Statistics" (John Wiley, NY, 1950).
   - Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.
     (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.
   - Dasarathy, B.V. (1980) "Nosing Around the Neighborhood: A New System
     Structure and Classification Rule for Recognition in Partially Exposed
     Environments".  IEEE Transactions on Pattern Analysis and Machine
     Intelligence, Vol. PAMI-2, No. 1, 67-71.
   - Gates, G.W. (1972) "The Reduced Nearest Neighbor Rule".  IEEE Transactions
     on Information Theory, May 1972, 431-433.
   - See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al"s AUTOCLASS II
     conceptual clustering system finds 3 classes in the data.
   - Many, many more ...
In [3]:
# 预处理:分割训练集和测试集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.25, random_state=33)
In [6]:
# 调用模型-标准化
from sklearn.preprocessing import StandardScaler
ss = StandardScaler()
x_train = ss.fit_transform(x_train)
x_test = ss.transform(x_test)
In [8]:
# 调用模型-分析,预测
from sklearn.neighbors import KNeighborsClassifier
knc = KNeighborsClassifier()
knc.fit(x_train, y_train)
y_predict = knc.predict(x_test)
In [13]:
# 性能测评
print 'The accuracy of K-Nearest Neighbor Classifier is:', knc.score(x_test, y_test)
from sklearn.metrics import classification_report
print classification_report(y_test, y_predict, target_names=iris.target_names)
The accuracy of K-Nearest Neighbor Classifier is: 0.894736842105
              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00         8
  versicolor       0.73      1.00      0.85        11
   virginica       1.00      0.79      0.88        19

   micro avg       0.89      0.89      0.89        38
   macro avg       0.91      0.93      0.91        38
weighted avg       0.92      0.89      0.90        38

决策树

In [24]:
# titanic生存预测
# 从互联网导入数据
import pandas as pd
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
titanic.head()
Out[24]:
row.names pclass survived name age embarked home.dest room ticket boat sex
0 1 1st 1 Allen, Miss Elisabeth Walton 29.0000 Southampton St Louis, MO B-5 24160 L221 2 female
1 2 1st 0 Allison, Miss Helen Loraine 2.0000 Southampton Montreal, PQ / Chesterville, ON C26 NaN NaN female
2 3 1st 0 Allison, Mr Hudson Joshua Creighton 30.0000 Southampton Montreal, PQ / Chesterville, ON C26 NaN (135) male
3 4 1st 0 Allison, Mrs Hudson J.C. (Bessie Waldo Daniels) 25.0000 Southampton Montreal, PQ / Chesterville, ON C26 NaN NaN female
4 5 1st 1 Allison, Master Hudson Trevor 0.9167 Southampton Montreal, PQ / Chesterville, ON C22 NaN 11 male
In [25]:
# 预处理:查看数据
titanic.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1313 entries, 0 to 1312
Data columns (total 11 columns):
row.names    1313 non-null int64
pclass       1313 non-null object
survived     1313 non-null int64
name         1313 non-null object
age          633 non-null float64
embarked     821 non-null object
home.dest    754 non-null object
room         77 non-null object
ticket       69 non-null object
boat         347 non-null object
sex          1313 non-null object
dtypes: float64(1), int64(2), object(8)
memory usage: 112.9+ KB
In [26]:
# 选择特征
x = titanic[['pclass', 'age', 'sex']]
y = titanic['survived']
x.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1313 entries, 0 to 1312
Data columns (total 3 columns):
pclass    1313 non-null object
age       633 non-null float64
sex       1313 non-null object
dtypes: float64(1), object(2)
memory usage: 30.8+ KB
In [27]:
# 预处理:age:使用平均值填充
x['age'].fillna(x['age'].mean(), inplace=True)
x.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1313 entries, 0 to 1312
Data columns (total 3 columns):
pclass    1313 non-null object
age       1313 non-null float64
sex       1313 non-null object
dtypes: float64(1), object(2)
memory usage: 30.8+ KB
In [28]:
# 预处理:分割训练集和测试集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=33)
In [29]:
# 预处理:无论类别数据还是数值数据,都使用特征转换器(数值型特征将被略过)
from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer()
x_train = vec.fit_transform(x_train.to_dict(orient='record'))
x_test = vec.transform(x_test.to_dict(orient='record'))
In [31]:
print vec.feature_names_
['age', 'pclass=1st', 'pclass=2nd', 'pclass=3rd', 'sex=female', 'sex=male']
In [32]:
# 调用模型
from sklearn.tree import DecisionTreeClassifier
dtc = DecisionTreeClassifier()
dtc.fit(x_train, y_train)
y_predict = dtc.predict(x_test)
In [37]:
# 性能测试
print 'The accuracy of Decision Tree Classifier is:', dtc.score(x_test, y_test)
from sklearn.metrics import classification_report
print classification_report(y_test, y_predict, target_names=['died', 'survived'])
The accuracy of Decision Tree Classifier is: 0.781155015198
              precision    recall  f1-score   support

        died       0.78      0.91      0.84       202
    survived       0.80      0.58      0.67       127

   micro avg       0.78      0.78      0.78       329
   macro avg       0.79      0.74      0.75       329
weighted avg       0.78      0.78      0.77       329

集成模型(分类)

随机森林,梯度提升决策树

In [46]:
# titanic
# 读取数据
import pandas as pd
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
# 预处理:选择特征
x = titanic[['age', 'pclass', 'sex']]
y = titanic['survived']
# 预处理:age:缺失值用平均值填充
x['age'].fillna(x['age'].mean(), inplace=True)
# 预处理:分割训练集和测试集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=33)
# 预处理:特征转换
from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer()
x_train = vec.fit_transform(x_train.to_dict(orient='record'))
x_test = vec.transform(x_test.to_dict(orient='record'))
# 调用模型:随机森林
from sklearn.ensemble import RandomForestClassifier
rfc = RandomForestClassifier()
rfc.fit(x_train, y_train)
rfc_y_predict = rfc.predict(x_test)
# 调用模型:梯度提升决策树
from sklearn.ensemble import GradientBoostingClassifier
gbc = GradientBoostingClassifier()
gbc.fit(x_train, y_train)
gbc_y_predict = gbc.predict(x_test)
# 性能测试
from sklearn.metrics import classification_report
print 'The accruracy of Random Forest Classifier is', rfc.score(x_test, y_test)
print classification_report(y_test, rfc_y_predict)
print 'The accruracy of Gradient tree Boosting is', gbc.score(x_test, y_test)
print classification_report(y_test, gbc_y_predict)
The accruracy of Random Forest Classifier is 0.784194528875
              precision    recall  f1-score   support

           0       0.78      0.90      0.84       202
           1       0.79      0.60      0.68       127

   micro avg       0.78      0.78      0.78       329
   macro avg       0.79      0.75      0.76       329
weighted avg       0.79      0.78      0.78       329

The accruracy of Gradient tree Boosting is 0.790273556231
              precision    recall  f1-score   support

           0       0.78      0.92      0.84       202
           1       0.82      0.58      0.68       127

   micro avg       0.79      0.79      0.79       329
   macro avg       0.80      0.75      0.76       329
weighted avg       0.80      0.79      0.78       329