教程

游戏 AI 实战课—深入浅出 tensorflow.jsopen in new window

TensorFlow.js 学会游戏通关open in new window

张量(Tensor)

TensorFlow.js 中数据的中心单位是张量:一组数值形成一个或多个维度的数组。 张量实例具有定义数组形状的形状属性(即,数组的每个维度中有多少个值)。

变量(Variable)

变量用张量的值进行初始化。 然而,与张量不同的是,它们的值是可变的。 您可以使用 assign 方法为现有变量分配一个新的张量:

const initialValues = tf.zeros([5]);
const biases = tf.variable(initialValues); // 初始化biases
biases.print(); // 输出: [0, 0, 0, 0, 0]

const updatedValues = tf.tensor1d([0, 1, 0, 1, 0]);
biases.assign(updatedValues); // 更新 biases的值
biases.print(); // 输出: [0, 1, 0, 1, 0]
// 2x3 Tensor
const shape = [2, 3]; // 2 行, 3 列
const a = tf.tensor([1.0, 2.0, 3.0, 10.0, 20.0, 30.0], shape);
a.print(); // 打印张量值
// 输出:    [[1 , 2 , 3 ],
//          [10, 20, 30]]

// shape也可以用下面的方式实现:
const b = tf.tensor([
	[1.0, 2.0, 3.0],
	[10.0, 20.0, 30.0]
]);
b.print();
// 输出:    [[1 , 2 , 3 ],
//          [10, 20, 30]]

线性回归和可视化

线性回归open in new window:预测两种或者两种以上变量间相互依赖的定量关系。

可视化使用的是tfjs-visopen in new window

TIP

点击没反应请刷新浏览器

const xs = [1, 2, 3, 4];
const ys = [1, 3, 5, 7];

// 新建可视化
tfvis.render.scatterplot(
	{ name: "线性回归训练集" },
	{ values: xs.map((x, i) => ({ x, y: ys[i] })) },
	{ xAxisDomain: [0, 5], yAxisDomain: [0, 8] }
);

// 线性模型
const model = tf.sequential();
// 添加一个神经元 全联接层 units:神经元个数
model.add(tf.layers.dense({ units: 1, inputShape: [1] }));
// 均方误差损失函数与优化器
model.compile({ loss: tf.losses.meanSquaredError, optimizer: tf.train.sgd(0.1) });

const inputs = tf.tensor(xs);
const labels = tf.tensor(ys);
// 开始训练
await model.fit(inputs, labels, {
	batchSize: 4,
	epochs: 200,
	callbacks: tfvis.show.fitCallbacks({ name: "训练过程" }, ["loss"])
});

// 预测结果
const output = model.predict(tf.tensor([5]));
const result = output.dataSync()[0];

ElMessageBox.alert(`输入为5,预测结果:${result}`, "预测结果", {
	confirmButtonText: "确定"
});

逻辑回归

逻辑回归open in new window logistic 回归又称 logistic 回归分析,是一种广义的线性回归分析模型,常用于数据挖掘,疾病自动诊断,经济预测等领域。常用于输出值为”是“或”否“


TIP

点击没反应请刷新浏览器

const normalRandom = (mean = 0, variance = 1) => {
	let v1, v2, s;
	do {
		v1 = 2 * Math.random() - 1;
		v2 = 2 * Math.random() - 1;
		s = v1 * v1 + v2 * v2;
	} while (s > 1);

	let result = Math.sqrt((-2 * Math.log(s)) / s) * v1;
	return mean + Math.sqrt(variance) * result;
};

const getData = (numSamples) => {
	let points = [];

	const genGauss = (cx, cy, label) => {
		for (let i = 0; i < numSamples / 2; i++) {
			let x = normalRandom(cx);
			let y = normalRandom(cy);
			points.push({ x, y, label });
		}
	};

	genGauss(2, 2, 1);
	genGauss(-2, -2, 0);
	return points;
};
// 获得训练的数据集
const data = getData(400);
// 可视化数据
tfvis.render.scatterplot(
	{ name: "逻辑回归训练数据" },
	{
		values: [data.filter((p) => p.label === 1), data.filter((p) => p.label === 0)]
	}
);
// 线性模型
const model = tf.sequential();
// 神经元
model.add(
	tf.layers.dense({
		units: 1,
		inputShape: [2],
		activation: "sigmoid" // 激活函数 sigmoid适用于二分类
	})
);
model.compile({
	loss: tf.losses.logLoss, // 对数损失函数 次方的逆运算 如 16的对数就是4  2的4次方
	optimizer: tf.train.adam(0.1) // 优化器
});

const inputs = tf.tensor(data.map((p) => [p.x, p.y]));
const labels = tf.tensor(data.map((p) => p.label));

await model.fit(inputs, labels, {
	batchSize: 40,
	epochs: 20,
	callbacks: tfvis.show.fitCallbacks({ name: "训练效果" }, ["loss"])
});
const pred = model.predict(tf.tensor([[2, 1]]));
ElMessageBox.alert(`预测结果:${pred.dataSync()[0]}`, "预测结果", {
	confirmButtonText: "确定"
});
Last Updated: