1、TypeError: 'dict_keys' object does not support indexing

机器学习实战第三章决策树中遇到的,主要是Python的版本问题,下面这段是Python2的写法:

firstStr = myTree.keys()[0]

Python3:先转换成list

firstStr = list(myTree.keys())[0]

2、TypeError: write() argument must be str, not bytes

使用pickle存储的时候出现错误

错误代码:

try:with open(fileName, 'w') as fw:pickle.dump(inputTree, fw)
except IOError as e:print("File Error : " + str(e))

错误原因:pickle的存储方式默认是二进制

修正:

try:with open(fileName, 'wb') as fw:pickle.dump(inputTree, fw)
except IOError as e:print("File Error : " + str(e))

3、UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 199: illegal multibyte sequence

  • 文件中包含了非法字符,gbk无法解析
def spamTest():docList = []classList = []fullList = []for i in range(1, 26):wordList = textParse(open('email/spam/%d.txt' % i).read())docList.append(wordList)fullList.extend(wordList)classList.append(1)wordList = textParse(open('email/ham/%d.txt' % i).read()) # 出错部分docList.append(wordList)fullList.extend(wordList)classList.append(0)vocabList = bayes.createVocabList(docList)trainingSet = list(range(50))testSet = []for i in range(10):randIndex = int(random.uniform(0, len(trainingSet)))testSet.append(trainingSet[randIndex])del trainingSet[randIndex]trainMat = []trainClasses = []for docIndex in trainingSet:trainMat.append(bayes.setOfWords2Vec(vocabList, docList[docIndex]))trainClasses.append(classList[docIndex])p0V, p1V, pSpam = bayes.trainNB0(array(trainMat), array(trainClasses))errorCount = 0for docIndex in testSet:wordVector = bayes.setOfWords2Vec(vocabList, docList[docIndex])if bayes.classifyNB(array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:errorCount += 1print('the error rate is:', float(errorCount) / len(testSet))

1、尝试使用比gbk包含字符更多的gb18030,卒

wordList = textParse(open('email/ham/%d.txt' % i, encoding='gb18030').read())

2、忽略错误,通过

wordList = textParse(open('email/ham/%d.txt' % i, encoding='gb18030', errors='ignore').read())

3、打开文件看看哪个是非法字符,我选择放弃

4、TypeError: 'range' object doesn't support item deletion

# spamTest():
def spamTest():docList = []classList = []fullList = []for i in range(1, 26):wordList = textParse(open('email/spam/%d.txt' % i, encoding='gb18030', errors='ignore').read())docList.append(wordList)fullList.extend(wordList)classList.append(1)wordList = textParse(open('email/ham/%d.txt' % i, encoding='gb18030', errors='ignore').read())docList.append(wordList)fullList.extend(wordList)classList.append(0)vocabList = bayes.createVocabList(docList)trainingSet = range(50) # 需要修改部分testSet = []for i in range(10):randIndex = int(random.uniform(0, len(trainingSet)))testSet.append(trainingSet[randIndex])del trainingSet[randIndex] # 出错代码部分trainMat = []trainClasses = []for docIndex in trainingSet:trainMat.append(bayes.setOfWords2Vec(vocabList, docList[docIndex]))trainClasses.append(classList[docList])p0V, p1V, pSpam = bayes.trainNB0(array(trainMat), array(trainClasses))errorCount = 0for docIndex in testSet:wordVector = bayes.setOfWords2Vec(vocabList, docList[docIndex])if bayes.classifyNB(array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:errorCount += 1print('the error rate is:', float(errorCount) / len(testSet))

python3.x , 出现错误 'range' object doesn't support item deletion

原因:python3.x   range返回的是range对象,不返回数组对象

解决方法:

把 trainingSet = range(50) 改为 trainingSet = list(range(50))

5、TypeError: 'numpy.float64' object cannot be interpreted as an integer

出错代码:随机梯度上升算法

# 随机梯度上升算法
def stocGradAscent0(dataMatrix, classLabels):m, n = shape(dataMatrix)alpha = 0.01weights = ones(n)for i in range(m):h = sigmoid(sum(dataMatrix[i] * weights))error = classLabels[i] - hweights = weights + alpha * error * dataMatrix[i]return weights

出错原因:error 是一个float64,

weights :<class 'numpy.ndarray'>

dataMatrix[i] :<class 'list'>

在Python中,如果是一个整型n乘以一个列表L, 列表长度会变成n*len(L),而当你用一个浮点数乘以一个列表,自然而然也就出错了,而且我们要的也不是这个结果,而是对于当前向量的每一位乘上一个error。

其实这地方就是Python 中的list和numpy的array混用的问题,对dataMatrix进行强制类型转换就行了(也可以在参数传递之前进行转换,吐槽Python的类型机制)

# 随机梯度上升算法
def stocGradAscent0(dataMatrix, classLabels):# 强制类型转换,避免array和list混用dataMatrix = array(dataMatrix)m, n = shape(dataMatrix)alpha = 0.01weights = ones(n)for i in range(m):h = sigmoid(sum(dataMatrix[i] * weights))error = classLabels[i] - hweights = weights + alpha * error * dataMatrix[i]return weights

