Embedding asset types

本文详细介绍了如何在Flex应用中嵌入JPEG、GIF、PNG等图像,SVG矢量图形,MP3声音文件,Flash SWF文件以及9-slice缩放图像的方法。此外,还涵盖了如何处理不同类型的SWF文件和嵌入Flex应用的实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Embedding asset types

        

          

You can import various types of media, including images, SWF files, and sound files.

Embedding JPEG, GIF, and PNG images

Flex supports embedding JPEG, GIF, and PNG files. You can use these images for icons, skins, and other types of application assets.

You might want to manipulate an embedded image at run time. To manipulate it, you determine the data type of the object representing the image and then use the appropriate ActionScript methods and properties of the object.

For example, you use the [Embed] metadata tag in ActionScript to embed a GIF image, as the following code shows:

[Embed(source="logo.gif")] 
[Bindable] 
public var imgCls:Class;

In this example, you define a class named imgCls that represents the embedded image. When embedding JPEG, GIF, and PNG files, Flex defines imgCls as a reference to a subclass of the mx.core.BitmapAsset class, which is a subclass of the flash.display.Bitmap class.

In ActionScript, you can create and manipulate an object that represents the embedded image before passing it to a control. To do so, you create an object with the type of the embedded class, manipulate it, and then pass the object to the control, as the following example shows:

<?xml version="1.0"?>
<!-- embed/EmbedAccessClassObject.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">
    
    <fx:Script>
        <![CDATA[        
            import mx.core.BitmapAsset;
        
            [Embed(source="logo.gif")]
            [Bindable]
            public var imgCls:Class;

            private function modImage():void {            
                // Create an object from the embed class. 
                // Since the embedded image is a GIF file, 
                // the data type is BitmapAsset.
                var imgObj:BitmapAsset = new imgCls() as BitmapAsset;
                
                // Modify the object.
                imgObj.bitmapData.noise(4);

                // Write the modified object to the Image control.
                myImage.source=imgObj;
            }
        ]]>
    </fx:Script>
    
    <s:HGroup>
        <s:Image id="myImageRaw" source="{imgCls}"/>
        <s:Image id="myImage" creationComplete="modImage();"/>
    </s:HGroup>
</s:Application>

The executing SWF file for the previous example is shown below:

In this example, the first Image control displays the unaltered image and the second Image control displays the modified image. You use the bitmapData property of the mx.core.BitmapAsset class to modify the object. The bitmapData property is of type flash.display.BitmapData; therefore you can use all of the methods and properties of the BitmapData class to manipulate the object.

Embedding SVG images

Flex supports importing Scalable Vector Graphics (SVG) images, or a GZip compressed SVG image in a SVGZ file, into an application. This lets you import SVG images and use SVG images as icons for Flex controls.

Flex supports a subset of the SVG 1.1 specification to let you import static, two-dimensional scalable vector graphics. This includes support for basic SVG document structure, Cascading Style Sheets (CSS) styling, transformations, paths, basic shapes, colors, and a subset of text, painting, gradients, and fonts. Flex does not support SVG animation, scripting, or interactivity with the imported SVG image.

For example, you use the [Embed] metadata tag in ActionScript to embed an SVG image, as the following code shows:

[Embed(source="logo.svg")] 
[Bindable] 
public var imgCls:Class;

In this example, you define a class named imgCls that represents the embedded image. When embedding an SVG image, Flex defines imgCls as a reference to a subclass of the mx.core.SpriteAsset class, which is a subclass of the flash.display.Sprite class. Therefore, you can manipulate the image by using the methods and properties of the SpriteAsset class. For an example that manipulates an imported image, see Embedding JPEG, GIF, and PNG images.

Embedding sounds

Flex supports embedding MP3 sound files for later playback. The following example creates a simple media player with Play and Stop buttons:

<?xml version="1.0"?>
<!-- embed/EmbedSound.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx">

    <fx:Script>
        <![CDATA[
        
            import flash.media.*; 
        
            [Embed(source="sample.mp3")]
            [Bindable]
            public var sndCls:Class;
            
            public var snd:Sound = new sndCls() as Sound; 
            public var sndChannel:SoundChannel;
            
            public function playSound():void {
                sndChannel=snd.play();
            }   
            
            public function stopSound():void {
                sndChannel.stop();
            }   
        ]]>
    </fx:Script>

    <s:HGroup>
        <s:Button label="play" click="playSound();"/>
        <s:Button label="stop" click="stopSound();"/>
    </s:HGroup>
</s:Application>

The executing SWF file for the previous example is shown below:

