机器学习实战的Logistic回归梯度上升优化算法中遇到了这个问题

numpy.core._exceptions.UFuncTypeError: ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U1'), dtype('float64')) -> None

代码如下

import math
import numpy as np def loadDataSet():
dataSet = []
labelSet = []
with open('testSet.txt') as fbj:
for line in fbj.readlines():
lineArr = line.strip().split()
# print(lineArr)
dataSet.append([1.0, float(lineArr[0]), float(lineArr[1])])
labelSet.append(lineArr[2])
return dataSet, labelSet def sigmoid(inX):
result = 1/(1+np.exp(-inX))
return result def gradAscent(dataSet, labelSet):
dataMtrix = np.mat(dataSet)
labelMat = np.mat(labelSet).transpose()
m, n = np.shape(dataMtrix)
alpha = 0.001
maxCycles = 500
weights = np.ones((n, 1))
for _ in range(maxCycles):
h = sigmoid(dataMtrix * weights)
error = labelMat - h
weights = weights + alpha * dataMtrix.transpose() * error
return weights dataSet, labelSet = loadDataSet()
# print(dataSet)
# print(labelSet)
print(gradAscent(dataSet, labelSet))

这里报错说的是数据类型不符不能相减

那么分别查看一下(在jupyter调试)

labelMat.dtype

dtype('<U1')
h.dtype

dtype('float64')

那么解决办法就是将<U1类型换成float64

但是使用如下方法还是报错

labelMat.dtype = 'float64'

ValueError: When changing to a larger dtype, its size must be a divisor of the total size in bytes of the last axis of the array.

那么只好乖乖使用astype方法

labelMat = labelMat.astype(np.float64)

修改后的代码及结果如下

import math
import numpy as np def loadDataSet():
dataSet = []
labelSet = []
with open('testSet.txt') as fbj:
for line in fbj.readlines():
lineArr = line.strip().split()
# print(lineArr)
dataSet.append([1.0, float(lineArr[0]), float(lineArr[1])])
labelSet.append(lineArr[2])
return dataSet, labelSet def sigmoid(inX):
result = 1/(1+np.exp(-inX))
return result def gradAscent(dataSet, labelSet):
dataMtrix = np.mat(dataSet)
labelMat = np.mat(labelSet).transpose()
labelMat = labelMat.astype(np.float64)
m, n = np.shape(dataMtrix)
alpha = 0.001
maxCycles = 500
weights = np.ones((n, 1))
for _ in range(maxCycles):
h = sigmoid(dataMtrix * weights)
error = labelMat - h
weights = weights + alpha * dataMtrix.transpose() * error
return weights dataSet, labelSet = loadDataSet()
# print(dataSet)
# print(labelSet)
print(gradAscent(dataSet, labelSet)) [[ 4.12414349]
[ 0.48007329]
[-0.6168482 ]]

