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

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. 在react中使用到的好用的插件

    1)antd UI组件 蚂蚁金服出品的 挺好用的 还有个移动端的antd-moblie 2) moment 日期处理类库 3)prop-types 第三方库 对组件props变量进行类型检测 4)qs ...

  2. Mac OS下安装mysqlclient遇到的一些坑

    在玩django的同时,必须需要mysqlclient和pillow包,想在本地Mac上装上mysqlclient,但着实遇到不少坑,最终还是在github issue中找到了解决方法,这里记录一下, ...

  3. 快来!我从源码中学习到了一招Dubbo的骚操作!

    荒腔走板 大家好,我是 why,欢迎来到我连续周更优质原创文章的第 55 篇. 老规矩,先来一个简短的荒腔走板,给冰冷的技术文注入一丝色彩. 魔幻的 2020 年的上半年过去了,很多人都在朋友圈和上半 ...

  4. day63 django入门(4)

    目录 一.CBV源码解析 二.模版语法 1 传值 2 过滤器(最多只能传两个参数) 3 标签 4 自定义过滤器,标签,inclusion_tag 4.1 自定义过滤器 4.2 自定义标签(可以传多个参 ...

  5. Scala 基础(八):Scala 程序流程控制

    1.顺序控制 顺序控制介绍 程序从上到下逐行地执行,中间没有任何判断和跳转. 顺序控制举例和注意事项 Scala中定义变量时采用合法的前向引用.如: def main(args : Array[Str ...

  6. JVM 专题十三:运行时数据区(八)直接内存

    1. 直接内存 不是虚拟机运行时数据区的一部分,也不是<Java虚拟机规范>中定义的内存区域. 直接内存是Java堆外的.直接向系统申请的内存区间. 来源于NIO,通过存在堆中的Direc ...

  7. shell专题(一):Shell概述

    大数据程序员为什么要学习Shell呢? 1)需要看懂运维人员编写的Shell程序. 2)偶尔会编写一些简单Shell程序来管理集群.提高开发效

  8. python 生成器(五):生成器实例(一)创建数据处理管道

    问题 你想以数据管道(类似Unix管道)的方式迭代处理数据. 比如,你有个大量的数据需要处理,但是不能将它们一次性放入内存中. 解决方案 生成器函数是一个实现管道机制的好办法. 为了演示,假定你要处理 ...

  9. vue 修改浏览器标题

    主要思路: 1.可以从路由获取当前页面的标题,再通过document.title设值,或者在最外层的index.html页面添加<title>标签 import router from ' ...

  10. SpringBoot 接收前端参数的几种方式

    昨天和前端小伙伴在联调是碰到了参数接收不到的错误,我在postman上测试接口是正常的,但是与前端对接时就接受不到参数,请求方式都是get,但是问题就在于json  和 form-data 的区别!这 ...