asp動態(tài)網(wǎng)站制作流程2022年最新新聞播報(bào)稿件
SVD 是一種矩陣分解和降維的算法,通過分解矩陣找到奇異值,奇異值越大代表特征越重要。公式如下
A = U Σ V T A = U \Sigma V^T A=UΣVT
- U : 左矩陣 ( m × \times × m )
- Σ \Sigma Σ: 對角奇異值矩陣
- V:右矩陣( n × \times × n )
Sklearn 實(shí)現(xiàn) SVD
import numpy as np
A = np.array([[0,1],[1,1],[1,0]])
u, s, vt = np.linalg.svd(A, full_matrices=True)
print(u.shape, s.shape, vt.shape)
SVD 可以用于圖片的壓縮,只保留最重要信息,從 k=1 到 k=50:
import numpy as np
import os
from PIL import Image
from tqdm import tqdm# 定義恢復(fù)函數(shù),由分解后的矩陣恢復(fù)到原矩陣
def restore(u, s, v, K): '''u:左奇異矩陣v:右奇異矩陣s:奇異值矩陣K:奇異值個(gè)數(shù)'''m, n = len(u), len(v[0])a = np.zeros((m, n))for k in range(K):uk = u[:, k].reshape(m, 1)vk = v[k].reshape(1, n)# 前k個(gè)奇異值的加總a += s[k] * np.dot(uk, vk) a = a.clip(0, 255)return np.rint(a).astype('uint8')A = np.array(Image.open("./mountain.png", 'r'))
# 對RGB圖像進(jìn)行奇異值分解
u_r, s_r, v_r = np.linalg.svd(A[:, :, 0])
u_g, s_g, v_g = np.linalg.svd(A[:, :, 1])
u_b, s_b, v_b = np.linalg.svd(A[:, :, 2])# 使用前50個(gè)奇異值
K = 50
output_path = './svd_pic'
#
for k in tqdm(range(1, K+1)):R = restore(u_r, s_r, v_r, k)G = restore(u_g, s_g, v_g, k)B = restore(u_b, s_b, v_b, k)I = np.stack((R, G, B), axis=2) Image.fromarray(I).save('%s/svd_%d.jpg' % (output_path, k))
顯示圖片
from PIL import Image
from IPython.display import display, HTML
import os
import re
import time# Path to the folder containing images
image_folder = "./svd_pic"# List all image files
image_files = [f for f in os.listdir(image_folder) if f.endswith(('.png', '.jpg', '.jpeg'))]# Sort image files by the numeric part of the filename
def extract_number(filename):match = re.search(r'_(\d+)\.', filename)return int(match.group(1)) if match else float('inf')image_files = sorted(image_files, key=extract_number)# Generate HTML for horizontal display with cache busting
html = "<div style='display: flex; flex-direction: row; flex-wrap: wrap;'>"
timestamp = int(time.time()) # Use current timestamp for cache bustingfor idx, image_file in enumerate(image_files):img_path = os.path.join(image_folder, image_file)# Add a unique query parameter to disable cachingimg_url = f"{img_path}?v={timestamp}"img = Image.open(img_path)img_resized = img.resize((150, 150)) # Resize to 300x300img_resized.save("temp_resized.jpg") # Save resized image temporarily# Add image with index number overlayhtml += f"""<div style="margin: 10px; position: relative; display: inline-block; text-align: center;"><img src="{img_url}" style="width: 150px; height: 150px; display: block;"><div style="position: absolute; top: 10px; left: 10px; background-color: rgba(0, 0, 0, 0.6); color: white; padding: 5px 10px; font-size: 16px; border-radius: 5px;">{idx + 1}</div></div>"""html += "</div>"# Display the images horizontally with no cache
display(HTML(html))
隨著K 值增大,圖片會越來越清晰。
總結(jié)
SVD 算法通過求解奇異值對矩陣進(jìn)行分解,較大奇異值能表達(dá)更重要的信息。