我尝试构建一个tensorflow模型。这是代码。有三个python文件。 (1)opt4_8generateData.py
#coding:utf-8
import matplotlib.pyplot as plt
import numpy as np
seed=2
def generates():
rdm=np.random.RandomState(seed)
X=rdm.randn(300,2)
Y_=[int(x0*x0+x1*x1<2) for (x0,x1) in X]
Y_c=[['red' if y else 'blue'] for y in Y_]
#对数据集进行整理,第一个元素为-1表示跟随第二列计算,第二个元素表示多少 #列
X=np.vstack(X).reshape(-1,2)
Y_=np.vstack(X).reshape(-1,1)
return X,Y_,Y_c
(2)opt4_8forward.py
#coding:utf-8
import tensorflow as tf
def get_weight(shape,rugalarizer):
w=tf.Variable(tf.random_normal(shape),dtype=tf.float32)
tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))
return w
def get_bias(shape):
b=tf.Variable(tf.constant(0.01,shape=shape))
return b
def forward(x,regularizer):
w1=get_weight([2,11],regularizer)
b1=get_bias([11])
y1=tf.nn.relu(tf.matmul(x,w1)+b1)
w2=get_weight([11,1],regularizer)
b2=get_bias([1])
y=tf.matmul(y1,w2)+b2
return y
(3)opt4_8backward.py
#coding:utf-8
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import opt4_8generateData
import opt4_8forward
STEPS=40000
BATCH_SIZE=30
LEARNING_RATE_BASE=0.001
LEARNING_RATE_DECAY=0.999
REGULARIZER=0.01
def backward():
x=tf.placeholder(tf.float32,shape=(None,2))
y_=tf.placeholder(tf.float32,shape=(None,1))
X,Y_,Y_c=opt4_8generateData.generates()
y=opt4_8forward.forward(x,REGULARIZER)
global_step=tf.Variable(0,trainable=False)
learning_rate=tf.train.exponential_decay(
LEARNING_RATE_BASE,
global_step,
300/BATCH_SIZE,
LEARNING_RATE_DECAY,
staircase=True)
loss_mse=tf.reduce_mean(tf.square(y-y_))
loss_total=loss_mse+tf.add_n(tf.get_collection("losses"))
#定义反向传播方法:包含正则化
train_step=tf.train.AdamOptimizer(learning_rate).minimize(loss_total)
with tf.Session() as sess:
init_op=tf.global_variables_initializer()
sess.run(init_op)
for i in range(STEPS):
start=(i*BATCH_SIZE)%300
end=start+BATCH_SIZE
sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
if i%2000==0:
loss_y=sess.run(loss_total,feed_dict={x:X,y_:Y_})
print "After %d steps,loss is:%f" %(i,loss_y)
xx,yy=np.mgrid[-3:3:.01,-3:3:.01]
grid=np.c_[xx.ravel(),yy.ravel()]
probs=sess.run(y,feed_dict={x:grid})
probs=probs.reshape(xx.shape)
plt.scatter(X[:,0],X[:,1],c=np.squeeze(Y_c))
plt.contour(xx,yy,probs,levels=[.5])
plt.show()
if __name__=='__main__':
backward()
当我运行&#34; python opt4_8backward.py&#34;时,它出错了:
Traceback (most recent call last):
File "opt4_8backward.py", line 57, in <module>
backward()
File "opt4_8backward.py", line 19, in backward
y=opt4_8forward.forward(x,REGULARIZER)
File "/home/yuan/tf/opt4_8forward.py", line 14, in forward
w1=get_weight([2,11],regularizer)
File "/home/yuan/tf/opt4_8forward.py", line 6, in get_weight
tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))
NameError: global name 'regularizer' is not defined
如何修复此错误?非常感谢。 我检查了我的代码。似乎我和老师之间没有区别。
答案 0 :(得分:0)
在opt4_8forward.py
中,get_weight
函数定义为:
def get_weight(shape,rugalarizer):
w=tf.Variable(tf.random_normal(shape),dtype=tf.float32)
tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))
return w
这里,函数参数名为rugalarizer
,在同一函数中有以下代码行:
tf.add_to_collection('losses',tf.contrib.layers.l2_regularizer(regularizer)(w))
因此,regularizer
未定义。 IIUC,功能必须定义为:
def get_weight(shape,regularizer):