我正在尝试为用户提供的输入结果。以下是我遇到的通用代码,其工作原理如下: 输入数据集分为训练集和测试集。训练集用于训练朴素贝叶斯模型,测试集用于测试训练后的模型的结果。结果,它预测了如何正确预测测试集的准确性。
import csv
import math
import random
"""
Load the CSV File
"""
def loadCSV(filename):
lines = csv.reader(open(r'diabetes.csv'))
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]]
return dataset
"""
Training
"""
def splitDataset(dataset, splitRatio):
trainSize = int(len(dataset) * splitRatio)
trainSet = []
copy = list(dataset)
while len(trainSet) < trainSize:
index = random.randrange(len(copy))
trainSet.append(copy.pop(index))
return [trainSet, copy]
def seperateByClass(dataset):
separated = {}
for i in range(len(dataset)):
vector = dataset[i]
if (vector[-1] not in separated):
separated[vector[-1]] = []
separated[vector[-1]].append(vector)
return separated
def mean(numbers):
return sum(numbers)/float(len(numbers))
def stdev(numbers):
avg = mean(numbers)
variance = sum([pow(x-avg, 2) for x in numbers])/float(len(numbers)-1)
return math.sqrt(variance)
def summarize(dataset):
summaries = [(mean(attribute), stdev(attribute)) for attribute in zip(*dataset)]
del summaries[-1]
return summaries
def summariesByClass(dataset):
separated = seperateByClass(dataset)
summaries = {}
for classValue, instances in separated.items():
summaries[classValue] = summarize(instances)
return summaries
"""
Prediction
"""
def calculateProbability(x, mean, stdev):
exponent = math.exp(-(math.pow(x-mean, 2)/(2*math.pow(stdev, 2))))
return (1/(math.sqrt(2*math.pi)*stdev))*exponent
def calculateClassProbabilities(summaries, inputVector):
probabilities = {}
for classValue, classSummaries in summaries.items():
probabilities[classValue] = 1
for i in range(len(classSummaries)):
mean, stdev = classSummaries[i]
x = inputVector[i]
probabilities[classValue] *= calculateProbability(x, mean, stdev)
return probabilities
def predict(summaries, inputVector):
probabilities = calculateClassProbabilities(summaries, inputVector)
bestLabel, bestProb = None, -1
for classValue, probability in probabilities.items():
if bestLabel is None or probability > bestProb:
bestProb = probability
bestLabel = classValue
return bestLabel
def getPredictions(summaries, testSet):
predictions = []
for i in range(len(testSet)):
result = predict(summaries, testSet[i])
predictions.append(result)
return predictions
def getAccuracy(testSet, Predictions):
correct = 0
for x in range(len(testSet)):
if testSet[x][-1] == Predictions[x]:
correct += 1
return (correct/float(len(testSet)))*100.0
"""
Main Method
"""
def main():
filename = 'diabetes.csv'
splitRatio = 0.66
dataset = loadCSV(filename)
trainSet, testSet = splitDataset(dataset, splitRatio)
print('Split {0} rows into train = {1} and test = {2} rows'.format(len(dataset),len(trainSet), len(testSet)))
summaries = summariesByClass(trainSet)
# Test Model
predictions = getPredictions(summaries, testSet)
print(predictions)
accuracy = getAccuracy(testSet, predictions)
print('Accuracy : {0}%'.format(accuracy))
if __name__ == '__main__':
main()
我要进行的修改不是将数据集拆分为训练和测试数据集,而是完全使用数据集来训练模型并提供用户输入并检查是否获得结果。 也就是说,在我们的dataset中,我们基于提供给模型的数据集来预测患者是否会成为糖尿病的受害者。所以我想给用户输入这样的内容:
testSet = [[6, 148, 72, 36, 0, 33.6, 0.627, 50], [8, 183, 64, 0, 0, 23.3, 0.672, 32]]
注意:这些是我们数据集的随机两行,仅用于测试输出。
此给定测试集的预期输出为:
result = 0.0 # For 1st sample
result = 1.0 # For 2nd sample
请帮帮我。预先谢谢你。
答案 0 :(得分:0)
要使用所有数据作为训练集来训练模型,只需设置
splitRatio=1
实际上,训练集大小是使用表达式计算的:
trainSize = int(len(dataset) * splitRatio)
为了接受用户的输入并将其转换为列表,可以使用:
# user input 6 148 72 36 0 33.6 0.627 50
testSet=[int(x) for x in input().split()]