tensorflow学习心得【一】
自己编写代码实现神经网络层layer拟合线性函数的出现的一些问题:
编写的代码是根据莫烦老师的代码(基本是copy重写的)
直接上代码:
// 建立神经网络layer的基本步骤
import tensorflow as tf
import numpy as np
###定义层间处理###
def add_layer(inputs,input_size,output_size,act_func=None):
#这里W是矩阵所以首字母大写
Weight = tf.Variable(tf.random.normal([input_size, output_size]))
#这里的b偏置初始化不推荐设置为0,所以我们加上0.1
biases = tf.Variable(tf.zeros([1, output_size])+0.1)
#函数处理值
Wx_plus_biases = tf.matmul(inputs, Weight)+biases
if act_func is None:
output = Wx_plus_biases
else:
output = act_func(Wx_plus_biases)
return output
###导入数据###
#x_data = np.linspace(-1,1,300, dtype=np.float32)[:, np.newaxis]
#noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
#y_data = np.square(x_data) - 0.5 + noise
#产生(-1,1)的300个float32型的数
x_data = np.linspace(-1, 1, 300, dtype= np.float32)[:, np.newaxis]
#产生噪声
noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
y_data = np.square(x_data)-0.5+noise
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
###创建网络###
l1 = add_layer(xs, 1, 10, act_func=tf.nn.relu)
predict = add_layer(l1, 10, 1, act_func=None)
loss = tf.reduce_mean(tf.reduce_sum(tf.square(predict-ys),
reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(1000):
#sess.run(train_step, feed_dict={xs: x_date, ys: y_date})
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})
if i%20==0 :
print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))
我在写的时候遇到的一些问题,基本上是低智商问题
- 问题1:return
return output 不应该写在else里;这个问题我到没有遇到。但是我在网上看到有的同学遇到过 - 向量维数错误:
这是terminal中报错显示的问题:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [1,10], In[1]: [300,1]
一看就知道是向量维度出现了问题,但是这个问题也处理了比较长时间;
问题出现在:
#函数处理值
Wx_plus_biases = tf.matmul( Weight,inputs)+biases
这是我一开始想当然的认为Wx就是Weight*inputs,正确的代码应该是
#函数处理值
Wx_plus_biases = tf.matmul(inputs, Weight)+biases
- 忘记sess.run(init)
也是初学tensorflow的同学经常会犯的错误吧,莫烦老师也是提过很多次。嘿嘿,还是犯了。