This is the record of the 85th "Dimension compression by principal component analysis" of Language processing 100 knock 2015. Compresses about 400,000 dimensions to 300 dimensions. This time, we are doing singular value decomposition instead of principal component analysis. If we were to analyze the principal components with scikit-learn, we couldn't do it with a sparse matrix, so we compromised, "Both are dimensional reductions!" Principal component analysis was learned in 8th week of the famous Coursera Machine Learning Online Course. If you are interested in the course, please refer to the article ["Coursera Machine Learning Introductory Online Course Cheat Sheet (Recommended for Humanities)" (https://qiita.com/FukuharaYohei/items/b2143413063376e97948).
Link | Remarks |
---|---|
085.Dimensional compression by principal component analysis.ipynb | Answer program GitHub link |
100 amateur language processing knocks:85 | I am always indebted to you by knocking 100 language processing |
TruncatedSVD | Official help for Truncated SVD |
About the relationship between PCA and SVD | Difference between principal component analysis and singular value decomposition 1 |
Show the relationship between PCA and SVD | Difference between principal component analysis and singular value decomposition 2 |
type | version | Contents |
---|---|---|
OS | Ubuntu18.04.01 LTS | It is running virtually |
pyenv | 1.2.15 | I use pyenv because I sometimes use multiple Python environments |
Python | 3.6.9 | python3 on pyenv.6.I'm using 9 3.7 or 3.There is no deep reason not to use 8 series Packages are managed using venv |
In the above environment, I am using the following additional Python packages. Just install with regular pip.
type | version |
---|---|
matplotlib | 3.1.1 |
numpy | 1.17.4 |
pandas | 0.25.3 |
scipy | 1.4.1 |
scikit-learn | 0.21.3 |
enwiki-20150112-400-r10-105752.txt.bz2 Is the text of 105,752 articles randomly sampled 1/10 from the English Wikipedia articles as of January 12, 2015, which consist of more than 400 words, compressed in bzip2 format. is there. Using this text as a corpus, I want to learn a vector (distributed expression) that expresses the meaning of a word. In the first half of Chapter 9, principal component analysis is applied to the word context co-occurrence matrix created from the corpus, and the process of learning word vectors is implemented by dividing it into several processes. In the latter half of Chapter 9, the word vector (300 dimensions) obtained by learning is used to calculate the similarity of words and perform analogy.
Note that if problem 83 is implemented obediently, a large amount (about 7GB) of main memory is required. If you run out of memory, devise a process or 1/100 sampling corpus enwiki-20150112-400-r100-10576.txt.bz2 Use /nlp100/data/enwiki-20150112-400-r100-10576.txt.bz2).
This time * "1/100 sampling corpus [enwiki-20150112-400-r100-10576.txt.bz2](http://www.cl.ecei.tohoku.ac.jp/nlp100/data/enwiki-20150112-" 400-r100-10576.txt.bz2) ”* is used.
Apply principal component analysis to the word context matrix obtained in> 84 and compress the word meaning vector to 300 dimensions.
import matplotlib.pyplot as plt
import numpy as np
from scipy import io
from sklearn.decomposition import TruncatedSVD
matrix_x = io.loadmat('084.matrix_x.mat')['x']
#Confirm reading
print('matrix_x Shape:', matrix_x.shape)
print('matrix_x Number of non-zero entries:', matrix_x.nnz)
print('matrix_x Format:', matrix_x.getformat())
#Dimensional compression
svd = TruncatedSVD(300)
matrix_x300 = svd.fit_transform(matrix_x)
print(type(matrix_x300))
print('matrix_x300 Shape:',matrix_x300.shape)
print('Explained Variance Ratio Sum:', svd.explained_variance_ratio_.sum())
ev_ratio = svd.explained_variance_ratio_
ev_ratio = np.hstack([0,ev_ratio.cumsum()])
plt.plot(ev_ratio)
plt.show()
np.savez_compressed('085.matrix_x300.npz', matrix_x300)
Load the mat format file saved by knocking last time.
matrix_x = io.loadmat('084.matrix_x.mat')['x']
#Confirm reading
print('matrix_x Shape:', matrix_x.shape)
print('matrix_x Number of non-zero entries:', matrix_x.nnz)
print('matrix_x Format:', matrix_x.getformat())
In the above output, you can see that both Shape and non-zero elements are the same as last time. However, the format is csc
even though I saved it as lil
. Is it such a thing? I will proceed without worrying about it.
matrix_x Shape: (388836, 388836)
matrix_x Number of non-zero entries: 447875
matrix_x Format: csc
This is the main dimensional compression part. However, I'm just using the function TruncatedSVD
, so I'm not having any trouble. It took about 8 minutes.
svd = TruncatedSVD(300)
matrix_x300 = svd.fit_transform(matrix_x)
print(type(matrix_x300))
print('matrix_x300 Shape:',matrix_x300.shape)
If you check the return value, it looks like numpy.ndarray
format. It's true that the dimension is compressed, so the dense matrix is correct, not the sparse matrix.
<class 'numpy.ndarray'>
matrix_x300 Shape: (388836, 300)
Now let's see how well we can keep the variance. I refer to the article "Principal component analysis with scikit-learn (calculate cumulative contribution rate)".
print('Explained Variance Ratio Sum:', svd.explained_variance_ratio_.sum())
ev_ratio = svd.explained_variance_ratio_
ev_ratio = np.hstack([0,ev_ratio.cumsum()])
plt.plot(ev_ratio)
plt.show()
About 30%. Low···. Is it better to increase the number of dimensions? ["It is desirable to exceed 99%. However, it seems that 95% or 90% may be the threshold value."](Https://qiita.com/FukuharaYohei/items/7a71be58818719cdf73c#232-choosing -the-number-of-principal-components) I learned ...
Explained Variance Ratio Sum: 0.31949196039604355
This is a line graph that accumulates the variance retention ratios for each principal component.
The file is compressed and saved with the function save_compressed
to make it lighter. Still, the file size is 118MB. The file size saved in the previous sparse matrix was 7MB, so even if it was dimensionally compressed, it swelled due to the dense matrix. By the way, the memory usage before compression saving is 933MB, so it seems that it is made much smaller by compression. However, on the other hand, the time that took 9 seconds has increased to 36.
Regarding saving, I referred to the article "Compare the difference in file size depending on the serialization method of numpy array".
np.savez_compressed('085.matrix_x300.npz', matrix_x300)
I investigated whether "principal component analysis" could be done as described in the assignment. The bottleneck is whether sparse matrices can be used as Input. Stackoverflow's "Performing PCA on large sparse matrix by using sklearn" has a sparse matrix It was written that it was impossible. [MRG] Implement randomized PCA # 12841 seems to be implementing a function to input a sparse matrix, but it remains Open. ・ ・ ・ I thought that it would be possible to learn little by little with the amount of memory that can be overcome in a dense matrix, but even if it could be done, it would take a huge amount of time, so I gave up ...
I felt that the dispersion retention rate of about 30% was low, so I increased the dimension. At first I did it in 1000 dimensions, but an error occurred due to insufficient memory ... With 600 dimensions, it didn't end even after 30 minutes, and it was troublesome, so I stopped halfway. It took 18 minutes for 450 dimensions. The dispersion retention rate at that time was 38%, which is considerably higher. It looks like this when compared.
dimension | processing time | Return value(matrix_x300)memory | file size |
---|---|---|---|
300 dimensions | 8 minutes | 0.9GB | 118MB |
450 dimensions | 18 minutes | 1.40GB | 178MB |
Recommended Posts