Welcome to Day 7! Today, you’ll learn how to integrate sentiment analysis into your app using a pre-trained Natural Language Processing (NLP) model. Sentiment analysis is used to determine the emotional tone behind a body of text, making it useful for social media, customer feedback, and chat applications.
What You’ll Learn Today
- Integrate a pre-trained NLP model using TensorFlow.js.
- Process text for sentiment analysis.
- Implement a simple UI for sentiment predictions.
- Extend the app for real-time text analysis.
Step 1: Install and Load the Sentiment Analysis Model
1. Install TensorFlow.js NLP Model
npm install @tensorflow-models/toxicity @tensorflow/tfjs
2. Set Up Sentiment Analysis
Create a new file SentimentAnalyzer.js
:
import * as toxicity from '@tensorflow-models/toxicity';
let model;
export const loadModel = async () => {
const threshold = 0.9; // Confidence threshold
model = await toxicity.load(threshold);
console.log('Sentiment analysis model loaded!');
};
export const analyzeText = async (text) => {
if (!model) {
console.error('Model not loaded.');
return [];
}
const predictions = await model.classify(text);
return predictions.filter((p) => p.results.some((r) => r.match));
};
Step 2: Build the Sentiment Analysis UI
1. Update App.js
import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, TextInput, Button, FlatList } from 'react-native';
import { loadModel, analyzeText } from './SentimentAnalyzer';
const App = () => {
const [text, setText] = useState('');
const [predictions, setPredictions] = useState([]);
useEffect(() => {
loadModel();
}, []);
const handleAnalyze = async () => {
const results = await analyzeText(text);
setPredictions(results);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Sentiment Analysis</Text>
<TextInput
style={styles.input}
placeholder="Enter text to analyze"
value={text}
onChangeText={setText}
/>
<Button title="Analyze Sentiment" onPress={handleAnalyze} />
<FlatList
data={predictions}
keyExtractor={(item) => item.label}
renderItem={({ item }) => (
<View style={styles.result}>
<Text style={styles.label}>{item.label}</Text>
<Text style={styles.match}>Match: {item.results[0].match ? 'Yes' : 'No'}</Text>
<Text style={styles.probability}>
Probability: {(item.results[0].probabilities[1] * 100).toFixed(2)}%
</Text>
</View>
)}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
},
input: {
width: '100%',
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
padding: 10,
marginBottom: 20,
},
result: {
marginVertical: 10,
padding: 10,
borderWidth: 1,
borderColor: '#ddd',
borderRadius: 8,
width: '100%',
},
label: {
fontSize: 16,
fontWeight: 'bold',
},
match: {
fontSize: 14,
},
probability: {
fontSize: 14,
color: '#555',
},
});
export default App;
Step 3: Test the Sentiment Analysis Feature
- Run the app:
npx react-native run-android npx react-native run-ios
- Enter text into the input field and click Analyze Sentiment.
- Review the analysis results displayed below the button. For example:
- Input: “I love this product!”
- Output: Positive sentiment detected with 98% probability.
Step 4: Enhance Sentiment Analysis
- Handle Real-Time Analysis: Modify the
TextInput
to analyze sentiment as the user types:onChangeText={async (value) => { setText(value); const results = await analyzeText(value); setPredictions(results); }}
- Support Multiple Languages: Extend your model or preprocess text using translation APIs like Google Translate before analysis.
- Visualize Sentiments: Use graphs or icons (e.g., happy/sad faces) to represent predictions visually.
SEO Optimization for This Tutorial
Keywords: TensorFlow.js sentiment analysis, NLP React Native app, sentiment analysis mobile app, TensorFlow.js text analysis, real-time sentiment prediction.
Meta Description: Learn how to integrate sentiment analysis into your mobile app using TensorFlow.js. Step-by-step guide with live text analysis and UI implementation.
Summary
Today, you integrated a pre-trained sentiment analysis model into your app to analyze text in real-time. This feature is ideal for apps that deal with customer feedback, chat, or social media content.
What’s Next: Tomorrow, you’ll customize and train your own machine learning model for more advanced use cases.
Stay tuned for Day 8: Customizing and Training Your Own Machine Learning Model.