如何通过 Python 使用 Azure Blob 存储

Python014

如何通过 Python 使用 Azure Blob 存储,第1张

Overview

Azure Blob storage is a service that stores unstructured data in the cloud as objects/blobs. Blob storage can store any type of text or binary data, such as a document, media file, or application installer. Blob storage is also referred to as object storage.

This article will show you how to perform common scenarios using Blob storage. The samples are written in Python and use the Microsoft Azure Storage SDK for Python. The scenarios covered include uploading, listing, downloading, and deleting blobs.

What is Blob Storage?

Azure Blob storage is a service for storing large amounts of unstructured object data, such as text or binary data, that can be accessed from anywhere in the world via HTTP or HTTPS. You can use Blob storage to expose data publicly to the world, or to store application data privately.

Common uses of Blob storage include:

Serving images or documents directly to a browser

Storing files for distributed access

Streaming video and audio

Storing data for backup and restore, disaster recovery, and archiving

Storing data for analysis by an on-premises or Azure-hosted service

Blob service concepts

The Blob service contains the following components:

Storage Account: All access to Azure Storage is done through a storage account. This storage account can be a General-purpose storage account or a Blob storage accountwhich is specialized for storing objects/blobs. See About Azure storage accounts for more information.

Container: A container provides a grouping of a set of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs. Note that the container name must be lowercase.

Blob: A file of any type and size. Azure Storage offers three types of blobs: block blobs, page blobs, and append blobs.

Block blobs are ideal for storing text or binary files, such as documents and media files. Append blobs are similar to block blobs in that they are made up of blocks, but they are optimized for append operations, so they are useful for logging scenarios. A single block blob can contain up to 50,000 blocks of up to 100 MB each, for a total size of slightly more than 4.75 TB (100 MB X 50,000). A single append blob can contain up to 50,000 blocks of up to 4 MB each, for a total size of slightly more than 195 GB (4 MB X 50,000).

Page blobs can be up to 1 TB in size, and are more efficient for frequent read/write operations. Azure Virtual Machines use page blobs as OS and data disks.

For details about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

Create an Azure storage account

The easiest way to create your first Azure storage account is by using the Azure portal. To learn more, see Create a storage account.

You can also create an Azure storage account by using Azure PowerShell, Azure CLI, or the Storage Resource Provider Client Library for .NET.

If you prefer not to create a storage account at this time, you can also use the Azure storage emulator to run and test your code in a local environment. For more information, see Use the Azure Storage Emulator for Development and Testing.

Download and Install Azure Storage SDK for Python

Azure Storage SDK for Python requires Python 2.7, 3.3, 3.4, 3.5, or 3.6, and comes in 4 different packages: azure-storage-blob, azure-storage-file, azure-storage-table and azure-storage-queue. In this tutorial we are going to use azure-storage-blob package.

Install via PyPi

To install via the Python Package Index (PyPI), type:

bashCopy

pip install azure-storage-blob

Note

If you are upgrading from the Azure Storage SDK for Python version 0.36 or earlier, you will first need to uninstall using pip uninstall azure-storage as we are no longer releasing the Storage SDK for Python in a single package.

For alternative installation methods, visit the Azure Storage SDK for Python on Github.

Create a container

Based on the type of blob you would like to use, create a BlockBlobService, AppendBlobService, or PageBlobService object. The following code uses a BlockBlobServiceobject. Add the following near the top of any Python file in which you wish to programmatically access Azure Block Blob Storage.

PythonCopy

from azure.storage.blob import BlockBlobService

The following code creates a BlockBlobService object using the storage account name and account key. Replace 'myaccount' and 'mykey' with your account name and key.2

PythonCopy

block_blob_service = BlockBlobService(account_name='myaccount', account_key='mykey')

Every blob in Azure storage must reside in a container. The container forms part of the blob name. For example, mycontainer is the name of the container in these sample blob URIs:2

Copy

A container name must be a valid DNS name, conforming to the following naming rules:

Container names must start with a letter or number, and can contain only letters, numbers, and the dash (-) character.

Every dash (-) character must be immediately preceded and followed by a letter or numberconsecutive dashes are not permitted in container names.

All letters in a container name must be lowercase.

Container names must be from 3 through 63 characters long.

Important

Note that the name of a container must always be lowercase. If you include an upper-case letter in a container name, or otherwise violate the container naming rules, you may receive a 400 error (Bad Request).

In the following code example, you can use a BlockBlobService object to create the container if it doesn't exist.

PythonCopy

block_blob_service.create_container('mycontainer')

By default, the new container is private, so you must specify your storage access key (as you did earlier) to download blobs from this container. If you want to make the blobs within the container available to everyone, you can create the container and pass the public access level using the following code.

PythonCopy

from azure.storage.blob import PublicAccess

block_blob_service.create_container('mycontainer', public_access=PublicAccess.Container)

Alternatively, you can modify a container after you have created it using the following code.

PythonCopy

block_blob_service.set_container_acl('mycontainer', public_access=PublicAccess.Container)

After this change, anyone on the Internet can see blobs in a public container, but only you can modify or delete them.

Upload a blob into a container

To create a block blob and upload data, use the create_blob_from_path, create_blob_from_stream, create_blob_from_bytes or create_blob_from_text methods. They are high-level methods that perform the necessary chunking when the size of the data exceeds 64 MB.

create_blob_from_path uploads the contents of a file from the specified path, and create_blob_from_stream uploads the contents from an already opened file/stream. create_blob_from_bytes uploads an array of bytes, and create_blob_from_text uploads the specified text value using the specified encoding (defaults to UTF-8).

The following example uploads the contents of the sunset.png file into the myblockblob blob.

PythonCopy

from azure.storage.blob import ContentSettings

block_blob_service.create_blob_from_path(    'mycontainer',    'myblockblob',    'sunset.png',

   content_settings=ContentSettings(content_type='image/png')

           )

List the blobs in a container

To list the blobs in a container, use the list_blobs method. This method returns a generator. The following code outputs the name of each blob in a container to the console.

PythonCopy

generator = block_blob_service.list_blobs('mycontainer')for blob in generator:

   print(blob.name)

Download blobs

To download data from a blob, use get_blob_to_path, get_blob_to_stream, get_blob_to_bytes, or get_blob_to_text. They are high-level methods that perform the necessary chunking when the size of the data exceeds 64 MB.

The following example demonstrates using get_blob_to_path to download the contents of the myblockblob blob and store it to the out-sunset.png file.2

PythonCopy

block_blob_service.get_blob_to_path('mycontainer', 'myblockblob', 'out-sunset.png')

Delete a blob

Finally, to delete a blob, call delete_blob.

PythonCopy

block_blob_service.delete_blob('mycontainer', 'myblockblob')

Writing to an append blob

An append blob is optimized for append operations, such as logging. Like a block blob, an append blob is comprised of blocks, but when you add a new block to an append blob, it is always appended to the end of the blob. You cannot update or delete an existing block in an append blob. The block IDs for an append blob are not exposed as they are for a block blob.

Each block in an append blob can be a different size, up to a maximum of 4 MB, and an append blob can include a maximum of 50,000 blocks. The maximum size of an append blob is therefore slightly more than 195 GB (4 MB X 50,000 blocks).

The example below creates a new append blob and appends some data to it, simulating a simple logging operation.

PythonCopy

from azure.storage.blob import AppendBlobService

append_blob_service = AppendBlobService(account_name='myaccount', account_key='mykey')# The same containers can hold all types of blobsappend_blob_service.create_container('mycontainer')# Append blobs must be created before they are appended toappend_blob_service.create_blob('mycontainer', 'myappendblob')

append_blob_service.append_blob_from_text('mycontainer', 'myappendblob', u'Hello, world!')

append_blob = append_blob_service.get_blob_to_text('mycontainer', 'myappendblob')

13个最常用的Python深度学习库介绍

如果你对深度学习和卷积神经网络感兴趣,但是并不知道从哪里开始,也不知道使用哪种库,那么这里就为你提供了许多帮助。

在这篇文章里,我详细解读了9个我最喜欢的Python深度学习库。

这个名单并不详尽,它只是我在计算机视觉的职业生涯中使用并在某个时间段发现特别有用的一个库的列表。

这其中的一些库我比别人用的多很多,尤其是Keras、mxnet和sklearn-theano。

其他的一些我是间接的使用,比如Theano和TensorFlow(库包括Keras、deepy和Blocks等)。

另外的我只是在一些特别的任务中用过(比如nolearn和他们的Deep Belief Network implementation)。

这篇文章的目的是向你介绍这些库。我建议你认真了解这里的每一个库,然后在某个具体工作情境中你就可以确定一个最适用的库。

我想再次重申,这份名单并不详尽。此外,由于我是计算机视觉研究人员并长期活跃在这个领域,对卷积神经网络(细胞神经网络)方面的库会关注更多。

我把这个深度学习库的列表分为三个部分。

第一部分是比较流行的库,你可能已经很熟悉了。对于这些库,我提供了一个通俗的、高层次的概述。然后,针对每个库我详细解说了我的喜欢之处和不喜欢之处,并列举了一些适当的应用案例。

第二部分进入到我个人最喜欢的深度学习库,也是我日常工作中使用最多的,包括:Keras、mxnet和sklearn-theano等。

最后,我对第一部分中不经常使用的库做了一个“福利”板块,你或许还会从中发现有用的或者是在第二板块中我还没有尝试过但看起来很有趣的库。

接下来就让我们继续探索。

针对初学者:

Caffe