In this example, you define a class named sndCls that represents the embedded MP3 file. When embedding MP3 files, Flex defines sndCls as a reference to a subclass of the mx.core.SoundAsset, which is a subclass of the flash.media.Sound class.

Flex can handle any legal filename, including filenames that contain spaces and punctuation marks. If the MP3 filename includes regular quotation marks, be sure to use single quotation marks around the filename.

You do not have to embed the sound file to use it with Flex. You can also use the Sound class to load a sound file at run time. For more information, see the Sound class in the ActionScript 3.0 Reference for the Adobe Flash Platform.

Embedding SWF files

Flex fully supports embedding Flash SWF files. You can embed different types of SWF files.

Embedding SWF files for Flash Player 8 and earlier, and for static Flash Player 9 or later assets

You can embed SWF files created for Flash Player 8 and earlier and for Flash Player 9 or later static assets. Use static assets for simple artwork or skins that do not contain any ActionScript 3.0 code. When embedded, your Flex application cannot interact with the embedded SWF file. That is, you cannot use ActionScript in a Flex application to access the properties or methods of a SWF file created for Flash Player 8 or earlier or for static Flash Player 9 or later assets.

Note:  You can use the flash.net.LocalConnection class to communicate between a Flex application and a SWF file.

For example, you use the [Embed] metadata tag in ActionScript to embed a SWF file, as the following code shows:

[Embed(source="icon.swf")] 
[Bindable] 
public var imgCls:Class;

In this example, you define a class named imgCls that represents the embedded SWF file. Flex defines imgCls as a reference to a subclass of the mx.core.MovieClipAsset class, which is a subclass of the flash.display.MovieClip class. Therefore you can manipulate the image by using the methods and properties of the MovieClipAsset class.

Embedding SWF symbols

Flex lets you reference exported symbols in an embedded SWF file. If the symbol has dependencies, Flex embeds them also; otherwise, Flex embeds only the specified symbol from the SWF file. To reference a symbol, you specify the symbol parameter:

[Embed(source='SWFFileName.swf', symbol='symbolName')]
Note:  Flash defines three types of symbols: Button, MovieClip, and Graphic. You can embed Button and MovieClip symbols in a Flex application, but you cannot embed a Graphic symbol because it cannot be exported for ActionScript.

This capability is useful when you have a SWF file that contains multiple exported symbols, but you want to load only some of them into your Flex application. Loading only the symbols that your application requires makes the resulting Flex SWF file smaller than if you imported the entire SWF file.

A Flex application can import any number of SWF files. However, if two SWF files have the same filename and the exported symbol names are the same, you cannot reference the duplicate symbols, even if the SWF files are in separate directories.

If the SWF file contains any ActionScript code, Flex prints a warning during compilation and then strips out the ActionScript from the embed symbol. This means that you can only embed the symbol itself.

The following example imports a green square from a SWF file that contains a library of different shapes:

<?xml version="1.0"?>
<!-- embed\EmbedSWFSymbol.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx" >

    <s:Image id="image0" 
        source="@Embed(source='circleSquare.swf', symbol='greenSquare')"/>
</s:Application>

The executing SWF file for the previous example is shown below:

If you use the [Embed] metadata tag in ActionScript to embed the symbol, you can access the object that represents the symbol, as the following code shows:

[Embed(source='shapes.swf', symbol='greenSquare')] 
[Bindable] 
public var imgCls:Class;

In this example, you define a class named imgCls that represents the embedded symbol. Internally, Flex defines imgCls as a reference to a subclass of either one of the following classes:

SpriteAsset 
For single-frame SWF files

MovieClipAsset
For multiframe SWF files

Embedding SWF files that represent Flex applications

You can embed SWF files that represent Flex applications. For example, you use the [Embed] metadata tag in ActionScript to embed a SWF file, as the following code shows:

[Embed(source="flex2.swf")] 
[Bindable] 
public var flexAppCls:Class;

In this example, you define a class named flexAppCls that represents the embedded SWF file. Flex defines flexAppCls as a reference to a subclass of the mx.core.MovieClipAsset class, which is a subclass of the flash.display.MovieClip class. Therefore you can manipulate the embedded SWF file by using the methods and properties of the MovieClipAsset class.

You typically embed a Flex application when you do not require the embedding application to interact with the embedded application. If the embedding application requires interactivity with the embedded application, you might consider implementing it as a custom component, rather than as a separate application.

Alternatively, if you use the SWFLoader control to load the Flex application at run time, the embedding application can interact with the loaded application to access its properties and methods. For more information and examples, see Interacting with a loaded Flex application.

