import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import make_blobs
# 1. 基本特征值和特征向量计算
def basic_eigen_example():
"""基本的特征值和特征向量示例"""
# 创建对称矩阵
A = np.array([[4, 2], [2, 3]])
print("矩阵A:")
print(A)
# 计算特征值和特征向量
eigenvalues, eigenvectors = np.linalg.eig(A)
print(f"\n特征值: {eigenvalues}")
print("特征向量:")
print(eigenvectors)
# 验证特征值分解
for i in range(len(eigenvalues)):
eigenvector = eigenvectors[:, i]
eigenvalue = eigenvalues[i]
# 验证 Av = λv
Av = np.dot(A, eigenvector)
lambda_v = eigenvalue * eigenvector
print(f"\n特征值 {i+1}: λ = {eigenvalue:.4f}")
print(f"Av = {Av}")
print(f"λv = {lambda_v}")
print(f"误差 = {np.linalg.norm(Av - lambda_v):.2e}")
return eigenvalues, eigenvectors
# 2. 特征分解可视化
def visualize_eigen_decomposition():
"""可视化特征分解"""
# 创建变换矩阵
A = np.array([[2, 1], [1, 2]])
# 计算特征值和特征向量
eigenvalues, eigenvectors = np.linalg.eig(A)
# 创建单位圆上的点
theta = np.linspace(0, 2*np.pi, 100)
unit_circle = np.array([np.cos(theta), np.sin(theta)])
# 应用变换
transformed_circle = np.dot(A, unit_circle)
# 绘制结果
plt.figure(figsize=(12, 5))
# 原始单位圆
plt.subplot(1, 2, 1)
plt.plot(unit_circle[0], unit_circle[1], 'b-', label='单位圆')
plt.plot(eigenvectors[0, 0], eigenvectors[1, 0], 'ro', markersize=10, label=f'特征向量1 (λ={eigenvalues[0]:.2f})')
plt.plot(eigenvectors[0, 1], eigenvectors[1, 1], 'go', markersize=10, label=f'特征向量2 (λ={eigenvalues[1]:.2f})')
plt.xlabel('x')
plt.ylabel('y')
plt.title('原始单位圆和特征向量')
plt.legend()
plt.grid(True, alpha=0.3)
plt.axis('equal')
# 变换后的椭圆
plt.subplot(1, 2, 2)
plt.plot(transformed_circle[0], transformed_circle[1], 'b-', label='变换后的椭圆')
plt.plot(eigenvalues[0]*eigenvectors[0, 0], eigenvalues[0]*eigenvectors[1, 0], 'ro', markersize=10, label=f'缩放特征向量1')
plt.plot(eigenvalues[1]*eigenvectors[0, 1], eigenvalues[1]*eigenvectors[1, 1], 'go', markersize=10, label=f'缩放特征向量2')
plt.xlabel('x')
plt.ylabel('y')
plt.title('变换后的椭圆和缩放特征向量')
plt.legend()
plt.grid(True, alpha=0.3)
plt.axis('equal')
plt.tight_layout()
plt.show()
# 3. PCA降维示例
def pca_dimensionality_reduction():
"""PCA降维示例"""
# 生成3D数据
X, _ = make_blobs(n_samples=100, n_features=3, centers=3, random_state=42)
print("原始数据形状:", X.shape)
# 应用PCA
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)
print("降维后数据形状:", X_pca.shape)
print("解释方差比例:", pca.explained_variance_ratio_)
print("累计解释方差:", np.sum(pca.explained_variance_ratio_))
# 可视化结果
plt.figure(figsize=(12, 5))
# 原始3D数据
ax1 = plt.subplot(1, 2, 1, projection='3d')
ax1.scatter(X[:, 0], X[:, 1], X[:, 2], alpha=0.6)
ax1.set_xlabel('特征1')
ax1.set_ylabel('特征2')
ax1.set_zlabel('特征3')
ax1.set_title('原始3D数据')
# 降维后的2D数据
plt.subplot(1, 2, 2)
plt.scatter(X_pca[:, 0], X_pca[:, 1], alpha=0.6)
plt.xlabel('主成分1')
plt.ylabel('主成分2')
plt.title('PCA降维后的2D数据')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
return X, X_pca, pca
# 4. 特征值分解的数值稳定性
def numerical_stability_example():
"""数值稳定性示例"""
# 创建接近奇异的矩阵
A = np.array([[1, 1e-10], [1e-10, 1]])
print("接近奇异的矩阵A:")
print(A)
# 计算特征值
eigenvalues = np.linalg.eigvals(A)
print(f"\n特征值: {eigenvalues}")
# 计算条件数
condition_number = np.linalg.cond(A)
print(f"条件数: {condition_number:.2e}")
# 添加小扰动
A_perturbed = A + 1e-12 * np.random.randn(2, 2)
eigenvalues_perturbed = np.linalg.eigvals(A_perturbed)
print(f"\n扰动后特征值: {eigenvalues_perturbed}")
print(f"特征值变化: {np.abs(eigenvalues - eigenvalues_perturbed)}")
return A, eigenvalues, eigenvalues_perturbed
# 5. 推荐系统中的特征分解
def recommendation_system_example():
"""推荐系统中的特征分解示例"""
# 创建用户-项目评分矩阵(简化示例)
ratings = np.array([
[5, 3, 0, 1], # 用户1的评分
[4, 0, 0, 1], # 用户2的评分
[1, 1, 0, 5], # 用户3的评分
[1, 0, 0, 4], # 用户4的评分
[0, 1, 5, 4], # 用户5的评分
])
print("用户-项目评分矩阵:")
print(ratings)
# 计算协方差矩阵
covariance_matrix = np.cov(ratings.T)
print(f"\n协方差矩阵形状: {covariance_matrix.shape}")
# 特征值分解
eigenvalues, eigenvectors = np.linalg.eig(covariance_matrix)
# 按特征值大小排序
sorted_indices = np.argsort(eigenvalues)[::-1]
eigenvalues = eigenvalues[sorted_indices]
eigenvectors = eigenvectors[:, sorted_indices]
print(f"\n特征值: {eigenvalues}")
print("解释方差比例:", eigenvalues / np.sum(eigenvalues))
# 选择前2个主成分
n_components = 2
selected_eigenvectors = eigenvectors[:, :n_components]
# 降维
ratings_reduced = np.dot(ratings, selected_eigenvectors)
print(f"\n降维后评分矩阵形状: {ratings_reduced.shape}")
print("降维后评分矩阵:")
print(ratings_reduced)
return ratings, ratings_reduced, eigenvalues, eigenvectors
# 运行所有示例
if __name__ == "__main__":
print("=== 基本特征值和特征向量 ===")
eigenvalues, eigenvectors = basic_eigen_example()
print("\n=== 特征分解可视化 ===")
visualize_eigen_decomposition()
print("\n=== PCA降维 ===")
X, X_pca, pca = pca_dimensionality_reduction()
print("\n=== 数值稳定性 ===")
A, eigenvalues, eigenvalues_perturbed = numerical_stability_example()
print("\n=== 推荐系统示例 ===")
ratings, ratings_reduced, eigenvalues, eigenvectors = recommendation_system_example()