In [9]:
import numpy as np
import tensorflow as tf


def add_layer(inputs, in_size,out_size,activiation_function=None):
    Weights=tf.Variable(tf.random_normal([in_size,out_size]))
    biases=tf.Variable(tf.zeros[1,out_size]+0.1)
    Wx_plus_b=tf.matmul(input,Weights)+biases
    if activiation_function is None:
        outputs=Wx_plus_b
    else:
        outputs=activiation_function(Wx_plus_b)
        return outputs
    
x_data=np.linspace(-1,1,300)[:,np.newaxis]
noise=np.random.normal(0,0.05,x_data.shape)
y_data=np.sqrt(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,activiation_function=tf.nn.relu)

'''

precision=add_layer(l1,10,1,activiation_function=None)
loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-precision),reduction_indices=[1]))

train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)


init=tf.initialize_all_variables()



print x_data


sess = tf.InteractiveSession(config=tf.ConfigProto(log_device_placement=True))
sess.run(init)

for _ in range(1000):
    sess.run(train_step,feed_dict={xs : x_data, ys : y_data})
    if _ % 50:
        print(sess.run(loss,feed_dict={xs : x_data, ys : y_data}))

'''


print "OK"


/home/A/SW/Anaconda2/lib/python2.7/site-packages/ipykernel_launcher.py:17: RuntimeWarning: invalid value encountered in sqrt
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-87df9cd34c32> in <module>()
     21 
     22 
