forked from SmirkCao/Lihang
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
51 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,34 @@ | ||
#! /usr/bin/env python | ||
|
||
# Project: Lihang | ||
# Filename: lsa | ||
# Date: 6/03/19 | ||
# Author: 😏 <smirk dot cao at gmail dot com> | ||
# 截断奇异值分解用在count/tf-idf矩阵的时候,叫做潜在语义分析。 | ||
import numpy as np | ||
|
||
|
||
class LSA(object): | ||
def __init__(self, n_components): | ||
self.n_components = n_components | ||
self.components = None | ||
self.singular_values = None | ||
self.explained_variance_ratio = None | ||
|
||
def fit(self, x): | ||
pass | ||
u, s, vh = np.linalg.svd(x, full_matrices=False) | ||
max_abs_raws = np.argmax(np.abs(vh), axis=1) | ||
signs = np.sign(vh[range(vh.shape[0]), max_abs_raws]) | ||
u *= signs | ||
vh *= signs[:, np.newaxis] | ||
k = self.n_components | ||
# | ||
self.components = vh[:k] | ||
self.singular_values = s[:k] | ||
# | ||
x_transformed = u*s | ||
self.explained_variance = np.var(x_transformed, axis=0) | ||
self.explained_variance_ratio = (self.explained_variance/self.explained_variance.sum())[:k] | ||
self.explained_variance = self.explained_variance[:k] | ||
return x_transformed | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters