TensorFlow入门教程:1:安装和第一个例子程序

来源:互联网 发布:快消行业数据分析 编辑:程序博客网 时间:2024/04/27 02:58

这里写图片描述
TensorFlow™ 是Google开源的一个采用数据流图用于数值计算的开源库。截止到目前为止在github上已经获得超过6万个Star,已经成为深度学习和机器学习方面最为受欢迎的项目,炙手可热。这篇文章介绍一下如何安装tensorflow并使用其写下第一个程序。

版本信息

时间 版本信息 2015年底 Google开源了tensorflow 2017年2月 发布了tensorflow的1.0版本 目前 稳定版本1.2,prerelease版本1.3

github项目信息

项目 详细信息 URL https://github.com/tensorflow/tensorflow

安装方式

安装平台 安装步骤 Ubuntu https://www.tensorflow.org/install/install_linux Mac OS X https://www.tensorflow.org/install/install_mac Windows https://www.tensorflow.org/install/install_windows

源码安装方式

方式 安装步骤 源码方式 https://www.tensorflow.org/install/install_sources

通用Linux方式

方式 安装步骤 linux https://www.tensorflow.org/install/install_linux#determine_which_tensorflow_to_install

简单来说,使用python-pip进行安装,一步即可。

安装日志

本文使用python-pip方式进行直接安装,执行日志如下:

[root@liumiaocn ~]# pip install tensorflowCollecting tensorflow  Downloading tensorflow-1.2.1-cp27-cp27mu-manylinux1_x86_64.whl (34.5MB)    100% |████████████████████████████████| 34.5MB 8.7kB/s Collecting wheel (from tensorflow)  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)    100% |████████████████████████████████| 71kB 117kB/s Collecting html5lib==0.9999999 (from tensorflow)  Downloading html5lib-0.9999999.tar.gz (889kB)    100% |████████████████████████████████| 890kB 444kB/s Collecting mock>=2.0.0 (from tensorflow)  Downloading mock-2.0.0-py2.py3-none-any.whl (56kB)    100% |████████████████████████████████| 61kB 1.5MB/s Collecting bleach==1.5.0 (from tensorflow)  Downloading bleach-1.5.0-py2.py3-none-any.whlCollecting numpy>=1.11.0 (from tensorflow)  Downloading numpy-1.13.1-cp27-cp27mu-manylinux1_x86_64.whl (16.6MB)    100% |████████████████████████████████| 16.6MB 43kB/s Collecting markdown>=2.6.8 (from tensorflow)  Downloading Markdown-2.6.8.tar.gz (307kB)    100% |████████████████████████████████| 317kB 262kB/s Collecting werkzeug>=0.11.10 (from tensorflow)  Downloading Werkzeug-0.12.2-py2.py3-none-any.whl (312kB)    100% |████████████████████████████████| 317kB 301kB/s Collecting backports.weakref==1.0rc1 (from tensorflow)  Downloading backports.weakref-1.0rc1-py2-none-any.whlCollecting protobuf>=3.2.0 (from tensorflow)  Downloading protobuf-3.3.0-cp27-cp27mu-manylinux1_x86_64.whl (5.7MB)    100% |████████████████████████████████| 5.7MB 121kB/s Requirement already satisfied (use --upgrade to upgrade): six>=1.10.0 in /usr/lib/python2.7/site-packages (from tensorflow)Collecting funcsigs>=1; python_version < "3.3" (from mock>=2.0.0->tensorflow)  Downloading funcsigs-1.0.2-py2.py3-none-any.whlCollecting pbr>=0.11 (from mock>=2.0.0->tensorflow)  Downloading pbr-3.1.1-py2.py3-none-any.whl (99kB)    100% |████████████████████████████████| 102kB 44kB/s Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/lib/python2.7/site-packages (from protobuf>=3.2.0->tensorflow)Installing collected packages: wheel, html5lib, funcsigs, pbr, mock, bleach, numpy, markdown, werkzeug, backports.weakref, protobuf, tensorflow  Running setup.py install for html5lib ... done  Running setup.py install for markdown ... doneSuccessfully installed backports.weakref-1.0rc1 bleach-1.5.0 funcsigs-1.0.2 html5lib-0.9999999 markdown-2.6.8 mock-2.0.0 numpy-1.13.1 pbr-3.1.1 protobuf-3.3.0 tensorflow-1.2.1 werkzeug-0.12.2 wheel-0.29.0You are using pip version 8.1.2, however version 9.0.1 is available.You should consider upgrading via the 'pip install --upgrade pip' command.[root@liumiaocn ~]# 

第一个例子程序

[root@liumiaocn ~]# cat hello_tensorflow.py import tensorflow as tfhello = tf.constant('Hello, TensorFlow!')meaning = tf.constant('The Answer to Life, the Universe and Everything is ')sess    = tf.Session()msg_op  = sess.run(hello)mean_op = sess.run(meaning)print(msg_op)print(mean_op)a       = tf.constant(10)b       = tf.constant(32)cal_op  = sess.run(a + b)print(cal_op)sess.close()[root@liumiaocn ~]#

执行确认

[root@liumiaocn ~]# python hello_tensorflow.py 2017-08-14 03:39:29.856883: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.2017-08-14 03:39:29.857266: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.Hello, TensorFlow!The Answer to Life, the Universe and Everything is 42[root@liumiaocn ~]#

我们可以看到,简单的信息输出和计算都是正常的运行,提示的信息就是告诉你如果你使用源码的方式进行编译的话可能会快一些,如果不想看到这些输出信息,可以在代码中加入如下信息设定LOG的级别即可

import osos.environ['TF_CPP_MIN_LOG_LEVEL']='2'

因为我们在Linux上,设定环境变量非常方便,可以如下即可:

[root@liumiaocn ~]# export TF_CPP_MIN_LOG_LEVEL=2[root@liumiaocn ~]# python hello_tensorflow.py Hello, TensorFlow!The Answer to Life, the Universe and Everything is 42[root@liumiaocn ~]#

42是什么

例子程序为什么是42,仔细查了一下发现一些很无聊又很有趣的事情。Douglas Adams写过一本著名的科幻小说”银河系漫游指南(The Hitchhiker’s Guide to the Galaxy)”,里面提到了一个终极问题,“the Answer to Life, the Universe and Everything is?”生命,宇宙和一切的答案是什么?那个非常厉害的计算机算了半天,回答就是42, 这已经是一个梗,被放到了无数的彩蛋之中,比如你google一下,你会发先google算的快的多了
这里写图片描述

关于为什么是42,很多人给出了不同的解释,比如程序员是这样说的:

[root@liumiaocn ~]# pythonPython 2.7.5 (default, Nov  6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> ord('*')42>>> 

通配符*代表一切,它的ASCII是42.

更有不知道是认真还是无聊的人,整理了42个为什么是42的原因

项番 详细 1 Queen Victoria’s husband Prince Albert died aged 42; they had 42 grandchildren and their great-grandson, Edward VIII, abdicated at the age of 42. 2 The world’s first book printed with movable type is the Gutenberg Bible which has 42 lines per page. 3 On page 42 of Harry Potter and the Philosopher’s Stone, Harry discovers he’s a wizard. 4 The first time Douglas Adams essayed the number 42 was in a sketch called “The Hole in the Wall Club”. In it, comedian Griff Rhys Jones mentions the 42nd meeting of the Crawley and District Paranoid Society. 5 Lord Lucan’s last known location was outside 42 Norman Road, Newhaven, East Sussex. 6 The Doctor Who episode entitled “42” lasts for 42 minutes. 7 Titanic was travelling at a speed equivalent to 42km/hour when it collided with an iceberg. 8 The marine battalion 42 Commando insists that it be known as “Four two, Sir!” 9 In east Asia, including parts of China, tall buildings often avoid having a 42nd floor because of tetraphobia – fear of the number four because the words “four” and “death” sound the same (si or sei). Likewise, four 14, 24, etc. 10 Elvis Presley died at the age of 42. 11 BBC Radio 4’s Desert Island Discs was created in 1942. There are 42 guests per year. 12 Toy Story character Buzz Lightyear’s spaceship is named 42. 13 Fox Mulder’s apartment in the US TV series The X Files was number 42. 14 The youngest president of the United States,Theodore Roosevelt, was 42 when he was elected. 15 The office of Google’s chief executive Eric Schmidt is called Building 42 of the firm’s San Francisco complex. 16 The Bell-X1 rocket plane Glamorous Glennis piloted by Chuck Yeager, first broke the sound barrier at 42,000 feet. 17 The atomic bomb that devastated Nagasaki, Japan, contained the destructive power of 42 million sticks of dynamite. 18 A single Big Mac contains 42 per cent of the recommended daily intake of salt. 19 Cricket has 42 laws. 20 On page 42 of Bram Stoker’s Dracula, Jonathan Harker discovers he is a prisoner of the vampire. And on the same page of Frankenstein, Victor Frankenstein reveals he is able to create life. 21 In Shakespeare’s Romeo and Juliet, Friar Laurence gives Juliet a potion that allows for her to be in a death-like coma for “two and forty hours”. 22 The three best-selling music albums – Michael Jackson’s Thriller, AC/DC’s Back in Black and Pink Floyd’s The Dark Side of the Moon – last 42 minutes. 23 The result of the most famous game in English football – the world cup final of 1966 – was 4-2. 24 The type 42 vacuum tube was one of the most popular audio output amplifiers of the 1930s. 25 A marathon course is 42km and 195m. 26 Samuel Johnson compiled the Dictionary of the English Language, regarded as one of the greatest works of scholarship. In a nine-year period he defined a total of 42,777 words. 27 42,000 balls were used at Wimbledon last year. 28 The wonder horse Nijinsky was 42 months old in 1970 when he became the last horse to win the English Triple Crown: the Derby; the 2000 Guineas and the St Leger. 29 The element molybdenum has the atomic number 42 and is also the 42nd most common element in the universe. 30 Dodi Fayed was 42 when he was killed alongside Princess Diana. 31 Cell 42 on Alcatraz Island was once home to Robert Stroud who was transferred to The Rock in 1942. After murdering a guard he spent 42 years in solitary confinement in different prisons. 32 In the Book of Revelation, it is prophesised that the beast will hold dominion over the earth for 42 months. 33 The Moorgate Tube disaster of 1975 killed 42 passengers. 34 When the growing numbers of Large Hadron Collider scientists acquired more office space recently, they named their new complex Building 42. 35 Lewis Carroll’s Alice’s Adventures in Wonderland has 42 illustrations. 36 42 is the favourite number of Dr House, the American television doctor played by Hugh Laurie. 37 There are 42 US gallons in a barrel of oil. 38 In an episode of The Simpsons, police chief Wiggum wakes up to a question aimed at him and replies “42”. 39 Best Western is the world’s largest hotel chain with more than 4,200 hotels in 80 countries. 40 There are 42 principles of Ma’at, the ancient Egyptian goddess – and concept – of physical and moral law, order and truth. 41 Mungo Jerry’s 1970 hit “In the Summertime”, written by Ray Dorset, has a tempo of 42 beats per minute. 42 The band Level 42 chose their name in recognition of The Hitchhiker’s Guide to the Galaxy and not – as is often repeated – after the world’s tallest car park.

这样的例子无穷无尽,直到Douglas Adams在1993年正式回答之后,依然后很多人认为Douglas Adams其实不是那样想的,这个42有深层的含义。Douglas Adams这样说:

The answer to this is very simple. It was a joke. It had to be a number, an ordinary, smallish number, and I chose that one. Binary representations, base thirteen, Tibetan monks are all complete nonsense. I sat at my desk, stared into the garden and thought '42 will do'. I typed it out. End of story

vim的彩蛋

突然想起来很久以前使用vim时发现的一个彩蛋,调出来之后一看,果然是这个梗(:help 42),只是当时读书太少,没有能理解埋彩蛋的人的心情,真是太不应该了。
这里写图片描述

为什么生命,宇宙和一切的答案是42。很不幸的是,唯一真正知道这个答案的人Douglas Adams已经死了。现在你可能开始要考虑死亡的意义是什么了…

我们程序员看来还真是前赴后继比较有趣的一个群体。
为什么要死,当然是让别人无法理解你埋得彩蛋是什么意思啦。你每天都能看到,每天又不知道为什么,闹不闹心,想不想知道,就不告诉你。

总结

我们花了一分钟学习和安装了一下tensorflow,一分钟做了一个简单的例子,10分钟去理解了一下42到底是什么这样一个关于生命和宇宙答案的哲学问题。

参考文献

https://github.com/tensorflow/tensorflow/issues/7778
https://www.tensorflow.org/
https://www.tensorflow.org/get_started/
https://www.zhihu.com/question/19846530