本文整理汇总了Python中sklearn.naive_bayes.GaussianNB.score方法的典型用法代码示例。如果您正苦于以下问题:Python GaussianNB.score方法的具体用法?Python GaussianNB.score怎么用?Python GaussianNB.score使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.naive_bayes.GaussianNB
的用法示例。
在下文中一共展示了GaussianNB.score方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_classification
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def test_classification():
t = zeros(len(target))
t[target == 'setosa'] = 1
t[target == 'versicolor'] = 2
t[target == 'virginica'] = 3
from sklearn.naive_bayes import GaussianNB
classifier = GaussianNB()
classifier.fit(data,t) # training on the iris dataset
print classifier.predict(data[0])
print t[0]
from sklearn import cross_validation
train, test, t_train, t_test = cross_validation.train_test_split(data, t, test_size=0.4, random_state=0)
classifier.fit(train,t_train) # train
print classifier.score(test,t_test) # test
from sklearn.metrics import confusion_matrix
print confusion_matrix(classifier.predict(test),t_test)
from sklearn.metrics import classification_report
print classification_report(classifier.predict(test), t_test, target_names=['setosa', 'versicolor', 'virginica'])
from sklearn.cross_validation import cross_val_score
# cross validation with 6 iterations
scores = cross_val_score(classifier, data, t, cv=6)
print scores
from numpy import mean
print mean(scores)
示例2: crossvalidate
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def crossvalidate(X_trn, Y_trn):
"""Cross validation with comparison to classifiers that classify as only good or only bad"""
import numpy as np
X_train, X_test, Y_train, Y_test = cross_validation.train_test_split(X_trn.toarray(), Y_trn, test_size=0.4, random_state=1)
dumb_labels1 = Y_test.copy()
dumb_labels2 = Y_test.copy()
dumb_labels1[dumb_labels1 == 0] = 1; #Labels all 1s
dumb_labels2[dumb_labels2 == 1] = 0; #Labels all 0s
dumb_labels3 = np.random.randint(2, size=(len(Y_test),))
clf = GaussianNB()
#clf = Perceptron()
#clf = SGDClassifier()
#clf = MultinomialNB()
#clf = KNeighborsClassifier()
#clf = LinearSVC()
clf.fit(X_train, Y_train)
accuracy = clf.score(X_test, Y_test)
dumb_clf1_score = clf.score(X_test, dumb_labels1)
dumb_clf2_score = clf.score(X_test, dumb_labels2)
dumb_clf3_score = clf.score(X_test, dumb_labels3)
print "Classifier Score : ", accuracy
print "Dumb_classifier with all 1s : ", dumb_clf1_score
print "Dumb classifier with all 0s : ", dumb_clf2_score
print "Dumb classifier with random sequence : ", dumb_clf3_score
return accuracy
示例3: get_GNB
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def get_GNB(Xtrain, Xtest, Ytrain, Ytest):
gnb = GaussianNB()
gnb.fit(Xtrain,Ytrain)
scores = np.empty((4))
scores[0] = gnb.score(Xtrain,Ytrain)
scores[1] = gnb.score(Xtest,Ytest)
print('GNB, train: {0:.02f}% '.format(scores[0]*100))
print('GNB, test: {0:.02f}% '.format(scores[1]*100))
return gnb
示例4: get_GNB
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def get_GNB(Xtrain, Ytrain, Xtest = None , Ytest = None, verbose = 0):
gnb = GaussianNB()
gnb.fit(Xtrain,Ytrain)
if (verbose == 1):
scores = np.empty((2))
scores[0] = gnb.score(Xtrain,Ytrain)
print('GNB, train: {0:.02f}% '.format(scores[0]*100))
if (type(Xtest) != type(None)):
scores[1] = gnb.score(Xtest,Ytest)
print('GNB, test: {0:.02f}% '.format(scores[1]*100))
return gnb
示例5: cvalidate
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def cvalidate():
from sklearn import cross_validation
targetset = np.genfromtxt(open('trainLabels.csv','r'), dtype='f16')
y = [x for x in targetset]
trainset = np.genfromtxt(open('train.csv','r'), delimiter=',', dtype='f16')
X = np.array([x for x in trainset])
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size = 0.3, random_state = 0)
gnb = GaussianNB()
X_train, X_test = decomposition_pca(X_train, X_test)
gnb.fit(X_train, y_train)
print gnb.score(X_test, y_test)
示例6: GaussianNBcls
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
class GaussianNBcls(object):
"""docstring for ClassName"""
def __init__(self):
self.gnb_cls = GaussianNB()
self.prediction = None
self.train_x = None
self.train_y = None
def train_model(self, train_x, train_y):
try:
self.train_x = train_x
self.train_y = train_y
self.gnb_cls.fit(train_x, train_y)
except:
print(traceback.format_exc())
def predict(self, test_x):
try:
self.test_x = test_x
self.prediction = self.gnb_cls.predict(test_x)
return self.prediction
except:
print(traceback.format_exc())
def accuracy_score(self, test_y):
try:
# return r2_score(test_y, self.prediction)
return self.gnb_cls.score(self.test_x, test_y)
except:
print(traceback.format_exc())
示例7: PriceModel
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
class PriceModel(object):
"""Linear Regression Model used to predict future prices"""
def __init__(self, algorithm='gnb'):
self.algorithm = algorithm
if algorithm == 'svm':
self.clf = SVC(kernel='rbf')
elif algorithm == 'rf':
self.clf = RandomForestClassifier(n_estimators=10,
max_depth=None,
min_samples_split=1,
random_state=0)
elif algorithm == 'lr':
self.clf = LogisticRegression()
elif algorithm == 'knn':
self.clf = KNeighborsClassifier(n_neighbors=3)
else:
# Naive Bayes
self.clf = GaussianNB()
def train(self, X_train, y_train):
self.clf.fit(X_train, y_train)
def predict(self, x):
return self.clf.predict(x)
def score(self, X_test, y_test):
return self.clf.score(X_test, y_test)
示例8: trainData
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def trainData(username):
"""
Trains the data based on the users performance so far
Returns a trained Gaussian Naive Bayes model and updates result collection
"""
X = getFeatures(username)
Y = getClassList(username)
trainX = np.array(X)
trainY = np.array(Y)
gnb = GaussianNB()
gnb.fit(trainX, trainY)
print "Score with Naive Bayes: ", gnb.score(trainX, trainY)
testData = words.posts.find({}, {'id' : 1,
'points' : 1,
'diff' : 1,
'_id' : 0})
testData = map(lambda x : (x['id'], x['points'], x['diff']), testData)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
for data in testData:
testWord = words.posts.find_one({'id' : data[0]}, {'word' : 1, '_id' : 0})['word']
wordClass = setWordClass(list(gnb.predict_proba(data))[0])
classWord = result.posts.update({'username' : username}, {'$set' : {testWord : wordClass}}, upsert = True)
示例9: NB
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def NB(text):
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = Preprocess()
Ifeatures_train,Ifeatures_test,Ilabels_train=preprocess_input([text])
# classification goes here
clf = GaussianNB()
# training
train_t0 = time()
clf.fit(features_train, labels_train)
train_t1 = time()
# prediction or testing
test_t0 = time()
predict = clf.predict(features_test)
test_t1 = time()
print "accuracy: ", clf.score(features_test, labels_test)
print "#################################"
print "tain time: ", round(train_t1 - train_t0, 3), "s"
print "prediction time: ", round(test_t1 - test_t0, 3), "s"
print "#################################"
clf.fit(Ifeatures_train,Ilabels_train)
print ("prediction of ",str(clf.predict(Ifeatures_test))[1])
#print "prediction of ", clf.predict(preprocess_input(text))
return str(clf.predict(Ifeatures_test))[1]
示例10: NBAccuracy
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def NBAccuracy(features_train, labels_train, features_test, labels_test):
""" compute the accuracy of your Naive Bayes classifier """
### import the sklearn module for GaussianNB
from sklearn.naive_bayes import GaussianNB
### create classifier
clf = GaussianNB()
t0 = time()
### fit the classifier on the training features and labels
clf.fit(features_train, labels_train)
print "training time:", round(time()-t0, 3), "s"
### use the trained classifier to predict labels for the test features
import numpy as np
t1 = time()
pred = clf.predict(features_test)
print "predicting time:", round(time()-t1, 3), "s"
### calculate and return the accuracy on the test data
### this is slightly different than the example,
### where we just print the accuracy
### you might need to import an sklearn module
accuracy = clf.score(features_test, labels_test)
return accuracy
示例11: NBAccuracy
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def NBAccuracy(features_train, labels_train, features_test, labels_test):
""" compute the accuracy of your Naive Bayes classifier """
### import the sklearn module for GaussianNB
from sklearn.naive_bayes import GaussianNB
### create classifier
clf = GaussianNB()
### fit the classifier on the training features and labels
clf.fit(features_train, labels_train)
### use the trained classifier to predict labels for the test features
pred = clf.predict(features_test)
### calculate and return the accuracy on the test data
### this is slightly different than the example,
### where we just print the accuracy
### you might need to import an sklearn module
#from sklearn.metrics import accuracy_score
#accuarcy = accuracy_score(pred, labels_test)
accuracy = clf.score(features_test, labels_test)
return accuracy
示例12: gaussian_bayes_test
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def gaussian_bayes_test(self):
print 'gaussian bayes test'
g_bayes_clf = GaussianNB()
print 'cross validation score',cross_val_score(g_bayes_clf, self.x_data, self.y_data)
start_time = time.time()
g_bayes_clf.fit(self.x_train, self.y_train)
print 'score',g_bayes_clf.score(self.x_test, self.y_test)
print 'time cost', time.time() - start_time
示例13: classify
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def classify(features_train, labels_train, features_test, labels_test):
classifier = GaussianNB()
t0 = time()
classifier.fit(features_train, labels_train)
print "training time: ", round(time() - t0), "s"
t1 = time()
classifier.predict(features_test)
print "predicting time: ", round(time() - t1), "s"
return classifier.score(features_test, labels_test)
示例14: naiveBayesClassifierTraining
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def naiveBayesClassifierTraining(compounds_all):
print "Building naive Bayes classifier (" + str(NB_FOLDS) + "-fold cross-validation)..."
# get the data
keys = compounds_all.keys()
fingerprint_data = [compounds_all[cmpnd_id]['fingerprint'] for cmpnd_id in keys]
fingerprint_data = numpy.asarray(fingerprint_data)
activity_data = [compounds_all[cmpnd_id]['active'] for cmpnd_id in keys]
activity_data = numpy.asarray(activity_data)
# perform K-fold cross-validation
classifier = GaussianNB()
kfold_xv_strat = cross_validation.StratifiedKFold(activity_data, NB_FOLDS, indices=False)
confusion_matrices = []
probabilities = []
scores = []
models = []
true_activities = []
aucs = []
for train, test in kfold_xv_strat:
fingerprint_data_train = fingerprint_data[train]
fingerprint_data_test = fingerprint_data[test]
activity_data_train = activity_data[train]
activity_data_test = activity_data[test]
# model building
classifier.fit(fingerprint_data_train, activity_data_train)
# testing
activity_data_predictions = classifier.predict(fingerprint_data_test)
models.append(classifier)
probability_estimates = classifier.predict_proba(fingerprint_data_test)
probabilities.append(probability_estimates)
scores.append(classifier.score(fingerprint_data_test, activity_data_test))
activity_confusion_matrix = confusion_matrix(activity_data_test, activity_data_predictions)
confusion_matrices.append(activity_confusion_matrix)
true_activities.append(activity_data_test)
# ROC curves
fpr, tpr, thresholds = roc_curve(activity_data_test, probability_estimates[:, 1])
aucs.append(auc(fpr, tpr))
classifier.fit(fingerprint_data, activity_data)
print "Done."
return {
'confusion_matrices' : confusion_matrices
, 'probabilities' : probabilities
, 'scores' : scores
, 'models' : models
, 'true_activity_data' : true_activities
, 'AUCs' : aucs
, 'fingerprint_data' : fingerprint_data
, 'activity_data' : activity_data
, 'final_model' : classifier
}
示例15: run_test
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import score [as 别名]
def run_test(trainData, trainLabels, testData, testLabels):
start_time = time()
classifier = GaussianNB()
classifier.fit(trainData, trainLabels)
score = classifier.score(testData, testLabels)
duration = time() - start_time
print "training set size: " + str(len(trainData))
print "score: " + str(score)
print "time: " + str(duration) + "\n"