recommendation

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: MIT Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrFresh = errors.New("recommendation model is fresh; skipped retrain")

ErrFresh is returned by Train when the persisted model is younger than Config.MinRetrainAge, so training was skipped.

Functions

This section is empty.

Types

type Config

type Config struct {
	Factors       int     // latent dimension k
	Iterations    int     // ALS sweeps
	Lambda        float64 // L2 regularization
	Alpha         float64 // confidence scaling: c = 1 + alpha*weight
	NeighborsTopN int     // item-item edges stored per work
	Seed          int64   // RNG seed for reproducible factors
	// MinRetrainAge skips a Train call when the persisted model is younger
	// than this. With several instances on independent tickers it stops
	// each of them retraining every interval. Zero = always train.
	MinRetrainAge time.Duration
}

Config controls the implicit-ALS training. Defaults are tuned for a small corpus; all are env-overridable via pkg/config and Service/Trainer wiring.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig's Lambda is sized against Alpha: observed confidences reach 1+40·5 = 201, and with λ=0.1 that left the model effectively unregularized — with more factors than items it reproduced each user's training row exactly and scored every unseen work ≈0, so held-out items ranked no better than popularity (TestMFBeatsPopularityBaseline lost on ~half of seeds). λ=10 recovers held-out items reliably at k=8..32.

type Dismissal

type Dismissal struct {
	ID        uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`
	UserID    uint      `gorm:"not null;uniqueIndex:idx_dismissal_user_work" json:"user_id"`
	WorkID    uuid.UUID `gorm:"type:uuid;not null;uniqueIndex:idx_dismissal_user_work" json:"work_id"`
	CreatedAt time.Time `json:"created_at"`
}

Dismissal records that a user hid a recommendation; excluded from future results. Unique on (user_id, work_id) so re-dismissing is idempotent.

func (Dismissal) TableName

func (Dismissal) TableName() string

type EvalResult

type EvalResult struct {
	K            int
	Users        int
	MFHitRate    float64 // fraction of users with ≥1 held-out item in their top-K
	PopHitRate   float64
	MFPrecision  float64 // mean held-out items recovered / K
	PopPrecision float64
}

EvalResult holds leave-N-out holdout metrics for the MF system vs a pure popularity baseline, averaged over evaluated users.

func Evaluate

func Evaluate(ctx context.Context, db *gorm.DB, cfg Config, k int, holdoutFrac float64, seed int64) (EvalResult, error)

Evaluate runs a destructive leave-N-out holdout against `db` (intended for a throwaway eval database): for each user with enough liked items it hides a `holdoutFrac` slice of them, trains MF on the remainder, then measures how well the deployed Recommend path (MF + fallback) recovers the hidden items vs ranking purely by global popularity. The held-out rows are deleted from user_books, so do NOT point this at a database you care about.

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

func NewHandler

func NewHandler(s *Service) *Handler

func (*Handler) Dismiss

func (h *Handler) Dismiss(w http.ResponseWriter, r *http.Request)

Dismiss hides the work named in the path from the caller's future recommendations. {id} is the work id.

func (*Handler) Recommend

func (h *Handler) Recommend(w http.ResponseWriter, r *http.Request)

Recommend returns the calling user's personalized work suggestions.

func (*Handler) Undismiss

func (h *Handler) Undismiss(w http.ResponseWriter, r *http.Request)

Undismiss reverses Dismiss (the For You "Undo"). {id} is the work id.

type Recommendation

type Recommendation struct {
	Work   catalog.Work `json:"work"`
	Reason string       `json:"reason"`
	Score  float64      `json:"score,omitempty"`
}

Recommendation is one suggested work plus why it surfaced.

type Service

type Service struct {
	// contains filtered or unexported fields
}

func NewService

func NewService(db *gorm.DB) *Service

func (*Service) Dismiss

func (s *Service) Dismiss(ctx context.Context, userID uint, workID uuid.UUID) error

Dismiss hides a work from the user's future recommendations. Idempotent: re-dismissing the same work is a no-op (unique index on user_id+work_id).

func (*Service) Recommend

func (s *Service) Recommend(ctx context.Context, userID uint, limit int) ([]Recommendation, error)

Recommend returns up to `limit` works the user hasn't added or dismissed. The matrix-factorization model (userVec·workVec) is primary; when the user has no trained vector (cold start / pre-train) it falls back to the v0 content+popularity scorer. Both paths get a diversity cap and a popular fill.

func (*Service) Undismiss

func (s *Service) Undismiss(ctx context.Context, userID uint, workID uuid.UUID) error

Undismiss reverses Dismiss so the work can be recommended again. Idempotent: undismissing a work that isn't dismissed is a no-op.

type Trainer

type Trainer struct {
	// contains filtered or unexported fields
}

Trainer fits an implicit-feedback ALS model (Hu–Koren–Volinsky) over the user_books interaction matrix and writes the factor + neighbor tables.

func NewTrainer

func NewTrainer(db *gorm.DB, cfg Config) *Trainer

func (*Trainer) Train

func (t *Trainer) Train(ctx context.Context) error

Train fits the model and atomically replaces the factor/neighbor tables. A corpus with no interactions clears the tables (serving then falls back to the v0 content+popularity path).

Only one instance trains at a time: the whole run holds a cluster-wide lock (runlock.KeyRecTrainer), and a caller that can't take it gets runlock.ErrBusy immediately instead of racing the winner's DELETE + bulk insert. Returns ErrFresh if another instance trained recently.

type UserFactors

type UserFactors struct {
	UserID    uint           `gorm:"primaryKey" json:"user_id"`
	Vector    datatypes.JSON `json:"vector"`
	UpdatedAt time.Time      `json:"updated_at"`
}

UserFactors is a user's latent vector.

func (UserFactors) TableName

func (UserFactors) TableName() string

type WorkFactors

type WorkFactors struct {
	WorkID    uuid.UUID      `gorm:"type:uuid;primaryKey" json:"work_id"`
	Vector    datatypes.JSON `json:"vector"`
	UpdatedAt time.Time      `json:"updated_at"`
}

WorkFactors is a work's latent vector.

func (WorkFactors) TableName

func (WorkFactors) TableName() string

type WorkNeighbor

type WorkNeighbor struct {
	WorkID     uuid.UUID `gorm:"type:uuid;not null;index" json:"work_id"`
	NeighborID uuid.UUID `gorm:"type:uuid;not null" json:"neighbor_id"`
	Score      float64   `json:"score"`
}

WorkNeighbor is one top-N item-item similarity edge (cosine over work vectors). Powers "Because you liked X" explanations and item-based cold start.

func (WorkNeighbor) TableName

func (WorkNeighbor) TableName() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL