入门篇
最近在学习tensorflow,里面介绍了一些概念,首先我认为最重要的就是张量,
那么,这个东西是什么东东呢?我认为暂时我们就可以把他当作一个向量数据(因为机器学习中的数据大多都是多维向量数据。)
OK!!!
那么,现在,我们就假装我们已经知道神经网络是怎么回事了,现在,我们就要开始构造我们的神经网络了,
第一步,像我们开始学习编程时一样,首先我们应该定义一些变量,然后使用我们,定义的一些变量进行四则运算
import tensorflow as tf
num1 = tf.Variable(tf.constant(10.0),name='num1')
num2 = tf.Variable(tf.constant(0.9),name='num2')
观察上面的定义变量的方式,是的,不错,我们定义变量时,使用Variable来定义变量
那么,constant是什么呢?这个是定义常量的,就像PI一样一样的
另外,我们还使用属性name给每个变量定义了一个名称,那么这个可以不可以不定义呢?是可以的,但是呢
我习惯定义,在以后的调式可视化是会有用处。。。
下面定义四则运算
add = tf.add(num1,num2,name='add')#加法运算
sub = tf.subtract(num1,num2,name ='sub')#减法运算
mul = tf.multiply(num1,num2,name='multiply') #乘法
div = tf.div(num1,num2, name='divide') #出发运算
好了,上面的运算,我们已经写完了,那么,下面,我们首先想到的就是,吧计算结果打印出来,
那么,我们打印一下,看看吧。。。
print('%f + %f = %f'%(num1,num2,add))
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-12-36959a8dfa1b> in <module>() ----> 1 print('%f + %f = %f'%(num1,num2,add)) TypeError: a float is required
哎呀,不好,怎么出错了呢?明明没有问题
其实,是这样的,上面我们定义好的变量和逻辑运算,实际上,是不会运行的,我们必须使用Session来运行它才可以
没办法,我们继续看.....
with tf.Session() as sess:
print('%f + %f = %f'%(num1,num2,sess.run(add)))
--------------------------------------------------------------------------- FailedPreconditionError Traceback (most recent call last) /opt/conda/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args) 1291 try: -> 1292 return fn(*args) 1293 except errors.OpError as e: /opt/conda/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata) 1276 return self._call_tf_sessionrun( -> 1277 options, feed_dict, fetch_list, target_list, run_metadata) 1278 /opt/conda/lib/python3.5/site-packages/tensorflow/python/client/session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata) 1366 self._session, options, feed_dict, fetch_list, target_list, -> 1367 run_metadata) 1368 FailedPreconditionError: Attempting to use uninitialized value num2_2 [[{{node num2_2/read}} = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](num2_2)]] During handling of the above exception, another exception occurred: FailedPreconditionError Traceback (most recent call last) <ipython-input-24-40bba783f050> in <module>() 1 with tf.Session() as sess: ----> 2 print('%f + %f = %f'%(num1,num2,sess.run(add))) /opt/conda/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata) 885 try: 886 result = self._run(None, fetches, feed_dict, options_ptr, --> 887 run_metadata_ptr) 888 if run_metadata: 889 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr) /opt/conda/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata) 1108 if final_fetches or final_targets or (handle and feed_dict_tensor): 1109 results = self._do_run(handle, final_targets, final_fetches, -> 1110 feed_dict_tensor, options, run_metadata) 1111 else: 1112 results = [] /opt/conda/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata) 1284 if handle is None: 1285 return self._do_call(_run_fn, feeds, fetches, targets, options, -> 1286 run_metadata) 1287 else: 1288 return self._do_call(_prun_fn, handle, feeds, fetches) /opt/conda/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args) 1306 self._config.experimental.client_handles_error_formatting): 1307 message = error_interpolation.interpolate(message, self._graph) -> 1308 raise type(e)(node_def, op, message) 1309 1310 def _extend_graph(self): FailedPreconditionError: Attempting to use uninitialized value num2_2 [[{{node num2_2/read}} = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](num2_2)]] Caused by op 'num2_2/read', defined at: File "/opt/conda/lib/python3.5/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/opt/conda/lib/python3.5/runpy.py", line 85, in _run_code exec(code, run_globals) File "/opt/conda/lib/python3.5/site-packages/ipykernel_launcher.py", line 16, in <module> app.launch_new_instance() File "/opt/conda/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance app.start() File "/opt/conda/lib/python3.5/site-packages/ipykernel/kernelapp.py", line 497, in start self.io_loop.start() File "/opt/conda/lib/python3.5/site-packages/zmq/eventloop/ioloop.py", line 177, in start super(ZMQIOLoop, self).start() File "/opt/conda/lib/python3.5/site-packages/tornado/ioloop.py", line 888, in start handler_func(fd_obj, events) File "/opt/conda/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "/opt/conda/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events self._handle_recv() File "/opt/conda/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv self._run_callback(callback, msg) File "/opt/conda/lib/python3.5/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback callback(*args, **kwargs) File "/opt/conda/lib/python3.5/site-packages/tornado/stack_context.py", line 277, in null_wrapper return fn(*args, **kwargs) File "/opt/conda/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher return self.dispatch_shell(stream, msg) File "/opt/conda/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 233, in dispatch_shell handler(stream, idents, msg) File "/opt/conda/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 399, in execute_request user_expressions, allow_stdin) File "/opt/conda/lib/python3.5/site-packages/ipykernel/ipkernel.py", line 262, in do_execute res = shell.run_cell(code, store_history=store_history, silent=silent) File "/opt/conda/lib/python3.5/site-packages/ipykernel/zmqshell.py", line 537, in run_cell return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) File "/opt/conda/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2662, in run_cell raw_cell, store_history, silent, shell_futures) File "/opt/conda/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2785, in _run_cell interactivity=interactivity, compiler=compiler, result=result) File "/opt/conda/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2901, in run_ast_nodes if self.run_code(code, result): File "/opt/conda/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2961, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-17-8cd041a3e322>", line 2, in <module> num2 = tf.Variable(tf.constant(.9,tf.float32),name='num2') File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 145, in __call__ return cls._variable_call(*args, **kwargs) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 141, in _variable_call aggregation=aggregation) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 120, in <lambda> previous_getter = lambda **kwargs: default_variable_creator(None, **kwargs) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/ops/variable_scope.py", line 2441, in default_variable_creator expected_shape=expected_shape, import_scope=import_scope) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 147, in __call__ return super(VariableMetaclass, cls).__call__(*args, **kwargs) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 1104, in __init__ constraint=constraint) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/ops/variables.py", line 1266, in _init_from_args self._snapshot = array_ops.identity(self._variable, name="read") File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 81, in identity return gen_array_ops.identity(input, name=name) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 3354, in identity "Identity", input=input, name=name) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper op_def=op_def) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func return func(*args, **kwargs) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 3272, in create_op op_def=op_def) File "/opt/conda/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1768, in __init__ self._traceback = tf_stack.extract_stack() FailedPreconditionError (see above for traceback): Attempting to use uninitialized value num2_2 [[{{node num2_2/read}} = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](num2_2)]]
怎么,有出错了,明明不是我的错。。。
其实啊,只要我们有用到Variable定义变量的地方,我们在运行脚本的时候,都要先初始化
我们再看。。。
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op) #初始化
print('%.2f + %.2f = %.2f'%(sess.run(num1),sess.run(num2),sess.run(add)))
#自己试着把其他的结果打印出来吧
10.00 + 0.90 = 10.90
本社区仅针对特定人员开放
查看需注册登录并通过风险意识测评
5秒后跳转登录页面...