工程项目的目录结构如下:
self_attention文件的内容如下:
import numpy as np
from testAAA.my_softmax import *
from testBBB.myPrint import *
my_print()
print("*"*30)
# from My_softmax import self_softmax
# from .My_softmax import self_softmax
input_all = np.array([[1, 0, 1, 0], [0, 2, 0, 2], [1, 1, 1, 1]])
print(input_all)
w_k = np.array([[0, 0, 1], [1, 1, 0], [0, 1, 0], [1, 1, 0]])
print(w_k)
w_q = np.array([[1, 0, 1], [1, 0, 0], [0, 0, 1], [0, 1, 1]])
w_v = np.array([[0, 2, 0], [0, 3, 0], [1, 0, 3], [1, 1, 0]])
kk = np.matmul(input_all, w_k)
print("这是K的结果\n", kk)
vv = np.matmul(input_all, w_v)
print("这是V的结果\n", vv)
qq = np.dot(input_all, w_q)
print("这是Q的结果\n", qq)
att_score = np.matmul(qq, kk.T)
print("这是注意力得分\n", att_score)
att = self_softmax(att_score)
print(att)
my_print()
在上面这个py文件里面调用testAAA 和testBBB的内容 如何导包 大家请看里面内容。
然后my_softmax.py文件代码如下:
import numpy as np
def self_softmax(x):
orig_shape = x.shape
print("orig_shape", orig_shape)
if len(x.shape) > 1:
# 矩阵
tmp = np.max(x, axis=1)
x -= tmp.reshape((x.shape[0], 1))
x = np.exp(x)
tmp = np.sum(x, axis=1)
x /= tmp.reshape((x.shape[0], 1))
print("matrix")
else:
# 向量
tmp = np.max(x)
x -= tmp
x = np.exp(x)
tmp = np.sum(x)
x /= tmp
print("vector")
return x
myPrint代码如下:
def my_print():
print("导包也没有那么难")
运行self_attention_my.py是可以正常运行的,没有任何问题。但是用相对路径 我还是有点不清楚 暂时有点问题。