---> 23 l1=add_layer(xs,1,10,activiation_function=tf.nn.relu)
     24 
     25 '''

<ipython-input-9-87df9cd34c32> in add_layer(inputs, in_size, out_size, activiation_function)
      5 def add_layer(inputs, in_size,out_size,activiation_function=None):
      6     Weights=tf.Variable(tf.random_normal([in_size,out_size]))
----> 7     biases=tf.Variable(tf.zeros[1,out_size]+0.1)
      8     Wx_plus_b=tf.matmul(input,Weights)+biases
      9     if activiation_function is None:

TypeError: 'function' object has no attribute '__getitem__'

In [3]:
import tensorflow as tf    
import numpy as np    
    
def add_layer(inputs,in_size,out_size,n_layer,activation_function=None): #activation_function=None线性函数    
    layer_name="layer%s" % n_layer    
    with tf.name_scope(layer_name):    
        with tf.name_scope('weights'):    
            Weights = tf.Variable(tf.random_normal([in_size,out_size])) #Weight中都是随机变量    
            tf.summary.histogram(layer_name+"/weights",Weights) #可视化观看变量    
        with tf.name_scope('biases'):    
            biases = tf.Variable(tf.zeros([1,out_size])+0.1) #biases推荐初始值不为0    
            tf.summary.histogram(layer_name+"/biases",biases) #可视化观看变量    
        with tf.name_scope('Wx_plus_b'):    
            Wx_plus_b = tf.matmul(inputs,Weights)+biases #inputs*Weight+biases    
            tf.summary.histogram(layer_name+"/Wx_plus_b",Wx_plus_b) #可视化观看变量    
        if activation_function is None:    
            outputs = Wx_plus_b    
        else:    
            outputs = activation_function(Wx_plus_b)    
        tf.summary.histogram(layer_name+"/outputs",outputs) #可视化观看变量    
        return outputs    
    
#创建数据x_data,y_data    
x_data = np.linspace(-1,1,300)[:,np.newaxis] #[-1,1]区间,300个单位,np.newaxis增加维度    
noise = np.random.normal(0,0.05,x_data.shape) #噪点    
y_data = np.square(x_data)-0.5+noise    
    
with tf.name_scope('inputs'): #结构化    
    xs = tf.placeholder(tf.float32,[None,1],name='x_input')    
    ys = tf.placeholder(tf.float32,[None,1],name='y_input')    
    
#三层神经,输入层(1个神经元),隐藏层(10神经元),输出层(1个神经元)    
l1 = add_layer(xs,1,10,n_layer=1,activation_function=tf.nn.relu) #隐藏层    
prediction = add_layer(l1,10,1,n_layer=2,activation_function=None) #输出层    
    
#predition值与y_data差别    
with tf.name_scope('loss'):    
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1])) #square()平方,sum()求和,mean()平均值    
    tf.summary.scalar('loss',loss) #可视化观看常量    
with tf.name_scope('train'):    
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) #0.1学习效率,minimize(loss)减小loss误差    
    
init = tf.initialize_all_variables()    
sess = tf.Session()    
#合并到Summary中    
merged = tf.summary.merge_all()    
#选定可视化存储目录    
writer = tf.summary.FileWriter("Desktop/",sess.graph)    
sess.run(init) #先执行init    
    
#训练1k次    
for i in range(1000):    
    sess.run(train_step,feed_dict={xs:x_data,ys:y_data})    
    if i%50==0:    
        result = sess.run(merged,feed_dict={xs:x_data,ys:y_data}) #merged也是需要run的    
        writer.add_summary(result,i) #result是summary类型的,需要放入writer中,i步数(x轴)


WARNING:tensorflow:From <ipython-input-3-806197971944>:43: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
---------------------------------------------------------------------------
InternalError                             Traceback (most recent call last)
<ipython-input-3-806197971944> in <module>()
     51 #训练1k次
     52 for i in range(1000):
---> 53     sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
     54     if i%50==0:
     55         result = sess.run(merged,feed_dict={xs:x_data,ys:y_data}) #merged也是需要run的

/home/A/SW/Anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/home/A/SW/Anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
    980     if final_fetches or final_targets:
    981       results = self._do_run(handle, final_targets, final_fetches,
--> 982                              feed_dict_string, options, run_metadata)
    983     else:
    984       results = []

/home/A/SW/Anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1030     if handle is None:
   1031       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1032                            target_list, options, run_metadata)
   1033     else:
   1034       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/home/A/SW/Anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
   1050         except KeyError:
   1051           pass
-> 1052       raise type(e)(node_def, op, message)
   1053 
   1054   def _extend_graph(self):

<type 'str'>: (<type 'exceptions.UnicodeEncodeError'>, UnicodeEncodeError('ascii', u'Blas GEMM launch failed : a.shape=(300, 1), b.shape=(1, 10), m=300, n=10, k=1\n\t [[Node: layer1/Wx_plus_b/MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_inputs/x_input_0/_7, layer1/weights/Variable/read)]]\n\nCaused by op u\'layer1/Wx_plus_b/MatMul\', defined at:\n  File "/home/A/SW/Anaconda2/lib/python2.7/runpy.py", line 174, in _run_module_as_main\n    "__main__", fname, loader, pkg_name)\n  File "/home/A/SW/Anaconda2/lib/python2.7/runpy.py", line 72, in _run_code\n    exec code in run_globals\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/ipykernel_launcher.py", line 16, in <module>\n    app.launch_new_instance()\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/traitlets/config/application.py", line 658, in launch_instance\n    app.start()\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/ipykernel/kernelapp.py", line 477, in start\n    ioloop.IOLoop.instance().start()\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/zmq/eventloop/ioloop.py", line 177, in start\n    super(ZMQIOLoop, self).start()\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/tornado/ioloop.py", line 888, in start\n    handler_func(fd_obj, events)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/tornado/stack_context.py", line 277, in null_wrapper\n    return fn(*args, **kwargs)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events\n    self._handle_recv()\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv\n    self._run_callback(callback, msg)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback\n    callback(*args, **kwargs)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/tornado/stack_context.py", line 277, in null_wrapper\n    return fn(*args, **kwargs)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher\n    return self.dispatch_shell(stream, msg)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 235, in dispatch_shell\n    handler(stream, idents, msg)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 399, in execute_request\n    user_expressions, allow_stdin)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/ipykernel/ipkernel.py", line 196, in do_execute\n    res = shell.run_cell(code, store_history=store_history, silent=silent)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/ipykernel/zmqshell.py", line 533, in run_cell\n    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell\n    interactivity=interactivity, compiler=compiler, result=result)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2821, in run_ast_nodes\n    if self.run_code(code, result):\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code\n    exec(code_obj, self.user_global_ns, self.user_ns)\n  File "<ipython-input-3-806197971944>", line 33, in <module>\n    l1 = add_layer(xs,1,10,n_layer=1,activation_function=tf.nn.relu) #\u9690\u85cf\u5c42\n  File "<ipython-input-3-806197971944>", line 14, in add_layer\n    Wx_plus_b = tf.matmul(inputs,Weights)+biases #inputs*Weight+biases\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/math_ops.py", line 1801, in matmul\n    a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/gen_math_ops.py", line 1263, in _mat_mul\n    transpose_b=transpose_b, name=name)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 768, in apply_op\n    op_def=op_def)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 2336, in create_op\n    original_op=self._default_original_op, op_def=op_def)\n  File "/home/A/SW/Anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1228, in __init__\n    self._traceback = _extract_stack()\n\nInternalError (see above for traceback): Blas GEMM launch failed : a.shape=(300, 1), b.shape=(1, 10), m=300, n=10, k=1\n\t [[Node: layer1/Wx_plus_b/MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_inputs/x_input_0/_7, layer1/weights/Variable/read)]]\n', 3385, 3388, 'ordinal not in range(128)'))

In [27]:


In [22]:



Help on function random_uniform in module tensorflow.python.ops.random_ops:

random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None)
    Outputs random values from a uniform distribution.
    
    The generated values follow a uniform distribution in the range
    `[minval, maxval)`. The lower bound `minval` is included in the range, while
    the upper bound `maxval` is excluded.
    
    For floats, the default range is `[0, 1)`.  For ints, at least `maxval` must
    be specified explicitly.
    
    In the integer case, the random integers are slightly biased unless
    `maxval - minval` is an exact power of two.  The bias is small for values of
    `maxval - minval` significantly smaller than the range of the output (either
    `2**32` or `2**64`).
    
    Args:
      shape: A 1-D integer Tensor or Python array. The shape of the output tensor.
      minval: A 0-D Tensor or Python value of type `dtype`. The lower bound on the
        range of random values to generate.  Defaults to 0.
      maxval: A 0-D Tensor or Python value of type `dtype`. The upper bound on
        the range of random values to generate.  Defaults to 1 if `dtype` is
        floating point.
      dtype: The type of the output: `float32`, `float64`, `int32`, or `int64`.
      seed: A Python integer. Used to create a random seed for the distribution.
        See @{tf.set_random_seed}
        for behavior.
      name: A name for the operation (optional).
    
    Returns:
      A tensor of the specified shape filled with random uniform values.
    
    Raises:
      ValueError: If `dtype` is integral and `maxval` is not specified.


In [26]:



[[ 0.  0.  0.  0.  0.]]

In [ ]: