5

I'm using a training and testing dataset of tweets which were combined together. (combi = train.append(test, ignore_index=True).

the training csv has manually labelled sentiments of: -1, 0 and 1 (basically negative, neutral and positive) whereas the testing doesn't.

i want the code to use logistic regression to output the f1 score but an issue occurs at: f1_score(yvalid, prediction_int) is used:

my code is as follows:

from sklearn.feature_extraction.text import CountVectorizer
bow_vectorizer = CountVectorizer(max_df=0.90, min_df=2,        max_features=1000, stop_words='english')
bow = bow_vectorizer.fit_transform(combi['tidy_tweet'])

from sklearn.feature_extraction.text import TfidfVectorizer
tfidf_vectorizer = TfidfVectorizer(max_df=0.90, min_df=2, max_features=1000, stop_words='english')
tfidf = tfidf_vectorizer.fit_transform(combi['tidy_tweet'])

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score

train_bow = bow[:1300,:]
test_bow = bow[1300:,:]

xtrain_bow, xvalid_bow, ytrain, yvalid =     train_test_split(train_bow, train['label'], random_state=42,  test_size=0.3)

lreg = LogisticRegression()
lreg.fit(xtrain_bow, ytrain) # training the model

prediction = lreg.predict_proba(xvalid_bow) 
prediction_int = prediction[:,1] >= 0.3 
prediction_int = prediction_int.astype(np.int)

f1_score(yvalid, prediction_int)
desertnaut
  • 57,590
  • 26
  • 140
  • 166

1 Answers1

10

Reading the relevant documentation, you will see that the default value for the argument average in f1_score is binary; since here you do not specify it, it takes this default value, which however is invalid for your case of multi-class classification (agreed, it is maybe a bad design choice).

As the error message advises, you should explicitly choose and specify one of the other available arguments shown in the docs; here is the example from the docs with dummy multi-class data:

from sklearn.metrics import f1_score
# dummy multi-class data, similar to yours:
y_true = [0, 1, 2, 0, 1, 2]
y_pred = [0, 2, 1, 0, 0, 1]

f1_score(y_true, y_pred, average='macro') 
# 0.26666666666666666

f1_score(y_true, y_pred, average='micro')
# 0.33333333333333331

f1_score(y_true, y_pred, average='weighted') 
# 0.26666666666666666

f1_score(y_true, y_pred) 
# ValueError: Target is multiclass but average='binary'. Please choose another average setting.
desertnaut
  • 57,590
  • 26
  • 140
  • 166