-
Notifications
You must be signed in to change notification settings - Fork 23
feat: add cosine similarity algorithm #69
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
7476f19
feat: cosine similarity algorithm
zqqcee 64e3e6c
test: unit test
zqqcee c1c39ae
Merge remote-tracking branch 'upstream/next' into v5-algo-cosinesim
zqqcee 39e7191
fix: change default export to export
zqqcee 4712412
feat: v5 algorithm nodes-cosine-similarity
zqqcee c3dd035
test: nodes cossim unit test
zqqcee 411ea1a
fix: fix import bug, fix: change NodeSimilarity type
zqqcee cb2a2e2
fix: remove annotation
zqqcee File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { cosineSimilarity } from "../../packages/graph/src"; | ||
|
|
||
| describe('cosineSimilarity abnormal demo: ', () => { | ||
| it('item contains only zeros: ', () => { | ||
| const item = [0, 0, 0]; | ||
| const targetTtem = [3, 1, 1]; | ||
| const cosineSimilarityValue = cosineSimilarity(item, targetTtem); | ||
| expect(cosineSimilarityValue).toBe(0); | ||
| }); | ||
| it('targetTtem contains only zeros: ', () => { | ||
| const item = [3, 5, 2]; | ||
| const targetTtem = [0, 0, 0]; | ||
| const cosineSimilarityValue = cosineSimilarity(item, targetTtem); | ||
| expect(cosineSimilarityValue).toBe(0); | ||
| }); | ||
| it('item and targetTtem both contains only zeros: ', () => { | ||
| const item = [0, 0, 0]; | ||
| const targetTtem = [0, 0, 0]; | ||
| const cosineSimilarityValue = cosineSimilarity(item, targetTtem); | ||
| expect(cosineSimilarityValue).toBe(0); | ||
| }); | ||
| }); | ||
|
|
||
| describe('cosineSimilarity normal demo: ', () => { | ||
| it('demo similar: ', () => { | ||
| const item = [30, 0, 100]; | ||
| const targetTtem = [32, 1, 120]; | ||
| const cosineSimilarityValue = cosineSimilarity(item, targetTtem); | ||
| expect(cosineSimilarityValue).toBeGreaterThanOrEqual(0); | ||
| expect(cosineSimilarityValue).toBeLessThan(1); | ||
| expect(Number(cosineSimilarityValue.toFixed(3))).toBe(0.999); | ||
| }); | ||
| it('demo dissimilar: ', () => { | ||
| const item = [10, 300, 2]; | ||
| const targetTtem = [1, 2, 30]; | ||
| const cosineSimilarityValue = cosineSimilarity(item, targetTtem); | ||
| expect(cosineSimilarityValue).toBeGreaterThanOrEqual(0); | ||
| expect(cosineSimilarityValue).toBeLessThan(1); | ||
| expect(Number(cosineSimilarityValue.toFixed(3))).toBe(0.074); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| import { nodesCosineSimilarity } from "../../packages/graph/src"; | ||
| import propertiesGraphData from '../data/cluster-origin-properties-data.json'; | ||
| import { NodeSimilarity } from "../../packages/graph/src/types"; | ||
|
|
||
| describe('nodesCosineSimilarity abnormal demo', () => { | ||
| it('no properties demo: ', () => { | ||
| const nodes = [ | ||
| { | ||
| id: 'node-0', | ||
| data: {}, | ||
| }, | ||
| { | ||
| id: 'node-1', | ||
| data: {}, | ||
| }, | ||
| { | ||
| id: 'node-2', | ||
| data: {}, | ||
| }, | ||
| { | ||
| id: 'node-3', | ||
| data: {}, | ||
| } | ||
| ]; | ||
| const { allCosineSimilarity, similarNodes } = nodesCosineSimilarity(nodes as NodeSimilarity[], nodes[0]); | ||
| expect(allCosineSimilarity.length).toBe(3); | ||
| expect(similarNodes.length).toBe(3); | ||
| expect(allCosineSimilarity[0]).toBe(0); | ||
| expect(allCosineSimilarity[1]).toBe(0); | ||
| expect(allCosineSimilarity[2]).toBe(0); | ||
| }); | ||
| }); | ||
|
|
||
|
|
||
| describe('nodesCosineSimilarity normal demo', () => { | ||
| it('simple demo: ', () => { | ||
| const nodes = [ | ||
| { | ||
| id: 'node-0', | ||
| data: { | ||
| amount: 10, | ||
| } | ||
| }, | ||
| { | ||
| id: 'node-2', | ||
| data: { | ||
| amount: 100, | ||
| } | ||
| }, | ||
| { | ||
| id: 'node-3', | ||
| data: { | ||
| amount: 1000, | ||
| } | ||
| }, | ||
| { | ||
| id: 'node-4', | ||
| data: { | ||
| amount: 50, | ||
| } | ||
| } | ||
| ]; | ||
| const { allCosineSimilarity, similarNodes } = nodesCosineSimilarity(nodes as NodeSimilarity[], nodes[0], ['amount']); | ||
| expect(allCosineSimilarity.length).toBe(3); | ||
| expect(similarNodes.length).toBe(3); | ||
| allCosineSimilarity.forEach(data => { | ||
| expect(data).toBeGreaterThanOrEqual(0); | ||
| expect(data).toBeLessThanOrEqual(1); | ||
| }) | ||
| }); | ||
|
|
||
| it('complex demo: ', () => { | ||
| const { nodes } = propertiesGraphData; | ||
| const { allCosineSimilarity, similarNodes } = nodesCosineSimilarity(nodes as NodeSimilarity[], nodes[16]); | ||
| expect(allCosineSimilarity.length).toBe(16); | ||
| expect(similarNodes.length).toBe(16); | ||
| allCosineSimilarity.forEach(data => { | ||
| expect(data).toBeGreaterThanOrEqual(0); | ||
| expect(data).toBeLessThanOrEqual(1); | ||
| }) | ||
| }); | ||
|
|
||
|
|
||
| it('demo use involvedKeys: ', () => { | ||
| const involvedKeys = ['amount', 'wifi']; | ||
| const { nodes } = propertiesGraphData; | ||
| const { allCosineSimilarity, similarNodes } = nodesCosineSimilarity(nodes as NodeSimilarity[], nodes[16], involvedKeys); | ||
| expect(allCosineSimilarity.length).toBe(16); | ||
| expect(similarNodes.length).toBe(16); | ||
| allCosineSimilarity.forEach(data => { | ||
| expect(data).toBeGreaterThanOrEqual(0); | ||
| expect(data).toBeLessThanOrEqual(1); | ||
| }) | ||
| expect(similarNodes[0].id).toBe('node-11'); | ||
| }); | ||
|
|
||
| it('demo use uninvolvedKeys: ', () => { | ||
| const uninvolvedKeys = ['amount']; | ||
| const { nodes } = propertiesGraphData; | ||
| const { allCosineSimilarity, similarNodes } = nodesCosineSimilarity(nodes as NodeSimilarity[], nodes[16], [], uninvolvedKeys); | ||
| expect(allCosineSimilarity.length).toBe(16); | ||
| expect(similarNodes.length).toBe(16); | ||
| allCosineSimilarity.forEach(data => { | ||
| expect(data).toBeGreaterThanOrEqual(0); | ||
| expect(data).toBeLessThanOrEqual(1); | ||
| }) | ||
| expect(similarNodes[0].id).toBe('node-11'); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import { Vector } from "./vector"; | ||
|
|
||
| /** | ||
| Calculates the cosine similarity | ||
| @param item - The element. | ||
| @param targetItem - The target element. | ||
| @returns The cosine similarity between the item and the targetItem. | ||
| */ | ||
| export const cosineSimilarity = ( | ||
| item: number[], | ||
| targetItem: number[], | ||
| ): number => { | ||
| // Vector of the target element | ||
| const targetItemVector = new Vector(targetItem); | ||
| // Norm of the target element vector | ||
| const targetNodeNorm2 = targetItemVector.norm2(); | ||
| // Vector of the item | ||
| const itemVector = new Vector(item); | ||
| // Norm of the item vector | ||
| const itemNorm2 = itemVector.norm2(); | ||
| // Calculate the dot product of the item vector and the target element vector | ||
| const dot = targetItemVector.dot(itemVector); | ||
| const norm2Product = targetNodeNorm2 * itemNorm2; | ||
| // Calculate the cosine similarity between the item vector and the target element vector | ||
| const cosineSimilarity = norm2Product ? dot / norm2Product : 0; | ||
| return cosineSimilarity; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import { clone } from '@antv/util'; | ||
| import { getAllProperties, oneHot } from './utils'; | ||
| import { NodeSimilarity } from './types'; | ||
| import { cosineSimilarity } from '.'; | ||
|
|
||
| /** | ||
| Calculates the cosine similarity based on node attributes using the nodes-cosine-similarity algorithm. | ||
| This algorithm is used to find similar nodes based on a seed node in a graph. | ||
| @param nodes - The data of graph nodes. | ||
| @param seedNode - The seed node for similarity calculation. | ||
| @param involvedKeys - The collection of keys that are involved in the calculation. | ||
| @param uninvolvedKeys - The collection of keys that are not involved in the calculation. | ||
| @returns An array of nodes that are similar to the seed node based on cosine similarity. | ||
| */ | ||
| export const nodesCosineSimilarity = ( | ||
| nodes: NodeSimilarity[] = [], | ||
| seedNode: NodeSimilarity, | ||
| involvedKeys: string[] = [], | ||
| uninvolvedKeys: string[] = [], | ||
| ): { | ||
| allCosineSimilarity: number[], | ||
| similarNodes: NodeSimilarity[], | ||
| } => { | ||
| const similarNodes = clone(nodes.filter(node => node.id !== seedNode.id)); | ||
| const seedNodeIndex = nodes.findIndex(node => node.id === seedNode.id); | ||
| // Collection of all node properties | ||
| const properties = getAllProperties(nodes); | ||
| // One-hot feature vectors for all node properties | ||
| const allPropertiesWeight = oneHot(properties, involvedKeys, uninvolvedKeys) as number[][]; | ||
| // Seed node properties | ||
| const seedNodeProperties = allPropertiesWeight[seedNodeIndex]; | ||
| const allCosineSimilarity: number[] = []; | ||
| similarNodes.forEach((node: NodeSimilarity, index: number) => { | ||
| const nodeProperties = allPropertiesWeight[index]; | ||
| // Calculate the cosine similarity between node vector and seed node vector | ||
| const cosineSimilarityValue = cosineSimilarity(nodeProperties, seedNodeProperties); | ||
| allCosineSimilarity.push(cosineSimilarityValue); | ||
| node.cosineSimilarity = cosineSimilarityValue; | ||
| }); | ||
| // Sort the returned nodes according to cosine similarity | ||
| similarNodes.sort((a: NodeSimilarity, b: NodeSimilarity) => b.cosineSimilarity - a.cosineSimilarity); | ||
| return { allCosineSimilarity, similarNodes }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -37,4 +37,7 @@ export interface IAlgorithmCallbacks { | |
| allowTraversal?: (param: { previous?: NodeID; current?: NodeID; next: NodeID }) => boolean; | ||
| } | ||
|
|
||
| export type NodeID = string | number; | ||
| export type NodeID = string | number; | ||
| export interface NodeSimilarity extends Node<{ [key: string]: any }> { | ||
|
||
| cosineSimilarity?: number; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
import { cosineSimilarity } from './cosine-similarity';
这样引入吧。从 index 容易出现循环引用