Using 9-slice scaling with embedded images

Flex supports the 9-slice scaling of embedded images. This feature lets you define nine sections of an image that scale independently. The nine regions are defined by two horizontal lines and two vertical lines running through the image, which form the inside edges of a 3 by 3 grid. For images with borders or fancy corners, 9-slice scaling provides more flexibility than full-graphic scaling.

The following example show an image, and the same image with the regions defined by the 9-slice scaling borders:

An image, and the same image with the regions defined by the 9-slice scaling borders

When you scale an embedded image that uses 9-slice scaling, all text and gradients are scaled normally. However, for other types of objects the following rules apply:

  • Content in the center region is scaled normally.

  • Content in the corners is not scaled.

  • Content in the top and bottom regions is scaled only horizontally. Content in the left and right regions is scaled only vertically.

  • All fills (including bitmaps, video, and gradients) are stretched to fit their shapes.

If you rotate the image, all subsequent scaling is normal, as if you did not define any 9-slice scaling.

To use 9-slice scaling, define the following four parameters in your embed statement: scaleGridTop, scaleGridBottom, scaleGridLeft, and scaleGridRight. For more information on these parameters, see Embed parameters.

An embedded SWF file may already contain 9-slice scaling information specified by using Adobe Flash Professional. In that case, the SWF file ignores any 9-slice scaling parameters that you specify in the embed statement.

The following example uses 9-slice scaling to maintain a set border, regardless of how the image itself is resized.

<?xml version="1.0"?>
<!-- embed\Embed9slice.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx" 
    height="1200" width="600"> 

    <fx:Script>
        <![CDATA[
            [Embed(source="slice_9_grid.gif", 
                scaleGridTop="25", scaleGridBottom="125", 
                scaleGridLeft="25", scaleGridRight="125")]
            [Bindable]
            public var imgCls:Class;            
        ]]>
    </fx:Script>
    
    <s:VGroup>
        <s:Image source="{imgCls}"/>
        <s:Image source="{imgCls}" width="300" height="300"/>
        <s:Image source="{imgCls}" width="450" height="450"/>
    </s:VGroup>
</s:Application>

The executing SWF file for the previous example is shown below:

The original image is 30 by 30 pixels. The preceding code produces a resizable image that maintains a 5-pixel border:

If you had omitted the 9-slice scaling, the scaled image would have appeared exactly like the unscaled image, as the following image shows:

Omitting the 9-slice scaling means the scaled image appears exactly like the unscaled image

In this example, you define a class named imgCls that represents the embedded image. If the image is a SWF file that uses 9-slice scaling, Flex defines imgCls as a subclass of the mx.core.SpriteAsset class, which is a subclass of the flash.display.Sprite class. Therefore you can use all of the methods and properties of the SpriteAsset class to manipulate the object.

Embedding all other file types

You can embed any file type in a Flex application as a bit map array. However, Flex does not recognize or process files other than those described previously. If you embed any other file type, you must provide the transcode logic to properly present it to the application user.

To load a file type that is not specifically supported by Flex, use the [Embed] metadata tag to define the source file and MIME type "application/octet-stream". Then define a new class variable for the embedded file. The embedded object is a ByteArrayAsset type object.

The following code embeds a bitmap (.bmp) file and displays properties of the embedded object when you click the Show Properties button. To display or use the object in any other way, you must provide code to create a supported object type.

<?xml version="1.0"?>
<!-- embed\EmbedOtherFileTypes.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" 
    xmlns:mx="library://ns.adobe.com/flex/mx"> 
    <s:layout>
        <s:VerticalLayout/>
    </s:layout>
 
    <fx:Script>
        <![CDATA[
            import mx.core.UIComponent;
            import mx.core.BitmapAsset;
   
            [Embed(source="logo.bmp",mimeType="application/octet-stream")]
            private var FileClass : Class;
   
            private function captureEmbeddedImage():void {
                var fileByteArray:Object = new FileClass();
                myTA.text+= "File length:  " + String(fileByteArray.length) + "\n";
                myTA.text+="File type:  " + 
                    String(getQualifiedSuperclassName(fileByteArray)) + "\n";
            }   
        ]]>
    </fx:Script> 
 
    <s:Button
        id="showProperties" 
        label="Show Properties" 
        click="captureEmbeddedImage();"/>
        
    <s:TextArea id="myTA"
        width="75%"
        height="100"/>                
</s:Application>

The executing SWF file for the previous example is shown below:

