import * as tf from '@tensorflow/tfjs';
import * as tfvis from '@tensorflow/tfjs-vis';
window.onload = async () => {
// 浏览量-粉丝量
const flows = [20333,25759,101190,86334,265252,1366198,166114,109979,371423,1291843,1239191,225711,1163189,882702,31415,678478,545108,1304729,73479,2515393,1714555,344847,3147811,1626033,3702785,377376,258472,312769,540292,616665,1207153,2577882,11564515,28231,328984,585611,595275];
const fans = [0,494,6618,3411,12023,7791,65,7109,14014,11840,1202,266,7915,7503,2216,33265,284,34849,4188,41721,25384,1269,62207,20754,192980,28601,7645,1779,13112,10824,4612,548,2311,44,34,259,150];
tfvis.render.scatterplot(
{name: 'csdn浏览量和粉丝量关联'},
{values: flows.map((x, i) => ({x,y:fans[i]}))},
{
xAxisDomain: [20333, 11600000],
yAxisDomain: [0, 200000]
}
);
// 对数据集进行归一化处理
const inputs = tf.tensor(flows).sub(20333).div(11544182);
const lables = tf.tensor(fans).div(192980);
const model = tf.sequential();
// 给模型添加层级和神经元
//model.add(tf.layers.dense({unit: 1, inputShape: [1]}));
model.add(tf.layers.dense({ units: 1, inputShape: [1] }));
// 配置模型训练,设置损失计算函数(均方差等),优化器的SGD配置
model.compile({loss: tf.losses.meanSquaredError, optimizer: tf.train.sgd(0.1)});
await model.fit(
inputs,
lables,
{
batchSize:37,
epochs:200,
callbacks: tfvis.show.fitCallbacks(
{ name: '训练过程' },
['loss']
)
}
);
// 模型预测,输入浏览量输出预测的粉丝数
const output = model.predict(tf.tensor([165265]).sub(20333).div(11544182));
alert('165265预测粉丝数'+output.mul(192980).dataSync()[0]);
//保存模型
window.download = async () => {
await model.save('downloads://my-model');
}
};
评论