本文整理汇总了Python中sklearn.naive_bayes.GaussianNB.predict方法的典型用法代码示例。如果您正苦于以下问题:Python GaussianNB.predict方法的具体用法?Python GaussianNB.predict怎么用?Python GaussianNB.predict使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sklearn.naive_bayes.GaussianNB
的用法示例。
在下文中一共展示了GaussianNB.predict方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
def main():
config = dict()
config['resource_dir'] = os.path.abspath(os.path.join(os.path.realpath(__file__), '../../')) + "/resources/"
config['raw_file'] = config['resource_dir'] + "ideal_weight.csv"
ideal_weight_df = None
ideal_weight_df = pd.read_csv(config['raw_file'])
ideal_weight_df.columns = [x.replace("\'","") for x in ideal_weight_df.columns.values.tolist()]
ideal_weight_df.loc[:,'sex'] = ideal_weight_df['sex'].map(lambda x: x.replace("\'",""))
#print ideal_weight_df
#print config
plt.hist(ideal_weight_df['actual'], alpha=0.5, label='actual')
plt.hist(ideal_weight_df['ideal'], alpha=0.5, label='ideal')
plt.show() # figure_1.png
ideal_weight_df['diff'].hist()
ideal_weight_df['sex_id'] = ideal_weight_df['sex'].map(lambda x: 1 if x == 'Male' else 0)
clf = GaussianNB()
clf.fit(ideal_weight_df[['actual','ideal','diff']],ideal_weight_df['sex'])
print clf.predict([[145,160,-15]]) # male
print clf.predict([[160,145,15]]) # female
示例2: test_classification
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [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)
示例3: GaussianNBLearner
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
class GaussianNBLearner(AbstractLearner):
"""
Gaussian Naive Bayes Learner
http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html
We need to use X.toarray() because those functions expect dense arrays.
"""
def __init__(self):
self.nb = GaussianNB()
def train(self, X, Y):
if hasattr(X, 'toarray'):
self.nb.fit(X.toarray(), Y)
else:
self.nb.fit(X, Y)
def predict(self, X):
if (hasattr(X, "toarray")):
return self.nb.predict(X.toarray())
else:
return self.nb.predict(X)
def score(self, X, Y):
return np.mean(np.abs(self.nb.predict(X) - np.array(Y)))
示例4: __init__
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
class GaussianNBClassifier:
def __init__(self):
"""
This is the constructor responsible for initializing the classifier
"""
self.outputHeader = "#gnb"
self.clf = None
def buildModel(self):
"""
This builds the model of the Gaussian NB classifier
"""
self.clf = GaussianNB()
def trainGaussianNB(self,X, Y):
"""
Training the Gaussian NB Classifier
"""
self.clf.fit(X, Y)
def validateGaussianNB(self,X, Y):
"""
Validate the Gaussian NB Classifier
"""
YPred = self.clf.predict(X)
print accuracy_score(Y, YPred)
def testGaussianNB(self,X, Y):
"""
Test the Gaussian NB Classifier
"""
YPred = self.clf.predict(X)
print accuracy_score(Y, YPred)
示例5: MyNaiveBayes
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
def MyNaiveBayes(object):
pre = PreProcess()
(training_value, test_value, test_pos_x, test_pos_y, training_pos_x, training_pos_y) = pre.split()
# 模型初始化
clf_x = GaussianNB()
clf_y = GaussianNB()
# 进行模型的训练
clf_x.fit(training_value, training_pos_x)
clf_y.fit(training_value, training_pos_y)
# 计算结果
result_pos_x = clf_x.predict(test_value)
result_pos_y = clf_y.predict(test_value)
'''
print result_pos_x
print test_pos_x
print result_pos_y
print test_pos_y
'''
# 计算误差
x_dis = []
y_dis = []
d_dis = []
for i in range(len(result_pos_x)):
x_dis.append(abs(result_pos_x[i] - test_pos_x[i]))
y_dis.append(abs(result_pos_y[i] - test_pos_y[i]))
d_dis.append(math.sqrt((result_pos_x[i]-test_pos_x[i])**2+(result_pos_y[i]-test_pos_y[i])**2))
x = (sum(x_dis))/len(result_pos_x)
y = (sum(y_dis))/len(result_pos_y)
d = (sum(d_dis))/len(d_dis)
print x, y, d
return x, y, d
示例6: NB
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [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]
示例7: NBMatcher
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
class NBMatcher(MLMatcher):
def __init__(self, *args, **kwargs):
super(NBMatcher, self).__init__(*args, **kwargs)
self.clf = GaussianNB(*args, **kwargs)
def fit(self, X, Y):
self.clf.fit(X, Y)
def predict(self, X):
self.clf.predict(X)
示例8: naive_bayes
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
def naive_bayes(train_features, train_labels, test_features, test_labels):
# Train SVM classifier
model = GaussianNB()
model.fit(train_features, train_labels)
test_results = model.predict(test_features)
train_results = model.predict(train_features)
return (test_results, train_results)
示例9: classify
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [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)
示例10: bayes_test
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
def bayes_test():
X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
Y = np.array([1, 1, 1, 2, 2, 2])
clf = GaussianNB()
clf.fit(X, Y)
print(clf.predict([[-0.8, -1]]))
clf_pf = GaussianNB()
clf_pf.partial_fit(X, Y, np.unique(Y))
print(clf_pf.predict([[-0.8, -1]]))
示例11: TreeClassifier
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
class TreeClassifier(Classifier):
def __init__(self):
self.classifier = GaussianNB()
def do_train(self, X, y):
self.classifier.fit(X, y)
def do_classification(self, X, y):
self.classifier.predict(X, y)
示例12: __init__
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
class NaiveBayes:
__theta = 0
__sigma = 0
def __init__(self):
pass
#self.__new_data = 0
def learning(self,x_data,y_data):
self.rssi = np.loadtxt(x_data, delimiter=',')
print(self.rssi)
self.position = np.loadtxt(y_data, delimiter=',')
print(self.position)
self.gaussian_nb = GaussianNB()
from sklearn.cross_validation import train_test_split
rssi_train, rssi_test, position_train, position_test = train_test_split(self.rssi, self.position, random_state=0)
self.gaussian_nb.fit(rssi_train,position_train)
print("theta",self.gaussian_nb.theta_)
print("sigma",self.gaussian_nb.sigma_)
predicted = self.gaussian_nb.predict(rssi_test)
print(metrics.accuracy_score(position_test, predicted))
'''
def set_params(self,theta,sigma):
__theta = theta
__sigma = sigma
print __theta
print __sigma
'''
def inference(self,r_data):
self.predicted_class = self.gaussian_nb.predict(r_data)
post_prob = self.gaussian_nb.predict_proba(r_data)
log_prob = self.gaussian_nb.predict_log_proba(r_data)
self.post_prob_float16 = post_prob.astype(np.float16)
#E = 1*self.post_prob_float16[0][0]+2*self.post_prob_float16[0][1]+3*self.post_prob_float16[0][2]
#var = (1*self.post_prob_float16[0][0]+4*self.post_prob_float16[0][1]+9*self.post_prob_float16[0][2])-E**2
#print(self.post_prob_float16)
#print(self.post_prob_float16[0])
#print(var)
print(self.predicted_class)
#print(self.gaussian_nb.class_prior_)
#print(log_prob)
return self.predicted_class
def output(self):
output = graph.Graph()
output.bar_graph(self.post_prob_float16[0])
示例13: predict_author
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
def predict_author(arr, yazar_features, yazar_classes):
results = []
print "\n[DEBUG] K-NN result (neighbors: 10)"
knn = KNeighborsClassifier(n_neighbors=10)
knn.fit(yazar_features, yazar_classes)
print knn.predict(arr)
results.append(knn.predict(arr)[0])
print "\n[DEBUG] SVC result (linear) (degree=3)"
svc = svm.SVC(kernel='linear', degree=3)
svc.fit(yazar_features, yazar_classes)
print svc.predict(arr)
results.append(svc.predict(arr)[0])
print "\n[DEBUG] Logistic Regression result ()"
regr = linear_model.LogisticRegression()
regr.fit(yazar_features, yazar_classes)
print regr.predict(arr)
results.append(regr.predict(arr)[0])
print "\n[DEBUG] Gaussian Naive Bayes"
gnb = GaussianNB()
gnb.fit(yazar_features, yazar_classes)
print gnb.predict(arr)
results.append(gnb.predict(arr)[0])
print "\n[DEBUG] Decision Tree Classifier"
dtc = tree.DecisionTreeClassifier()
dtc.fit(yazar_features, yazar_classes)
print dtc.predict(arr)
results.append(dtc.predict(arr)[0])
print "\n[DEBUG] Gradient Boosting Classification"
gbc = GradientBoostingClassifier()
gbc.fit(yazar_features, yazar_classes)
print gbc.predict(arr)
results.append(gbc.predict(arr)[0])
# output = open('features.pkl', 'wb')
# pickle.dump(yazar_features, output)
# output.close()
# output = open('classes.pkl', 'wb')
# pickle.dump(yazar_classes, output)
# output.close()
# test_yazar_features = [] # for test data
# test_yazar_classes = [] # for test classes
# # yazar_features = [] # for train data
# # yazar_classes = [] # for train classes
return results
示例14: trainer
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [as 别名]
def trainer(dataset = "Features.csv"):
# Train the various machine learning algorithms using the features extracted.
data, labels = extractor(dataset)
train, test, train_labels, test_labels = train_test_split(data, labels, test_size = 0.20, random_state = 42)
names, expected_results = zip(*test_labels)
names1, train_labels = zip(*train_labels)
print 'S' + '\t' + 'H' + '\t' + 'F' + '\t' + 'A' + '\t' + 'N'
# Random Forest Classifier
rf = RandomForestClassifier(n_estimators = 100, n_jobs = 2)
rf.fit(train, train_labels)
results_boosting = rf.predict(test)
conf_matrix = confusion_matrix(expected_results, results_boosting)
print "Forset Classifier:\n"
print conf_matrix
accuracy_Boosting = float(np.trace(conf_matrix))/float(np.sum(conf_matrix))
print accuracy_Boosting
# KNN Classifier
neigh = KNeighborsClassifier(n_neighbors=3)
neigh.fit(train, train_labels)
results_KNN = neigh.predict(test)
conf_matrix = confusion_matrix(expected_results, results_KNN)
print "KNN Classifier:\n"
print conf_matrix
accuracy_KNN = float(np.trace(conf_matrix))/float(np.sum(conf_matrix))
print accuracy_KNN
# Baye's Classifier
clf = GaussianNB()
clf.fit(train, train_labels)
results_Bayes = clf.predict(test)
conf_matrix = confusion_matrix(expected_results, results_Bayes)
print "\nBayes Classifier:\n"
print conf_matrix
accuracy_Bayes = float(np.trace(conf_matrix))/float(np.sum(conf_matrix))
print accuracy_Bayes
# Neural Network
clf = BernoulliNB()
clf.fit(train, train_labels)
results_NN = clf.predict(test)
conf_matrix = confusion_matrix(expected_results, results_NN)
print "\nNeural Network:\n"
print conf_matrix
accuracy_NN = float(np.trace(conf_matrix))/float(np.sum(conf_matrix))
print accuracy_NN
documenter(names, results_boosting, results_Bayes, results_NN, results_KNN, accuracy_Boosting, accuracy_Bayes, accuracy_NN, accuracy_KNN)
示例15: NBAccuracy
# 需要导入模块: from sklearn.naive_bayes import GaussianNB [as 别名]
# 或者: from sklearn.naive_bayes.GaussianNB import predict [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