常见模块和函数

1、from sklearn.model_selection import train_test_split     用于拆分数据

2、from sklearn.feature_extraction.text import TfidfVectorizer 用于转换字符串

      TfidfVectorizer.fit_transform()

       参数必须是字符串的一维数组(比如列表或者Series)返回的是一个稀疏矩阵类型的对象,行数为样本数,列数为所有出现的单词统计个数。

3、credit[col][cond_0].plot(kind = 'hist',bins = 500,normed = True,ax = ax)

      credit[col][cond_1].plot(kind = 'hist',bins = 50,normed = True,ax = ax)

        上图是不同变量在信用卡被盗刷和信用卡正常的不同分布情况,我们将选择在不同信用卡状态下的分布有明显区别的变量

4、from sklearn.preprocessing import StandardScaler

        Amount变量和Time变量的取值范围与其他变量相差较大,所以要对其进行特征缩放

5、from sklearn.ensemble import GradientBoostingClassifier    利用GBDT梯度提升决策树进行特征重要性排序

6、from imblearn.over_sampling import SMOTE

        smote.fit_sample(X_train,y_train)

        过采样(oversampling),增加正样本使得正、负样本数目接近,然后再进行学习。

        欠采样(undersampling),去除一些负样本使得正、负样本数目接近,然后再进行学习

        SMOET的基本原理是:采样最邻近算法,计算出每个少数类样本的K个近邻,从K个近邻中随机挑选N个样本进行随机线性插值,构造新的少数样本,同时将新样本与原数据合成,产生新的训练集。

7、绘制真实值和预测值对比情况

def plot_confusion_matrix(cm, classes, title='Confusion matrix',cmap=plt.cm.Blues):

        """

        This function prints and plots the confusion matrix.

        """

        plt.imshow(cm, interpolation='nearest', cmap=cmap)

        plt.title(title)

        plt.colorbar()

        tick_marks = np.arange(len(classes))

        plt.xticks(tick_marks, classes, rotation=0)

        plt.yticks(tick_marks, classes)

        threshold = cm.max() / 2.

        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):

                plt.text(j, i, cm[i, j],

                horizontalalignment="center",

                color="white" if cm[i, j] > threshold else "black")#若对应格子上面的数量不超过阈值则,上面的字体为白色,为了方便查看

            plt.tight_layout()

            plt.ylabel('True label')

            plt.xlabel('Predicted label')

from sklearn.metrics import confusion_matrix

cm = confusion_matrix(y_test,y_),classes参数表示正负例0/1

8、 

        TruePositiveRate=TP/(TP+FN),代表将真实正样本划分为正样本的概率

        FalsePositiveRate=FP/(FP+TN),代表将真实负样本划分为正样本的概率

        

        接着,我们以“True Positive Rate”作为纵轴,以“False Positive Rate”作为横轴,画出ROC曲线,ROC曲线下的面积,即为AUC的值。类似下图:

ROC

9、from scipy import interp         线性插值,用于处理已知两元素关系,给定一个元素求同样关系的另外一元素

10、from sklearn.decomposition import PCA         降维处理,压缩特征数量降低处理时间

11、from sklearn.model_selection import GridSearchCV        网格搜索是用来帮助我们寻找合适的参数的.

12、pd.crosstab(index=y_, columns=y_test, rownames=['预测值',], colnames=['真实值'], margins=True)        交叉表展示结果

13、标准的字符串转数字的操作:

        for col in cols:

                # 找到这一列数据的unique

                uni = data[col].unique()

                def convert(item):

                        index = np.argwhere(uni == item)[0,0]

                        return index

          data[col] = data[col].map(convert)

14、归一化处理数据(把值变成0到1直接的小数)

        def normalized(x):

                return (x - x.min()) / (x.max() - x.min())

         for col in data.columns:

          # 使用transform进行转化, transform会一次性把一整列数据都传入normalized

          data[col] = data[col].transform(normalized)

15、from sklearn.externals import joblib

        joblib.dump(knn, 'knn.plk')保存模型

        knn = joblib.load('knn.plk')加载模型

16、按照样本比例进行训练和测试数据的划分

        from sklearn.model_selection import StratifiedKFold

        train,test = sKFold.split(X,y)    返回训练数据索引,测试数据索引

17、from sklearn.metrics import roc_curve

        fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])    返回fpr,tpr,thresholds

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • http://www.ithao123.cn/content-647680.html Classification...
    hzyido阅读 7,730评论 0 1
  • 古城流转千百年,这些历史的遗迹,历经了风雨的磨砺和剥蚀,风霜的雕琢和磨练,默默的迎来送往那些历朝历代的大儒先贤、达...
    渤海经济圈阅读 4,629评论 0 0
  • 敬爱的老师,睿智的曹主任,亲爱的家人们: 大家好!我是威海汇彩夏惠,今天是2018.11.23我日精进行动的第89...
    夏惠阅读 1,287评论 0 0
  • 廊边落木萧萧下,恍然知事,已是初秋。 又逢冷月当空照,穷寂寞,更煽情愁。 曾记否? 偷窗剪影当年似,落日楼头,望眼...
    晚颦阅读 3,365评论 7 11