TensorFlow踩坑

本文没有教程只有经验教训。
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 24 21:01:28 2018

@author: ZZH 
function  add_layer
"""
import tensorflow as tf
import numpy as np

def add_layer(inputs,in_size,out_size,activation_function = None):
    Weights = tf.Variable(tf.random_normal([in_size,out_size]))
    biases = tf.Variable(tf.add(tf.zeros([1,out_size]),0.1))
    Wx_plus_b =tf.add(tf.matmul(inputs,Weights),biases)
    if activation_function == None:
        outputs = Wx_plus_b 
    else:
        outputs = activation_function(Wx_plus_b)
        
    return outputs




x_data =np.linspace(-1,1,300)[:,np.newaxis]
noise = np.random.normal(0, 0.1,x_data.shape)
y_data = np.square(x_data)+noise-0.5
#x_data = tf.cast(x_data,tf.float32)
#y_data = tf.cast(y_data,tf.float32)
#print(y_data)

xs = tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])

#定义隐含层
l1 = add_layer(xs,1,10,activation_function = tf.nn.relu)
predition = add_layer(l1,10,1,activation_function = None)

#定义神经网络结构
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - predition)
        ,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,{xs:x_data, ys:y_data})
    if i% 50==0:
        print(sess.run(loss, {xs:x_data,ys:y_data}))

跟着莫烦大神的教程,慢慢摸索TensorFlow中,但在今天在模仿过程中,出了一些小小的纰漏。上文即是最终版。可以放心食用

x_data =np.linspace(-1,1,300)[:,np.newaxis]
noise = np.random.normal(0, 0.1,x_data.shape)
y_data = tf.add(tf.subtract(x_data,0.6),noise)

一开始时,由于觉得自己学了几个TensorFlow的命令就为所欲为,就用了tf.add和tf.subtract两个

本来是没事问题的。但是后来自己使用了tf.placeholder建立了xs和ys.

毕竟placeholder是个容器,最后再装上x_data和y_data的数据,应该是万事大吉。

但是运行之后,出现了以下的问题:

  File "G:/python项目/ZZhTf/add_layer.py", line 49, in <module>
    sess.run(train_step,{xs:x_data, ys:y_data})

TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles.

TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, numpy ndarrays, or TensorHandles.

看完之后,第一反应就是x_data出现了问题。于是就相当设法的将其改为 np.array。

之后仍然是无用功,还尝试了

x_data = tf.cast(x_data,tf.float32)
y_data = tf.cast(y_data,tf.float32)

z结果越搅越浑,之后换了思路,看看是不是y_data的问题。

将其tf.add换为“+”j就解决了该问题

tips:一旦使用了TensorFlow的函数,即表明了该变量成为了一个Tensor ,而不再是一个单纯的数据。

Tensor是不能作为数据feed_dict到TensorFlow的计算图中的!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值