为什么要在浏览器中运行AI?
传统AI应用通常将数据发送到服务器进行处理,这种方式存在延迟高、隐私风险、网络依赖等问题。TensorFlow.js的出现改变了这一局面------它让我们能够在用户的浏览器中直接运行机器学习模型,实现零延迟响应、数据本地处理和离线可用性。
核心概念快速入门
张量(Tensor):TensorFlow.js的基本数据结构,类似于多维数组。
javascript
import * as tf from '@tensorflow/tfjs'
// 创建标量
const scalar = tf.scalar(3.14)
// 创建向量
const vector = tf.tensor1d([1, 2, 3, 4])
// 创建矩阵
const matrix = tf.tensor2d([[1, 2], [3, 4]])
模型加载方式:
预训练模型:使用官方提供的现成模型
自定义模型:自己训练并导出
迁移学习:基于现有模型微调
实战:实时图像分类应用
让我们构建一个简单的图像分类器:
javascript
<template>
<div class="container">
<h2>实时图像分类器</h2>
<input type="file" @change="onFileChange" accept="image/*">
<div v-if="imageUrl" class="preview">
<img :src="imageUrl" alt="预览">
<div v-if="predictions.length > 0" class="results">
<h3>预测结果:</h3>
<div v-for="(pred, index) in predictions" :key="index" class="prediction">
<span>{{ pred.className }}</span>
<div class="bar">
<div class="fill" :style="{ width: pred.probability * 100 + '%' }"></div>
</div>
<span>{{ (pred.probability * 100).toFixed(2) }}%</span>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import * as tf from '@tensorflow/tfjs'
import * as mobilenet from '@tensorflow-models/mobilenet'
const imageUrl = ref('')
const predictions = ref([])
let model = null
onMounted(async () => {
// 加载预训练的MobileNet模型
model = await mobilenet.load()
console.log('MobileNet模型加载完成')
})
const onFileChange = async (event) => {
const file = event.target.files[0]
if (!file) return
// 读取文件
const reader = new FileReader()
reader.onload = async (e) => {
imageUrl.value = e.target.result
// 创建图像元素
const img = new Image()
img.src = imageUrl.value
await img.decode()
// 进行预测
predictions.value = await model.classify(img)
console.log('预测结果:', predictions.value)
}
reader.readAsDataURL(file)
}
</script>
<style scoped>
.container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.preview {
margin-top: 20px;
text-align: center;
}
img {
max-width: 100%;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.results {
margin-top: 20px;
text-align: left;
}
.prediction {
display: flex;
align-items: center;
margin-bottom: 10px;
padding: 10px;
background: #f5f5f5;
border-radius: 4px;
}
.bar {
flex: 1;
height: 20px;
background: #e0e0e0;
border-radius: 10px;
margin: 0 10px;
overflow: hidden;
}
.fill {
height: 100%;
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
transition: width 0.3s ease;
}
</style>```
## 性能优化技巧
1. 模型量化
```javascript
// 使用量化模型减少体积
const model = await mobilenet.load({
version: 2,
alpha: 0.5, // 更小的模型
quantizationBytes: 2 // 2字节量化
})
- 惰性加载
javascript
// 只在需要时加载模型
let modelPromise = null
const getModel = async () => {
if (!modelPromise) {
modelPromise = mobilenet.load()
}
return modelPromise
}
- GPU加速
javascript
// TensorFlow.js自动使用WebGL,但可以手动优化
tf.env().set('WEBGL_PACK', true)
tf.env().set('WEBGL_SIZE_UPLOAD_UNIFORM', 0)
最佳实践
选择合适的模型:根据应用场景选择轻量级模型
错误处理:捕获并处理加载和推理过程中的错误
用户体验:显示加载状态,避免界面卡顿
兼容性检测:检测浏览器是否支持WebGL