Learn Module

New in version 0.1.1.

A collection of classes for interfacing with built-in ML/AI features in macOS.

Classes:

XALSM([dataset, from_file])

class PyXA.Additions.Learn.XALSM(dataset: dict[str, list[str]] | None = None, from_file: bool = False)[source]

Bases: object

Methods:

add_category(name[, initial_data])

Adds a new category to the map, optionally filling the category with initial text data.

add_data(data)

Adds the provided data, organized by category, to the active map.

add_text(text, category[, weight])

Adds the given text to the specified category, applying an optional weight.

categorize_query(query[, num_results])

Categorizes the query based on the current weights in the map.

load()

Loads a map from an external file.

save(file_path)

Saves the map to an external file.

add_category(name: str, initial_data: list[str] | None = None) int[source]

Adds a new category to the map, optionally filling the category with initial text data.

Parameters:
  • name (str) – The name of the category

  • initial_data (list[str]) – _description_

Returns:

The ID of the new category

Return type:

int

Example:

Add a category for cleaning-related Reddit posts to the previous example

>>> import PyXA
>>> lsm = PyXA.XALSM.load("/Users/steven/Downloads/gaming-productivity.map")
>>> lsm.add_category("cleaning", ["Curtains stained from eyelet reaction at dry cleaner", "How do I get these stains out of my pink denim overalls? from a black denim jacket that was drying next to them", "Cleaned my depression room after months 🥵", "Tip: 30 minute soak in Vinegar", "Regular floor squeegee pulled a surprising amount of pet hair out of my carpet!", "Before and after…", "It actually WORKS", "CLR is actually magic. (With some elbow grease)", "It was 100% worth it to scrape out my old moldy caulk and replace it. $5 dollars and a bit of time to make my shower look so much cleaner!", "Thanks to the person who recommended the Clorox Foamer. Before and after pics", "TIL you can dissolve inkstains with milk.", "Fixing cat scratch marks to couch using felting needle: Before and After", "Turns out BKF isn't a meme! Really satisfied with this stuff"])
>>> print(lsm.categorize_query("Hidden survival base on our server"))
>>> print(lsm.categorize_query("Your memory is FAR more powerful than you think… school just never taught us to use it properly."))
>>> print(lsm.categorize_query("A carpet rake will change your life."))
[(1, 0.7474805116653442)]
[(2, 0.7167008519172668)]
[(3, 0.797333300113678)]

New in version 0.1.0.

add_data(data: dict[int | str, list[str]]) list[int][source]

Adds the provided data, organized by category, to the active map.

Parameters:

data (dict[Union[int, str], list[str]]) – A dictionary specifying new or existing categories along with data to input into them

Returns:

A list of newly created category IDs

Return type:

int

Example:

Classify text by language

>>> import PyXA
>>> lsm = PyXA.XALSM({})
>>> lsm.add_data({
>>>     # 1
>>>     "english": ["brilliance outer jacket artist flat mosquito recover restrict official gas ratio publish domestic realize pure offset obstacle thigh favorite demonstration revive nest reader slide pudding symptom ballot auction characteristic complete Mars ridge student explosion dive emphasis the buy perfect motif penny a errand to fur far spirit random integration of with"],
>>>
>>>     # 2
>>>     "italian": ["da piazza proposta di legge legare nazionale a volte la salute bar farti farmi il pane aggiunta valore artista chiamata settentrionale scuro buio classe signori investitore in grado di fidanzato tagliare arriva successo altrimenti speciale esattamente definizione sorriso chiamo madre pulire esperto rurale vedo malattia era amici libertà l'account immaginare lingua soldi più perché"],
>>> })
>>> print(lsm.categorize_query("Here's to the crazy ones"))
>>> print(lsm.categorize_query("Potete parlarmi in italiano"))
[(1, 1.0)]
[(2, 1.0)]

New in version 0.1.0.

add_text(text: str, category: int | str, weight: float = 1)[source]

Adds the given text to the specified category, applying an optional weight.

Parameters:
  • text (str) – The text to add to the dataset

  • category (Union[int, str]) – The category to add the text to

  • weight (float, optional) – The weight to assign to the text entry, defaults to 1

Raises:

ValueError – The specified category must be a valid category name or ID

Example:

>>> import PyXA
>>> lsm = PyXA.XALSM({"colors": [], "numbers": ["One", "Two", "Three"]})
>>> lsm.add_text("red orange yellow green blue purple", "colors")
>>> lsm.add_text("white black grey gray brown pink", 1)
>>> print(lsm.categorize_query("pink"))

New in version 0.1.0.

categorize_query(query: str, num_results: int = 1) list[tuple[int, float]][source]

Categorizes the query based on the current weights in the map.

