Title: | Formal Concept Analysis |
---|---|
Description: | Provides tools to perform fuzzy formal concept analysis, presented in Wille (1982) <doi:10.1007/978-3-642-01815-2_23> and in Ganter and Obiedkov (2016) <doi:10.1007/978-3-662-49291-8>. It provides functions to load and save a formal context, extract its concept lattice and implications. In addition, one can use the implications to compute semantic closures of fuzzy sets and, thus, build recommendation systems. |
Authors: | Domingo Lopez Rodriguez [aut, cre]
|
Maintainer: | Domingo Lopez Rodriguez <[email protected]> |
License: | GPL-3 |
Version: | 1.2.1.9000 |
Built: | 2025-03-12 05:48:22 UTC |
Source: | https://github.com/malaga-fca-group/fcar |
Difference in Sets
S1 %-% S2
S1 %-% S2
S1 |
A |
S2 |
A |
Both S1
and S2
must be Sets.
Returns the difference S1 - S2
.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1) # Difference S %-% T
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1) # Difference S %-% T
Intersection (Logical AND) of Fuzzy Sets
S1 %&% S2
S1 %&% S2
S1 |
A |
S2 |
A |
Both S1
and S2
must be Sets.
Returns the intersection of S1
and S2
.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1, C = 1) # Intersection S %&% T
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1, C = 1) # Intersection S %&% T
Partial Order in Sets and Concepts
C1 %<=% C2
C1 %<=% C2
C1 |
A |
C2 |
A |
Both C1
and C2
must be of the same class.
Returns TRUE
if concept C1
is subconcept of C2
or if set C1
is subset of C2
.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1, B = 1) # Test whether S is subset of T S %<=% T
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1, B = 1) # Test whether S is subset of T S %<=% T
Equality in Sets and Concepts
C1 %==% C2
C1 %==% C2
C1 |
A |
C2 |
A |
Both C1
and C2
must be of the same class.
Returns TRUE
if C1
is equal to C2
.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1) # Test whether S and T are equal S %==% T
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(A = 1) # Test whether S and T are equal S %==% T
Equivalence of sets of implications
imps %~% imps2
imps %~% imps2
imps |
A |
imps2 |
Another |
TRUE
of and only if imps
and imps2
are equivalent, that is, if every implication in imps
follows from imps2
and viceversa.
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() imps2 <- imps$clone() imps2$apply_rules(c("simp", "rsimp")) imps %~% imps2 imps %~% imps2[1:9]
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() imps2 <- imps$clone() imps2$apply_rules(c("simp", "rsimp")) imps %~% imps2 imps %~% imps2[1:9]
Entailment between implication sets
imps %entails% imps2
imps %entails% imps2
imps |
( |
imps2 |
( |
A logical vector, where element k is TRUE
if the
k-th implication in imps2
follows from imps
.
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications[1:4]$clone() imps2 <- fc$implications[3:6]$clone() imps %entails% imps2
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications[1:4]$clone() imps2 <- fc$implications[3:6]$clone() imps %entails% imps2
Implications that hold in a Formal Context
imps %holds_in% fc
imps %holds_in% fc
imps |
( |
fc |
( |
A logical vector, indicating if each implication holds in the formal context.
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() imps %holds_in% fc
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() imps %holds_in% fc
Union (Logical OR) of Fuzzy Sets
S1 %|% S2
S1 %|% S2
S1 |
A |
S2 |
A |
Both S1
and S2
must be Sets.
Returns the union of S1
and S2
.
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(C = 1) # Union S %|% T
# Build two sparse sets S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1, B = 1) T <- Set$new(attributes = c("A", "B", "C")) T$assign(C = 1) # Union S %|% T
Check if Set or FormalContext respects an ImplicationSet
set %respects% imps
set %respects% imps
set |
(list of |
imps |
( |
A logical matrix with as many rows as Set
s and as many columns as implications in the ImplicationSet
. A TRUE
in element (i, j) of the result means that the i-th Set
respects the j-th implication of the ImplicationSet
.
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() fc %respects% imps
fc <- FormalContext$new(planets) fc$find_implications() imps <- fc$implications$clone() fc %respects% imps
Convert Named Vector to Set
as_Set(A)
as_Set(A)
A |
A named vector or matrix to build a new |
A Set
object.
A <- c(a = 0.1, b = 0.2, p = 0.3, q = 0) as_Set(A)
A <- c(a = 0.1, b = 0.2, p = 0.3, q = 0) as_Set(A)
Convert Set to vector
as_vector(v)
as_vector(v)
v |
A |
A vector.
A <- c(a = 0.1, b = 0.2, p = 0.3, q = 0) v <- as_Set(A) A2 <- as_vector(v) all(A == A2)
A <- c(a = 0.1, b = 0.2, p = 0.3, q = 0) v <- as_Set(A) A2 <- as_vector(v) all(A == A2)
A subset of the COBRE dataset has been retrieved, by querying SchizConnect for 105 patients with neurological and clinical symptoms, collecting also their corresponding diagnosis.
cobre32
cobre32
A matrix with 105 rows and 32 columns. Column names are related to different scales for depression and Schizophrenia:
The Simpson-Angus Scale, 7 items to evaluate Parkinsonism-like alterations, related to schizophrenia, in an individual.
The Calgary Depression Scale for Schizophrenia, 9 items (attributes) assessing the level of depression in schizophrenia, differentiating between positive and negative aspects of the disease.
The Structured Clinical Interview for DSM-III-R Personality Disorders, with 14 variables related to the presence of signs affecting personality.
if TRUE
, the diagnosis is strict schizophrenia.
it TRUE
, the diagnosis is other than schizophrenia, including schizoaffective, bipolar disorder and major depression.
In summary, the dataset consists in the previous 30 attributes related to signs or symptoms, and 2 attributes related to diagnosis (these diagnoses are mutually exclusive, thus only one of them is assigned to each patient). This makes a dataset with 105 objects (patients) and 32 attributes to explore. The symptom attributes are multi-valued.
Thus, according to the specific scales used, all attributes are fuzzy and graded. For a given attribute (symptom), the available grades range from absent to extreme, with minimal, mild, moderate, moderate severe and severe in between.
These fuzzy attributes are mapped to values in the interval [0, 1].
Aine, C. J., Bockholt, H. J., Bustillo, J. R., Cañive, J. M., Caprihan, A., Gasparovic, C., ... & Liu, J. (2017). Multimodal neuroimaging in schizophrenia: description and dissemination. Neuroinformatics, 15(4), 343-364. https://pubmed.ncbi.nlm.nih.gov/26142271/
A subset of the COBRE dataset has been retrieved, by querying SchizConnect for 105 patients with neurological and clinical symptoms, collecting also their corresponding diagnosis.
cobre61
cobre61
A matrix with 105 rows and 61 columns. Column names are related to different scales for depression and Schizophrenia:
The Simpson-Angus Scale, 7 items to evaluate Parkinsonism-like alterations, related to schizophrenia, in an individual.
The Positive and Negative Syndrome Scale, a set of 29 attributes measuring different aspects and symptoms in schizophrenia.
The Calgary Depression Scale for Schizophrenia, 9 items (attributes) assessing the level of depression in schizophrenia, differentiating between positive and negative aspects of the disease.
The Structured Clinical Interview for DSM-III-R Personality Disorders, with 14 variables related to the presence of signs affecting personality.
if TRUE
, the diagnosis is strict schizophrenia.
it TRUE
, the diagnosis is other than schizophrenia, including schizoaffective, bipolar disorder and major depression.
In summary, the dataset consists in the previous 59 attributes related to signs or symptoms, and 2 attributes related to diagnosis (these diagnoses are mutually exclusive, thus only one of them is assigned to each patient). This makes a dataset with 105 objects (patients) and 61 attributes to explore. The symptom attributes are multi-valued.
Thus, according to the specific scales used, all attributes are fuzzy and graded. For a given attribute (symptom), the available grades range from absent to extreme, with minimal, mild, moderate, moderate severe and severe in between.
These fuzzy attributes are mapped to values in the interval [0, 1].
Aine, C. J., Bockholt, H. J., Bustillo, J. R., Cañive, J. M., Caprihan, A., Gasparovic, C., ... & Liu, J. (2017). Multimodal neuroimaging in schizophrenia: description and dissemination. Neuroinformatics, 15(4), 343-364. https://pubmed.ncbi.nlm.nih.gov/26142271/
This class implements the data structure and methods for fuzzy concepts.
new()
Creator for objects of class Concept
Concept$new(extent, intent)
extent
(Set
) The extent of the concept.
intent
(Set
) The intent of the concept.
An object of class Concept
.
get_extent()
Internal Set
for the extent
Concept$get_extent()
The Set
representation of the extent.
get_intent()
Internal Set
for the intent
Concept$get_intent()
The Set
representation of the intent.
print()
Prints the concept to console
Concept$print()
A string with the elements of the set and their grades between brackets .
to_latex()
Write the concept in LaTeX format
Concept$to_latex(print = TRUE)
print
(logical) Print to output?
The fuzzy concept in LaTeX.
clone()
The objects of this class are cloneable with this method.
Concept$clone(deep = FALSE)
deep
Whether to make a deep clone.
# Build a formal context and find its concepts fc_planets <- FormalContext$new(planets) fc_planets$find_concepts() # Print the first three concepts fc_planets$concepts[1:3] # Select the first concept: C <- fc_planets$concepts$sub(1) # Get its extent and intent C$get_extent() C$get_intent()
# Build a formal context and find its concepts fc_planets <- FormalContext$new(planets) fc_planets$find_concepts() # Print the first three concepts fc_planets$concepts[1:3] # Select the first concept: C <- fc_planets$concepts$sub(1) # Get its extent and intent C$get_extent() C$get_intent()
This class implements the data structure and methods for concept lattices.
fcaR::ConceptSet
-> ConceptLattice
new()
Create a new ConceptLattice
object.
ConceptLattice$new(extents, intents, objects, attributes, I = NULL)
extents
(dgCMatrix
) The extents of all concepts
intents
(dgCMatrix
) The intents of all concepts
objects
(character vector) Names of the objects in the formal context
attributes
(character vector) Names of the attributes in the formal context
I
(dgCMatrix
) The matrix of the formal context
A new ConceptLattice
object.
plot()
Plot the concept lattice
ConceptLattice$plot(object_names = TRUE, to_latex = FALSE, ...)
object_names
(logical) If TRUE
, plot object names, otherwise omit them from the diagram.
to_latex
(logical) If TRUE
, export the plot as a tikzpicture
environment that can be included in a LaTeX
file.
...
Other parameters to be passed to the tikzDevice
that renders the lattice in LaTeX
, or for the figure caption. See Details
.
Particular parameters that control the size of the tikz
output are: width
, height
(both in inches), and pointsize
(in points), that should be set to the font size used in the documentclass
header in the LaTeX
file where the code is to be inserted.
If a caption
is provided, the whole tikz
picture will be wrapped by a figure
environment and the caption set.
If to_latex
is FALSE
, it returns nothing, just plots the graph of the concept lattice. Otherwise, this function returns the LaTeX
code to reproduce the concept lattice.
sublattice()
Sublattice
ConceptLattice$sublattice(...)
...
See Details.
As argument, one can provide both integer indices or Concepts
, separated by commas. The corresponding concepts are used to generate a sublattice.
The generated sublattice as a new ConceptLattice
object.
top()
Top of a Lattice
ConceptLattice$top()
The top of the Concept Lattice
fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$top()
bottom()
Bottom of a Lattice
ConceptLattice$bottom()
The bottom of the Concept Lattice
fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$bottom()
join_irreducibles()
Join-irreducible Elements
ConceptLattice$join_irreducibles()
The join-irreducible elements in the concept lattice.
meet_irreducibles()
Meet-irreducible Elements
ConceptLattice$meet_irreducibles()
The meet-irreducible elements in the concept lattice.
decompose()
Decompose a concept as the supremum of meet-irreducible concepts
ConceptLattice$decompose(C)
C
A list of Concept
s
A list, each field is the set of meet-irreducible elements whose supremum is the corresponding element in C
.
supremum()
Supremum of Concepts
ConceptLattice$supremum(...)
...
See Details.
As argument, one can provide both integer indices or Concepts
, separated by commas. The corresponding concepts are used to compute their supremum in the lattice.
The supremum of the list of concepts.
infimum()
Infimum of Concepts
ConceptLattice$infimum(...)
...
See Details.
As argument, one can provide both integer indices or Concepts
, separated by commas. The corresponding concepts are used to compute their infimum in the lattice.
The infimum of the list of concepts.
subconcepts()
Subconcepts of a Concept
ConceptLattice$subconcepts(C)
C
(numeric or SparseConcept
) The concept to which determine all its subconcepts.
A list with the subconcepts.
superconcepts()
Superconcepts of a Concept
ConceptLattice$superconcepts(C)
C
(numeric or SparseConcept
) The concept to which determine all its superconcepts.
A list with the superconcepts.
lower_neighbours()
Lower Neighbours of a Concept
ConceptLattice$lower_neighbours(C)
C
(SparseConcept
) The concept to which find its lower neighbours
A list with the lower neighbours of C
.
upper_neighbours()
Upper Neighbours of a Concept
ConceptLattice$upper_neighbours(C)
C
(SparseConcept
) The concept to which find its upper neighbours
A list with the upper neighbours of C
.
clone()
The objects of this class are cloneable with this method.
ConceptLattice$clone(deep = FALSE)
deep
Whether to make a deep clone.
# Build a formal context fc_planets <- FormalContext$new(planets) # Find the concepts fc_planets$find_concepts() # Find join- and meet- irreducible elements fc_planets$concepts$join_irreducibles() fc_planets$concepts$meet_irreducibles() # Get concept support fc_planets$concepts$support() ## ------------------------------------------------ ## Method `ConceptLattice$top` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$top() ## ------------------------------------------------ ## Method `ConceptLattice$bottom` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$bottom()
# Build a formal context fc_planets <- FormalContext$new(planets) # Find the concepts fc_planets$find_concepts() # Find join- and meet- irreducible elements fc_planets$concepts$join_irreducibles() fc_planets$concepts$meet_irreducibles() # Get concept support fc_planets$concepts$support() ## ------------------------------------------------ ## Method `ConceptLattice$top` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$top() ## ------------------------------------------------ ## Method `ConceptLattice$bottom` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$find_concepts() fc$concepts$bottom()
This class implements the data structure and methods for concept sets.
new()
Create a new ConceptLattice
object.
ConceptSet$new(extents, intents, objects, attributes, I = NULL)
extents
(dgCMatrix
) The extents of all concepts
intents
(dgCMatrix
) The intents of all concepts
objects
(character vector) Names of the objects in the formal context
attributes
(character vector) Names of the attributes in the formal context
I
(dgCMatrix
) The matrix of the formal context
A new ConceptLattice
object.
size()
Size of the Lattice
ConceptSet$size()
The number of concepts in the lattice.
is_empty()
Is the lattice empty?
ConceptSet$is_empty()
TRUE
if the lattice has no concepts.
extents()
Concept Extents
ConceptSet$extents()
The extents of all concepts, as a dgCMatrix
.
intents()
Concept Intents
ConceptSet$intents()
The intents of all concepts, as a dgCMatrix
.
print()
Print the Concept Set
ConceptSet$print()
Nothing, just prints the concepts
to_latex()
Write in LaTeX
ConceptSet$to_latex(print = TRUE, ncols = 1, numbered = TRUE, align = TRUE)
print
(logical) Print to output?
ncols
(integer) Number of columns of the output.
numbered
(logical) Number the concepts?
align
(logical) Align objects and attributes independently?
The LaTeX
code to list all concepts.
to_list()
Returns a list with all the concepts
ConceptSet$to_list()
A list of concepts.
[()
Subsets a ConceptSet
ConceptSet$[(indices)
indices
(numeric or logical vector) The indices of the concepts to return as a list of Concepts. It can be a vector of logicals where TRUE
elements are to be retained.
Another ConceptSet.
sub()
Individual Concepts
ConceptSet$sub(index)
index
(numeric) The index of the concept to return.
The Concept.
support()
Get support of each concept
ConceptSet$support()
A vector with the support of each concept.
clone()
The objects of this class are cloneable with this method.
ConceptSet$clone(deep = FALSE)
deep
Whether to make a deep clone.
# Build a formal context fc_planets <- FormalContext$new(planets) # Find the concepts fc_planets$find_concepts() # Find join- and meet- irreducible elements fc_planets$concepts$join_irreducibles() fc_planets$concepts$meet_irreducibles()
# Build a formal context fc_planets <- FormalContext$new(planets) # Find the concepts fc_planets$find_concepts() # Find join- and meet- irreducible elements fc_planets$concepts$join_irreducibles() fc_planets$concepts$meet_irreducibles()
Equivalence Rules Registry
equivalencesRegistry
equivalencesRegistry
An object of class equivalence_registry
(inherits from registry
) of length 6.
This is a registry that stores the equivalence rules that can be
applied using the apply_rules()
method in an
ImplicationSet
.
One can obtain the list of available equivalence operators by:
equivalencesRegistry$get_entry_names()
The aim of this package is to provide tools to perform fuzzy formal concept analysis (FCA) from within R. It provides functions to load and save a Formal Context, extract its concept lattice and implications. In addition, one can use the implications to compute semantic closures of fuzzy sets and, thus, build recommendation systems.
The fcaR package provides data structures which allow the user to work seamlessly with formal contexts and sets of implications. More explicitly, three main classes are implemented, using the R6
object-oriented-programming paradigm in R:
FormalContext
encapsulates the definition of a formal context , being
the set of objects,
the set of attributes and
the (fuzzy) relationship matrix, and provides methods to operate on the context using FCA tools.
ImplicationSet
represents a set of implications over a specific formal context.
ConceptLattice
represents the set of concepts and their relationships, including methods to operate on the lattice.
Two additional helper classes are implemented:
Set
is a class solely used for visualization purposes, since it encapsulates in sparse format a (fuzzy) set.
Concept
encapsulates internally both extent and intent of a formal concept as Set
.
Since fcaR is an extension of the data model in the arules package, most of the methods and classes implemented interoperates with the main S4
classes in arules (transactions
and rules
).
Guigues J, Duquenne V (1986). “Familles minimales d'implications informatives résultant d'un tableau de données binaires.” Mathématiques et Sciences humaines, 95, 5-18.
Ganter B, Wille R (1999). Formal concept analysis : mathematical foundations. Springer. ISBN 3540627715.
Cordero P, Enciso M, Mora Á, Pérez de Guzman I (2002). “SLFD Logic: Elimination of Data Redundancy in Knowledge Representation.” Advances in Artificial Intelligence - IBERAMIA 2002, 2527, 141-150. doi: 10.1007/3-540-36131-6_15 (URL: http://doi.org/10.1007/3-540-36131-6_15).
Belohlavek R (2002). “Algorithms for fuzzy concept lattices.” In Proc. Fourth Int. Conf. on Recent Advances in Soft Computing. Nottingham, United Kingdom, 200-205.
Hahsler M, Grun B, Hornik K (2005). “arules - a computational environment for mining association rules and frequent item sets.” J Stat Softw, 14, 1-25.
Mora A, Cordero P, Enciso M, Fortes I, Aguilera G (2012). “Closure via functional dependence simplification.” International Journal of Computer Mathematics, 89(4), 510-526. Belohlavek R, Cordero P, Enciso M, Mora Á, Vychodil V (2016). “Automated prover for attribute dependencies in data with grades.” International Journal of Approximate Reasoning, 70, 51-67.
# Build a formal context fc_planets <- FormalContext$new(planets) # Find its concepts and implications fc_planets$find_implications() # Print the extracted implications fc_planets$implications
# Build a formal context fc_planets <- FormalContext$new(planets) # Find its concepts and implications fc_planets$find_implications() # Print the extracted implications fc_planets$implications
Set or get options for fcaR
fcaR_options(...)
fcaR_options(...)
... |
Option names to retrieve option values or |
The following options are supported
decimal_places
(numeric
;2) The number of decimal places to show when printing or exporting to LaTeX sets, implications, concepts, etc.
latex_size
(character
;"normalsize") Size to use when exporting to LaTeX.
reduced\_lattice
(logical
;TRUE) Plot the reduced concept lattice?
This class implements the data structure and methods for formal contexts.
I
The table of the formal context as a matrix.
attributes
The attributes of the formal context.
objects
The objects of the formal context.
grades_set
The set of degrees (in [0, 1]) the whole set of attributes can take.
expanded_grades_set
The set of degrees (in [0, 1]) each attribute can take.
concepts
The concept lattice associated to the formal context as a ConceptLattice
.
implications
A set of implications on the formal context as an ImplicationSet
.
new()
Creator for the Formal Context class
FormalContext$new(I, filename, remove_const = FALSE)
I
(numeric matrix) The table of the formal context.
filename
(character) Path of a file to import.
remove_const
(logical) If TRUE
, remove constant columns. The default is FALSE
.
Columns of I
should be named, since they are the names of the attributes of the formal context.
If no I
is used, the resulting FormalContext
will be empty and not usable unless for loading a previously saved one. In this case, one can provide a filename
to import. Only RDS, CSV and CXT files are currently supported.
An object of the FormalContext
class.
is_empty()
Check if the FormalContext
is empty
FormalContext$is_empty()
TRUE
if the FormalContext
is empty, that is, has not been provided with a matrix, and FALSE
otherwise.
scale()
Scale the context
FormalContext$scale(attributes, type, ...)
attributes
The attributes to scale
type
Type of scaling.
...
The types of scaling are implemented in a registry,
so that scalingRegistry$get_entries()
returns
all types.
The scaled formal context
filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal")
get_scales()
Scales applied to the formal context
FormalContext$get_scales(attributes = names(private$scales))
attributes
(character) Name of the attributes for which scales (if applied) are returned.
The scales that have been applied to the specified attributes
of the formal context. If no attributes
are passed,
then all applied scales are returned.
filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$get_scales()
background_knowledge()
Background knowledge of a scaled formal context
FormalContext$background_knowledge()
An ImplicationSet
with the implications
extracted from the application of scales.
filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$background_knowledge()
dual()
Get the dual formal context
FormalContext$dual()
A FormalContext
where objects and attributes have interchanged their roles.
intent()
Get the intent of a fuzzy set of objects
FormalContext$intent(S)
S
(Set
) The set of objects to compute the intent for.
A Set
with the intent.
uparrow()
Get the intent of a fuzzy set of objects
FormalContext$uparrow(S)
S
(Set
) The set of objects to compute the intent for.
A Set
with the intent.
extent()
Get the extent of a fuzzy set of attributes
FormalContext$extent(S)
S
(Set
) The set of attributes to compute the extent for.
A Set
with the intent.
downarrow()
Get the extent of a fuzzy set of attributes
FormalContext$downarrow(S)
S
(Set
) The set of attributes to compute the extent for.
A Set
with the intent.
closure()
Get the closure of a fuzzy set of attributes
FormalContext$closure(S)
S
(Set
) The set of attributes to compute the closure for.
A Set
with the closure.
obj_concept()
Object Concept
FormalContext$obj_concept(object)
object
(character) Name of the object to compute its associated concept
The object concept associated to the object given.
att_concept()
Attribute Concept
FormalContext$att_concept(attribute)
attribute
(character) Name of the attribute to compute its associated concept
The attribute concept associated to the attribute given.
is_concept()
Is a Concept?
FormalContext$is_concept(C)
C
A Concept
object
TRUE
if C
is a concept.
is_closed()
Testing closure of attribute sets
FormalContext$is_closed(S)
S
A Set
of attributes
TRUE
if the set S
is closed in this formal context.
clarify()
Clarify a formal context
FormalContext$clarify(copy = FALSE)
copy
(logical) If TRUE
, a new FormalContext
object is created with the clarified context, otherwise the current one is overwritten.
The clarified FormalContext
.
reduce()
Reduce a formal context
FormalContext$reduce(copy = FALSE)
copy
(logical) If TRUE
, a new FormalContext
object is created with the clarified and reduced context, otherwise the current one is overwritten.
The clarified and reduced FormalContext
.
standardize()
Build the Standard Context
FormalContext$standardize()
All concepts must be previously computed.
The standard context using the join- and meet- irreducible elements.
find_concepts()
Use Ganter Algorithm to compute concepts
FormalContext$find_concepts(verbose = FALSE)
verbose
(logical) TRUE will provide a verbose output.
A list with all the concepts in the formal context.
find_implications()
Use modified Ganter algorithm to compute both concepts and implications
FormalContext$find_implications(save_concepts = TRUE, verbose = FALSE)
save_concepts
(logical) TRUE
will also compute and save the concept lattice. FALSE
is usually faster, since it only computes implications.
verbose
(logical) TRUE
will provide a verbose output.
Nothing, just updates the internal fields concepts
and implications
.
to_transactions()
Convert the formal context to object of class transactions
from the arules
package
FormalContext$to_transactions()
A transactions
object.
save()
Save a FormalContext
to RDS or CXT format
FormalContext$save(filename = tempfile(fileext = ".rds"))
filename
(character) Path of the file where to store the FormalContext
.
The format is inferred from the extension of the filename.
Invisibly the current FormalContext
.
load()
Load a FormalContext
from a file
FormalContext$load(filename)
filename
(character) Path of the file to load the FormalContext
from.
Currently, only RDS, CSV and CXT files are supported.
The loaded FormalContext
.
dim()
Dimensions of the formal context
FormalContext$dim()
A vector with (number of objects, number of attributes).
print()
Prints the formal context
FormalContext$print()
Prints information regarding the formal context.
to_latex()
Write the context in LaTeX format
FormalContext$to_latex(table = TRUE, label = "", caption = "")
table
(logical) If TRUE
, surrounds everything between \begin{table}
and \end{table}
.
label
(character) The label for the table environment.
caption
(character) The caption of the table.
fraction
(character) If none
, no fractions are produced. Otherwise, if it is frac
, dfrac
or sfrac
, decimal numbers are represented as fractions with the corresponding LaTeX typesetting.
A table environment in LaTeX.
incidence()
Incidence matrix of the formal context
FormalContext$incidence()
The incidence matrix of the formal context
fc <- FormalContext$new(planets) fc$incidence()
subcontext()
Subcontext of the formal context
FormalContext$subcontext(objects, attributes)
objects
(character array) Name of the objects to keep.
attributes
(character array) Names of the attributes to keep.
A warning will be issued if any of the names is not present in the list of objects or attributes of the formal context.
If objects
or attributes
is empty, then it is
assumed to represent the whole set of objects or attributes
of the original formal context.
Another FormalContext
that is a subcontext
of the original one, with only the objects and attributes
selected.
fc <- FormalContext$new(planets) fc$subcontext(attributes = c("moon", "no_moon"))
[()
Subcontext of the formal context
FormalContext$[(objects, attributes)
objects
(character array) Name of the objects to keep.
attributes
(character array) Names of the attributes to keep.
A warning will be issued if any of the names is not present in the list of objects or attributes of the formal context.
If objects
or attributes
is empty, then it is
assumed to represent the whole set of objects or attributes
of the original formal context.
Another FormalContext
that is a subcontext
of the original one, with only the objects and attributes
selected.
fc <- FormalContext$new(planets) fc[, c("moon", "no_moon")]
plot()
Plot the formal context table
FormalContext$plot(to_latex = FALSE, ...)
to_latex
(logical) If TRUE
, export the plot as a tikzpicture
environment that can be included in a LaTeX
file.
...
Other parameters to be passed to the tikzDevice
that renders the lattice in LaTeX
, or for the figure caption. See Details
.
Particular parameters that control the size of the tikz
output are: width
, height
(both in inches), and pointsize
(in points), that should be set to the font size used in the documentclass
header in the LaTeX
file where the code is to be inserted.
If a caption
is provided, the whole tikz
picture will be wrapped by a figure
environment and the caption set.
If to_latex
is FALSE
, it returns nothing, just plots the graph of the formal context. Otherwise, this function returns the LaTeX
code to reproduce the formal context plot.
use_logic()
Sets the logic to use
FormalContext$use_logic(name = available_logics())
name
The name of the logic to use. To see the available names, run available_logics()
.
get_logic()
Gets the logic used
FormalContext$get_logic()
A string with the name of the logic.
use_connection()
Sets the name of the Galois connection to use
FormalContext$use_connection(connection)
connection
The name of the Galois connection. Available connections are "standard" (antitone), "benevolent1" and "benevolent2" (isotone)
get_connection()
Gets the name of the Galois connection
FormalContext$get_connection()
A string with the name of the Galois connection
clone()
The objects of this class are cloneable with this method.
FormalContext$clone(deep = FALSE)
deep
Whether to make a deep clone.
Guigues J, Duquenne V (1986). “Familles minimales d'implications informatives résultant d'un tableau de données binaires.” Mathématiques et Sciences humaines, 95, 5-18.
Ganter B, Wille R (1999). Formal concept analysis : mathematical foundations. Springer. ISBN 3540627715.
Belohlavek R (2002). “Algorithms for fuzzy concept lattices.” In Proc. Fourth Int. Conf. on Recent Advances in Soft Computing. Nottingham, United Kingdom, 200-205.
Hahsler M, Grun B, Hornik K (2005). “arules - a computational environment for mining association rules and frequent item sets.” J Stat Softw, 14, 1-25.
# Build and print the formal context fc_planets <- FormalContext$new(planets) print(fc_planets) # Define a set of attributes S <- Set$new(attributes = fc_planets$attributes) S$assign(moon = 1, large = 1) # Compute the closure of S Sc <- fc_planets$closure(S) # Is Sc a closed set? fc_planets$is_closed(Sc) # Clarify and reduce the formal context fc2 <- fc_planets$reduce(TRUE) # Find implications fc_planets$find_implications() # Read a formal context from CSV filename <- system.file("contexts", "airlines.csv", package = "fcaR") fc <- FormalContext$new(filename) # Read a formal context from a CXT file filename <- system.file("contexts", "lives_in_water.cxt", package = "fcaR") fc <- FormalContext$new(filename) ## ------------------------------------------------ ## Method `FormalContext$scale` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") ## ------------------------------------------------ ## Method `FormalContext$get_scales` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$get_scales() ## ------------------------------------------------ ## Method `FormalContext$background_knowledge` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$background_knowledge() ## ------------------------------------------------ ## Method `FormalContext$incidence` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$incidence() ## ------------------------------------------------ ## Method `FormalContext$subcontext` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$subcontext(attributes = c("moon", "no_moon")) ## ------------------------------------------------ ## Method `FormalContext$[` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc[, c("moon", "no_moon")]
# Build and print the formal context fc_planets <- FormalContext$new(planets) print(fc_planets) # Define a set of attributes S <- Set$new(attributes = fc_planets$attributes) S$assign(moon = 1, large = 1) # Compute the closure of S Sc <- fc_planets$closure(S) # Is Sc a closed set? fc_planets$is_closed(Sc) # Clarify and reduce the formal context fc2 <- fc_planets$reduce(TRUE) # Find implications fc_planets$find_implications() # Read a formal context from CSV filename <- system.file("contexts", "airlines.csv", package = "fcaR") fc <- FormalContext$new(filename) # Read a formal context from a CXT file filename <- system.file("contexts", "lives_in_water.cxt", package = "fcaR") fc <- FormalContext$new(filename) ## ------------------------------------------------ ## Method `FormalContext$scale` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") ## ------------------------------------------------ ## Method `FormalContext$get_scales` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$get_scales() ## ------------------------------------------------ ## Method `FormalContext$background_knowledge` ## ------------------------------------------------ filename <- system.file("contexts", "aromatic.csv", package = "fcaR") fc <- FormalContext$new(filename) fc$scale("nitro", "ordinal", comparison = `>=`, values = 1:3) fc$scale("OS", "nominal", c("O", "S")) fc$scale(attributes = "ring", type = "nominal") fc$background_knowledge() ## ------------------------------------------------ ## Method `FormalContext$incidence` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$incidence() ## ------------------------------------------------ ## Method `FormalContext$subcontext` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc$subcontext(attributes = c("moon", "no_moon")) ## ------------------------------------------------ ## Method `FormalContext$[` ## ------------------------------------------------ fc <- FormalContext$new(planets) fc[, c("moon", "no_moon")]
This class implements the structure needed to store implications and the methods associated.
new()
Initialize with an optional name
ImplicationSet$new(...)
...
See Details.
Creates and initialize a new ImplicationSet
object. It can be done in two ways:
initialize(name, attributes, lhs, rhs)
or initialize(rules)
In the first way, the only mandatory argument is attributes
, (character vector) which is a vector of names of the attributes on which we define the implications. Optional arguments are: name
(character string), name of the implication set, lhs
(a dgCMatrix
), initial LHS of the implications stored and the analogous rhs
.
The other way is used to initialize the ImplicationSet
object from a rules
object from package arules
.
A new ImplicationSet
object.
get_attributes()
Get the names of the attributes
ImplicationSet$get_attributes()
A character vector with the names of the attributes used in the implications.
[()
Get a subset of the implication set
ImplicationSet$[(idx)
idx
(integer or logical vector) Indices of the implications to extract or remove. If logical vector, only TRUE
elements are retained and the rest discarded.
A new ImplicationSet
with only the rules given by the idx
indices (if all idx > 0
and all but idx
if all idx < 0
.
to_arules()
Convert to arules format
ImplicationSet$to_arules(quality = TRUE)
quality
(logical) Compute the interest measures for each rule?
A rules
object as used by package arules
.
add()
Add a precomputed implication set
ImplicationSet$add(...)
...
An ImplicationSet
object, a rules
object, or a pair lhs
, rhs
of Set
objects or dgCMatrix
. The implications to add to this formal context.
Nothing, just updates the internal implications
field.
cardinality()
Cardinality: Number of implications in the set
ImplicationSet$cardinality()
The cardinality of the implication set.
is_empty()
Empty set
ImplicationSet$is_empty()
TRUE
if the set of implications is empty, FALSE
otherwise.
size()
Size: number of attributes in each of LHS and RHS
ImplicationSet$size()
A vector with two components: the number of attributes present in each of the LHS and RHS of each implication in the set.
closure()
Compute the semantic closure of a fuzzy set with respect to the implication set
ImplicationSet$closure(S, reduce = FALSE, verbose = FALSE)
S
(a Set
object) Fuzzy set to compute its closure. Use class Set
to build it.
reduce
(logical) Reduce the implications using simplification logic?
verbose
(logical) Show verbose output?
If reduce == FALSE
, the output is a fuzzy set corresponding to the closure of S
. If reduce == TRUE
, a list with two components: closure
, with the closure as above, and implications
, the reduced set of implications.
recommend()
Generate a recommendation for a subset of the attributes
ImplicationSet$recommend(S, attribute_filter)
S
(a vector) Vector with the grades of each attribute (a fuzzy set).
attribute_filter
(character vector) Names of the attributes to get recommendation for.
A fuzzy set describing the values of the attributes in attribute_filter
within the closure of S
.
apply_rules()
Apply rules to remove redundancies
ImplicationSet$apply_rules( rules = c("composition", "generalization"), batch_size = 25000L, parallelize = FALSE, reorder = FALSE )
rules
(character vector) Names of the rules to use. See details
.
batch_size
(integer) If the number of rules is large, apply the rules by batches of this size.
parallelize
(logical) If possible, should we parallelize the computation among different batches?
reorder
(logical) Should the rules be randomly reordered previous to the computation?
Currently, the implemented rules are "generalization"
, "simplification"
, "reduction"
and "composition"
.
Nothing, just updates the internal matrices for LHS and RHS.
to_basis()
Convert Implications to Canonical Basis
ImplicationSet$to_basis()
The canonical basis of implications obtained from the current ImplicationSet
print()
Print all implications to text
ImplicationSet$print()
A string with all the implications in the set.
to_latex()
Export to LaTeX
ImplicationSet$to_latex( print = TRUE, ncols = 1, numbered = TRUE, numbers = seq(self$cardinality()) )
print
(logical) Print to output?
ncols
(integer) Number of columns for the output.
numbered
(logical) If TRUE
(default), implications will be numbered in the output.
numbers
(vector) If numbered
, use these elements to enumerate the implications. The default is to enumerate 1, 2, ..., but can be changed.
A string in LaTeX format that prints nicely all the implications.
get_LHS_matrix()
Get internal LHS matrix
ImplicationSet$get_LHS_matrix()
A sparse matrix representing the LHS of the implications in the set.
get_RHS_matrix()
Get internal RHS matrix
ImplicationSet$get_RHS_matrix()
A sparse matrix representing the RHS of the implications in the set.
filter()
Filter implications by attributes in LHS and RHS
ImplicationSet$filter( lhs = NULL, not_lhs = NULL, rhs = NULL, not_rhs = NULL, drop = FALSE )
lhs
(character vector) Names of the attributes to filter the LHS by. If NULL
, no filtering is done on the LHS.
not_lhs
(character vector) Names of the attributes to not include in the LHS. If NULL
(the default), it is not considered at all.
rhs
(character vector) Names of the attributes to filter the RHS by. If NULL
, no filtering is done on the RHS.
not_rhs
(character vector) Names of the attributes to not include in the RHS. If NULL
(the default), it is not considered at all.
drop
(logical) Remove the rest of attributes in RHS?
An ImplicationSet
that is a subset of the current set, only with those rules which has the attributes in lhs
and rhs
in their LHS and RHS, respectively.
support()
Compute support of each implication
ImplicationSet$support()
A vector with the support of each implication
clone()
The objects of this class are cloneable with this method.
ImplicationSet$clone(deep = FALSE)
deep
Whether to make a deep clone.
Ganter B, Obiedkov S (2016). Conceptual Exploration. Springer. https://doi.org/10.1007/978-3-662-49291-8
Hahsler M, Grun B, Hornik K (2005). “arules - a computational environment for mining association rules and frequent item sets.” J Stat Softw, 14, 1-25.
Belohlavek R, Cordero P, Enciso M, Mora Á, Vychodil V (2016). “Automated prover for attribute dependencies in data with grades.” International Journal of Approximate Reasoning, 70, 51-67.
Mora A, Cordero P, Enciso M, Fortes I, Aguilera G (2012). “Closure via functional dependence simplification.” International Journal of Computer Mathematics, 89(4), 510-526.
# Build a formal context fc_planets <- FormalContext$new(planets) # Find its implication basis fc_planets$find_implications() # Print implications fc_planets$implications # Cardinality and mean size in the ruleset fc_planets$implications$cardinality() sizes <- fc_planets$implications$size() colMeans(sizes) # Simplify the implication set fc_planets$implications$apply_rules("simplification")
# Build a formal context fc_planets <- FormalContext$new(planets) # Find its implication basis fc_planets$find_implications() # Print implications fc_planets$implications # Cardinality and mean size in the ruleset fc_planets$implications$cardinality() sizes <- fc_planets$implications$size() colMeans(sizes) # Simplify the implication set fc_planets$implications$apply_rules("simplification")
Parses a string into an implication
parse_implication(string, attributes)
parse_implication(string, attributes)
string |
(character) The string to be parsed |
attributes |
(character vector) The attributes' names |
Two vectors as sparse matrices representing the LHS and RHS of the implication
Parses several implications given as a string
parse_implications(input)
parse_implications(input)
input |
(character) The string with the implications or a file containing the implications |
The format for the input file is:
Every implication in its own line or separated by semicolon (;)
Attributes are separated by commas (,)
The LHS and RHS of each implication are separated by an arrow (->)
An ImplicationSet
input <- system.file("implications", "ex_implications", package = "fcaR") imps <- parse_implications(input)
input <- system.file("implications", "ex_implications", package = "fcaR") imps <- parse_implications(input)
This dataset records some properties of the planets in our solar system.
planets
planets
A matrix with 9 rows (the planets) and 7 columns, representing additional features of the planets:
1 if the planet is small, 0 otherwise.
1 if the planet is medium-sized, 0 otherwise.
1 if the planet is large, 0 otherwise.
1 if the planet belongs in the inner solar system, 0 otherwise.
1 if the planet belongs in the outer solar system, 0 otherwise.
1 if the planet has a natural moon, 0 otherwise.
1 if the planet has no moon, 0 otherwise.
Wille R (1982). “Restructuring Lattice Theory: An Approach Based on Hierarchies of Concepts.” In Ordered Sets, pp. 445–470. Springer.
Scaling Registry
scalingRegistry
scalingRegistry
An object of class scaling_registry
(inherits from registry
) of length 6.
This is a registry that stores the implemented scales that can be
applied using the scale()
method in an
FormalContext
.
One can obtain the list of available equivalence operators by:
scalingRegistry$get_entry_names()
This class implements the data structure and methods for fuzzy sets.
new()
Creator for objects of class Set
Set$new(attributes, M = NULL, ...)
attributes
(character vector) Names of the attributes that will be available in the fuzzy set.
M
(numeric vector or column Matrix
) Values (grades) to be assigned to the attributes.
...
key
= value
pairs, where the value value
is assigned to the key
attribute name.
If M
is omitted and no pair key
= value
, the fuzzy set is the empty set. Later, one can use the assign
method to assign grades to any of its attributes.
An object of class Set
.
assign()
Assign grades to attributes in the set
Set$assign(attributes = c(), values = c(), ...)
attributes
(character vector) Names of the attributes to assign a grade to.
values
(numeric vector) Grades to be assigned to the previous attributes
.
...
key
= value
pairs, where the value value
is assigned to the key
attribute name.
One can use both of:
S$assign(A = 1, B = 0.3)
S$assign(attributes = c(A, B), values = c(1, 0.3))
.
[()
Get elements by index
Set$[(indices)
indices
(numeric, logical or character vector) The indices of the elements to return. It can be a vector of logicals where TRUE
elements are to be retained.
A Set
but with only the required elements.
cardinal()
Cardinal of the Set
Set$cardinal()
the cardinal of the Set
, counted
as the sum of the degrees of each element.
get_vector()
Internal Matrix
Set$get_vector()
The internal sparse Matrix
representation of the set.
get_attributes()
Attributes defined for the set
Set$get_attributes()
A character vector with the names of the attributes.
length()
Number of attributes
Set$length()
The number of attributes that are defined for this fuzzy set.
print()
Prints the set to console
Set$print(eol = TRUE)
eol
(logical) If TRUE
, adds an end of line to the output.
A string with the elements of the set and their grades between brackets .
to_latex()
Write the set in LaTeX format
Set$to_latex(print = TRUE)
print
(logical) Print to output?
The fuzzy set in LaTeX.
clone()
The objects of this class are cloneable with this method.
Set$clone(deep = FALSE)
deep
Whether to make a deep clone.
S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) print(S) S$to_latex() S <- Set$new(c("A", "B", "C"), C = 1, B = 0.5) S
S <- Set$new(attributes = c("A", "B", "C")) S$assign(A = 1) print(S) S$to_latex() S <- Set$new(c("A", "B", "C"), C = 1, B = 0.5) S
The dataset vegas
is the binary translation of the Las Vegas Strip dataset (@moro2017stripping), which records more than 500 TripAdvisor reviews of hotels in Las Vegas Strip. The uninformative attributes (such as the user continent or the weekday of the review) are removed.
vegas
vegas
A matrix with 504 rows and 25 binary columns. Column names are related to different features of the hotels:
4 categories are present in the original data, which produces as many binary variables: Period of stay=Dec-Feb
, Period of stay=Mar-May
, Period of stay=Jun-Aug
and Period of stay=Sep-Nov
.
Five binary categories are created from the original data: Traveler type=Business
, Traveler type=Couples
, Traveler type=Families
, Traveler type=Friends
and Traveler type=Solo
.
Binary variables for the services offered by each destination hotel
Five binary variables are created, according to the number of stars of the hotel, Stars=3
, Stars=3.5
, Stars=4
, Stars=4.5
and Stars=5
.
The score assigned in the review, from Score=1
to Score=5
.
Moro, S., Rita, P., & Coelho, J. (2017). Stripping customers' feedback on hotels through data mining: The case of Las Vegas Strip. Tourism Management Perspectives, 23, 41-52.