import numpy as np
import math
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.sans-serif']=['SimHei']
def showData(data):
# 创建柱状图
plt.figure(figsize=(10, 6))
plt.bar(range(len(data)), data)
# 添加标题和标签
plt.title('基本柱状图示例')
plt.xlabel('数据索引')
plt.ylabel('数值')
# 显示网格
plt.grid(axis='y', alpha=0.75)
plt.show()
def generate_matrices_and_compute(m, n):
"""
生成m*n矩阵和n*m矩阵,计算点积并应用softmax
"""
# 生成随机矩阵
matrix_a = np.random.rand(m, n) # m*n矩阵
matrix_b = np.random.rand(n, m) # n*m矩阵
print("矩阵 A ({}x{}):".format(m, n))
print(matrix_a)
print("\n矩阵 B ({}x{}):".format(n, m))
print(matrix_b)
# 计算点积
#dot_product = np.dot(matrix_a, matrix_b)
dot_product = np.dot(matrix_a, matrix_b)/math.sqrt(m)
#print("\n点积结果 ({}x{}):".format(m, m))
#print(dot_product)
# 应用softmax
# 对每一行应用softmax
softmax_result = np.exp(dot_product) / np.sum(np.exp(dot_product), axis=1, keepdims=True)
print("\nSoftmax结果 ({}x{}):".format(m, m))
print(softmax_result)
showData(softmax_result[0].tolist())
return matrix_a, matrix_b, dot_product, softmax_result
# 示例使用
if __name__ == "__main__":
m, n = 300, 400 # 可以修改这些值
print("=" * 50)
print("矩阵运算示例: m={}, n={}".format(m, n))
print("=" * 50)
A, B, dot, softmax = generate_matrices_and_compute(m, n)
# 验证结果
print("\n验证:")
print("点积矩阵形状:", dot.shape)
print("Softmax矩阵形状:", softmax.shape)
print("每行之和:", np.sum(softmax, axis=1)) # 每行之和应该为1