朴素贝叶斯NaiveBayes以及python实现
https://blog.csdn.net/CarryLvan/article/details/109236906
上面的博客有代码实现,但要实现测试集上每一个样本的预测时出错,这篇代码要求在测试集上要用的样本要在训练集上都有相应的值存在,才能进行预测。
测试集
训练集
如上,在验证集的balance中有-123,而在训练集中没有而报错,怎么解决?
将series转为dataframe的方法:https://blog.csdn.net/dta0502/article/details/82966790
将index变成columns,多个也可以,在pd.DataFrame 中加入index= [0]
二、调包实现
import numpy as np
import pandas as pd
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
df = pd.read_csv(r’C:\Users\Administrator\Desktop\统计推断\bank训练集.csv’)
df1 = pd.read_csv(r’C:\Users\Administrator\Desktop\统计推断\bank测试集.csv’)
df.columns = [‘age’,‘job’,‘marital’,‘education’,‘default’,‘balance’,‘housing’,‘loan’,‘contact’,‘day’,‘month’,‘duration’,‘campaign’,‘pdays’,‘previous’,‘poutcome’,‘y’]
df_value = df.loc[:,[‘age’,‘job’,‘marital’,‘education’,‘default’,‘balance’,‘housing’,‘loan’,‘contact’,‘day’,‘month’,‘duration’,‘campaign’,‘pdays’,‘previous’,‘poutcome’]]
df_y = df.loc[:,[‘y’]]
df_value = pd.get_dummies(df_value)
df_y = np.asarray(df_y)
for i in range(len(df_y)):
if df_y[i] == ‘no’:
df_y[i] = 0
else:
df_y[i] = 1
df_y = pd.DataFrame(df_y)
df_y = df_y.apply(pd.to_numeric,axis=0)
df1 = pd.get_dummies(df1)
clf = gnb.fit(df_value,df_y)
test = clf.predict(df1)
np.save(’./test.npy’,test)
①字符串类型的数据在使用时要进行one-hot编码(使用pd.get_dummies进行编码) (报can not convert string to float错误时)
②将dataframe转成array进行遍历 array与dataframe的互相转换
③用pd.to_numeric 将object类型变成int或float
④.npy文件的使用:np.save();np.load()