Parameters:
  • query (str) – The query to categorize

  • num_results (int, optional) – The number of categorizations to show, defaults to 1

Returns:

A list of tuples identifying categories and their associated score. A higher score indicates better fit. If not matching categorization is found, the list will be empty.

Return type:

list[tuple[int, float]]

Example:

>>> import PyXA
>>> dataset = {
>>>     # 1
>>>     "color": ["red", "orange", "yellow", "green", "emerald", "blue", "purple", "white", "black", "brown", "pink", "grey", "gray"],
>>>
>>>     # 2
>>>     "number": ["One Two Three Four Five Six Seven Eight Nine Ten"]
>>> }
>>> lsm = PyXA.XALSM(dataset)
>>> queries = ["emerald green three", "one hundred five", "One o' clock", "sky blue", "ninety nine", "purple pink"]
>>>
>>> for query in queries:
>>>     category = "Unknown"
>>>     categorization_tuple = lsm.categorize_query(query)
>>>     if len(categorization_tuple) > 0:
>>>         category = list(dataset.keys())[categorization_tuple[0][0] - 1]
>>>     print(query, "is a", category)
emerald green three is a color
one hundred five is a number
One o' clock is a number
sky blue is a color
ninety nine is a number
purple pink is a color

New in version 0.1.0.

load() XALSM[source]

Loads a map from an external file.

Parameters:

file_path (Union[XABase.XAPath, str]) – The file path for load the map from

Returns:

The populated LSM object

Return type:

XALSM

Example:

Using the gaming vs. productivity Reddit post map

>>> import PyXA
>>> lsm = PyXA.XALSM.load("/Users/steven/Downloads/gaming-productivity.map")
>>> print(lsm.categorize_query("Hidden survival base on our server"))
>>> print(lsm.categorize_query("Your memory is FAR more powerful than you think… school just never taught us to use it properly."))
[(1, 0.7313863635063171)]
[(2, 0.9422407150268555)]

New in version 0.1.0.

save(file_path: XAPath | str) bool[source]

Saves the map to an external file.

Parameters:

file_path (Union[XABase.XAPath, str]) – The path to save the map at

Returns:

True if the map was saved successfully

Return type:

bool

Example:

Create a Reddit post classifier for gaming vs. productivity posts

>>> import PyXA
>>> lsm = PyXA.XALSM({
>>>     # 1
>>>     "gaming": ["If you could vote on the 2017 Mob Vote again, which mob would you choose this time and why?", "Take your time, you got this", "My parents (late 70s) got me a ps5 controller for Christmas. I do not own a playstation 5...", "I got off the horse by accident right before a cutscene in red dead", "boy gamer", "Minesweeper 99 x 99, 1500 mines. Took me about 2.5 hours to finish, nerve-wracking. No one might care, but just wanted to share this.", "The perfect cosplay doesn’t ex...", "'Play until we lose'", "Can we please boycott Star Wars battlefront 2", "EA removed the refund button on their webpage, and now you have to call them and wait to get a refund.", "Train Simulator is so immersive!", "Been gaming with this dude for 15 years. Since Rainbow Six Vegas on 360. I have some good gaming memories with him. He tried but couldn’t get one. Little did he know I was able to get him one. Looking forward to playing another generation with him.", "EA will no longer have exclusive rights of the Star Wars games", "A ziplining contraption I created with 1000+ command blocks", "The steepest walkable staircase possible in 1.16", "I made a texture pack that gives mobs different facial expressions. Should I keep going?"],
>>>
>>>     # 2
>>>     "productivity": ["Looking for an alarm app that plays a really small alarm, doesn’t need to be switched off and doesn’t repeat.", "I want to build a second brain but I'm lost and don't know where to start.", "noise cancelling earplugs", "I have so much to do but I don't know where to start", "How to handle stressful work calls", "time tracking app/platform", "We just need to find ways to cope and keep moving forward.", "Ikigai - A Reason for Being", "Minimalist Productivity Tip: create two users on your computer ➞ One for normal use and leisure ➞ One for business/work only. I have nothing except the essentials logged in on my work user. Not even Messages or YouTube. It completely revolutionized my productivity 💸", "Trick yourself into productivity the same way you trick yourself into procrastination", "I spent 40 hours sifting through research papers to fix my mental clarity, focus, and productivity - I ended up going down a rabbit hole and figuring out it was all tied to sleep, even though I felt I sleep well - here's what I found.", "The Cycle of Procrastination. Always a good reminder", "'Most people underestimate what they can do in a year, and overestimate what they can do in a day' - When you work on getting 1% better each day you won't even recognize yourself in a year."],
>>> })
>>> lsm.save("/Users/steven/Downloads/gaming-productivity.map")

New in version 0.1.0.