1、数据获取
#引入文件处理包 pandas 与 numpy
import numpy as np
import pandas as pd
#pandas 读取数据
cancer = pd.read_excel("G:/07Python/classes/breast-cancer.xlsx")
2、数据处理
pd.set_option('display.max_columns', None) #显示所有的列
print(cancer.columns)
print(cancer.head(5))
cancer.shape
cancer['class'].value_counts()
#引入图库
import seaborn as sns
import matplotlib.pyplot as plt
for col in cancer.columns:
#画布大小设置
plt.figure(figsize=(10,3))
sns.barplot(cancer[col].value_counts().values,cancer[col].value_counts().index)
plt.title(col)
plt.tight_layout()
plt.show()
#查看某一列中的信息
cancer['breast-quad'].value_counts()
#查看某一列缺失的异常信息
cancer[cancer['breast-quad']=='?']
#某一列中包含的异常信息少,可考虑删除
cancer=cancer[cancer['breast-quad']!='?']
#某一列中包含的异常信息多,单独作为一类考虑保留
cancer['node-caps']=np.where(cancer['node-caps']=='?','unknown',cancer['node-caps'])
#情况一
cancer['age_new']=np.where(cancer['age'].isin(['20-29','30-39']),'20-39',cancer['age'])
#情况二
cancer['tumor_size_new']=np.where(cancer['tumor-size'].isin(['0-4','5-9']),'0-9',
np.where(cancer['tumor-size'].isin(['45-49','50-54']),'45-54',cancer['tumor-size']))
- 使用LabelEncoder对分类型特征值进行编码,即对不连续的数值或文本进行编码;
对lable编码的。比如label是一串地名,是无法直接输入到sklearn的分类模型里作为训练标签的,所以需要先把地名转成数字。
from sklearn.preprocessing import LabelEncoder
#对分类型特征值进行编码
X=cancer[cancer.columns[2:11]]
Y=cancer['class']
X=X.apply(LabelEncoder().fit_transform)
Y=LabelEncoder().fit_transform(Y)
- 可以通过热力图查看这个特征之间的关联性,进行特征降维
feature=list(X.columns[2:11])
print(feature)
corr = X[feature].corr()
plt.figure(figsize=(14,14))
# annot=True显示每个方格的数据
sns.heatmap(corr, annot=True)
from sklearn.model_selection import train_test_split
# 抽取30%的数据作为测试集,其余作为训练集
x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.25,random_state=42)
from sklearn.preprocessing import StandardScaler
# 采用Z-Score规范化数据,保证每个特征维度的数据均值为0,方差为1
ss = StandardScaler()
train_X = ss.fit_transform(x_train)
test_X = ss.transform(x_test)
from sklearn import svm
from sklearn import metrics
# 创建SVM分类器
model = svm.SVC()
# 用训练集做训练
model.fit(train_X,y_train)
# 用测试集做预测
prediction=model.predict(test_X)
print('准确率: ', metrics.accuracy_score(y_test,prediction))