import csv
import random
import math
def loadCsv(filename):
lines = csv.reader(open(filename, "rb"))
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]]
return dataset
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 separateByClass(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 summarizeByClass(dataset):
separated = separateByClass(dataset)
summaries = {}
for classValue, instances in separated.iteritems():
summaries[classValue] = summarize(instances)
return summaries
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.iteritems():
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.iteritems():
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 i in range(len(testSet)):
if testSet[i][-1] == predictions[i]:
correct += 1
return (correct/float(len(testSet))) * 100.0
def main():
filename = 'processed.cleveland.data.csv'
splitRatio = 0.67
dataset = loadCsv(filename)
trainingSet, testSet = splitDataset(dataset, splitRatio)
print('Split {0} rows into train={1} and test={2} rows').format(len(dataset), len(trainingSet), len(testSet))
summaries = summarizeByClass(trainingSet)
predictions = getPredictions(summaries, testSet)
accuracy = getAccuracy(testSet, predictions)
print('Accuracy: {0}%').format(accuracy)
main()
上面的代码是一个朴素的贝叶斯机器学习python脚本。我正在尝试使用存储在processed.cleveland.data.csv中的数据集上的代码。但是,我不断收到以下错误:
Traceback (most recent call last):
File "./naivebayespython.py", line 101, in <module>
main()
File "./naivebayespython.py", line 91, in main
dataset = loadCsv(filename)
File "./naivebayespython.py", line 10, in loadCsv
dataset[i] = [float(x) for x in dataset[i]]
ValueError: could not convert string to float: ?
有人可以告诉我我做错了什么并建议如何解决这个问题?我对Python比较陌生,所以解释也会有所帮助。谢谢!
答案 0 :(得分:1)
您可以使用except:
和def checkIfFloatable(something): # change the name ;)
try:
if float(something):
return True
except:
return False
def loadCsv(filename):
lines = csv.reader(open(filename, "rb"))
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i] if checkIfFloatable(x)] # else None
return dataset
来捕获转化错误
但是要知道可以转换的内容 - 请参阅此答案以获取详尽的列表:https://stackoverflow.com/a/20929881/7505395
修改以捕获错误的转化
import React, { Component } from 'react'
import ReactDom from 'react-dom'
import { Icon, Input, Form} from 'antd'
//
import Header from './layout/Header'
// Import Css
import '../css/Home.css'
class Home extends Component {
render() {
const { getFieldDecorator } = this.props.form
return (
<div>
<Form>
{getFieldDecorator('userName', {
rules: [{ required: true, message: 'Please input your username!' }],
})(
<Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
)}
</Form>
</div>
)
}
}
const WrappedLogin = Form.create()(Home)
ReactDom.render(<WrappedLogin/>, document.getElementById('root'))
export default Home