6. copy和copy.deepcopy

copy对于一个复杂对象的子对象并不会完全复制,什么是复杂对象的子对象呢?就比如序列里的嵌套序列,字典里的嵌套序列等都是复杂对象的子对象。对于子对象,python会把它当作一个公共镜像存储起来,所有对他的复制都被当成一个引用,所以说当其中一个引用将镜像改变了之后另一个引用使用镜像的时候镜像已经被改变了。

deepcopy的时候会将复杂对象的每一层复制一个单独的个体出来。

7. /和//

python3

/ 保留小数位, 3/2 = 1.5; 2/2 = 1.0

// floor(), 3/2 = 1 2//2 = 1

Python中的遇到的错误(持续更新)相关推荐

  1. Python中的XML解析错误[Et.parse(xml) ‘gbk‘ codec can‘t decode byte]分析与解决

    Python中的XML解析错误[Et.parse(xml) 'gbk' codec can't decode byte]分析与解决 在Python开发中,我们经常会使用XML格式的数据来进行数据传输或 ...

  2. closecmd python_如何在python中禁止控制台/ cmd错误消息

    如何在 python中为chromedriver和pyinstaller exe压缩错误消息? 我注意到当我在pyinstaller中使用chromedriver并运行它时,我得到一个错误消息列表.我 ...

  3. Python基础知识笔记(文章内容持续更新)

    python程序实例解析 2.1温度转换 2.2Python程序语法元素分析 2.2.3命名字与保留字 2.2.4字符串 2.2.5赋值语句 2.2.6 input函数 输入函数 2.2.7分支语句 ...

  4. Python基础之:Python中的异常和错误

    文章目录 简介 Python中的内置异常类 语法错误 异常 异常处理 抛出异常 异常链 自定义异常 finally 简介 和其他的语言一样,Python中也有异常和错误.在 Python 中,所有异常 ...

  5. 【华为云技术分享】Python 中的异常和错误

    [摘要] 异常就是程序运行时发生错误的信号,在python中,错误触发的异常如下 异常和错误 第一:程序中难免出现错误,而错误分成两种 1.语法错误(这种错误,根本过不了python解释器的语法检测, ...

  6. android 开发工具类,Android中常用开发工具类—持续更新...

    一.自定义ActionBar public class ActionBarTool { public static void setActionBarLayout(Activity act,Conte ...

  7. Salesforce Apex 中常用技能总结(持续更新)

    前言 博主也是Salesforce Apex 工作不久,有用到的知识和平时查阅到的知识和大家分享一下. 总结 1.使用SOQL语句查询时,字符串类型的只能使用'单引号',否则报错:Unknown er ...

  8. C语言中的常用库宏--持续更新

    c语言中的宏/持续更新 limits.h 名字 值 说明 CHAR_BIT 8 定义了一个字节中的比特数 SCHAR_MIN -127 定义最小值签署的字符 SCHAR_MAX 127 定义最大值签署 ...

  9. python中gmtime的hour错误_python中gmtime的hour错误_在Python中操作日期和时间之gmtime()方法的使用...

    python中datetime怎么用广告总是在最精彩的时候出现,你总是在小编爱的最深的时候离开. ''''' 日期相关的操作 ''' from datetime import datetime fro ...

最新文章

  1. Codeforces Round #649 (Div.2)题解
  2. 取代C语言标准输入输出:cin 和 cout【C++标准输入输出】
  3. DBSAN密度聚类算法
  4. 图像基本处理算法的简单实现(二)
  5. 【POJ - 1741】Tree(树分治,容斥,点分治,模板题)
  6. 实话!程序员大都不喜欢拉帮结派
  7. 使用Git版本控制查看文件的更改历史记录
  8. Gitlab+Jenkins学习之路(四)之gitlab备份和恢复
  9. 基于三星6.0.1的Xposed模块安装以及模拟位置的安装
  10. Linux内核启动工作流程初探
  11. 如何用自签名证书为.sis文件签名
  12. 初学C语言中的浮点数
  13. 4.3 51单片机-串口通信
  14. 2023蓝桥杯前端web组css复习
  15. 计算机专业可以考天文学研究生吗,报考南京大学天文系有什么要求?
  16. 从零开始用 Python 打造自己的区块链
  17. ICCV2019相关信息
  18. 计算机配置ppt制作,笔记本电脑怎么制作PPT
  19. 计算机专业毕业设计选题
  20. php报表控件,可以在任何客户端生成报表的PHP报表控件Stimulsoft Reports.Fx

热门文章

  1. 2018 中国准独角兽 TOP 50 夏榜发布!146 家投资机构、227 家企业参与
  2. 程序员如何让自己的工作更上一个台阶
  3. MySQL探索(一):B-Tree索引
  4. Java代码03-打印一个菱形
  5. HDU 5612 Baby Ming and Matrix games
  6. sealed、new、virtual、abstract与override 趣解
  7. android学习笔记(入门篇)
  8. 要活多久才能赚回你交的养老金
  9. Gartner:新安全环境对虚拟化和云计算提出更高要求
  10. int b = 1;int c = b^0xff;求C