-
Notifications
You must be signed in to change notification settings - Fork 64
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
Web3Recommend #160
Open
rmadhwal
wants to merge
48
commits into
Tribler:master
Choose a base branch
from
rmadhwal:TrustedRecommendations
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Web3Recommend #160
Changes from all commits
Commits
Show all changes
48 commits
Select commit
Hold shift + click to select a range
2f970b1
Add Node to Node network
rmadhwal a790a17
Added Node To Song Network and done basic setup, serialization still …
rmadhwal 8b7e1b8
Add serialisation for Node To Song network, remove JSON serialisation…
rmadhwal 8e1975b
Initial random walk for personalised page rank (untested)
rmadhwal 89e451a
Set up basic test for personalized page rank
rmadhwal d93e6e2
Update random walk iterator to be always present for pagerank
rmadhwal 58bfdfe
update test to reflect pagerank expectations
rmadhwal 312880b
add modification option to random walks iterator (not tested yet)
rmadhwal 73b6459
add ability to remove node, test iterative modifications and allow se…
rmadhwal 25a3ec4
add skeleton for Hybrid Random Walk and an initial implementation for…
rmadhwal dd2b853
Mostly refactoring, unify node and song interfaces, make an interface…
rmadhwal 8b913e2
implement Hybrid Random Walks partially
rmadhwal 27af486
Add tests to assert properties of random walk algos
rmadhwal 4779d48
test modification of edges in hybrid salse
rmadhwal a2e96ca
alter tests for hybrid personalized salsa, modify NodeOrSong so nodes…
rmadhwal 7ce9b41
Add test tp assert removal of edge from NtS network
rmadhwal 7540f48
add skeleton to enable gossipping
rmadhwal e473f0a
set up code for overlying trust network TODO: update existing tests a…
rmadhwal 03c3e9e
bug fixes and initial test for trust network and edge gossiper
rmadhwal 0e23913
bug fixes
rmadhwal d35a794
Implement beta decays from merit rank, some refactoring
rmadhwal c899000
add tests for edge gossiping init
rmadhwal 6963447
bug fix and add time window to edge gossiper
rmadhwal e13b9a4
Implement beta decays from merit rank, some refactoring
rmadhwal 41df694
add collaborative filtering and enhance tests to create initial conne…
rmadhwal 1897199
fix beta decay implementation and make it memory efficient
rmadhwal 03ecb0e
add non heap efficient implementation
rmadhwal d8443d6
add beta decays for hybrid merit rank and fix computation of scores t…
rmadhwal c4736a4
add functionality to reward recommenders for song recommendation
rmadhwal 373aeb8
test network is set up
rmadhwal ef272f7
change beta decays to be dynamically imposed
rmadhwal d49d538
mass commits with a lot of constants - fix later
rmadhwal fb3fec7
working, I think
rmadhwal a83411c
maybe works
rmadhwal 590dd5e
completely working
rmadhwal d1269d8
Add experiments
rmadhwal 980d530
Big Commit - Add local song count increments and create gossiper
rmadhwal 0296d74
recommendations now working - todo: refactor
rmadhwal 6be4781
versioning fixes
rmadhwal ee6b08a
Experiment tweeks
rmadhwal 5421470
Fix tests, delete files related to experiments
rmadhwal 36a191c
QoL fixes
rmadhwal 7b7a52c
cleanliness
rmadhwal 5c8a4f1
refactoring
rmadhwal 7f317fe
lint fixes
rmadhwal dc6b8f7
More lint fixes
rmadhwal 9a7a1a1
test lint fixes
rmadhwal a28c650
serialization doesnt seem to work on github runners
rmadhwal 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 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 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 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 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 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 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
97 changes: 97 additions & 0 deletions
97
...dao/src/main/java/nl/tudelft/trustchain/musicdao/core/ipv8/TrustedRecommenderCommunity.kt
This file contains 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,97 @@ | ||
package nl.tudelft.trustchain.musicdao.core.ipv8 | ||
|
||
import android.content.Context | ||
import nl.tudelft.ipv8.Community | ||
import nl.tudelft.ipv8.Overlay | ||
import nl.tudelft.ipv8.Peer | ||
import nl.tudelft.ipv8.messaging.Packet | ||
import nl.tudelft.trustchain.musicdao.core.recommender.gossip.NodeToNodeEdgeGossip | ||
import nl.tudelft.trustchain.musicdao.core.recommender.gossip.NodeToRecEdgeGossip | ||
import nl.tudelft.trustchain.musicdao.core.recommender.model.NodeRecEdge | ||
import nl.tudelft.trustchain.musicdao.core.recommender.model.NodeTrustEdgeWithSourceAndTarget | ||
import nl.tudelft.trustchain.musicdao.core.recommender.networks.SongRecTrustNetwork | ||
import java.sql.Timestamp | ||
import java.util.ArrayList | ||
|
||
class TrustedRecommenderCommunity( | ||
context: Context | ||
) : Community() { | ||
private val appDirectory = context.cacheDir | ||
override val serviceId = "12313685c1912a141279f8248fc8db5899c5df6c" | ||
|
||
lateinit var trustNetwork: SongRecTrustNetwork | ||
|
||
init { | ||
messageHandlers[MessageId.NODE_TO_NODE_EDGE] = ::onNodeToNodeEdge | ||
messageHandlers[MessageId.NODE_TO_REC_EDGE] = ::onNodeToRecEdge | ||
} | ||
|
||
fun sendNodeToNodeEdges(peer: Peer, nodeToNodeEdges: List<NodeTrustEdgeWithSourceAndTarget>) { | ||
for (edge in nodeToNodeEdges) { | ||
val packet = serializePacket(MessageId.NODE_TO_NODE_EDGE, NodeToNodeEdgeGossip(edge), sign = false) | ||
send(peer, packet) | ||
} | ||
} | ||
|
||
fun sendNodeRecEdges(peer: Peer, nodeToSongEdges: List<NodeRecEdge>) { | ||
for (edge in nodeToSongEdges) { | ||
val packet = serializePacket(MessageId.NODE_TO_REC_EDGE, NodeToRecEdgeGossip(edge), sign = false) | ||
send(peer, packet) | ||
} | ||
} | ||
|
||
private fun onNodeToNodeEdge(packet: Packet) { | ||
if (!::trustNetwork.isInitialized) { | ||
trustNetwork = SongRecTrustNetwork.getInstance(myPeer.key.pub().toString(), appDirectory.path.toString()) | ||
} | ||
val payload = packet.getPayload(NodeToNodeEdgeGossip.Deserializer).edge | ||
if (trustNetwork.nodeToNodeNetwork.graph.containsVertex(payload.sourceNode)) { | ||
val existingEdges = trustNetwork.nodeToNodeNetwork.graph.outgoingEdgesOf(payload.sourceNode) | ||
if (existingEdges.size > 4) { | ||
val oldestEdge = existingEdges.minByOrNull { it.timestamp }!! | ||
if (oldestEdge.timestamp > payload.nodeTrustEdge.timestamp) return | ||
trustNetwork.nodeToNodeNetwork.removeEdge(oldestEdge) | ||
} | ||
} else { | ||
trustNetwork.addNode(payload.sourceNode) | ||
} | ||
if (!trustNetwork.nodeToNodeNetwork.graph.containsVertex(payload.targetNode)) { | ||
trustNetwork.addNode(payload.targetNode) | ||
} | ||
trustNetwork.addNodeToNodeEdge(payload) | ||
} | ||
|
||
private fun onNodeToRecEdge(packet: Packet) { | ||
if (!::trustNetwork.isInitialized) { | ||
trustNetwork = SongRecTrustNetwork.getInstance(myPeer.key.pub().toString(), appDirectory.path.toString()) | ||
} | ||
val payload = packet.getPayload(NodeToRecEdgeGossip.Deserializer).edge | ||
if (trustNetwork.nodeToSongNetwork.graph.containsVertex(payload.node)) { | ||
val existingEdges = trustNetwork.nodeToSongNetwork.graph.outgoingEdgesOf(payload.node) | ||
if (existingEdges.size > 4) { | ||
val oldestEdge = existingEdges.minByOrNull { it.timestamp }!! | ||
if (oldestEdge.timestamp > payload.nodeSongEdge.timestamp) return | ||
trustNetwork.nodeToSongNetwork.removeEdge(oldestEdge) | ||
} | ||
} else { | ||
trustNetwork.addNode(payload.node) | ||
} | ||
if (!trustNetwork.nodeToSongNetwork.graph.containsVertex(payload.rec)) { | ||
trustNetwork.addSongRec(payload.rec) | ||
} | ||
trustNetwork.addNodeToSongEdge(payload) | ||
} | ||
|
||
object MessageId { | ||
const val NODE_TO_NODE_EDGE = 1 | ||
const val NODE_TO_REC_EDGE = 2 | ||
} | ||
|
||
class Factory( | ||
private val context: Context | ||
) : Overlay.Factory<TrustedRecommenderCommunity>(TrustedRecommenderCommunity::class.java) { | ||
override fun create(): TrustedRecommenderCommunity { | ||
return TrustedRecommenderCommunity(context) | ||
} | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
...lft/trustchain/musicdao/core/recommender/collaborativefiltering/CollaborativeFiltering.kt
This file contains 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,8 @@ | ||
package nl.tudelft.trustchain.musicdao.core.recommender.collaborativefiltering | ||
|
||
import nl.tudelft.trustchain.musicdao.core.recommender.model.Node | ||
import nl.tudelft.trustchain.musicdao.core.recommender.model.NodeRecEdge | ||
|
||
interface CollaborativeFiltering { | ||
fun similarNodes(nodeToSongEdges: List<NodeRecEdge>, size: Int): Map<Node, Double> | ||
} |
111 changes: 111 additions & 0 deletions
111
...usicdao/core/recommender/collaborativefiltering/UserBasedTrustedCollaborativeFiltering.kt
This file contains 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,111 @@ | ||
package nl.tudelft.trustchain.musicdao.core.recommender.collaborativefiltering | ||
|
||
import nl.tudelft.trustchain.musicdao.core.recommender.networks.TrustNetwork | ||
import nl.tudelft.trustchain.musicdao.core.recommender.model.* | ||
import java.lang.Float.POSITIVE_INFINITY | ||
import kotlin.math.sqrt | ||
|
||
class UserBasedTrustedCollaborativeFiltering( | ||
var sortedTopTrustedUsers: List<Node>, | ||
val trustNetwork: TrustNetwork, | ||
val a: Double, | ||
val b: Double | ||
) : CollaborativeFiltering { | ||
companion object { | ||
private lateinit var instance: UserBasedTrustedCollaborativeFiltering | ||
fun getInstance( | ||
topTrustedUsers: List<Node>, | ||
trustNetwork: TrustNetwork, | ||
a: Double, | ||
b: Double | ||
): UserBasedTrustedCollaborativeFiltering { | ||
if (!Companion::instance.isInitialized) { | ||
instance = UserBasedTrustedCollaborativeFiltering(topTrustedUsers, trustNetwork, a, b) | ||
} | ||
return instance | ||
} | ||
} | ||
|
||
override fun similarNodes(nodeToSongEdges: List<NodeRecEdge>, size: Int): Map<Node, Double> { | ||
val sourceAffinities = nodeToSongEdges.associateBy({ it.rec }, { it.nodeSongEdge.affinity }) | ||
val nodeSimilarities = mutableListOf<NodeSimilarity>() | ||
for (node in sortedTopTrustedUsers) { | ||
val targetSongEdges = trustNetwork.nodeToSongNetwork.graph.outgoingEdgesOf(node) | ||
val targetAffinities = | ||
targetSongEdges.associateBy( | ||
{ trustNetwork.nodeToSongNetwork.graph.getEdgeTarget(it) as Recommendation }, | ||
{ it.affinity } | ||
) | ||
val commonItems = sourceAffinities.keys.intersect(targetAffinities.keys) | ||
val nodeSimilarity = NodeSimilarity(node) | ||
if (commonItems.isNotEmpty()) { | ||
nodeSimilarity.pcc = calculatePearsonCorrelationCoefficient(sourceAffinities, targetAffinities, commonItems) | ||
nodeSimilarity.rdci = calculateRatingDifferenceOfCommonItem(sourceAffinities, targetAffinities, commonItems) | ||
nodeSimilarity.commonItems = commonItems.size | ||
} | ||
nodeSimilarities.add(nodeSimilarity) | ||
} | ||
val maxCommonItems = nodeSimilarities.map { it.commonItems }.maxOrNull() | ||
return if (maxCommonItems == null || maxCommonItems == 0) { | ||
sortedTopTrustedUsers.takeLast(size).associateBy({ it }, { it.getPersonalizedPageRankScore() }) | ||
} else { | ||
val nodesTrustAndSimilarity = mutableListOf<Pair<Node, Double>>() | ||
for (nodeSim in nodeSimilarities) { | ||
val cf = nodeSim.commonItems.toDouble() / maxCommonItems | ||
val nSim = cf * nodeSim.pcc | ||
val similarity = (nSim * b) + (nodeSim.rdci * (1 - b)) | ||
val combinedTrustAndSimilarity = | ||
(nodeSim.node.getPersonalizedPageRankScore() * a) + ((similarity + 1) * (1 - a)) | ||
nodesTrustAndSimilarity.add(Pair(nodeSim.node, combinedTrustAndSimilarity)) | ||
} | ||
nodesTrustAndSimilarity.sortedBy { it.second }.takeLast(size).associateBy({ it.first }, { it.second }) | ||
} | ||
} | ||
|
||
private fun calculateRatingDifferenceOfCommonItem( | ||
sourceAffinities: Map<Recommendation, Double>, | ||
targetAffinities: Map<Recommendation, Double>, | ||
commonItems: Set<Recommendation> | ||
): Double { | ||
var maxRating = 0.0 | ||
var minRating = POSITIVE_INFINITY.toDouble() | ||
val cumRatingDifference = commonItems.map { | ||
val largerRating = maxOf(sourceAffinities[it]!!, targetAffinities[it]!!) | ||
val smallerRating = minOf(sourceAffinities[it]!!, targetAffinities[it]!!) | ||
if (largerRating > maxRating) maxRating = largerRating | ||
if (smallerRating < minRating) minRating = smallerRating | ||
largerRating - smallerRating | ||
}.sum() | ||
val ratingDifferenceFactor = cumRatingDifference / commonItems.size | ||
val ratingSpan = maxRating - minRating | ||
return if (ratingSpan == 0.0) 0.0 | ||
else 1 - (ratingDifferenceFactor * (1 / ratingSpan)) | ||
} | ||
|
||
private fun calculatePearsonCorrelationCoefficient( | ||
sourceAffinities: Map<Recommendation, Double>, | ||
targetAffinities: Map<Recommendation, Double>, | ||
commonItems: Set<Recommendation> | ||
): Double { | ||
val sourceAvg = sourceAffinities.values.average() | ||
val targetAvg = targetAffinities.values.average() | ||
val sourceVariances = commonItems.associateBy({ it }, { sourceAffinities[it]!! - sourceAvg }) | ||
val targetVariances = commonItems.associateBy({ it }, { targetAffinities[it]!! - targetAvg }) | ||
val numerator = commonItems.sumOf { song -> | ||
sourceVariances[song]!! * targetVariances[song]!! | ||
} | ||
|
||
return if (numerator != 0.0) { | ||
val sourceDenominator = commonItems.sumOf { song -> | ||
sqrt(sourceVariances[song]!! * sourceVariances[song]!!) | ||
} | ||
val targetDenominator = commonItems.sumOf { song -> | ||
sqrt(targetVariances[song]!! * targetVariances[song]!!) | ||
} | ||
val denominator = sourceDenominator * targetDenominator | ||
numerator / denominator | ||
} else { | ||
numerator | ||
} | ||
} | ||
} |
Oops, something went wrong.
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.
this looked like a typo in a previous PR, I've removed it, wasn't sure if it was appropriate to do it as a part of this PR - will remove it if you'd rather I commit it separately