sklearn-embedding-transformer is a lightweight Python library designed to create and use feature embeddings with scikit-learn. It allows you to handcraft features and generate embeddings using a Multi-Layer Perceptron (MLP), making it easy to integrate with scikit-learn pipelines and workflows. The library does not have any additional dependencies beyond scikit-learn.
- Customizable Embeddings: Generate embeddings with adjustable hidden layers and embedding sizes.
- PCA for Dimensionality Reduction: Optionally apply PCA to reduce the dimensionality of the embeddings.
- Similarity Search: Perform similarity searches using cosine similarity to find the most similar items based on their embeddings.
- Easy Integration: Use seamlessly in scikit-learn pipelines and workflows.
- No Extra Dependencies: Built with scikit-learn only.
You can install the library via pip (TODO: publish it first...):
pip install sklearn-embedding-transformerfrom sklearn_embedding_transformer import MLPEmbeddingTransformer
# Define and train the transformer
transformer = MLPEmbeddingTransformer(
hidden_layer_sizes=(200, 100, 50),
hidden_layer_index=1,
embedding_size=64,
max_iter=1000
)
# Example data: List of dictionaries with categorical features
data = [
{'feature1': 'A', 'feature2': 'B'},
{'feature1': 'A', 'feature2': 'C'},
{'feature1': 'B', 'feature2': 'B'},
{'feature1': 'B', 'feature2': 'C'},
{'feature1': 'C', 'feature2': 'B'},
]
# Target labels - choose this in a way that creates meaningful embeddings for your specific domain
y = [0, 1, 0, 1, 0]
# Fit the transformer on your data
transformer.fit(data, y)
# Transform your data to get embeddings
embeddings = transformer.transform(data)
# Save and load the transformer
transformer.save('mlp_embedding_transformer.pkl')
loaded_transformer = MLPEmbeddingTransformer.load('mlp_embedding_transformer.pkl')
loaded_embeddings = loaded_transformer.transform(data)from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
def evaluate_classifiers(X_train, X_test, y_train, y_test):
classifiers = {
'Logistic Regression': LogisticRegression(max_iter=1000),
'MLP Classifier': MLPClassifier(max_iter=1000, random_state=42),
'SVM': SVC(),
'Random Forest': RandomForestClassifier(random_state=42)
}
results = {}
for name, clf in classifiers.items():
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
results[name] = accuracy
return results
# Example usage
X_train_emb, X_test_emb, y_train_emb, y_test_emb = train_test_split(embeddings, y, test_size=0.2, random_state=42)
results_embeddings = evaluate_classifiers(X_train_emb, X_test_emb, y_train_emb, y_test_emb)
print("Evaluating classifiers using embeddings:")
for name, accuracy in results_embeddings.items():
print(f"{name} accuracy: {accuracy:.2f}")
X_train_orig, X_test_orig, y_train_orig, y_test_orig = train_test_split(data, y, test_size=0.2, random_state=42)
vectorizer = DictVectorizer(sparse=False)
X_train_orig_vect = vectorizer.fit_transform(X_train_orig)
X_test_orig_vect = vectorizer.transform(X_test_orig)
results_original = evaluate_classifiers(X_train_orig_vect, X_test_orig_vect, y_train_orig, y_test_orig)
print("Evaluating classifiers using original features:")
for name, accuracy in results_original.items():
print(f"{name} accuracy: {accuracy:.2f}")from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
def find_most_similar(embeddings, query_embedding, top_n=5):
similarities = cosine_similarity(embeddings, query_embedding.reshape(1, -1))
most_similar_indices = np.argsort(similarities.flatten())[-top_n:]
return most_similar_indices, similarities[most_similar_indices]
# Example usage
query_index = 10
query_embedding = embeddings[query_index]
top_n = 5
most_similar_indices, similarities = find_most_similar(embeddings, query_embedding, top_n)
print(f"Query index: {query_index}")
print(f"Top {top_n} most similar indices:")
for idx, similarity in zip(most_similar_indices, similarities.flatten()):
print(f"Index: {idx}, Similarity: {similarity:.4f}")- Feature Engineering: Convert handcrafted features into embeddings for use in machine learning models.
- Recommendation Systems: Use embeddings to find items similar to a given query.
- Information Retrieval: Retrieve similar documents or records from a large dataset based on their embeddings.
- Anomaly Detection: Identify items that are most different from a given reference.
The classification task used to train the embeddings should align with your specific use case:
- Media Classification: For example, classifying media types like radio, movie, or podcast can help in building embeddings that are tailored to these categories.
- Artist to Genre Mapping: For mapping artist names to genres, embeddings can help in finding the closest artists by genre similarity.
You can compare embeddings using metrics like cosine similarity. This helps in identifying how similar two items are based on their vector representations. This can be useful for recommendation systems, similarity search, and more.