簡體   English   中英

sklearn LogisticRegression的densify()和sparsify()方法的output是什么

[英]What is the output of densify() and sparsify() methods of sklearn LogisticRegression

我想知道sklearn logisticRegression densify()sparsify()方法返回什么?

我認為這些方法將打印一個包含 coef_ 信息的矩陣,而不是如下所示的 output。

只是好奇如何打印出文檔提到的密集 coef_ 或稀疏 coef_ 矩陣。

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

df = pd.read_csv('https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/titanic_train.csv')
df = df.dropna(how='any', subset = ['Age','Fare','Sex'])
df['Sex'] = df['Sex'].map({'male':0, 'female':1})
X = df[['Age','Fare','Sex']]
y = df['Survived']


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 1)

logreg = LogisticRegression()
logreg.fit(X_train, y_train)
y_pred = logreg.predict(X_test)


logreg.densify()
#Output
<bound method SparseCoefMixin.densify of LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
                   intercept_scaling=1, l1_ratio=None, max_iter=100,
                   multi_class='auto', n_jobs=None, penalty='l2',
                   random_state=None, solver='lbfgs', tol=0.0001, verbose=0,
                   warm_start=False)>


logreg.sparsify()
#Output
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
                   intercept_scaling=1, l1_ratio=None, max_iter=100,
                   multi_class='auto', n_jobs=None, penalty='l2',
                   random_state=None, solver='lbfgs', tol=0.0001, verbose=0,
                   warm_start=False)

仔細查看文檔,我們看到:

致密化自我):

將系數矩陣轉換為密集數組格式。

coef_成員(返回)轉換為 numpy.ndarray。 這是coef_的默認格式

稀疏化自我):

將系數矩陣轉換為稀疏數組格式。

coef_成員轉換為 scipy.sparse 矩陣

因此,這兩種方法的效果都在返回的系數矩陣coef_ (將其在密集和稀疏格式之間轉換),並且在 model 摘要中確實不明顯,它們在調用時都顯示為 output。

這是一個使用 iris 數據的簡單演示:

from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression

X, y = load_iris(return_X_y=True)
clf = LogisticRegression(random_state=0)
clf.fit(X, y)

# by default, the coefficients are in dense format (numpy.ndarray):
clf.coef_
# array([[-0.41878528,  0.96703041, -2.5209973 , -1.08417682],
#        [ 0.53124457, -0.31475282, -0.20008433, -0.94861142],
#        [-0.1124593 , -0.65227759,  2.72108162,  2.03278825]])

type(clf.coef_)
# numpy.ndarray

# switch to sparse format:
clf.sparsify()
clf.coef_
# <3x4 sparse matrix of type '<class 'numpy.float64'>'
#   with 12 stored elements in Compressed Sparse Row format>

type(clf.coef_)
# scipy.sparse.csr.csr_matrix

# switch back to dense format:
clf.densify()

type(clf.coef_)
# numpy.ndarray

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM