离散型hopfield神经网络。参考自http://web.cs.ucla.edu/~rosen/161/notes/hopfield.html实现的草稿版本:
# http://web.cs.ucla.edu/~rosen/161/notes/hopfield.html attractors = np.array([[0, 1, 1, 0, 1], [1, 0, 1, 0, 1]]) print('attractors: ', attractors) weight_matrix = np.zeros((5, 5)) print('weight_matrix: ', weight_matrix) # 第一个向量表示第一个节点到各个节点的权值 # 初始化网络,权值是对称的,例如w12 = w21,而w11 w22都是0 # for i in range(len(weight_matrix)): def reflect_about_the_diagonal(matrix): # 将矩阵上三角翻转拷贝到下三角 matrix += matrix.T - np.diag(matrix.diagonal()) for attractor in attractors: temp_matrix = np.zeros((5, 5)) for i in range(0, 4): for j in range(i + 1, 5): temp_matrix[i, j] = (2 * attractor[i] - 1) * (2 * attractor[j] - 1) weight_matrix += temp_matrix reflect_about_the_diagonal(weight_matrix) print('weight_matrix: ', weight_matrix) # print(weight_matrix[2].dot(attractors[0])) # 类似于bp里的预测,som里的map def xxxx(input_vector): vector = input_vector.copy() stable_state = False random_order = np.arange(len(attractors[0])) while not stable_state: # 生成一个随机序列,以随机的顺序更新节点 np.random.shuffle(random_order) stable_state = True for i in random_order: original_value = vector[i] vector[i] = weight_matrix[i].dot(vector) if (vector[i] >= 0): vector[i] = 1 else: vector[i] = 0 if (vector[i] != original_value): print(i, "change ", original_value, '->', vector[i]) stable_state = False return vector x = [1, 1, 1, 1, 1] print('test:', x, '->', xxxx(np.array(x)))