Exemplo n.º 1
0
def test_not_fitted_exception():
    """Test predicting with a model that has not been fitted"""

    X_train, y_train, X_dev, y_dev = sst2_test_data()

    model = BertClassifier()
    model.max_seq_length = 64
    model.train_batch_size = 8
    model.epochs = 1

    # model has not been fitted: model.fit(X_train, y_train)
    with pytest.raises(Exception):
        model.score(X_dev, y_dev)
Exemplo n.º 2
0
def test_save_load_model():
    """Test saving/loading a fitted model to disk"""

    X_train, y_train, X_dev, y_dev = sst2_test_data()

    model = BertClassifier()
    model.max_seq_length = 64
    model.train_batch_size = 8
    model.epochs = 1

    model.fit(X_train, y_train)

    accy1 = model.score(X_dev, y_dev)

    savefile = './test_model_save.bin'
    print("\nSaving model to ", savefile)

    model.save(savefile)

    # load model from disk
    new_model = load_model(savefile)

    # predict with new model
    accy2 = new_model.score(X_dev, y_dev)

    # clean up
    print("Cleaning up model file: test_model_save.bin ")
    os.remove(savefile)

    assert accy1 == accy2
Exemplo n.º 3
0
def test_bert_sklearn_accy():
    """
    Test bert_sklearn accuracy
    compare against  huggingface run_classifier.py
    on 200 rows of SST-2 data.
    """
    print("Running bert-sklearn...")
    X_train, y_train, X_dev, y_dev, label_list = toxic_test_data()

    # define model
    model = BertClassifier()
    model.validation_fraction = 0.0
    model.learning_rate = 5e-5
    model.gradient_accumulation_steps = 2
    model.max_seq_length = 64
    model.train_batch_size = 16
    model.eval_batch_size = 8
    model.epochs = 2
    model.multilabel = True  # for multi-label classification
    model.label_list = label_list

    model.fit(X_train, y_train)

    bert_sklearn_accy = model.score(X_dev, y_dev)
    bert_sklearn_accy /= 100

    # run huggingface BERT run_classifier and check we get the same accuracy
    cmd = r"python tests/run_classifier.py --task_name sst-2 \
                                --data_dir ./tests/data/sst2 \
                                --do_train  --do_eval \
                                --output_dir ./comptest \
                                --bert_model bert-base-uncased \
                                --do_lower_case \
                                --learning_rate 5e-5 \
                                --gradient_accumulation_steps 2 \
                                --max_seq_length 64 \
                                --train_batch_size 16 \
                                --eval_batch_size 8 \
                                --num_train_epochs 2"

    print("\nRunning huggingface run_classifier.py...\n")
    os.system(cmd)
    print("...finished run_classifier.py\n")

    # parse run_classifier.py output file and find the accy
    accy = open("comptest/eval_results.txt").read().split("\n")[
        0]  # 'acc = 0.76'
    accy = accy.split("=")[1]
    accy = float(accy)
    print("bert_sklearn accy: %.02f, run_classifier.py accy : %0.02f" %
          (bert_sklearn_accy, accy))

    # clean up
    print("\nCleaning up eval file: eval_results.txt")
    #os.remove("eval_results.txt")
    shutil.rmtree("comptest")
    assert bert_sklearn_accy == accy
Exemplo n.º 4
0
def test_nonbinary_classify():
    """Test non-binary classification with different inputs"""

    train = pd.read_csv(DATADIR + "/mnli/train.csv")
    X_train = train[['text_a', 'text_b']]
    y_train = train['label']

    #X_train = list(X_train.values)
    #y_train = list(y_train.values)

    model = BertClassifier()
    model.validation_fraction = 0.0
    model.max_seq_length = 64
    model.train_batch_size = 16
    model.eval_batch_size = 8
    model.epochs = 1

    model.fit(X_train, y_train)
    accy = model.score(X_train, y_train)

    # pandas df input
    X = X_train[:5]
    print("testing %s input" % (type(X)))
    y1 = model.predict(X)

    # numpy array input
    X = X_train[:5].values
    print("testing %s input" % (type(X)))
    y2 = model.predict(X)
    assert list(y2) == list(y1)

    # list input
    X = list(X_train[:5].values)
    print("testing %s input" % (type(X)))
    y3 = model.predict(X)
    assert list(y3) == list(y1)
Exemplo n.º 5
0
    plt.show()

if __name__ == "__main__":
    #读取路径
    train_path = 'F:/code/tfcode/school_code/dataclean_code/train_data_vec.npz'
    test_path = 'F:/code/tfcode/school_code/dataclean_code/test_data_vec.npz'
    #读取训练集与测试集
    train_x , train_y = get_dataset(train_path)
    test_x , test_y = get_dataset(test_path)
    
    seed = 1234
    random.seed(seed)
    random.shuffle(train_x )
    random.seed(seed)
    random.shuffle(train_y)

    seed = 2143
    random.seed(seed)
    random.shuffle(test_x )
    random.seed(seed)
    random.shuffle(test_y)

    model = BertClassifier()
    model.fit(train_x , train_y)

    pre_y = model.predict(test_x)

    score = model.score(pre_y , test_y)

    print(score)
Exemplo n.º 6
0
# define model
model = BertClassifier('bert-base-uncased')
model.validation_fraction = 0.0
model.learning_rate = 3e-5
model.gradient_accumulation_steps = 1
model.max_seq_length = 64
model.train_batch_size = 1
model.eval_batch_size = 1
model.epochs = 1

# fit
model.fit(X_train, y_train)

# score
accy = model.score(X_dev, y_dev)

test_df = pd.read_csv(
    'data/nCov_10k_test.csv',
    skiprows=[0],
    names=['id', 'time', 'account', 'content', 'pic', 'video'])
test_df_not_na = test_df[test_df['content'].notna()]
## 直接设定没有微博内容的label为0
test_df_na = test_df[test_df['content'].isna()]
test_df_na['label'] = 0

X_test = test_df_not_na['content']
y_test_pred = model.predict(X_test)
test_df_not_na['label'] = y_test_pred
new_test_df = pd.concat([test_df_not_na, test_df_na]).sort_index()
temp_df = pd.DataFrame(columns=['id', 'y'])
train_sents, val_sents, train_label, val_labels = train_test_split(train_text, train_label, test_size=0.2)

train_sents.head()

model = BertClassifier(max_seq_length=128,
                       train_batch_size=32,
                       epochs=5,
                       bert_model='bert-base-multilingual-cased')
model

# Commented out IPython magic to ensure Python compatibility.
# %%time
# history = model.fit(train_text, train_label)

accy = model.score(val_sents, val_labels)

# make class probability predictions
y_prob = model.predict_proba(val_sents)
print("class prob estimates:\n", y_prob)

# make predictions
y_pred = model.predict(val_sents)
print("Accuracy: %0.2f%%"%(metrics.accuracy_score(y_pred, val_labels) * 100))

target_names = ['negative', 'positive']
print(classification_report(val_labels, y_pred, target_names=target_names))

X_test = test['comment']
test_id = test['id']
Exemplo n.º 8
0
def bert(train_x, train_y, test_x, test_y):
    bert = BertClassifier(**bert_params)
    bert.fit(train_x, train_y.values.ravel())
    print('BERT Accuracy:', bert.score(test_x, test_y.values.ravel()))