Lê *_*ành 1 python machine-learning scikit-learn
我执行Naive Bayes的sklearn不均衡的数据。我的数据有超过 16k 条记录和 6 个输出类别。
我试图用sample_weight计算出的模型来拟合模型sklearn.utils.class_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))
Run Code Online (Sandbox Code Playgroud)
我收到了这条消息:
ValueError: Found input variables with inconsistent numbers of samples: [13212, 6]
谁能告诉我我做错了什么以及如何解决?
非常感谢。
在sample_weight和class_weight是两个不同的东西。
顾名思义:
sample_weight将应用于单个样本(数据中的行)。所以 的长度sample_weight必须与您的X.
class_weight是让分类器对类给予更多的重视和关注。因此, 的长度class_weight必须与目标中的类数相匹配。
您正在计算class_weight而不是sample_weight通过使用sklearn.utils.class_weight,而是尝试将其传递给sample_weight。因此,尺寸不匹配错误。
请参阅以下问题以进一步了解这两个权重如何在内部相互作用:
| 归档时间: |
|
| 查看次数: |
1339 次 |
| 最近记录: |