{"id":3322,"date":"2022-02-27T14:56:07","date_gmt":"2022-02-27T06:56:07","guid":{"rendered":"https:\/\/egonlin.com\/?p=3322"},"modified":"2022-02-27T14:57:28","modified_gmt":"2022-02-27T06:57:28","slug":"%e7%ac%ac%e5%8d%81%e4%ba%94%e7%ab%a0%ef%bc%9atensorflow%e5%9f%ba%e6%9c%ac%e4%bd%bf%e7%94%a8","status":"publish","type":"post","link":"https:\/\/egonlin.com\/?p=3322","title":{"rendered":"\u7b2c\u5341\u4e94\u7ae0\uff1aTensorflow\u57fa\u672c\u4f7f\u7528"},"content":{"rendered":"<h1>Tensorflow\u57fa\u672c\u4f7f\u7528<\/h1>\n<h1>\u786e\u8ba4\u5b89\u88c5Tensorflow<\/h1>\n<pre><code class=\"language-python\">import tensorflow as tf\n\na = tf.constant(10)\nb = tf.constant(32)\nsess = tf.Session()\nprint(sess.run(a+b))<\/code><\/pre>\n<pre><code>42<\/code><\/pre>\n<h1>\u83b7\u53d6MNIST\u6570\u636e\u96c6<\/h1>\n<pre><code class=\"language-python\"># \u83b7\u53d6MNIST\u6570\u636e\u96c6\n# \u83b7\u53d6\u5730\u5740\uff1ahttps:\/\/tensorflow.googlesource.com\/tensorflow\/+\/master\/tensorflow\/examples\/tutorials\/mnist\/input_data.py\n# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n&quot;&quot;&quot;Functions for downloading and reading MNIST data.&quot;&quot;&quot;\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport gzip\nimport os\nimport tensorflow.python.platform\nimport numpy\nfrom six.moves import urllib\nfrom six.moves import xrange  # pylint: disable=redefined-builtin\nimport tensorflow as tf\nSOURCE_URL = &#039;http:\/\/yann.lecun.com\/exdb\/mnist\/&#039;\n\ndef maybe_download(filename, work_directory):\n    &quot;&quot;&quot;Download the data from Yann&#039;s website, unless it&#039;s already here.&quot;&quot;&quot;\n    if not os.path.exists(work_directory):\n        os.mkdir(work_directory)\n    filepath = os.path.join(work_directory, filename)\n    if not os.path.exists(filepath):\n        filepath, _ = urllib.request.urlretrieve(\n            SOURCE_URL + filename, filepath)\n        statinfo = os.stat(filepath)\n        print(&#039;Successfully downloaded&#039;, filename, statinfo.st_size, &#039;bytes.&#039;)\n    return filepath\n\ndef _read32(bytestream):\n    dt = numpy.dtype(numpy.uint32).newbyteorder(&#039;&gt;&#039;)\n    return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]\n\ndef extract_images(filename):\n    &quot;&quot;&quot;Extract the images into a 4D uint8 numpy array [index, y, x, depth].&quot;&quot;&quot;\n    print(&#039;Extracting&#039;, filename)\n    with gzip.open(filename) as bytestream:\n        magic = _read32(bytestream)\n        if magic != 2051:\n            raise ValueError(\n                &#039;Invalid magic number %d in MNIST image file: %s&#039; %\n                (magic, filename))\n        num_images = _read32(bytestream)\n        rows = _read32(bytestream)\n        cols = _read32(bytestream)\n        buf = bytestream.read(rows * cols * num_images)\n        data = numpy.frombuffer(buf, dtype=numpy.uint8)\n        data = data.reshape(num_images, rows, cols, 1)\n        return data\n\ndef dense_to_one_hot(labels_dense, num_classes=10):\n    &quot;&quot;&quot;Convert class labels from scalars to one-hot vectors.&quot;&quot;&quot;\n    num_labels = labels_dense.shape[0]\n    index_offset = numpy.arange(num_labels) * num_classes\n    labels_one_hot = numpy.zeros((num_labels, num_classes))\n    labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\n    return labels_one_hot\n\ndef extract_labels(filename, one_hot=False):\n    &quot;&quot;&quot;Extract the labels into a 1D uint8 numpy array [index].&quot;&quot;&quot;\n    print(&#039;Extracting&#039;, filename)\n    with gzip.open(filename) as bytestream:\n        magic = _read32(bytestream)\n        if magic != 2049:\n            raise ValueError(\n                &#039;Invalid magic number %d in MNIST label file: %s&#039; %\n                (magic, filename))\n        num_items = _read32(bytestream)\n        buf = bytestream.read(num_items)\n        labels = numpy.frombuffer(buf, dtype=numpy.uint8)\n        if one_hot:\n            return dense_to_one_hot(labels)\n        return labels\n\nclass DataSet(object):\n    def __init__(self, images, labels, fake_data=False, one_hot=False,\n                 dtype=tf.float32):\n        &quot;&quot;&quot;Construct a DataSet.\n        one_hot arg is used only if fake_data is true.  `dtype` can be either\n        `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into\n        `[0, 1]`.\n        &quot;&quot;&quot;\n        dtype = tf.as_dtype(dtype).base_dtype\n        if dtype not in (tf.uint8, tf.float32):\n            raise TypeError(&#039;Invalid image dtype %r, expected uint8 or float32&#039; %\n                            dtype)\n        if fake_data:\n            self._num_examples = 10000\n            self.one_hot = one_hot\n        else:\n            assert images.shape[0] == labels.shape[0], (\n                &#039;images.shape: %s labels.shape: %s&#039; % (images.shape,\n                                                       labels.shape))\n            self._num_examples = images.shape[0]\n            # Convert shape from [num examples, rows, columns, depth]\n            # to [num examples, rows*columns] (assuming depth == 1)\n            assert images.shape[3] == 1\n            images = images.reshape(images.shape[0],\n                                    images.shape[1] * images.shape[2])\n            if dtype == tf.float32:\n                # Convert from [0, 255] -&gt; [0.0, 1.0].\n                images = images.astype(numpy.float32)\n                images = numpy.multiply(images, 1.0 \/ 255.0)\n        self._images = images\n        self._labels = labels\n        self._epochs_completed = 0\n        self._index_in_epoch = 0\n\n    @property\n    def images(self):\n        return self._images\n\n    @property\n    def labels(self):\n        return self._labels\n\n    @property\n    def num_examples(self):\n        return self._num_examples\n\n    @property\n    def epochs_completed(self):\n        return self._epochs_completed\n\n    def next_batch(self, batch_size, fake_data=False):\n        &quot;&quot;&quot;Return the next `batch_size` examples from this data set.&quot;&quot;&quot;\n        if fake_data:\n            fake_image = [1] * 784\n            if self.one_hot:\n                fake_label = [1] + [0] * 9\n            else:\n                fake_label = 0\n            return [fake_image for _ in xrange(batch_size)], [\n                fake_label for _ in xrange(batch_size)]\n        start = self._index_in_epoch\n        self._index_in_epoch += batch_size\n        if self._index_in_epoch &gt; self._num_examples:\n            # Finished epoch\n            self._epochs_completed += 1\n            # Shuffle the data\n            perm = numpy.arange(self._num_examples)\n            numpy.random.shuffle(perm)\n            self._images = self._images[perm]\n            self._labels = self._labels[perm]\n            # Start next epoch\n            start = 0\n            self._index_in_epoch = batch_size\n            assert batch_size &lt;= self._num_examples\n        end = self._index_in_epoch\n        return self._images[start:end], self._labels[start:end]\n\ndef read_data_sets(train_dir, fake_data=False, one_hot=False, dtype=tf.float32):\n    class DataSets(object):\n        pass\n    data_sets = DataSets()\n    if fake_data:\n        def fake():\n            return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype)\n        data_sets.train = fake()\n        data_sets.validation = fake()\n        data_sets.test = fake()\n        return data_sets\n    TRAIN_IMAGES = &#039;train-images-idx3-ubyte.gz&#039;\n    TRAIN_LABELS = &#039;train-labels-idx1-ubyte.gz&#039;\n    TEST_IMAGES = &#039;t10k-images-idx3-ubyte.gz&#039;\n    TEST_LABELS = &#039;t10k-labels-idx1-ubyte.gz&#039;\n    VALIDATION_SIZE = 5000\n    local_file = maybe_download(TRAIN_IMAGES, train_dir)\n    train_images = extract_images(local_file)\n    local_file = maybe_download(TRAIN_LABELS, train_dir)\n    train_labels = extract_labels(local_file, one_hot=one_hot)\n    local_file = maybe_download(TEST_IMAGES, train_dir)\n    test_images = extract_images(local_file)\n    local_file = maybe_download(TEST_LABELS, train_dir)\n    test_labels = extract_labels(local_file, one_hot=one_hot)\n    validation_images = train_images[:VALIDATION_SIZE]\n    validation_labels = train_labels[:VALIDATION_SIZE]\n    train_images = train_images[VALIDATION_SIZE:]\n    train_labels = train_labels[VALIDATION_SIZE:]\n    data_sets.train = DataSet(train_images, train_labels, dtype=dtype)\n    data_sets.validation = DataSet(validation_images, validation_labels,\n                                   dtype=dtype)\n    data_sets.test = DataSet(test_images, test_labels, dtype=dtype)\n    return data_sets<\/code><\/pre>\n<h1>\u4f7f\u7528Tensorflow\u8bad\u7ec3\u2014\u2014Softmax\u56de\u5f52<\/h1>\n<p><\/p><div id=\"rml_readmorelogin_placeholder\" style=\"position:relative;\"><div id=\"rml_fade_content\" style=\"position: absolute;\r\ntop:-10em;\r\nwidth:100%;\r\nheight:10em;\r\nbackground: -webkit-linear-gradient(rgba(255, 255, 255, 0) 0%,#ffffff 100%);\r\nbackground-image: -moz-linear-gradient(rgba(255, 255, 255, 0) 0%,#ffffff 100%);\r\nbackground-image: -o-linear-gradient(rgba(255, 255, 255, 0) 0%,#ffffff 100%);\r\nbackground-image: linear-gradient(rgba(255, 255, 255, 0) 0%,#ffffff 100%);\r\nbackground-image: -ms-linear-gradient(rgba(255, 255, 255, 0) 0%,#ffffff 100%);\"><\/div><div class=\"wpf-controller aru_rml_from_in_post\" style=\"background-color:#eeeeee;border:5px solid #cce6ff;\" id=\"ARU_ReadMoreLogin_ReadMoreLoginController\"><h2 id=\"Header\">\u67e5\u770b\u66f4\u591a<\/h2><div id=\"Message\"><p>\u8054\u7cfb\u7ba1\u7406\u5458\u5fae\u4fe1tutu19192010\uff0c\u6ce8\u518c\u8d26\u53f7<\/p>\n<\/div><div id=\"StatusBarHeader\"><\/div><form id=\"ARU_ReadMoreLogin_ReadMoreLoginController\"><input name=\"post_id\" value=\"3322\" type=\"hidden\"\/><input name=\"_init_callback\" value=\"InitLogin\" type=\"hidden\"\/><input name=\"post_id\" value=\"3322\" type=\"hidden\"\/><input name=\"rt_ype\" value=\"1\" type=\"hidden\"\/><input name=\"nonce\" value=\"c0afc7072c\" type=\"hidden\"\/><input name=\"_wpnonce\" value=\"239b4c84ae\" type=\"hidden\"\/><input name=\"_controller\" value=\"ARU_ReadMoreLogin\\ReadMoreLoginController\" type=\"hidden\"\/><input name=\"_proxy_controller\" value=\"ARU_ReadMoreLogin\\ReadMoreLoginController\" type=\"hidden\"\/><input name=\"_view\" value=\"ARU_ReadMoreLogin\\ReadMoreLoginView\" type=\"hidden\"\/><table class=\"wpf-table-placeholder\"><tbody class=\"wpf-table-placeholder\"><tr class=\"wpf-table-placeholder\"><td class=\"wpf-table-placeholder-input\" width=\"400px\"><table class=\"wpf-table-placeholder\"><tbody class=\"wpf-table-placeholder\"><tr class=\"wpf-table-placeholder\"><th class=\"wpf-table-placeholder-input\"><label class=\"wpf-label\">Username:<\/label><\/th><\/tr><tr class=\"wpf-table-placeholder\"><td class=\"wpf-table-placeholder-input\"><input class=\"regular-text text_input\" name=\"username\" value=\"\" type=\"text\"\/><\/td><\/tr><tr class=\"wpf-table-placeholder\"><th class=\"wpf-table-placeholder-input\"><label class=\"wpf-label\">Password:<\/label><\/th><\/tr><tr class=\"wpf-table-placeholder\"><td class=\"wpf-table-placeholder-input\"><input class=\"regular-text text_input\" name=\"password\" value=\"\" type=\"password\"\/><\/td><\/tr><\/tbody><\/table><p class=\"wpf-table-placeholder submit\"><button class=\"wp_plugin_framework_ajax_button\" type=\"button\" style=\"background-color:#4D90FE;;color:#ffffff;;border:1px solid #3079ed;\" name=\"_event\" value=\"ButtonLogin\">Log in<\/button><\/p><\/td><td class=\"wpf-table-placeholder-input\"><\/td><\/tr><\/tbody><\/table><\/form><div id=\"ButtonStartRegister\"><a href=\"https:\/\/egonlin.com\/wp-login.php?action=register\">Register<\/a><\/div><div id=\"Link1\"><a href=\"https:\/\/egonlin.com\/wp-login.php?action=lostpassword\">Forgotten username or password?<\/a><\/div><div id=\"StatusBarFooter\"><\/div><\/div><\/div><div id=aru_remaining_content><\/div>","protected":false},"excerpt":{"rendered":"<p>Tensorflow\u57fa\u672c\u4f7f\u7528 \u786e\u8ba4\u5b89\u88c5Tensorflow import tensorflow as tf a [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[276,302],"tags":[],"_links":{"self":[{"href":"https:\/\/egonlin.com\/index.php?rest_route=\/wp\/v2\/posts\/3322"}],"collection":[{"href":"https:\/\/egonlin.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/egonlin.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/egonlin.com\/index.php?rest_route=\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/egonlin.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3322"}],"version-history":[{"count":0,"href":"https:\/\/egonlin.com\/index.php?rest_route=\/wp\/v2\/posts\/3322\/revisions"}],"wp:attachment":[{"href":"https:\/\/egonlin.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3322"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/egonlin.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3322"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/egonlin.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3322"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}