Published
Edited
May 31, 2020
Insert cell
Insert cell
// create array of title and sentiment score for each case
cases.map(d => {
let positivityScore = getPositivityScore(d.body);
return `- ${d.title} ${renderEmoji(positivityScore)}`;
})
Insert cell
// get csv data that was downloaded from Participedia and added to a google sheet to use here
cases = d3.csv(
"https://docs.google.com/spreadsheets/d/e/2PACX-1vRzUUTj-qZRuQwD3jrxIQqrMgHFeWKT8T6s3_BMjxt1uX4B-O3Ysp4zsSgt_ytVGnBJlWOT2qyPWAfm/pub?gid=916427632&single=true&output=csv"
)
Insert cell
function renderEmoji(positivityScore) {
let emoji = (() => {
if (positivityScore > 0.9) return '😍';
if (positivityScore > 0.8) return '😀';
if (positivityScore > 0.6) return '🙂';
if (positivityScore > 0.4) return '😐';
if (positivityScore > 0.2) return '🙁';
if (positivityScore > 0.1) return '😦';
return '😱';
})();
return emoji;
}
Insert cell
function getPositivityScore(text) {
const trimmed = text
.trim()
.toLowerCase()
.replace(/(\.|\,|\!)/g, '')
.split(' ');
const inputBuffer = tf.buffer([1, metadata.max_len], "float32");
trimmed.forEach((word, i) =>
inputBuffer.set(metadata.word_index[word] + metadata.index_from, 0, i)
);
const input = inputBuffer.toTensor();
const predictOut = model.predict(input);
const positivity = predictOut.dataSync()[0];
console.log("positivity score = ", positivity);
predictOut.dispose();
return positivity;
}
Insert cell
model = {
return this || await tf.loadModel("https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/model.json")
}
Insert cell
metadata = (await fetch("https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/metadata.json")).json()
Insert cell
tf = require("@tensorflow/tfjs@0.8.0")
Insert cell
d3 = require('d3@latest')
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more