【问题标题】:How can correct sample_weight in sklearn.naive_bayes?如何纠正 sklearn.naive_bayes 中的 sample_weight?
【发布时间】:2019-10-09 14:12:46
【问题描述】:

我正在通过sklearn 实施Naive Bayes,但数据不平衡。 我的数据有超过 16k 条记录和 6 个输出类别。

我试图用sklearn.utils.class_weight计算的sample_weight来拟合模型

sample_weight 收到如下信息:

sample_weight = [11.77540107 1.82284768 0.64688602 2.47138047 0.38577435 1.21389195]

import numpy as np

data_set = np.loadtxt("./data/_vector21.csv", delimiter=",")

inp_vec = data_set[:, 1:22]
out_vec = data_set[:, 22:]
#
# # Split dataset into training set and test set
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(inp_vec, out_vec, test_size=0.2)    # 80% training and 20% test
#
# class weight
from keras.utils.np_utils import to_categorical
output_vec_categorical = to_categorical(y_train)
from sklearn.utils import class_weight
y_ints = [y.argmax() for y in output_vec_categorical]
c_w = class_weight.compute_class_weight('balanced', np.unique(y_ints), y_ints)
cw = {}
for i in set(y_ints):
    cw[i] = c_w[i]

# Create a Gaussian Classifier
from sklearn.naive_bayes import *
model = GaussianNB()

# Train the model using the training sets
print(c_w)

model.fit(X_train, y_train, c_w)

# Predict the response for test dataset
y_pred = model.predict(X_test)

# Import scikit-learn metrics module for accuracy calculation
from sklearn import metrics

# Model Accuracy, how often is the classifier correct?
print("\nClassification Report: \n", (metrics.classification_report(y_test, y_pred)))
print("\nAccuracy: %.3f%%" % (metrics.accuracy_score(y_test, y_pred)*100))

我收到了这条消息: ValueError: Found input variables with inconsistent numbers of samples: [13212, 6]

谁能告诉我我做错了什么以及如何解决?

非常感谢。

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    sample_weightclass_weight 是两个不同的东西。

    顾名思义:

    • sample_weight 将应用于单个样本(数据中的行)。所以sample_weight的长度必须和你的X中的样本数相匹配。

    • class_weight是为了让分类器更加重视和关注类。因此class_weight 的长度必须与目标中的类数相匹配。

    您使用sklearn.utils.class_weight 计算class_weight 而不是sample_weight,然后尝试将其传递给sample_weight。因此尺寸不匹配错误。

    请参阅以下问题以进一步了解这两个权重如何在内部相互作用:

    【讨论】:

    • 谢谢,你的解释很清楚。我从compute_class_weight改成了compute_sample_weight
    【解决方案2】:

    通过这种方式,我能够计算权重以处理类不平衡。

    from sklearn.utils import class_weight
    
    sample = class_weight.compute_sample_weight('balanced', y_train)
    
    #Classifier Naive Bayes
    naive = naive_bayes.MultinomialNB()
    naive.fit(X_train,y_train, sample_weight=sample)
    predictions_NB = naive.predict(X_test)
    

    【讨论】:

    • 当它的损失函数不是交叉熵时,我如何可视化朴素贝叶斯对 sample_with 所做的事情?
    猜你喜欢
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多