numpy.core._exceptions.UFuncTypeError: ufunc 'subtract' did not contain a loop with signature matching types (dtype('<U1'), dtype('float64')) -> None的更多相关文章

  1. ImportError: numpy.core.multiarray failed to import

    1. ImportError: numpy.core.multiarray failed to import pip install -U numpy http://stackoverflow.com ...

  2. 异常 No module named 'numpy.core._multiarray_umath

    No module named 'numpy.core._multiarray_umath 解决方法: 1. 可能是由于模型保存时出错,导致模型没有保存成功,此时删掉保存的模型即可 2. numpy版 ...

  3. ‘No module named 'numpy.core._multiarray_umath’ 或者‘no module named numpy’

    在import TensorFlow时,如果遇到‘No module named 'numpy.core._multiarray_umath’ 或者‘no module named numpy’,大多 ...

  4. ImportError: DLL load failed: 找不到指定的模块;ImportError: numpy.core.multiarray failed to import 报错解决

    python程序运行出错,出错的两行主要信息如下: ImportError: DLL load failed: 找不到指定的模块 ImportError: numpy.core.multiarray ...

  5. No module named 'numpy.core._multiarray_umath'

    问题:基于anaconda prompt 安装好TensorFlow框架以后,引入的时候(import tensorflow as tf)报如下图片的错误: 回答:网上好多人说是需要升级numpy,我 ...

  6. ModuleNotFoundError: No module named 'numpy.core._multiarray_umath' ImportError: numpy.core.multiarray failed to import

      出现以下错误:可能是因为你的numpy版本太低 更新numpy的版本 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple --upgra ...

  7. pyinstaller打包出错numpy.core.multiarray failed to import

    py原文件运行时正常,但用pyinstaller打包为exe后,在运行则报错: 这是因为cv2要求的numpy版本与你装的numpy版本不一样,导致冲突:网上很多说升级numpy,但你把numpy升的 ...

  8. python3.6安装jpype1后引入jpype报“ImportError: numpy.core.multiarray failed to import”问题

    jpype是调用java接口的第三方库,通过该库,python可以运行java程序,从而解决一些调用java的问题,比如:java开发的接口,测试时, 有java的加密算法就不用python写一遍重复 ...

  9. Could not find a version that satisfies the requirement numpy>=1.7.0 (from pan das==0.17.0) (from versions: ) No matching distribution found for numpy>=1.7.0 (from pandas==0.17.0)

    今天晚上一直在安装pandas,天杀的,真的是太难了.后来发现提示: Could not find a version that satisfies the requirement numpy> ...

随机推荐

  1. Dubbo 推荐用什么协议?

    dubbo://(推荐) rmi:// hessian:// http:// webservice:// thrift:// memcached:// redis:// rest://

  2. spring boot 自动装配的原理

    参考: https://blog.csdn.net/Dongguabai/article/details/80865599.如有侵权,请联系本人删除! 入口: import org.springfra ...

  3. C语言之基本组成(知识点6)

    一.C程序基本组成 C程序是由语句组成的,通常包括一个或多个函数,其中有且只有一个函数称为 主函数,其函数名为main. 二.C程序的组成特点: 1.每个C程序由一个或多个函数组成.每个C程序有且仅有 ...

  4. 03. Pandas数据结构

    03. Pandas数据结构 Series DataFrame 从DataFrame中查询出Series 1. Series Series是一种类似于一维数组的对象,它由一组数据(不同数据类型)以及一 ...

  5. javascript 理解和使用回调函数

    在javascript中,function是内置的类对象,也就是说它是一种类型的对象,可以和其他String.Array.Number.Objec类的对象一样用于内置对象的管理.因为function实 ...

  6. 我的python学习记04

    列表,元组,字典的使用一.列表列表的格式:list[元素1,元素2,--]列表也是一个有序集合,下标索引从0开始与字符串类似1.在列表中添加数据append:list.append(添加元素) (在最 ...

  7. uniapp中websokcet封装和使用

    1.  websocket.js   封装代码 //是否已经连接上ws let isOpenSocket = false //心跳间隔,单位毫秒 let heartBeatDelay = 3000 l ...

  8. properties和XML配置文件内容的获取

    @ 目录 总结内容 1. Java中为什么要使用配置文件 2. Java中常用的配置文件类型有哪些以及它们的特点 Properties配置文件 XML配置文件 总结 总结内容 1. Java中为什么要 ...

  9. Python使用函数实现杨辉三角

    运行效果: 可在函数中指定阶层数,输出对应的杨辉三角 源代码如下: 1 # -*-coding:utf-8 -*- 2 ''' 3 chapter4_do.py 4 函数yanghui(n)用于输出n ...

  10. Docker入门(windows版),利用Docker创建一个Hello World的web项目

    Docker 当大家点开这篇博客的时候,相信大家对docker多多少少也有些认识了,最近学习docker这门技术,略微有些心得,写篇文章记录一下学习过程并帮大家跳过一些坑. docker的核心有两个, ...