Python待用

Sklearn-Pandas-Numpy 小课堂

2020-08-15  本文已影响0人  井底蛙蛙呱呱呱

本文仅用于记录日常使用sklearn、numpy、pandas过程中使用到的一些小函数,方便日后复用。

1、如何合并一个稀疏矩阵和一个稠密矩阵?

此问题背景是使用sklearn生成tfidf特征时是一个稀疏特征矩阵,但是有时候还需要考虑加入其他特征,这些特征常常是稠密矩阵(pandas其他列)。

from scipy import sparse
import numpy as np

A = sparse.csr_matrix([[1,0,0],[0,1,0]])
B = np.array([1,2])

# 合并为稠密矩阵
np.column_stack((A.A, B))
# 输出
array([[1, 0, 0, 1],
       [0, 1, 0, 2]], dtype=int64)

# 合并为稀疏矩阵
sparse.hstack((A,sparse.csr_matrix(B).T))
# 输出
<2x4 sparse matrix of type '<class 'numpy.int64'>'
    with 4 stored elements in COOrdinate format>

sparse.hstack((A,sparse.csr_matrix(B).T)).toarray()
# 输出
array([[1, 0, 0, 1],
       [0, 1, 0, 2]], dtype=int64)

2、sklearn labelencoder如何处理OOV问题?

在pyspark中,stringIndex可以非常方便的处理OOV问题——'skip'或者'keep'。
但是sklearn的labelencoder并没有这种功能。我们需要自己来处理OOV问题。

from sklearn.preprocessing import LabelEncoder

le = preprocessing.LabelEncoder()
le.fit(X)

le_dict = dict(zip(le.classes_, le.transform(le.classes_)))
df[your_col].apply(lambda x: le_dict.get(x, <unknown_value>))

参考:https://stackoverflow.com/questions/21057621/sklearn-labelencoder-with-never-seen-before-values

上一篇下一篇

猜你喜欢

热点阅读