针对第四章编写的代码出现的错误做一个总结

Traceback (most recent call last):

File "H:\image\chapter4\p81_chongxie.py", line 160, in <module>
l1 = Linear(X, W1, b1)

TypeError: Linear() takes no arguments

出问题时的init方法的图片

可以看出init两边只有一个下划线  _.

解决办法:把init的两边改成两个下划线 __。即可。

代码运行环境:win7系统 + anaconda3_2020

第四章的代码如下:

  1. #######################数据结构部分#############################################
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. # %matplotlib inline
  6.  
  7. class Node(object):
  8. def __init__(self, inbound_nodes = []):
  9. self.inbound_nodes = inbound_nodes
  10. self.value = None
  11. self.outbound_nodes = []
  12.  
  13. self.gradients = {}
  14.  
  15. for node in inbound_nodes:
  16. node.outbound_nodes.append(self)
  17.  
  18. def forward(self):
  19. raise NotImplementedError
  20.  
  21. def backward(self):
  22. raise NotImplementedError
  23.  
  24. class Input(Node):
  25. def __init__(self):
  26. Node.__init__(self)
  27.  
  28. def forward(self):
  29. pass
  30.  
  31. def backward(self):
  32. self.gradients = {self : 0}
  33. for n in self.outbound_nodes:
  34. self.gradients[self] += n.gradients[self]
  35.  
  36. ##################################################################################
  37. class Linear(Node):
  38. def __init__(self, X, W, b):
  39. Node.__init__(self, [X, W, b])
  40.  
  41. def forward(self):
  42. X = self.inbound_nodes[0].value
  43. W = self.inbound_nodes[1].value
  44. b = self.inbound_nodes[2].value
  45. self.value = np.dot(X, W) + b
  46.  
  47. def backward(self):
  48. self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes }
  49. for n in self.outbound_nodes:
  50. grad_cost = n.gradients[self]
  51. self.gradients[self.inbound_nodes[0]] += np.dot(grad_cost, self.inbound_nodes[1].value.T)
  52. self.gradients[self.inbound_nodes[1]] += np.dot(self.inbound_nodes[0].value.T, grad_cost)
  53. self.gradients[self.inbound_nodes[2]] += np.sum(grad_cost, axis = 0, keepdims = False)
  54.  
  55. ###################################################################################
  56. class Sigmoid(Node):
  57. def __init__(self, node):
  58. Node.__init__(self, [node])
  59.  
  60. def _sigmoid(self, x):
  61. return 1. / (1. + np.exp(-x)) #exp() 方法返回x的指数,e的x次幂
  62.  
  63. def forward(self):
  64. input_value = self.inbound_nodes[0].value
  65. self.value = self._sigmoid(input_value)
  66.  
  67. def backward(self):
  68. self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes}
  69. for n in self.outbound_nodes:
  70. grad_cost = n.gradients[self]
  71. sigmoid = self.value
  72. self.gradients[self.inbound_nodes[0]] += sigmoid * (1 - sigmoid) * grad_cost
  73.  
  74. class MSE(Node):
  75. def __init__(self, y, a):
  76. Node.__init__(self, [y, a])
  77.  
  78. def forward(self):
  79. y = self.inbound_nodes[0].value.reshape(-1, 1)
  80. a = self.inbound_nodes[1].value.reshape(-1, 1)
  81.  
  82. self.m = self.inbound_nodes[0].value.shape[0]
  83. self.diff = y - a
  84. self.value = np.mean(self.diff**2)
  85.  
  86. def backward(self):
  87. self.gradients[self.inbound_nodes[0]] = (2 / self.m) * self.diff
  88. self.gradients[self.inbound_nodes[1]] = (-2 / self.m) * self.diff
  89.  
  90. ##########################计算图部分#############################################
  91. def topological_sort(feed_dict):
  92. input_nodes = [n for n in feed_dict.keys()]
  93. G = {}
  94. nodes = [n for n in input_nodes]
  95. while len(nodes) > 0:
  96. n = nodes.pop(0)
  97. if n not in G:
  98. G[n] = {'in' : set(), 'out' : set()}
  99. for m in n.outbound_nodes:
  100. if m not in G:
  101. G[m] = {'in' : set(), 'out' : set()}
  102. G[n]['out'].add(m)
  103. G[m]['in'].add(n)
  104. nodes.append(m)
  105.  
  106. L = []
  107. S = set(input_nodes)
  108. while len(S) > 0 :
  109. n = S.pop()
  110. if isinstance(n, Input):
  111. n.value = feed_dict[n]
  112. L.append(n)
  113. for m in n.outbound_nodes:
  114. G[n]['out'].remove(m)
  115. G[m]['in'].remove(n)
  116. if len(G[m]['in']) == 0 :
  117. S.add(m)
  118. return L
  119.  
  120. #######################使用方法##############################################
  121. #首先由图的定义执行顺序
  122. #graph = topological_sort(feed_dict)
  123. def forward_and_backward(graph):
  124. for n in graph :
  125. n.forward()
  126.  
  127. for n in graph[:: -1]:
  128. n.backward()
  129.  
  130. #对各个模块进行正向计算和反向求导
  131. #forward_and_backward(graph)
  132.  
  133. #########################介绍梯度下降################
  134. def sgd_update(trainables, learning_rate = 1e-2):
  135. for t in trainables :
  136. t.value = t.value - learning_rate * t.gradients[t]
  137.  
  138. ###########使用这个模型#################################
  139. from sklearn.utils import resample
  140. from sklearn import datasets
  141.  
  142. # %matplotlib inline
  143.  
  144. data = datasets.load_iris()
  145. X_ = data.data
  146. y_ = data.target
  147. y_[y_ == 2] = 1 # 0 for virginica, 1 for not virginica
  148. print(X_.shape, y_.shape) # out (150,4) (150,)
  149.  
  150. ########################用写的模块来定义这个神经网络#########################
  151.  
  152. np.random.seed(0)
  153. n_features = X_.shape[1]
  154. n_class = 1
  155. n_hidden = 3
  156.  
  157. X, y = Input(), Input()
  158. W1, b1 = Input(), Input()
  159. W2, b2 = Input(), Input()
  160.  
  161. l1 = Linear(X, W1, b1)
  162. s1 = Sigmoid(l1)
  163. l2 = Linear(s1, W2, b2)
  164. t1 = Sigmoid(l2)
  165. cost = MSE(y, t1)
  166.  
  167. ###########训练模型###########################################
  168. #随即初始化参数值
  169. W1_0 = np.random.random(X_.shape[1] * n_hidden).reshape([X_.shape[1], n_hidden])
  170. W2_0 = np.random.random(n_hidden * n_class).reshape([n_hidden, n_class])
  171. b1_0 = np.random.random(n_hidden)
  172. b2_0 = np.random.random(n_class)
  173.  
  174. #将输入值带入算子
  175. feed_dict = {
  176. X: X_, y: y_,
  177. W1:W1_0, b1: b1_0,
  178. W2:W2_0, b2: b2_0
  179. }
  180.  
  181. #训练参数
  182. #这里训练100轮(eprochs),每轮抽4个样本(batch_size),训练150/4次(steps_per_eproch),学习率 0.1
  183. epochs = 100
  184. m = X_.shape[0]
  185. batch_size = 4
  186. steps_per_eproch = m // batch_size
  187. lr = 0.1
  188.  
  189. graph = topological_sort(feed_dict)
  190. trainables = [W1, b1,W2, b2]
  191.  
  192. l_Mat_W1 = [W1_0]
  193. l_Mat_W2 = [W2_0]
  194.  
  195. l_loss = []
  196. for i in range(epochs):
  197. loss = 0
  198. for j in range(steps_per_eproch):
  199. X_batch, y_batch = resample(X_, y_, n_samples = batch_size)
  200. X.value = X_batch
  201. y.value = y_batch
  202.  
  203. forward_and_backward(graph)
  204. sgd_update(trainables, lr)
  205. loss += graph[-1].value
  206.  
  207. l_loss.append(loss)
  208. if i % 10 ==9 :
  209. print("Eproch %d, Loss = %1.5f" % (i, loss))
  210.  
  211. #图形化显示
  212. plt.plot(l_loss)
  213. plt.title("Cross Entropy value")
  214. plt.xlabel("Eproch")
  215. plt.ylabel("Loss")
  216. plt.show()
  217.  
  218. ##########最后用模型预测所有的数据的情况
  219. X.value = X_
  220. y.value = y_
  221. for n in graph:
  222. n.forward()
  223.  
  224. plt.plot(graph[-2].value.ravel())
  225. plt.title("predict for all 150 Iris data")
  226. plt.xlabel("Sample ID")
  227. plt.ylabel("Probability for not a virginica")
  228. plt.show()

关于python中的 take no arguments 的解决方法的更多相关文章

  1. Python中pip install MySQL-python报错解决方法

    环境 Centos 7(其他Centos或者RHEL一样) 问题 在执行 pip install MySQL-python 时报错如: Command "python setup.py eg ...

  2. Python中执行系统命令常见的几种方法--转载

    Python中执行系统命令常见的几种方法 Python中执行系统命令常见的几种方法有: (1)os.system # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 # 如果再命令行下执 ...

  3. Python中日期和时间格式化输出的方法

    本文转自:https://www.jb51.net/article/62518.htm 本文实例总结了python中日期和时间格式化输出的方法.分享给大家供大家参考.具体分析如下: python格式化 ...

  4. python中readline判断文件读取结束的方法

    注:内容来自网络 本文实例讲述了python中readline判断文件读取结束的方法.分享给大家供大家参考.具体分析如下: 大家知道,python中按行读取文件可以使用readline函数,下面现介绍 ...

  5. python中执行shell命令的几个方法小结(转载)

    转载:http://www.jb51.net/article/55327.htm python中执行shell命令的几个方法小结 投稿:junjie 字体:[增加 减小] 类型:转载 时间:2014- ...

  6. Python中转换角度为弧度的radians()方法

    Python中转换角度为弧度的radians()方法 这篇文章主要介绍了Python中转换角度为弧度的radians()方法,是Python入门中的基础知识,需要的朋友可以参考下 radians()方 ...

  7. Python使用easy-install安装时报UnicodeDecodeError的解决方法

    Python使用easy-install安装时报UnicodeDecodeError的解决方法,有需要的朋友可以参考下. 问题描述: 在使用easy-install安装matplotlib.pypar ...

  8. sql server 还原数据库后,删除用户,提示数据库主体在该数据库中拥有架构,无法删除解决方法

    将另一台服务器上的数据库备份文件,在现在用的这台服务器上还原之后,再创建相同的用户名,提示用户已存在 想将之前的用户先删除掉,却提示“数据库主体在该数据库中拥有架构,无法删除解决方法” 在网上找到方法 ...

  9. jquery中checkbox全选失效的解决方法

    这篇文章主要介绍了jquery中checkbox全选失效的解决方法,需要的朋友可以参考下     如果你使用jQuery 1.6 ,代码if ( $(elem).attr(“checked”) ),将 ...

随机推荐

  1. mac篇---mac安装jupyter

    1.Jupyter搭建 pip install --user jupyter 如果是在python3中,则用如下命令: pip3 install --user jupyter 如下图所示: 2. Ju ...

  2. C++中复杂声明和定义的辨析

    0x00 前言 c++中的复杂声明往往令人无法下手,经常使人搞错这到底声明的是一个指针还是指针函数.但其实c++对于复杂声明是遵循一定的规则的,叫做变量名—>右--左-右规则. 0x01 规则解 ...

  3. day78 作业

    目录 1 在作业.html的代码基础上,完成商品数量的加减,注意商品数量如果低于0个,则自动删除当前商品 2 在作业.html的代码基础仧,完成购物车总价格的计算 3 使用ajax获取北京天气,并把昨 ...

  4. pytest框架使用教程

    Pytest框架 一.简介 pytest:基于unittest之上的单元测试框架 有什么特点? 自动发现测试模块和测试方法 断言更加方便,assert + 表达式,例如 assert 1 == 1 灵 ...

  5. pip install scrapy报错:error: Unable to find vcvarsall.bat解决方法

    今天在使用pip install scrapy 命令安装Scrapy爬虫框架时,出现了很让人头疼的错误,错误截图如下: 在网上查找解决方法时,大致知道了问题的原因.是因为缺少C语言的编译环境,其中一种 ...

  6. 数据可视化之DAX篇(十一)Power BI度量值不能作为坐标轴?这个解决思路送给你

    https://zhuanlan.zhihu.com/p/79522456 对于PowerBI使用者而言,经常碰到的一个问题是,想把度量值放到坐标轴上,却发现无法实现.尤其是初学者,更是习惯性的想这么 ...

  7. vue 写h5页面-摇一摇

    依赖的第三方的插件 shake.js github地址: https://github.com/alexgibson/shake.js 提供一个摇一摇音效下载地址:http://aspx.sc.chi ...

  8. Ethical Hacking - Web Penetration Testing(8)

    SQL INJECTION WHAT IS SQL? Most websites use a database to store data. Most data stored in it(userna ...

  9. Vue开发者必会的基础知识盘点

    你会Vue吗,你看以下知识点你掌握了多少?实际工作中是否运用的得心应手?如果是,那么恭喜你! Vue中的数据和DOM已经被关联起来,所有的东西都是响应式的.注意我们不再和HTML直接交互.一个Vue应 ...

  10. nodejs--抓取页面的数据--图

    感觉挺有意思,比php好玩 ----做个图留个 纪念