<jupyter_start><jupyter_text><NAME> 99201465  0. Importing the necessary modules<jupyter_code>from PIL import Image
import os
import matplotlib.pyplot as plt
import numpy as np
from sklearn.utils.extmath import randomized_svd
gorbe_file_path = '/content/drive/MyDrive/gorbe.jpg'
import numpy as np<jupyter_output><empty_output><jupyter_text>1. Reading the image to numpy<jupyter_code>!wget https://i.imgflip.com/w414e.jpg
gorbe_the_great = np.asarray(Image.open('w414e.jpg'))
gorbe_the_great.shape<jupyter_output><empty_output><jupyter_text>2. SVD Decomposition<jupyter_code>def truncated_svd(mat, n_components):
  return randomized_svd(mat, 
                        n_components=n_components,
                        random_state=None)<jupyter_output><empty_output><jupyter_text>3. Compressing each channel<jupyter_code>n_components = 15
compressed_svds = []

for i in range(3):
  compressed_svds.append(truncated_svd(gorbe_the_great[:, :, i], n_components))<jupyter_output><empty_output><jupyter_text>4. Reconstructing the image<jupyter_code>def reconstruct(U , Sigma , VT):
  return np.array(U @ np.diag(Sigma) @ VT).astype(np.uint8)
reconstructed_gorbe = []

for i in range(3):
  reconstructed_gorbe.append(reconstruct(*compressed_svds[i]))
another_gorbe = np.dstack(reconstructed_gorbe)
plt.imshow(another_gorbe)
plt.show()<jupyter_output><empty_output><jupyter_text>5. Running the compression with different values<jupyter_code>dims_file_sizes = {}
for i in range(1, min(gorbe_the_great.shape[0], gorbe_the_great.shape[1]), 10):
  compressed_svds = [truncated_svd(gorbe_the_great[:, :, c], i) for c in range(3)]

  reconstructed_gorbe = [reconstruct(*compressed_svds[c]) for c in range(3)]

  print(i)
  another_gorbe = np.dstack(reconstructed_gorbe)
  plt.imshow(another_gorbe)
  plt.show()

  img = Image.fromarray(another_gorbe)
  img.save("gorbe_khare.jpeg")
  file_size = os.path.getsize("gorbe_khare.jpeg")
  dims_file_sizes[i] = file_size<jupyter_output><empty_output><jupyter_text>6. Plotting the filesize vs. dimensions<jupyter_code>dims = list(dims_file_sizes.keys())
files_sizes = list(dims_file_sizes.values())

plt.plot(dims, files_sizes)
 
plt.xlabel("Dimensions")
plt.ylabel("File Sizes")
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12044444444444445, 'fraction_numerical': 0.014666666666666666, 'mean_word_length': 6.656462585034014, 'pattern_counts': {'":': 0, '<': 30, '<?xml version=': 0, '>': 30, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '104644', 'license': 'MIT', 'n_tokens_mistral': 901, 'n_tokens_neox': 856, 'n_words': 132, 'path': 'Exams/Mid-term/question_04.ipynb', 'repo_name': 'alimirferdos/Data_Mining_Course', 'size': '2263'}