<think>首先,用户的问题是关于“embedding”在深度学习、机器学习中的原理和应用。用户提到了“原理”和“应用”,所以我需要覆盖这两个方面。 系统级指令: - 所有行内数学表达式用$...$格式。 - 独立公式用$$...$$格式并单独成段。 - 使用中文回答。 - 生成相关问题。 - 引用的段落末尾自然地添加引用标识。 - 回答结构清晰,逐步解决问题,保证真实可靠。 参考站内引用: - 引用[1]:解释嵌入是创建数字指纹的技术,帮助计算机理解单词关系,用于翻译、问答等。 - 引用[2]:提到图嵌入方法。 - 引用[3]:讨论嵌入方法、降维、在PyTorch中的使用,以及entity embedding。 用户意图是查询与'embedding'相关的技术内容,涉及机器学习或深度学习中的嵌入层、嵌入向量等概念。 我的回答结构: 1. **介绍嵌入的概念**:简要解释什么是嵌入,在机器学习中的作用。 2. **原理**:解释嵌入的工作原理,包括数学基础(如向量空间、降维)。 3. **应用**:讨论嵌入在不同领域的应用,如自然语言处理、推荐系统等。 4. **实现示例**:提供一个简单的代码示例,展示如何在深度学习框架中使用嵌入。 5. **生成相关问题**:在最后添加相关问题。 确保使用中文回答。 数学表达式: - 行内数学:如$v_i$表示单词i的嵌入向量。 - 独立公式:如定义嵌入矩阵。 引用标识:在引用的段落末尾添加[^1]、[^2]等。但参考引用是给定的,我应该自然地融入它们。指令说“引用的段落末尾自然地添加引用标识”,所以如果我引用那些内容,就添加标识。例如,如果我用引用[1]的内容,就加[^1]。 在回答中,我需要参考那些引用: - 引用[1]:解释嵌入的基本概念。 - 引用[2]:提到图嵌入。 - 引用[3]:讨论实现和entity embedding。 所以,我可以这样组织: 1. **什么是嵌入?** - 解释嵌入是机器学习中用于表示离散对象(如单词)为连续向量的技术。引用[1]说“嵌入帮助计算机理解单词之间的关系”,所以可以引用。 - 数学上,嵌入是一个映射函数:$f: \text{离散对象} \to \mathbb{R}^d$,其中d是维度。 2. **原理** - 嵌入的原理基于分布式表示,如Word2Vec、GloVe等算法。 - 数学基础:降维(如PCA),矩阵分解。 - 独立公式:例如,Word2Vec的Skip-gram模型目标函数:$$ \max \sum_{(w,c) \in D} \log \sigma(v_c \cdot v_w) $$ 其中$v_w$是单词w的嵌入向量。 - 图嵌入原理:如Node2Vec,引用[2]。 3. **应用** - NLP:词嵌入用于翻译、情感分析。 - 推荐系统:item嵌入,如Airbnb的实践,引用[2]。 - 其他:知识图谱、entity embedding,引用[3]。 4. **实现** - 在PyTorch中使用嵌入层,引用[3]。 - 简单代码示例。 5. **相关问题** - 生成2-3个相关问题。 完整回答结构: - 引言 - 原理部分 - 应用部分 - 实现示例 - 相关问题 确保语言流畅、清晰。</think>### 嵌入(Embedding)在机器学习和深度学习中的原理与应用 嵌入(Embedding)是机器学习和深度学习中一种核心技术,它将离散对象(如单词、用户、物品)映射到低维连续向量空间中,从而捕捉对象之间的语义关系。这种技术广泛应用于自然语言处理(NLP)、推荐系统、图分析等领域。下面,我将从原理和应用两方面逐步解释,确保内容真实可靠,并基于参考引用进行阐述。 --- ### 一、嵌入的原理 嵌入的核心原理是通过学习一个映射函数,将高维离散数据转换为低维连续向量,实现降维和特征提取。这有助于计算机理解对象间的相似性(如语义关系),就像人类通过上下文推断含义一样[^1]。以下是关键原理点: 1. **数学基础**: - 嵌入通常表示为一个嵌入矩阵 $E \in \mathbb{R}^{|V| \times d}$,其中 $|V|$ 是离散对象的数量(如词汇表大小),$d$ 是嵌入向量的维度(通常远小于原始维度)。每个对象 $i$ 的嵌入向量为 $e_i \in \mathbb{R}^d$。 - 降维过程:通过优化算法,将原始稀疏数据(如one-hot编码)压缩为稠密向量。例如,主成分分析(PCA)可用于线性降维,但深度学习嵌入更常用非线性方法。 $$ \min_{E} \sum_{i,j} \| x_i - E e_j \|^2 $$ 其中 $x_i$ 是原始输入,$e_j$ 是嵌入向量。 - 学习目标:嵌入模型通过最大化对象间的相关性来训练。以Word2Vec为例(一种经典词嵌入算法),其Skip-gram模型的目标是预测上下文单词: $$ \max \sum_{(w,c) \in D} \log \sigma(v_c \cdot v_w) $$ 其中 $v_w$ 和 $v_c$ 是单词和上下文的嵌入向量,$\sigma$ 是sigmoid函数,$D$ 是训练数据集[^1]。 2. **算法机制**: - **分布式表示**:嵌入基于分布式假设,即相似对象在向量空间中靠近(如余弦相似度高)。例如,在NLP中,“king”和“queen”的嵌入向量距离较近。 - **图嵌入**:对于图数据(如社交网络),嵌入方法(如Node2Vec)将节点映射为向量,保留图结构信息。这通过随机游走采样路径,并优化节点相似度实现[^2]。 - **训练过程**:嵌入层通常在神经网络中作为可训练参数。例如,在PyTorch中,嵌入层通过反向传播更新权重,以最小化损失函数(如交叉熵)。这允许模型从数据中自动学习有意义的表示[^3]。 嵌入的原理本质是压缩高维信息,同时保留语义,这使得它在处理大规模离散数据时高效且可解释[^1][^3]。 --- ### 二、嵌入的应用 嵌入技术在多个领域有广泛应用,因为它能将复杂关系转化为可计算的向量形式。以下是主要应用场景,结合参考引用进行说明: 1. **自然语言处理(NLP)**: - **词嵌入**:用于表示单词的语义,支持机器翻译、问答系统和情感分析。例如,Word2Vec或GloVe嵌入帮助模型理解“apple”既可能指水果也可能指公司,提升翻译准确性[^1]。 - **实体嵌入(Entity Embedding)**:在结构化数据中,将分类变量(如产品类别)嵌入为向量,用于文本分类或序列建模。这在PyTorch中易于实现,能处理高基数特征[^3]。 2. **推荐系统**: - **Item/User嵌入**:将用户和物品映射到共享向量空间,用于计算相似度。例如,Airbnb使用嵌入技术来推荐房源,通过优化用户交互数据提升点击率[^2]。 - **协同过滤**:嵌入向量捕捉隐式特征(如用户偏好),支持个性化推荐,这在电商和流媒体服务中常见。 3. **图分析与知识图谱**: - **图嵌入**:应用于社交网络或生物网络,节点嵌入可用于社区检测或链接预测。例如,Graph Embedding方法帮助分析蛋白质相互作用网络[^2]。 - **知识表示**:将实体(如“人物”)和关系(如“朋友”)嵌入为向量,用于知识图谱补全,提升问答机器人性能[^3]。 4. **其他领域**: - **计算机视觉**:嵌入用于图像特征提取,如将图片映射到向量空间进行相似搜索。 - **异常检测**:在网络安全中,嵌入表示用户行为,以识别异常模式。 嵌入的应用优势在于其通用性:它能将任何离散对象(文本、图节点等)转化为数值向量,使深度学习模型更易处理非结构化数据[^1][^2][^3]。 --- ### 三、实现示例 在PyTorch中,嵌入层可通过`nn.Embedding`模块实现。以下是一个简单代码示例,展示如何创建和使用词嵌入: ```python import torch import torch.nn as nn # 定义词汇表大小和嵌入维度 vocab_size = 10000 # 假设有10,000个单词 embedding_dim = 128 # 嵌入向量维度 # 创建嵌入层 embedding_layer = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim) # 输入数据(单词索引,例如one-hot编码的索引) input_indices = torch.tensor([1, 23, 456]) # 三个单词的索引 # 获取嵌入向量 output_vectors = embedding_layer(input_indices) print(output_vectors.shape) # 输出: torch.Size([3, 128]) ``` 此代码中,嵌入层将离散单词索引映射为128维向量,这些向量可通过训练(如使用交叉熵损失)优化以捕捉语义[^3]。实际应用中,嵌入层常与LSTM或Transformer结合,用于NLP任务。 --- ### 相关问题 基于嵌入技术的深度和广度,以下是几个相关延伸问题,供进一步探索: 1. 嵌入向量如何评估质量?常用指标有哪些? 2. 在推荐系统中,嵌入如何解决冷启动问题? 3. 图嵌入(Graph Embedding)有哪些最新进展?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值