从 np.arange(5) 产生一个标准分布、size为 3、没有重复替换的随机采样:
>>> np.random.choice(5, 3, replace=False)
array([3,1,0])
>>> #This is equivalent to np.random.permutation(np.arange(5))[:3]
fpr,tpr,thresholds=roc_curve(y_test,y[:,1])fpr,tpr,thresholds=roc_curve(y_test,y[:,1])
#coding:utf-8
print(__doc__)
import numpy as np
from scipy import interp
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import StratifiedKFold
###############################################################################
# Data IO and generation,导入iris数据,做数据准备
# import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target
X, y = X[y != 2], y[y != 2]
n_samples, n_features = X.shape
# Add noisy features
random_state = np.random.RandomState(0)
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]
###############################################################################
# Classification and ROC analysis
#分类,做ROC分析
# Run classifier with cross-validation and plot ROC curves
#使用6折交叉验证,并且画ROC曲线
cv = StratifiedKFold(y, n_folds=6)
classifier = svm.SVC(kernel='linear', probability=True,
random_state=random_state)
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
all_tpr = []
for i, (train, test) in enumerate(cv):
print test
#通过训练数据,使用svm线性核建立模型,并对测试集进行测试,求出预测得分
probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])
# Compute ROC curve and area the curve
#通过roc_curve()函数,求出fpr和tpr,以及阈值
fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])
mean_tpr += interp(mean_fpr, fpr, tpr) #对mean_tpr在mean_fpr处进行插值,通过scipy包调用interp()函数
mean_tpr[0] = 0.0 #初始处为0
roc_auc = auc(fpr, tpr)
#画图,只需要plt.plot(fpr,tpr),变量roc_auc只是记录auc的值,通过auc()函数能计算出来
plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc))
#画对角线
plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck')
mean_tpr /= len(cv) #在mean_fpr100个点,每个点处插值插值多次取平均
mean_tpr[-1] = 1.0 #坐标最后一个点为(1,1)
mean_auc = auc(mean_fpr, mean_tpr) #计算平均AUC值
#画平均ROC曲线
#print mean_fpr,len(mean_fpr)
#print mean_tpr
plt.plot(mean_fpr, mean_tpr, 'k--',
label='Mean ROC (area = %0.2f)' % mean_auc, lw=2)
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic example')
plt.legend(loc="lower right")
plt.show()
原
Python数据可视化—seaborn简介和实例
Seaborn其实是在matplotlib的基础上进行了更高级的API封装,从而使得作图更加容易,在大多数情况下使用seaborn就能做出很具有吸引力的图。这里实例采用的数据集都是seaborn提供的几个经典数据集,dataset文件可见于Github。本博客只总结了一些,方便博主自己查询,详细介绍可以看seaborn官方API和example gallery,官方文档还是写的很好的。
1 set_style( ) set( )
set_style( )是用来设置主题的,Seaborn有五个预设好的主题: darkgrid , whitegrid , dark , white ,和 ticks 默认: darkgrid
-
import matplotlib.pyplot
as plt
-
import seaborn
as sns
-
sns.set_style(
“whitegrid”)
-
plt.plot(np.arange(
10))
-
plt.show()
set( )通过设置参数可以用来设置背景,调色板等,更加常用。
-
import seaborn
as sns
-
import matplotlib.pyplot
as plt
-
sns.set(style=
"white", palette=
"muted", color_codes=
True)
#set( )设置主题,调色板更常用
-
plt.plot(np.arange(
10))
-
plt.show()
2 distplot( ) kdeplot( )
distplot( )为hist加强版,kdeplot( )为密度曲线图
-
import matplotlib.pyplot
as plt
-
import seaborn
as sns
-
df_iris = pd.read_csv(
'../input/iris.csv')
-
fig, axes = plt.subplots(
1,
2)
-
sns.distplot(df_iris[
'petal length'], ax = axes[
0], kde =
True, rug =
True)
# kde 密度曲线 rug 边际毛毯
-
sns.kdeplot(df_iris[
'petal length'], ax = axes[
1], shade=
True)
# shade 阴影
-
plt.show()
-
import numpy
as np
-
import seaborn
as sns
-
import matplotlib.pyplot
as plt
-
sns.set( palette=
“muted”, color_codes=
True)
-
rs = np.random.RandomState(
10)
-
d = rs.normal(size=
100)
-
f, axes = plt.subplots(
2,
2, figsize=(
7,
7), sharex=
True)
-
sns.distplot(d, kde=
False, color=
“b”, ax=axes[
0,
0])
-
sns.distplot(d, hist=
False, rug=
True, color=
“r”, ax=axes[
0,
1])
-
sns.distplot(d, hist=
False, color=
“g”, kde_kws={
“shade”:
True}, ax=axes[
1,
0])
-
sns.distplot(d, color=
“m”, ax=axes[
1,
1])
-
plt.show()
3 箱型图 boxplot( )
-
import matplotlib.pyplot
as plt
-
import seaborn
as sns
-
df_iris = pd.read_csv(
'../input/iris.csv')
-
sns.boxplot(x = df_iris[
'class'],y = df_iris[
'sepal width'])
-
plt.show()
-
import matplotlib.pyplot
as plt
-
import seaborn
as sns
-
tips = pd.read_csv(
'../input/tips.csv')
-
sns.set(style=
"ticks")
#设置主题
-
sns.boxplot(x=
"day", y=
"total_bill", hue=
"sex", data=tips, palette=
"PRGn")
#palette 调色板
-
plt.show()
4 联合分布jointplot( )
-
tips = pd.read_csv(
‘../input/tips.csv’)
#右上角显示相关系数
-
sns.jointplot(
“total_bill”,
“tip”, tips)
-
plt.show()
-
tips = pd.read_csv(
‘../input/tips.csv’)
-
sns.jointplot(
“total_bill”,
“tip”, tips, kind=
‘reg’)
-
plt.show()
5 热点图heatmap( )
-
import matplotlib.pyplot
as plt
-
import seaborn
as sns
-
data = pd.read_csv(
"../input/car_crashes.csv")
-
data = data.corr()
-
sns.heatmap(data)
-
plt.show()
6 pairplot( )
-
import matplotlib.pyplot
as plt
-
import seaborn
as sns
-
data = pd.read_csv(
"../input/iris.csv")
-
sns.set()
#使用默认配色
-
sns.pairplot(data,hue=
"class")
#hue 选择分类列
-
plt.show()
-
import seaborn
as sns
-
import matplotlib.pyplot
as plt
-
iris = pd.read_csv(
'../input/iris.csv')
-
sns.pairplot(iris, vars=[
"sepal width",
"sepal length"],hue=
'class',palette=
"husl")
-
plt.show()
7 FacetGrid( )
-
import seaborn
as sns
-
import matplotlib.pyplot
as plt
-
tips = pd.read_csv(
'../input/tips.csv')
-
g = sns.FacetGrid(tips, col=
"time", row=
"smoker")
-
g = g.map(plt.hist,
"total_bill", color=
"r")
-
plt.show()
参考链接: