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

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

第四章的代码如下:

 #######################数据结构部分#############################################
import numpy as np
import matplotlib.pyplot as plt # %matplotlib inline class Node(object):
def __init__(self, inbound_nodes = []):
self.inbound_nodes = inbound_nodes
self.value = None
self.outbound_nodes = [] self.gradients = {} for node in inbound_nodes:
node.outbound_nodes.append(self) def forward(self):
raise NotImplementedError def backward(self):
raise NotImplementedError class Input(Node):
def __init__(self):
Node.__init__(self) def forward(self):
pass def backward(self):
self.gradients = {self : 0}
for n in self.outbound_nodes:
self.gradients[self] += n.gradients[self] ##################################################################################
class Linear(Node):
def __init__(self, X, W, b):
Node.__init__(self, [X, W, b]) def forward(self):
X = self.inbound_nodes[0].value
W = self.inbound_nodes[1].value
b = self.inbound_nodes[2].value
self.value = np.dot(X, W) + b def backward(self):
self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes }
for n in self.outbound_nodes:
grad_cost = n.gradients[self]
self.gradients[self.inbound_nodes[0]] += np.dot(grad_cost, self.inbound_nodes[1].value.T)
self.gradients[self.inbound_nodes[1]] += np.dot(self.inbound_nodes[0].value.T, grad_cost)
self.gradients[self.inbound_nodes[2]] += np.sum(grad_cost, axis = 0, keepdims = False) ###################################################################################
class Sigmoid(Node):
def __init__(self, node):
Node.__init__(self, [node]) def _sigmoid(self, x):
return 1. / (1. + np.exp(-x)) #exp() 方法返回x的指数,e的x次幂 def forward(self):
input_value = self.inbound_nodes[0].value
self.value = self._sigmoid(input_value) def backward(self):
self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes}
for n in self.outbound_nodes:
grad_cost = n.gradients[self]
sigmoid = self.value
self.gradients[self.inbound_nodes[0]] += sigmoid * (1 - sigmoid) * grad_cost class MSE(Node):
def __init__(self, y, a):
Node.__init__(self, [y, a]) def forward(self):
y = self.inbound_nodes[0].value.reshape(-1, 1)
a = self.inbound_nodes[1].value.reshape(-1, 1) self.m = self.inbound_nodes[0].value.shape[0]
self.diff = y - a
self.value = np.mean(self.diff**2) def backward(self):
self.gradients[self.inbound_nodes[0]] = (2 / self.m) * self.diff
self.gradients[self.inbound_nodes[1]] = (-2 / self.m) * self.diff ##########################计算图部分#############################################
def topological_sort(feed_dict):
input_nodes = [n for n in feed_dict.keys()]
G = {}
nodes = [n for n in input_nodes]
while len(nodes) > 0:
n = nodes.pop(0)
if n not in G:
G[n] = {'in' : set(), 'out' : set()}
for m in n.outbound_nodes:
if m not in G:
G[m] = {'in' : set(), 'out' : set()}
G[n]['out'].add(m)
G[m]['in'].add(n)
nodes.append(m) L = []
S = set(input_nodes)
while len(S) > 0 :
n = S.pop()
if isinstance(n, Input):
n.value = feed_dict[n]
L.append(n)
for m in n.outbound_nodes:
G[n]['out'].remove(m)
G[m]['in'].remove(n)
if len(G[m]['in']) == 0 :
S.add(m)
return L #######################使用方法##############################################
#首先由图的定义执行顺序
#graph = topological_sort(feed_dict)
def forward_and_backward(graph):
for n in graph :
n.forward() for n in graph[:: -1]:
n.backward() #对各个模块进行正向计算和反向求导
#forward_and_backward(graph) #########################介绍梯度下降################
def sgd_update(trainables, learning_rate = 1e-2):
for t in trainables :
t.value = t.value - learning_rate * t.gradients[t] ###########使用这个模型#################################
from sklearn.utils import resample
from sklearn import datasets # %matplotlib inline data = datasets.load_iris()
X_ = data.data
y_ = data.target
y_[y_ == 2] = 1 # 0 for virginica, 1 for not virginica
print(X_.shape, y_.shape) # out (150,4) (150,) ########################用写的模块来定义这个神经网络######################### np.random.seed(0)
n_features = X_.shape[1]
n_class = 1
n_hidden = 3 X, y = Input(), Input()
W1, b1 = Input(), Input()
W2, b2 = Input(), Input() l1 = Linear(X, W1, b1)
s1 = Sigmoid(l1)
l2 = Linear(s1, W2, b2)
t1 = Sigmoid(l2)
cost = MSE(y, t1) ###########训练模型###########################################
#随即初始化参数值
W1_0 = np.random.random(X_.shape[1] * n_hidden).reshape([X_.shape[1], n_hidden])
W2_0 = np.random.random(n_hidden * n_class).reshape([n_hidden, n_class])
b1_0 = np.random.random(n_hidden)
b2_0 = np.random.random(n_class) #将输入值带入算子
feed_dict = {
X: X_, y: y_,
W1:W1_0, b1: b1_0,
W2:W2_0, b2: b2_0
} #训练参数
#这里训练100轮(eprochs),每轮抽4个样本(batch_size),训练150/4次(steps_per_eproch),学习率 0.1
epochs = 100
m = X_.shape[0]
batch_size = 4
steps_per_eproch = m // batch_size
lr = 0.1 graph = topological_sort(feed_dict)
trainables = [W1, b1,W2, b2] l_Mat_W1 = [W1_0]
l_Mat_W2 = [W2_0] l_loss = []
for i in range(epochs):
loss = 0
for j in range(steps_per_eproch):
X_batch, y_batch = resample(X_, y_, n_samples = batch_size)
X.value = X_batch
y.value = y_batch forward_and_backward(graph)
sgd_update(trainables, lr)
loss += graph[-1].value l_loss.append(loss)
if i % 10 ==9 :
print("Eproch %d, Loss = %1.5f" % (i, loss)) #图形化显示
plt.plot(l_loss)
plt.title("Cross Entropy value")
plt.xlabel("Eproch")
plt.ylabel("Loss")
plt.show() ##########最后用模型预测所有的数据的情况
X.value = X_
y.value = y_
for n in graph:
n.forward() plt.plot(graph[-2].value.ravel())
plt.title("predict for all 150 Iris data")
plt.xlabel("Sample ID")
plt.ylabel("Probability for not a virginica")
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. 合并两个有序链表(剑指offer-16)

    题目描述输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则. 解答方法1:递归 /* public class ListNode { int val; List ...

  2. 记一道CTF隐写题解答过程

      0x00 前言 由于我是这几天才开始接触隐写这种东西,所以作为新手我想记录一下刚刚所学.这道CTF所需的知识点包括了图片的内容隐藏,mp3隐写,base64解密,当铺解密,可能用到的工具包括bin ...

  3. 配置类需要标注@Configuration却不知原因?那这次就不能给你涨薪喽

    专注Java领域分享.成长,拒绝浅尝辄止.关注公众号[BAT的乌托邦]开启专栏式学习,拒绝浅尝辄止.本文 https://www.yourbatman.cn 已收录,里面一并有Spring技术栈.My ...

  4. Scala 基础(十五):Scala 模式匹配(三)

    1 变量声明中的模式 match中每一个case都可以单独提取出来,意思是一样的. 应用案例 val (x, y) = (1, 2) val (q, r) = BigInt(10) /% 3 //说明 ...

  5. python 面向对象专题(九):特殊方法 (二)__get__、__set__、__delete__ 描述符(二)覆盖型与非覆盖型描述符对比

    前言 根据是否定义__set__ 方法,描述符可分为两大类. 实现 __set__ 方法的描述符属于覆盖型描述符,因为虽然描述符是类属性,但是实现 __set__ 方法的话,会覆盖对实例属性的赋值操作 ...

  6. Hangfire实战二——为DashBoard页面添加权限认证

    概述 Hangfire Dashboard为我们提供了可视化的对后台任务进行管理的界面,我们可以直接在这个页面上对定时任务进行删除.立即执行等操作,如下图所示: 默认情况下,这个页面只能在部署Hang ...

  7. HTTP版本比较

    HTTP2.0优势 1.采用二进制格式传输数据,而非http1.1文本格式,二进制格式在协议的解析和优化扩展上带来了跟多的优势和可能 2.对消息头采用Hpack进行压缩传输,能够节省消息头占用的网络流 ...

  8. CSS上划线、下划线、删除线等方法

    text-decoration:underline;     下划线 text-decoration:overline;    顶划线 text-decoration:line-through;  删 ...

  9. iOS倒计时button闪烁

    v _button.titleLabel.text = [NSString stringWithFormat:@"%d后重发",t]; [_button setTitle:[NSS ...

  10. 毫无基础的人入门Python,Python入门教程

    随着人工智能的发展,Python近两年也是大火,越来越多的人加入到Python学习大军,对于毫无基础的人该如何入门Python呢?这里整理了一些个人经验和Python入门教程供大家参考. 如果你是零基 ...