三维动态模型:-DeEAR语音情感三维可视化:D3.js动态渲染A-N-P三角坐标系及聚类分布 - attr("
DeEAR语音情感三维可视化:D3.js动态渲染A-N-P三角坐标系及聚类分布
1. 引言:从声音到情感的可视化之旅
你有没有想过,一段语音里除了文字信息,还藏着多少情感秘密?当我们说“我很好”时,声音可能是平静的、激动的、自然的,或者有点不自然的。这些细微的差别,就是语音的情感表达。
今天我要分享的,就是如何把一个专业的语音情感分析系统——DeEAR的分析结果,用酷炫的动态图表展示出来。DeEAR基于wav2vec2这个强大的语音模型,能够识别语音中的三个关键情感维度:唤醒度(Arousal)、自然度(Nature)和韵律(Prosody)。简单来说,它能听出你说话时是平静还是激动,声音听起来自不自然,节奏和语调怎么样。
但光有分析结果还不够直观。想象一下,如果能把成百上千条语音的情感特征,在一个三维空间里动态地展示出来,还能看到它们是怎么聚类的,那该多有意思!这就是我们今天要做的:用D3.js这个强大的数据可视化库,构建一个动态的A-N-P三角坐标系,让语音情感数据“活”起来。
2. DeEAR语音情感分析系统快速上手
2.1 系统概述与环境准备
DeEAR(Deep Emotional Expressiveness Recognition)是一个基于深度学习的语音情感表达识别系统。它使用wav2vec2作为基础模型,专门分析语音中的情感表达特征。系统把情感分为三个维度,每个维度都有两个类别:
唤醒度(Arousal):语音的激动程度
低唤醒:平静、沉稳的声音高唤醒:激动、兴奋的声音 自然度(Nature):语音的自然程度
不自然:机械、生硬的声音自然:流畅、真实的声音 韵律(Prosody):语音的节奏和抑扬顿挫
平淡:单调、缺乏变化的声音富有韵律:有节奏感、语调丰富的声音
系统运行在Python 3.11环境下,主要依赖PyTorch、Transformers和Gradio框架。Gradio提供了一个友好的Web界面,让用户可以直接上传语音文件进行分析。
2.2 快速部署与启动
部署DeEAR非常简单,这里提供两种启动方式:
方式一:使用启动脚本(推荐)
/root/DeEAR_Base/start.sh
方式二:直接运行Python应用
python /root/DeEAR_Base/app.py
启动后,你可以通过以下地址访问系统:
本地访问:http://localhost:7860远程访问:http://<容器IP>:7860
2.3 基础使用演示
启动系统后,你会看到一个简洁的Web界面。使用起来很简单:
上传语音文件:支持常见的音频格式,如wav、mp3等点击分析按钮:系统会自动处理并分析语音查看分析结果:系统会显示三个维度的得分和分类
比如你上传一段演讲录音,系统可能会告诉你:唤醒度得分0.8(高唤醒),自然度得分0.9(自然),韵律得分0.7(富有韵律)。这意味着这段演讲比较激动人心,声音自然流畅,而且有一定的节奏感。
3. 数据准备:从分析结果到可视化数据
3.1 理解DeEAR的输出格式
DeEAR分析完语音后,会输出一个结构化的JSON结果。这个结果包含了每个维度的详细信息和整体情感表达的分类。理解这个输出格式,是我们进行可视化的第一步。
一个典型的DeEAR输出结果长这样:
{
"audio_id": "speech_001",
"arousal": {
"score": 0.75,
"category": "高唤醒",
"confidence": 0.92
},
"nature": {
"score": 0.88,
"category": "自然",
"confidence": 0.95
},
"prosody": {
"score": 0.62,
"category": "富有韵律",
"confidence": 0.87
},
"timestamp": "2024-01-15T10:30:00Z"
}
每个维度都有三个关键信息:
score:得分,范围0-1,越高表示越倾向于该维度的正向类别category:分类结果(低唤醒/高唤醒、不自然/自然、平淡/富有韵律)confidence:置信度,表示模型对这个判断的把握程度
3.2 构建可视化数据集
为了进行三维可视化,我们需要把DeEAR的分析结果转换成适合D3.js处理的数据格式。这里的关键是创建一个包含多个语音样本的数据集,每个样本都有三个维度的坐标。
假设我们有100个语音样本,我们可以这样组织数据:
// 可视化数据格式示例
const emotionData = [
{
id: "sample_001",
arousal: 0.75, // 唤醒度得分
nature: 0.88, // 自然度得分
prosody: 0.62, // 韵律得分
category: "演讲", // 语音类型标签
confidence: 0.91 // 平均置信度
},
{
id: "sample_002",
arousal: 0.35,
nature: 0.92,
prosody: 0.45,
category: "对话",
confidence: 0.87
},
// ... 更多样本
];
在实际应用中,你可能需要处理成百上千个语音样本。这时候,可以考虑批量处理DeEAR的输出,或者直接从数据库导出分析结果。
3.3 数据预处理与归一化
在可视化之前,我们通常需要对数据进行一些预处理:
数据清洗:检查是否有异常值或缺失值归一化处理:确保所有维度的得分都在0-1范围内标签编码:把文本分类转换成数值或颜色编码置信度加权:根据置信度调整数据点的显示大小或透明度
这里有一个简单的数据预处理函数示例:
function preprocessEmotionData(rawData) {
return rawData.map(sample => {
// 计算平均置信度
const avgConfidence = (
sample.arousal.confidence +
sample.nature.confidence +
sample.prosody.confidence
) / 3;
// 返回处理后的数据
return {
id: sample.audio_id,
arousal: sample.arousal.score,
nature: sample.nature.score,
prosody: sample.prosody.score,
category: determineCategory(sample), // 根据得分确定整体类别
confidence: avgConfidence,
size: 5 + avgConfidence * 10, // 根据置信度调整点的大小
opacity: 0.3 + avgConfidence * 0.7 // 根据置信度调整透明度
};
});
}
// 根据三个维度的得分确定整体情感类别
function determineCategory(sample) {
const a = sample.arousal.score;
const n = sample.nature.score;
const p = sample.prosody.score;
if (a > 0.7 && n > 0.7 && p > 0.7) return "积极激动";
if (a < 0.3 && n > 0.7 && p > 0.7) return "平静自然";
if (a > 0.7 && n < 0.3 && p > 0.7) return "激动但不自然";
// ... 更多分类逻辑
return "混合情感";
}
4. D3.js三维可视化核心实现
4.1 构建三角坐标系基础
A-N-P三角坐标系是一个等边三角形,三个顶点分别代表三个情感维度。这种可视化方式特别适合展示三个维度的相对关系。
首先,我们需要设置画布和基础结构:
// 设置画布尺寸和边距
const width = 800;
const height = 700;
const margin = { top: 50, right: 50, bottom: 50, left: 50 };
// 创建SVG画布
const svg = d3.select("#emotion-visualization")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
// 定义三角坐标系的顶点
const triangleSize = 500;
const trianglePoints = [
[triangleSize / 2, 0], // Arousal顶点(顶部)
[0, triangleSize * Math.sqrt(3) / 2], // Nature顶点(左下)
[triangleSize, triangleSize * Math.sqrt(3) / 2] // Prosody顶点(右下)
];
// 绘制三角形边框
const triangle = svg.append("polygon")
.attr("points", trianglePoints.map(p => p.join(",")).join(" "))
.attr("fill", "none")
.attr("stroke", "#333")
.attr("stroke-width", 2);
// 添加顶点标签
const vertexLabels = [
{ text: "唤醒度 (Arousal)", x: triangleSize / 2, y: -20 },
{ text: "自然度 (Nature)", x: -40, y: triangleSize * Math.sqrt(3) / 2 + 20 },
{ text: "韵律 (Prosody)", x: triangleSize + 20, y: triangleSize * Math.sqrt(3) / 2 + 20 }
];
vertexLabels.forEach(label => {
svg.append("text")
.attr("x", label.x)
.attr("y", label.y)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#333")
.text(label.text);
});
4.2 坐标映射与数据点定位
在三角坐标系中,每个数据点的位置由三个维度的得分共同决定。我们需要一个函数把三维数据映射到二维平面上的坐标。
// 将A-N-P得分映射到三角坐标系中的位置
function mapToTriangle(arousal, nature, prosody) {
// 确保三个值之和为1(归一化)
const total = arousal + nature + prosody;
const a = arousal / total;
const n = nature / total;
const p = prosody / total;
// 三角坐标系的重心坐标转换
const x = a * trianglePoints[0][0] +
n * trianglePoints[1][0] +
p * trianglePoints[2][0];
const y = a * trianglePoints[0][1] +
n * trianglePoints[1][1] +
p * trianglePoints[2][1];
return { x, y };
}
// 添加网格线和刻度标签
function addGridLines() {
// 添加从顶点到对边的网格线
for (let i = 0; i <= 10; i++) {
const ratio = i / 10;
// 唤醒度网格线(从顶部顶点到底边)
const arousalLine = [
[
trianglePoints[0][0] * (1 - ratio) + trianglePoints[1][0] * ratio,
trianglePoints[0][1] * (1 - ratio) + trianglePoints[1][1] * ratio
],
[
trianglePoints[0][0] * (1 - ratio) + trianglePoints[2][0] * ratio,
trianglePoints[0][1] * (1 - ratio) + trianglePoints[2][1] * ratio
]
];
svg.append("line")
.attr("x1", arousalLine[0][0])
.attr("y1", arousalLine[0][1])
.attr("x2", arousalLine[1][0])
.attr("y2", arousalLine[1][1])
.attr("stroke", "#e0e0e0")
.attr("stroke-width", 1)
.attr("stroke-dasharray", "2,2");
// 添加刻度标签
if (i % 2 === 0) {
svg.append("text")
.attr("x", arousalLine[0][0] - 20)
.attr("y", arousalLine[0][1])
.attr("text-anchor", "end")
.attr("font-size", "10px")
.attr("fill", "#666")
.text(`${(1 - ratio).toFixed(1)}`);
}
}
}
4.3 动态渲染数据点
有了坐标映射函数,我们就可以把DeEAR分析的数据点渲染到三角坐标系中了。为了让可视化更生动,我们可以添加一些交互效果。
// 渲染数据点
function renderDataPoints(data) {
// 创建数据点容器
const pointsGroup = svg.append("g")
.attr("class", "data-points");
// 绑定数据并创建圆点
const points = pointsGroup.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("class", "emotion-point")
.attr("r", d => d.size || 5) // 点的大小可以根据置信度调整
.attr("fill", d => getColorByCategory(d.category))
.attr("opacity", d => d.opacity || 0.7)
.attr("cx", d => mapToTriangle(d.arousal, d.nature, d.prosody).x)
.attr("cy", d => mapToTriangle(d.arousal, d.nature, d.prosody).y);
// 添加鼠标悬停效果
points.on("mouseover", function(event, d) {
// 放大当前点
d3.select(this)
.transition()
.duration(200)
.attr("r", (d.size || 5) * 1.5)
.attr("opacity", 1);
// 显示工具提示
showTooltip(event, d);
})
.on("mouseout", function(event, d) {
// 恢复原始大小
d3.select(this)
.transition()
.duration(200)
.attr("r", d.size || 5)
.attr("opacity", d.opacity || 0.7);
// 隐藏工具提示
hideTooltip();
});
// 添加点击交互
points.on("click", function(event, d) {
highlightSimilarPoints(d, data);
});
return points;
}
// 根据情感类别获取颜色
function getColorByCategory(category) {
const colorMap = {
"积极激动": "#ff6b6b", // 红色
"平静自然": "#4ecdc4", // 青色
"激动但不自然": "#ffd166", // 黄色
"自然但平淡": "#06d6a0", // 绿色
"混合情感": "#a0a0a0", // 灰色
// ... 更多类别
};
return colorMap[category] || "#888";
}
// 显示工具提示
function showTooltip(event, d) {
const tooltip = d3.select("#tooltip");
const [x, y] = d3.pointer(event);
tooltip
.style("display", "block")
.style("left", (event.pageX + 10) + "px")
.style("top", (event.pageY - 10) + "px")
.html(`
${d.id}
唤醒度: ${(d.arousal * 100).toFixed(1)}%
自然度: ${(d.nature * 100).toFixed(1)}%
韵律: ${(d.prosody * 100).toFixed(1)}%
类别: ${d.category}
置信度: ${(d.confidence * 100).toFixed(1)}%
`);
}
// 高亮相似的数据点
function highlightSimilarPoints(target, allData) {
// 计算与目标点的相似度
const similarities = allData.map(point => {
const distance = Math.sqrt(
Math.pow(point.arousal - target.arousal, 2) +
Math.pow(point.nature - target.nature, 2) +
Math.pow(point.prosody - target.prosody, 2)
);
return { point, distance };
});
// 找到最相似的10个点
const similarPoints = similarities
.sort((a, b) => a.distance - b.distance)
.slice(0, 11) // 包括目标点自己
.map(item => item.point);
// 高亮显示相似点
d3.selectAll(".emotion-point")
.transition()
.duration(300)
.attr("opacity", d =>
similarPoints.includes(d) ? 1 : 0.2
);
}
5. 聚类分析与动态效果
5.1 实现K-means聚类算法
为了发现数据中的自然分组,我们可以实现一个简单的K-means聚类算法。这能帮助我们识别出不同的情感表达模式。
// 简单的K-means聚类实现
function kmeansClustering(data, k = 4, maxIterations = 100) {
// 初始化聚类中心(随机选择k个点)
let centroids = [];
const indices = new Set();
while (indices.size < k && indices.size < data.length) {
const randomIndex = Math.floor(Math.random() * data.length);
indices.add(randomIndex);
}
centroids = Array.from(indices).map(i => ({
arousal: data[i].arousal,
nature: data[i].nature,
prosody: data[i].prosody,
points: []
}));
// 迭代优化
for (let iter = 0; iter < maxIterations; iter++) {
// 清空每个簇的点
centroids.forEach(c => c.points = []);
// 分配每个点到最近的簇
data.forEach(point => {
let minDistance = Infinity;
let closestCentroidIndex = 0;
centroids.forEach((centroid, index) => {
const distance = Math.sqrt(
Math.pow(point.arousal - centroid.arousal, 2) +
Math.pow(point.nature - centroid.nature, 2) +
Math.pow(point.prosody - centroid.prosody, 2)
);
if (distance < minDistance) {
minDistance = distance;
closestCentroidIndex = index;
}
});
centroids[closestCentroidIndex].points.push(point);
});
// 重新计算簇中心
let centroidsChanged = false;
centroids.forEach(centroid => {
if (centroid.points.length === 0) return;
const newArousal = centroid.points.reduce((sum, p) => sum + p.arousal, 0) / centroid.points.length;
const newNature = centroid.points.reduce((sum, p) => sum + p.nature, 0) / centroid.points.length;
const newProsody = centroid.points.reduce((sum, p) => sum + p.prosody, 0) / centroid.points.length;
if (Math.abs(newArousal - centroid.arousal) > 0.001 ||
Math.abs(newNature - centroid.nature) > 0.001 ||
Math.abs(newProsody - centroid.prosody) > 0.001) {
centroidsChanged = true;
}
centroid.arousal = newArousal;
centroid.nature = newNature;
centroid.prosody = newProsody;
});
// 如果簇中心不再变化,停止迭代
if (!centroidsChanged) break;
}
return centroids;
}
// 可视化聚类结果
function visualizeClusters(data, centroids) {
// 为每个簇分配颜色
const clusterColors = d3.schemeCategory10;
// 根据所属簇为数据点着色
data.forEach(point => {
let minDistance = Infinity;
let clusterIndex = 0;
centroids.forEach((centroid, index) => {
const distance = Math.sqrt(
Math.pow(point.arousal - centroid.arousal, 2) +
Math.pow(point.nature - centroid.nature, 2) +
Math.pow(point.prosody - centroid.prosody, 2)
);
if (distance < minDistance) {
minDistance = distance;
clusterIndex = index;
}
});
point.cluster = clusterIndex;
point.color = clusterColors[clusterIndex % clusterColors.length];
});
// 更新数据点的颜色
d3.selectAll(".emotion-point")
.transition()
.duration(500)
.attr("fill", d => d.color);
// 绘制簇中心
const centroidGroup = svg.append("g")
.attr("class", "centroids");
centroids.forEach((centroid, index) => {
const pos = mapToTriangle(centroid.arousal, centroid.nature, centroid.prosody);
centroidGroup.append("circle")
.attr("cx", pos.x)
.attr("cy", pos.y)
.attr("r", 8)
.attr("fill", clusterColors[index % clusterColors.length])
.attr("stroke", "#fff")
.attr("stroke-width", 2);
centroidGroup.append("text")
.attr("x", pos.x)
.attr("y", pos.y - 12)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#333")
.text(`簇 ${index + 1}`);
});
}
5.2 添加动态过渡效果
动态效果能让可视化更加生动,帮助用户理解数据的变化和关系。
// 添加数据点动画
function animateDataPoints() {
d3.selectAll(".emotion-point")
.attr("r", 0) // 初始大小为0
.transition()
.delay((d, i) => i * 20) // 延迟效果,逐个出现
.duration(800)
.attr("r", d => d.size || 5)
.attr("opacity", d => d.opacity || 0.7);
}
// 力导向图布局(展示数据点之间的关系)
function createForceLayout(data) {
// 创建力模拟
const simulation = d3.forceSimulation(data)
.force("charge", d3.forceManyBody().strength(-30))
.force("center", d3.forceCenter(width / 2, height / 2))
.force("collision", d3.forceCollide().radius(d => (d.size || 5) + 2))
.force("x", d3.forceX().strength(0.1).x(d =>
mapToTriangle(d.arousal, d.nature, d.prosody).x
))
.force("y", d3.forceY().strength(0.1).y(d =>
mapToTriangle(d.arousal, d.nature, d.prosody).y
));
// 更新数据点位置
simulation.on("tick", () => {
d3.selectAll(".emotion-point")
.attr("cx", d => d.x)
.attr("cy", d => d.y);
});
return simulation;
}
// 添加时间轴动画(展示数据随时间变化)
function createTimelineAnimation(dataByTime) {
let currentIndex = 0;
const timePoints = Object.keys(dataByTime).sort();
function updateToTimePoint(index) {
const timeKey = timePoints[index];
const currentData = dataByTime[timeKey];
// 更新数据点
const points = d3.selectAll(".emotion-point")
.data(currentData, d => d.id);
// 进入新点
points.enter()
.append("circle")
.attr("class", "emotion-point")
.attr("r", 0)
.attr("fill", d => getColorByCategory(d.category))
.attr("opacity", 0)
.attr("cx", d => mapToTriangle(d.arousal, d.nature, d.prosody).x)
.attr("cy", d => mapToTriangle(d.arousal, d.nature, d.prosody).y)
.transition()
.duration(500)
.attr("r", d => d.size || 5)
.attr("opacity", d => d.opacity || 0.7);
// 更新现有点
points.transition()
.duration(500)
.attr("cx", d => mapToTriangle(d.arousal, d.nature, d.prosody).x)
.attr("cy", d => mapToTriangle(d.arousal, d.nature, d.prosody).y);
// 移除消失的点
points.exit()
.transition()
.duration(500)
.attr("r", 0)
.attr("opacity", 0)
.remove();
// 更新时间显示
d3.select("#time-display").text(`时间点: ${timeKey}`);
}
// 自动播放
const interval = setInterval(() => {
currentIndex = (currentIndex + 1) % timePoints.length;
updateToTimePoint(currentIndex);
}, 2000);
// 返回清理函数
return () => clearInterval(interval);
}
5.3 交互式聚类探索
让用户能够交互式地探索聚类结果,可以大大提升可视化的实用性。
// 创建聚类控制面板
function createClusterControls(onClusterChange) {
const controls = d3.select("#controls");
// 聚类数量滑块
controls.append("div")
.attr("class", "control-group")
.html(`
聚类数量:4
`);
d3.select("#k-slider").on("input", function() {
const k = parseInt(this.value);
d3.select("#k-value").text(k);
onClusterChange(k);
});
// 聚类方法选择
controls.append("div")
.attr("class", "control-group")
.html(`
聚类算法:
`);
d3.select("#cluster-method").on("change", function() {
onClusterChange(parseInt(d3.select("#k-slider").node().value), this.value);
});
// 显示/隐藏聚类中心
controls.append("div")
.attr("class", "control-group")
.html(`
显示聚类中心
`);
d3.select("#show-centroids").on("change", function() {
const show = this.checked;
d3.selectAll(".centroids")
.style("display", show ? "block" : "none");
});
}
// 层次聚类实现(简化版)
function hierarchicalClustering(data, k) {
// 初始时每个点自成一簇
let clusters = data.map((point, index) => ({
points: [point],
centroid: {
arousal: point.arousal,
nature: point.nature,
prosody: point.prosody
},
id: index
}));
// 计算两个簇之间的距离
function clusterDistance(cluster1, cluster2) {
// 使用平均链接法
let totalDistance = 0;
let count = 0;
cluster1.points.forEach(p1 => {
cluster2.points.forEach(p2 => {
totalDistance += Math.sqrt(
Math.pow(p1.arousal - p2.arousal, 2) +
Math.pow(p1.nature - p2.nature, 2) +
Math.pow(p1.prosody - p2.prosody, 2)
);
count++;
});
});
return totalDistance / count;
}
// 合并最近的簇,直到剩下k个簇
while (clusters.length > k) {
let minDistance = Infinity;
let mergeI = 0;
let mergeJ = 0;
// 找到距离最近的两个簇
for (let i = 0; i < clusters.length; i++) {
for (let j = i + 1; j < clusters.length; j++) {
const distance = clusterDistance(clusters[i], clusters[j]);
if (distance < minDistance) {
minDistance = distance;
mergeI = i;
mergeJ = j;
}
}
}
// 合并两个簇
const mergedCluster = {
points: [...clusters[mergeI].points, ...clusters[mergeJ].points],
centroid: {
arousal: (clusters[mergeI].centroid.arousal + clusters[mergeJ].centroid.arousal) / 2,
nature: (clusters[mergeI].centroid.nature + clusters[mergeJ].centroid.nature) / 2,
prosody: (clusters[mergeI].centroid.prosody + clusters[mergeJ].centroid.prosody) / 2
},
id: clusters.length
};
// 移除被合并的簇,添加新簇
clusters = clusters.filter((_, index) => index !== mergeI && index !== mergeJ);
clusters.push(mergedCluster);
}
return clusters.map(cluster => cluster.centroid);
}
6. 完整应用集成与优化
6.1 整合DeEAR与可视化系统
现在我们把所有部分整合起来,创建一个完整的语音情感可视化应用。
// 主应用函数
async function initEmotionVisualization() {
try {
// 1. 加载DeEAR分析数据
const emotionData = await loadEmotionData();
// 2. 数据预处理
const processedData = preprocessEmotionData(emotionData);
// 3. 初始化可视化
initVisualizationCanvas();
addGridLines();
// 4. 渲染数据点
const points = renderDataPoints(processedData);
animateDataPoints();
// 5. 初始聚类分析
const initialK = 4;
const centroids = kmeansClustering(processedData, initialK);
visualizeClusters(processedData, centroids);
// 6. 添加交互控制
createClusterControls((k, method = 'kmeans') => {
let newCentroids;
if (method === 'kmeans') {
newCentroids = kmeansClustering(processedData, k);
} else if (method === 'hierarchical') {
newCentroids = hierarchicalClustering(processedData, k);
}
// 清除旧的聚类可视化
d3.selectAll(".centroids").remove();
// 重新可视化聚类
visualizeClusters(processedData, newCentroids);
});
// 7. 添加力导向图布局
const simulation = createForceLayout(processedData);
// 8. 添加数据筛选功能
createDataFilters(processedData, points, simulation);
// 9. 添加导出功能
createExportFunctions(processedData, centroids);
} catch (error) {
console.error("初始化失败:", error);
showErrorMessage("数据加载失败,请检查DeEAR服务是否正常运行");
}
}
// 从DeEAR API加载数据
async function loadEmotionData() {
// 这里可以替换为实际的API调用
const response = await fetch('/api/deear/analysis-results');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
// 或者使用模拟数据
// return generateMockData(100);
}
// 创建数据筛选控件
function createDataFilters(data, points, simulation) {
const filters = d3.select("#filters");
// 情感类别筛选
const categories = [...new Set(data.map(d => d.category))];
filters.append("div")
.attr("class", "filter-group")
.html(`
情感类别:
`);
const categoryContainer = d3.select("#category-filters");
categories.forEach(category => { 拼多多帮助力入口
categoryContainer.append("label")
.style("display", "inline-block")
.style("margin-right", "10px")
.html(`
${category}
`)
.select("input")
.on("change", updateFilteredView);
});
// 置信度筛选
filters.append("div")
.attr("class", "filter-group")
.html(`
最小置信度:0.7
`);
d3.select("#confidence-slider").on("input", function() {
const value = parseFloat(this.value);
d3.select("#confidence-value").text(value.toFixed(2));
updateFilteredView();
});
function updateFilteredView() {
// 获取选中的类别
const selectedCategories = [];
d3.selectAll("#category-filters input:checked").each(function() {
selectedCategories.push(this.value);
});
// 获取置信度阈值
const minConfidence = parseFloat(d3.select("#confidence-slider").node().value);
// 筛选数据
const filteredData = data.filter(d =>
selectedCategories.includes(d.category) &&
d.confidence >= minConfidence
);
// 更新数据点显示
points.data(filteredData)
.join(
enter => enter.append("circle")
.attr("class", "emotion-point")
.attr("r", d => d.size || 5)
.attr("fill", d => d.color || getColorByCategory(d.category))
.attr("opacity", d => d.opacity || 0.7)
.attr("cx", d => mapToTriangle(d.arousal, d.nature, d.prosody).x)
.attr("cy", d => mapToTriangle(d.arousal, d.nature, d.prosody).y),
update => update,
exit => exit.remove()
);
// 更新力导向图
simulation.nodes(filteredData).alpha(0.3).restart();
}
}
// 创建数据导出功能
function createExportFunctions(data, centroids) {
const exportDiv = d3.select("#export-controls");
exportDiv.append("button")
.text("导出可视化图片")
.on("click", exportAsImage);
exportDiv.append("button")
.text("导出分析数据 (CSV)")
.on("click", () => exportAsCSV(data));
exportDiv.append("button")
.text("导出聚类结果 (JSON)")
.on("click", () => exportAsJSON(centroids));
}
// 导出为图片
function exportAsImage() {
const svgElement = d3.select("svg").node();
const serializer = new XMLSerializer();
const source = serializer.serializeToString(svgElement);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.onload = function() {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const link = document.createElement("a");
link.download = "emotion-visualization.png";
link.href = canvas.toDataURL("image/png");
link.click();
};
img.src = "data:image/svg+xml;base64," + btoa(source);
}
// 导出为CSV
function exportAsCSV(data) {
const headers = ["ID", "唤醒度", "自然度", "韵律", "类别", "置信度"];
const rows = data.map(d => [
d.id,
d.arousal.toFixed(4),
d.nature.toFixed(4),
d.prosody.toFixed(4),
d.category,
d.confidence.toFixed(4)
]);
const csvContent = [
headers.join(","),
...rows.map(row => row.join(","))
].join("\n");
const blob = new Blob([csvContent], { type: "text/csv" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "emotion-analysis.csv";
link.click();
}
6.2 性能优化与响应式设计
当处理大量数据时,性能优化变得很重要。同时,响应式设计确保可视化在不同设备上都能良好显示。
// 性能优化:数据抽样和聚合
function optimizeLargeDataset(data, maxPoints = 1000) {
if (data.length <= maxPoints) return data;
// 使用网格聚合减少数据点
const gridSize = 20; // 20x20的网格
const grid = {};
data.forEach(point => {
const gridX = Math.floor(point.arousal * gridSize);
const gridY = Math.floor(point.nature * gridSize);
const gridZ = Math.floor(point.prosody * gridSize);
const key = `${gridX},${gridY},${gridZ}`;
if (!grid[key]) {
grid[key] = {
points: [],
count: 0
};
}
grid[key].points.push(point);
grid[key].count++;
});
// 从每个网格单元中选取代表性点
const sampledData = [];
Object.values(grid).forEach(cell => {
if (cell.points.length === 1) {
sampledData.push(cell.points[0]);
} else {
// 取中心点或随机点
const centerIndex = Math.floor(cell.points.length / 2);
sampledData.push(cell.points[centerIndex]);
}
});
return sampledData;
}
// 响应式设计:适应不同屏幕尺寸
function makeVisualizationResponsive() {
function updateDimensions() {
const container = d3.select("#visualization-container");
const containerWidth = container.node().getBoundingClientRect().width;
// 保持宽高比
const newWidth = Math.min(containerWidth - 40, 1200);
const newHeight = newWidth * 0.875; // 保持7:8的宽高比
// 更新SVG尺寸
d3.select("svg")
.attr("width", newWidth)
.attr("height", newHeight);
// 更新所有元素的尺寸和位置
updateVisualizationLayout(newWidth, newHeight);
}
// 初始设置
updateDimensions();
// 监听窗口大小变化
window.addEventListener("resize", debounce(updateDimensions, 250));
}
// 防抖函数
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// 更新可视化布局
function updateVisualizationLayout(width, height) {
// 更新三角形大小和位置
const triangleSize = Math.min(width, height) * 0.7;
const trianglePoints = [
[width / 2, height * 0.15],
[width * 0.15, height * 0.85],
[width * 0.85, height * 0.85]
];
// 更新三角形
d3.select("polygon")
.attr("points", trianglePoints.map(p => p.join(",")).join(" "));
// 更新顶点标签
d3.selectAll(".vertex-label")
.attr("x", (d, i) => {
if (i === 0) return width / 2; // 顶部
if (i === 1) return width * 0.15 - 40; // 左下
return width * 0.85 + 40; // 右下
})
.attr("y", (d, i) => {
if (i === 0) return height * 0.15 - 20;
return height * 0.85 + 30;
});
// 更新数据点位置
d3.selectAll(".emotion-point")
.attr("cx", d => {
const pos = mapToTriangle(d.arousal, d.nature, d.prosody);
return scaleToNewTriangle(pos.x, pos.y);
})
.attr("cy", d => {
const pos = mapToTriangle(d.arousal, d.nature, d.prosody);
return scaleToNewTriangle(pos.x, pos.y, true);
});
// 更新聚类中心
d3.selectAll(".centroid")
.attr("cx", d => {
const pos = mapToTriangle(d.arousal, d.nature, d.prosody);
return scaleToNewTriangle(pos.x, pos.y);
})
.attr("cy", d => {
const pos = mapToTriangle(d.arousal, d.nature, d.prosody);
return scaleToNewTriangle(pos.x, pos.y, true);
});
}
// 坐标缩放函数
function scaleToNewTriangle(x, y, isY = false) {
const oldTriangleSize = 500;
const oldCenterX = oldTriangleSize / 2;
const oldCenterY = oldTriangleSize * Math.sqrt(3) / 4;
const newWidth = d3.select("svg").attr("width");
const newHeight = d3.select("svg").attr("height");
const newTriangleSize = Math.min(newWidth, newHeight) * 0.7;
const newCenterX = newWidth / 2;
const newCenterY = newHeight * 0.5;
if (isY) {
const scaleY = newTriangleSize * Math.sqrt(3) / 2 / (oldTriangleSize * Math.sqrt(3) / 2);
return newCenterY + (y - oldCenterY) * scaleY;
} else {
const scaleX = newTriangleSize / oldTriangleSize;
return newCenterX + (x - oldCenterX) * scaleX;
}
}
7. 总结
通过本文的介绍,我们完成了一个完整的DeEAR语音情感三维可视化系统。从DeEAR语音情感分析的基础使用,到D3.js动态可视化的实现,再到聚类分析和交互功能的添加,我们一步步构建了一个功能丰富、视觉效果出色的情感数据探索工具。
这个系统的核心价值在于,它把抽象的语音情感数据转化为了直观的视觉呈现。用户不仅能看到单个语音样本的情感特征,还能通过聚类分析发现数据中的模式,通过动态交互深入探索数据关系。无论是语音情感研究、用户体验测试,还是语音交互系统优化,这个工具都能提供有价值的洞察。
在实际应用中,你可以根据自己的需求调整和扩展这个系统。比如添加更多的情感维度,集成实时语音分析功能,或者结合其他可视化库创建更复杂的交互效果。可视化不仅仅是展示数据,更是理解数据、发现洞见的重要手段。
希望这个项目能为你提供灵感,帮助你更好地理解和分析语音中的情感表达。情感计算是一个充满潜力的领域,而好的可视化工具能让这个领域的研究和应用更加生动有趣。
获取更多AI镜像
想探索更多AI镜像和应用场景?访问 夸智星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。,三维动态模型