提到“深度学习库”就不可能不说到Caffe。事实上,自从你打开这个页面学习深度学习库,我就敢打保票你肯定听说Caffe。

那么,究竟Caffe是什么呢?

Caffe是由Berkeley Vision and Learning Center(BVLC)建立的深度学习框架。它是模块化的,速度极快。而且被应用于学术界和产业界的start-of-the-art应用程序中。

事实上,如果你去翻阅最新的深度学习出版物(也提供源代码),你就很可能会在它们相关的GitHub库中找到Caffe模型。

虽然Caffe本身并不是一个Python库,但它提供绑定到Python上的编程语言。我们通常在新领域开拓网络的时候使用这些绑定。

我把Caffe放在这个列表的原因是它几乎被应用在各个方面。你可以在一个空白文档里定义你的模型架构和解决方案,建立一个JSON文件类型的.prototxt配置文件。Caffe二进制文件提取这些.prototxt文件并培训你的网络。Caffe完成培训之后,你可以把你的网络和经过分类的新图像通过Caffe二进制文件,更好的就直接通过Python或MATLAB的API。

虽然我很喜欢Caffe的性能(它每天可以在K40 GPU上处理60万张图片),但相比之下我更喜欢Keras和mxnet。

主要的原因是,在.prototxt文件内部构建架构可能会变得相当乏味和无聊。更重要的是, Caffe不能用编程方式调整超参数!由于这两个原因,在基于Python的API中我倾向于对允许我实现终端到终端联播网的库倾斜(包括交叉验证和调整超参数)。

Theano

在最开始我想说Theano是美丽的。如果没有Theano,我们根本不会达到现有的深度学习库的数量(特别是在Python)。同样的,如果没有numpy,我们就不会有SciPy、scikit-learn和 scikit-image,,同样可以说是关于Theano和深度学习更高级别的抽象。

非常核心的是,Theano是一个Python库,用来定义、优化和评估涉及多维数组的数学表达式。 Theano通过与numpy的紧密集成,透明地使用GPU来完成这些工作。

虽然可以利用Theano建立深度学习网络,但我倾向于认为Theano是神经网络的基石,同样的numpy是作为科学计算的基石。事实上,大多数我在文章中提到的库都是围绕着Theano,使自己变得更加便利。

不要误会我的意思,我爱Theano,我只是不喜欢用Theano编写代码。

在Theano建设卷积神经网络就像只用本机Python中的numpy写一个定制的支持向量机(SVM),当然这个对比并不是很完美。

你可以做到吗?

当然可以。

它值得花费您的时间和精力吗?

嗯,也许吧。这取决于你是否想摆脱低级别或你的应用是否需要。

就个人而言,我宁愿使用像Keras这样的库,它把Theano包装成更有人性化的API,同样的方式,scikit-learn使机器学习算法工作变得更加容易。

TensorFlow

与Theano类似,TensorFlow是使用数据流图进行数值计算的开源库(这是所有神经网络固有的特征)。最初由谷歌的机器智能研究机构内的Google Brain Team研究人员开发,此后库一直开源,并提供给公众。

相比于Theano ,TensorFlow的主要优点是分布式计算,特别是在多GPU的环境中(虽然这是Theano正在攻克的项目)。

除了用TensorFlow而不是Theano替换Keras后端,对于TensorFlow库我并没有太多的经验。然而在接下来的几个月里,我希望这有所改变。

Lasagne

Lasagne是Theano中用于构建和训练网络的轻量级库。这里的关键词是轻量级的,也就意味着它不是一个像Keras一样围绕着Theano的重包装的库。虽然这会导致你的代码更加繁琐,但它会把你从各种限制中解脱出来,同时还可以让您根据Theano进行模块化的构建。

简而言之:Lasagne的功能是Theano的低级编程和Keras的高级抽象之间的一个折中。

我最喜欢的:

Keras

如果我必须选出一个最喜欢的深度学习Python库,我将很难在Keras和mxnet中做出抉择——但最后,我想我会选Keras。

说真的,Keras的好处我说都说不完。

Keras是一个最低限度的、模块化的神经网络库,可以使用Theano或TensorFlow作为后端。Keras最主要的用户体验是,从构思到产生结果将会是一个非常迅速的过程。

在Keras中架构网络设计是十分轻松自然的。它包括一些state-of-the-art中针对优化(Adam,RMSProp)、标准化(BatchNorm)和激活层(PReLU,ELU,LeakyReLU)最新的算法。

Keras也非常注重卷积神经网络,这也是我十分需要的。无论它是有意还是无意的,我觉得从计算机视觉的角度来看这是非常有价值的。

更重要的是,你既可以轻松地构建基于序列的网络(其中输入线性流经网络)又可以创建基于图形的网络(输入可以“跳过”某些层直接和后面对接)。这使得创建像GoogLeNet和SqueezeNet这样复杂的网络结构变得容易得多。

