Biblioteca amigable de Scikit-Learn para explicar, predecir y dirigir modelos/datos de texto.
También un montón de servicios públicos para comenzar con datos de texto.
cuadernos de demostración
Modelado/dirección explicable
| Modelo | Referencia | Producción | Descripción |
|---|---|---|---|
| Prompte de árboles | ,?,? ,, | Explicación + Dirección | Genera un árbol de indicaciones para Steer An LLM ( oficial ) |
| iprompt | ,?,?, | Explicación + Dirección | Genera un mensaje que explica los patrones en los datos ( oficial ) |
| Autopromptar | ㅤㅤ,? ,? | Explicación + Dirección | Encuentra un aviso de lenguaje natural Usando gradientes de entrada |
| D3 | ,?,?, | Explicación | Explicar la diferencia entre dos distribuciones |
| SASC | ㅤㅤ,? ,? | Explicación | Explique un módulo de texto de caja negra Usando un LLM ( oficial ) |
| Agosto-lineal | ,?,?, | Modelo lineal | Fit Better Lineal Model usando un LLM extraer incrustaciones ( oficial ) |
| Agosto | ,?,?, | Árbol de decisión | Ajuste mejor árbol de decisión usando un LLM Para expandir las características ( oficial ) |
| Chaón | ,?,?, | Explicable incrustación | Generar incrustaciones interpretables Haciendo preguntas de LLMS ( oficial ) |
| Kan | ,?,?, | Pequeño red | Ajustar la red Kolmogorov-Arnold de 2 capas |
¿Notebooks de demostración doc? Código de referencia? Trabajo de investigación
⌛ Planeamos apoyar otros algoritmos interpretables como RLPROMPT, CBMS y NBDT. Si desea contribuir con un algoritmo, ¿no dude en abrir un PR?
Utilidades generales
| Modelo | Referencia |
|---|---|
| Envoltura de LLM | Llame fácilmente a diferentes LLM |
| Contenedor de datos | Descargue conjuntos de datos de Facing de Huggingface mínimamente procesados |
| Bolsa de ngrams | Aprenda un modelo lineal de ngrams |
| Finetune lineal | Finetune una sola capa lineal sobre las embebidos de LLM |
Instalación : pip install imodelsx (o, para obtener más control, clon e instalar desde la fuente)
Demoss : ver los cuadernos de demostración
from imodelsx import TreePromptClassifier
import datasets
import numpy as np
from sklearn . tree import plot_tree
import matplotlib . pyplot as plt
# set up data
rng = np . random . default_rng ( seed = 42 )
dset_train = datasets . load_dataset ( 'rotten_tomatoes' )[ 'train' ]
dset_train = dset_train . select ( rng . choice (
len ( dset_train ), size = 100 , replace = False ))
dset_val = datasets . load_dataset ( 'rotten_tomatoes' )[ 'validation' ]
dset_val = dset_val . select ( rng . choice (
len ( dset_val ), size = 100 , replace = False ))
# set up arguments
prompts = [
"This movie is" ,
" Positive or Negative? The movie was" ,
" The sentiment of the movie was" ,
" The plot of the movie was really" ,
" The acting in the movie was" ,
]
verbalizer = { 0 : " Negative." , 1 : " Positive." }
checkpoint = "gpt2"
# fit model
m = TreePromptClassifier (
checkpoint = checkpoint ,
prompts = prompts ,
verbalizer = verbalizer ,
cache_prompt_features_dir = None , # 'cache_prompt_features_dir/gp2',
)
m . fit ( dset_train [ "text" ], dset_train [ "label" ])
# compute accuracy
preds = m . predict ( dset_val [ 'text' ])
print ( ' n Tree-Prompt acc (val) ->' ,
np . mean ( preds == dset_val [ 'label' ])) # -> 0.7
# compare to accuracy for individual prompts
for i , prompt in enumerate ( prompts ):
print ( i , prompt , '->' , m . prompt_accs_ [ i ]) # -> 0.65, 0.5, 0.5, 0.56, 0.51
# visualize decision tree
plot_tree (
m . clf_ ,
fontsize = 10 ,
feature_names = m . feature_names_ ,
class_names = list ( verbalizer . values ()),
filled = True ,
)
plt . show () from imodelsx import explain_dataset_iprompt , get_add_two_numbers_dataset
# get a simple dataset of adding two numbers
input_strings , output_strings = get_add_two_numbers_dataset ( num_examples = 100 )
for i in range ( 5 ):
print ( repr ( input_strings [ i ]), repr ( output_strings [ i ]))
# explain the relationship between the inputs and outputs
# with a natural-language prompt string
prompts , metadata = explain_dataset_iprompt (
input_strings = input_strings ,
output_strings = output_strings ,
checkpoint = 'EleutherAI/gpt-j-6B' , # which language model to use
num_learned_tokens = 3 , # how long of a prompt to learn
n_shots = 3 , # shots per example
n_epochs = 15 , # how many epochs to search
verbose = 0 , # how much to print
llm_float16 = True , # whether to load the model in float_16
)
- - - - - - - -
prompts is a list of found natural - language prompt strings from imodelsx import explain_dataset_d3
hypotheses , hypothesis_scores = explain_dataset_d3 (
pos = positive_samples , # List[str] of positive examples
neg = negative_samples , # another List[str]
num_steps = 100 ,
num_folds = 2 ,
batch_size = 64 ,
)Aquí, explicamos un módulo en lugar de un conjunto de datos
from imodelsx import explain_module_sasc
# a toy module that responds to the length of a string
mod = lambda str_list : np . array ([ len ( s ) for s in str_list ])
# a toy dataset where the longest strings are animals
text_str_list = [ "red" , "blue" , "x" , "1" , "2" , "hippopotamus" , "elephant" , "rhinoceros" ]
explanation_dict = explain_module_sasc (
text_str_list ,
mod ,
ngrams = 1 ,
)Use estos solo un modelo de ciencia ficción. Durante el entrenamiento, se ajustan a mejores características a través de LLMS, pero en el tiempo de prueba son extremadamente rápidos y completamente transparentes.
from imodelsx import AugLinearClassifier , AugTreeClassifier , AugLinearRegressor , AugTreeRegressor
import datasets
import numpy as np
# set up data
dset = datasets . load_dataset ( 'rotten_tomatoes' )[ 'train' ]
dset = dset . select ( np . random . choice ( len ( dset ), size = 300 , replace = False ))
dset_val = datasets . load_dataset ( 'rotten_tomatoes' )[ 'validation' ]
dset_val = dset_val . select ( np . random . choice ( len ( dset_val ), size = 300 , replace = False ))
# fit model
m = AugLinearClassifier (
checkpoint = 'textattack/distilbert-base-uncased-rotten-tomatoes' ,
ngrams = 2 , # use bigrams
)
m . fit ( dset [ 'text' ], dset [ 'label' ])
# predict
preds = m . predict ( dset_val [ 'text' ])
print ( 'acc_val' , np . mean ( preds == dset_val [ 'label' ]))
# interpret
print ( 'Total ngram coefficients: ' , len ( m . coefs_dict_ ))
print ( 'Most positive ngrams' )
for k , v in sorted ( m . coefs_dict_ . items (), key = lambda item : item [ 1 ], reverse = True )[: 8 ]:
print ( ' t ' , k , round ( v , 2 ))
print ( 'Most negative ngrams' )
for k , v in sorted ( m . coefs_dict_ . items (), key = lambda item : item [ 1 ])[: 8 ]:
print ( ' t ' , k , round ( v , 2 )) import imodelsx
from sklearn . datasets import make_classification , make_regression
from sklearn . metrics import accuracy_score
import numpy as np
X , y = make_classification ( n_samples = 5000 , n_features = 5 , n_informative = 3 )
model = imodelsx . KANClassifier ( hidden_layer_size = 64 , device = 'cpu' ,
regularize_activation = 1.0 , regularize_entropy = 1.0 )
model . fit ( X , y )
y_pred = model . predict ( X )
print ( 'Test acc' , accuracy_score ( y , y_pred ))
# now try regression
X , y = make_regression ( n_samples = 5000 , n_features = 5 , n_informative = 3 )
model = imodelsx . kan . KANRegressor ( hidden_layer_size = 64 , device = 'cpu' ,
regularize_activation = 1.0 , regularize_entropy = 1.0 )
model . fit ( X , y )
y_pred = model . predict ( X )
print ( 'Test correlation' , np . corrcoef ( y , y_pred . flatten ())[ 0 , 1 ])Las líneas de base fáciles de ajustar que siguen a la API Sklearn.
from imodelsx import LinearFinetuneClassifier , LinearNgramClassifier
# fit a simple one-layer finetune on top of LLM embeddings
m = LinearFinetuneClassifier (
checkpoint = 'distilbert-base-uncased' ,
)
m . fit ( dset [ 'text' ], dset [ 'label' ])
preds = m . predict ( dset_val [ 'text' ])
acc = ( preds == dset_val [ 'label' ]). mean ()
print ( 'validation acc' , acc )API fácil para llamar a diferentes modelos de idiomas con almacenamiento en caché (mucho más liviano que Langchain).
import imodelsx . llm
# supports any huggingface checkpoint or openai checkpoint (including chat models)
llm = imodelsx . llm . get_llm (
checkpoint = "gpt2-xl" , # text-davinci-003, gpt-3.5-turbo, ...
CACHE_DIR = ".cache" ,
)
out = llm ( "May the Force be" )
llm ( "May the Force be" ) # when computing the same string again, uses the cacheAPI para cargar conjuntos de datos Huggingface con preprocesamiento básico.
import imodelsx . data
dset , dataset_key_text = imodelsx . data . load_huggingface_dataset ( 'ag_news' )
# Ensures that dset has a split named 'train' and 'validation',
# and that the input data is contained for each split in a column given by {dataset_key_text}