【问题标题】:sklearn Naive Bayes in pythonpython中的sklearn朴素贝叶斯
【发布时间】:2018-12-15 16:57:33
【问题描述】:

我已经在“Rocks and Mines”数据集上训练了一个分类器 (https://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data) 在计算准确度分数时,它似乎总是非常准确(输出为 1.0),我很难相信。是我犯了什么错误,还是朴素贝叶斯这么强大?

url = 'https://archive.ics.uci.edu/ml/machine-learning-databases/undocumented/connectionist-bench/sonar/sonar.all-data'
data = urllib.request.urlopen(url)
df = pd.read_csv(data)

# replace R and M with 1 and 0
m = len(df.iloc[:, -1])
Y = df.iloc[:, -1].values
y_val = []
for i in range(m):
    if Y[i] == 'M':
        y_val.append(1)
    else:
        y_val.append(0)
df = df.drop(df.columns[-1], axis = 1) # dropping column containing 'R', 'M'

X = df.values

from sklearn.model_selection import train_test_split
    # initializing the classifier
    clf = GaussianNB()
    # splitting the data
    train_x, test_x, train_y, test_y = train_test_split(X, y_val, test_size = 0.33, random_state = 42)
    # training the classifier
    clf.fit(train_x, train_y)
    pred = clf.predict(test_x) # making a prediction
    from sklearn.metrics import accuracy_score
    score = accuracy_score(pred, test_y)
    # printing the accuracy score
    print(score)

X 是输入,y_val 是输出(我已将“R”和“M”转换为 0 和 1)

【问题讨论】:

  • 你能用你把数据分成 X 和 y_val 的部分更新代码吗?
  • @Mufeed 当然,我会更新帖子
  • 我的准确度得分为 0.6666
  • 删除 train_test_split() 中的随机状态 =42 或给出其他随机值。
  • 恭喜您在 SO 中提出第一个问题,MCVE;现在,既然答案解决了您的问题,请接受 - 请参阅What should I do when someone answers my question?

标签: python scikit-learn naivebayes


【解决方案1】:

这是因为 train_test_split() 函数中的 random_state 参数。
当您将random_state 设置为整数时,sklearn 可确保您的数据采样保持不变。
这意味着每次通过指定 random_state 运行它时,都会得到相同的结果,这是预期的行为。
请参阅docs 了解更多详情。

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2013-11-24
    • 2020-02-28
    • 2021-10-18
    • 2017-11-13
    • 2012-02-21
    • 2011-12-28
    • 2017-03-17
    • 2021-07-16
    相关资源
    最近更新 更多