diff --git a/ljp.py b/ljp.py new file mode 100644 index 0000000..e6b2ff2 --- /dev/null +++ b/ljp.py @@ -0,0 +1,114 @@ +# ====================== 练习1:图像矩阵基本操作 ====================== +print("=" * 50) +print("练习1:图像矩阵操作") +print("=" * 50) + +image = np.array([ + [100, 150, 200], + [80, 120, 180], + [60, 90, 140] +], dtype=np.uint8) + +print("原图:") +print(image) + +# 1. 整体变暗 20 +darker = image - 20 +print("\n变暗20:") +print(darker) + +# 2. 裁剪左上角 2×2 +crop = image[0:2, 0:2] +print("\n裁剪左上角2×2:") +print(crop) + +# 3. 水平翻转 +flip_horizontal = np.fliplr(image) +print("\n水平翻转:") +print(flip_horizontal) + +# ====================== 练习2:4×4 黑白图像 ====================== +print("\n" + "=" * 50) +print("练习2:4×4图像矩阵") +print("=" * 50) + +img = np.array([ + [255, 255, 0, 0], + [255, 255, 0, 0], + [0, 0, 255, 255], + [0, 0, 255, 255] +], dtype=np.uint8) + +# 统计像素 +count_white = np.sum(img == 255) +count_black = np.sum(img == 0) +print("白色像素:", count_white) +print("黑色像素:", count_black) + +# 水平翻转 +flip_h = np.fliplr(img) +print("\n水平翻转:") +print(flip_h) + +# 逆时针旋转90度 +rotate_90_ccw = np.flipud(img.T) +print("\n逆时针旋转90度:") +print(rotate_90_ccw) + +# ====================== 练习3:特征向量相似度计算 ====================== +print("\n" + "=" * 50) +print("练习3:特征向量与相似度") +print("=" * 50) + +feature_map1 = np.array([[1, 0, 1], + [0, 1, 0], + [1, 0, 1]]) + +feature_map2 = np.array([[1, 1, 1], + [1, 0, 0], + [1, 0, 0]]) + +vec1 = feature_map1.flatten() +vec2 = feature_map2.flatten() + +print("展平向量1:", vec1) +print("展平向量2:", vec2) + +# 欧氏距离 +euclidean_dist = np.linalg.norm(vec1 - vec2) +print("\n欧几里得距离:", euclidean_dist) + +# 余弦相似度 +def cos_sim(a, b): + return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) + +print("余弦相似度:", cos_sim(vec1, vec2)) + +# ====================== 练习4:文本向量化 ====================== +print("\n" + "=" * 50) +print("练习4:文本向量化") +print("=" * 50) + +vocab = ["Python", "学习", "数据", "人工智能", "编程"] +doc1 = "Python学习编程" +doc2 = "Python人工智能数据" + +def text2vec(text, vocab): + words = text.split() + vec = np.zeros(len(vocab)) + for i, w in enumerate(vocab): + vec[i] = words.count(w) + return vec + +v1 = text2vec(doc1, vocab) +v2 = text2vec(doc2, vocab) + +print("句子1向量:", v1) +print("句子2向量:", v2) +print("余弦相似度:", cos_sim(v1, v2)) + +# 扩展词汇表 +vocab_new = ["Python", "学习", "数据", "人工智能", "编程", "机器"] +doc3 = "机器学习" +v3 = text2vec(doc3, vocab_new) +print("\n扩展词汇表后句子3向量:", v3) \ No newline at end of file