我认为Keras唯一的问题是它不支持多GPU环境中并行地训练网络。这可能会也可能不会成为你的大忌。

如果我想尽快地训练网络,那么我可能会使用mxnet。但是如果我需要调整超参数,我就会用Keras设置四个独立的实验(分别在我的Titan X GPUs上运行)并评估结果。

mxnet

我第二喜欢的深度学习Python库无疑就是mxnet(重点也是训练图像分类网络)。虽然在mxnet中站立一个网络可能需要较多的代码,但它会提供给你惊人数量的语言绑定(C ++、Python、R、JavaScript等)。

Mxnet库真正出色的是分布式计算,它支持在多个CPU / GPU机训练你的网络,甚至可以在AWS、Azure以及YARN集群。

它确实需要更多的代码来设立一个实验并在mxnet上运行(与Keras相比),但如果你需要跨多个GPU或系统分配训练,我推荐mxnet。

sklearn-theano

有时候你并不需要终端到终端的培养一个卷积神经网络。相反,你需要把CNN看作一个特征提取器。当你没有足够的数据来从头培养一个完整的CNN时它就会变得特别有用。仅仅需要把你的输入图像放入流行的预先训练架构,如OverFeat、AlexNet、VGGNet或GoogLeNet,然后从FC层提取特征(或任何您要使用的层)。

总之,这就是sklearn-theano的功能所在。你不能用它从头到尾的训练一个模型,但它的神奇之处就是可以把网络作为特征提取器。当需要评估一个特定的问题是否适合使用深度学习来解决时,我倾向于使用这个库作为我的第一手判断。

nolearn

我在PyImageSearch博客上用过几次nolearn,主要是在我的MacBook Pro上进行一些初步的GPU实验和在Amazon EC2 GPU实例中进行深度学习。

Keras把 Theano和TensorFlow包装成了更具人性化的API,而nolearn也为Lasagne做了相同的事。此外,nolearn中所有的代码都是与scikit-learn兼容的,这对我来说绝对是个超级的福利。

我个人不使用nolearn做卷积神经网络(CNNs),但你当然也可以用(我更喜欢用Keras和mxnet来做CNNs)。我主要用nolearn来制作Deep Belief Networks (DBNs)。

DIGITS

DIGITS并不是一个真正的深度学习库(虽然它是用Python写的)。DIGITS(深度学习GPU培训系统)实际上是用于培训Caffe深度学习模式的web应用程序(虽然我认为你可以破解源代码然后使用Caffe以外其他的后端进行工作,但这听起来就像一场噩梦)。

如果你曾经用过Caffe,那么你就会知道通过它的终端来定义.prototxt文件、生成图像数据、运行网络并监管你的网络训练是相当繁琐的。 DIGITS旨在通过让你在浏览器中执行这些任务来解决这个问题。

此外,DIGITS的用户界面非常出色,它可以为你提供有价值的统计数据和图表作为你的模型训练。另外,你可以通过各种输入轻松地可视化网络中的激活层。最后,如果您想测试一个特定的图像,您可以把图片上传到你的DIGITS服务器或进入图片的URL,然后你的Caffe模型将会自动分类图像并把结果显示在浏览器中。干净利落!

Blocks

说实话,虽然我一直想尝试,但截至目前我的确从来没用过Blocks(这也是我把它包括在这个列表里的原因)。就像许多个在这个列表中的其他库一样,Blocks建立在Theano之上,呈现出一个用户友好型的API。

deepy

如果让你猜deepy是围绕哪个库建立的,你会猜什么?

没错,就是Theano。

我记得在前一段时间用过deepy(做了初始提交),但在接下里的大概6-8个月我都没有碰它了。我打算在接下来的博客文章里再尝试一下。

pylearn2

虽然我从没有主动地使用pylearn2,但由于历史原因,我觉得很有必要把它包括在这个列表里。 Pylearn2不仅仅是一般的机器学习库(地位类似于scikit-learn),也包含了深度学习算法的实现。

对于pylearn2我最大的担忧就是(在撰写本文时),它没有一个活跃的开发者。正因为如此,相比于像Keras和mxnet这样的有积极维护的库,推荐pylearn2我还有些犹豫。

Deeplearning4j

这本应是一个基于Python的列表,但我想我会把Deeplearning4j包括在这里,主要是出于对他们所做事迹的无比崇敬——Deeplearning4j为JVM建立了一个开源的、分布式的深度学习库。

如果您在企业工作,你可能会有一个塞满了用过的Hadoop和MapReduce服务器的储存器。也许这些你还在用,也许早就不用了。

你怎样才能把这些相同的服务器应用到深度学习里?

事实证明是可以的——你只需要Deeplearning4j。

总计

以上就是本文关于13个最常用的Python深度学习库介绍的全部内容