1598834160
Most of us find that it is very difficult to add additional layers and generate connections between the model and additional layers . But , here I am going to make it simple . So that , everyone can get benfit out of it . Just read this out once and we will be good to go .
So , here I am going to use the architechture of two small models (EfficientNet_b0 & ResNet18) as our example to understand the topic .
First of all we will install the pre-trained model
!pip install efficientnet_pytorch
then if we look in the GitHub of efficientNet of Pytorch we will find import for this
from efficientnet_pytorch import EfficientNet
finally we will define our own class
class EfficientNet_b0(nn.Module):
After that we define the constructor for our class
def __init__(self):
super(EfficientNet_b0, self).__init__()
## where this line super(EfficientNet_b0, self).__init__() is used to inherit nn.Module used above.
After that we will load the Pre-trained EfficientNet Model .
self.model = efficientnet_pytorch.EfficientNet.from_pretrained('efficientnet-b0')
and finally I dediced to add extra-layers of **a dense layer **, then a batch Normalisation layer then a dropout layer and finally two dense layers .
self.classifier_layer = nn.Sequential(
nn.Linear(1280 , 512),
nn.BatchNorm1d(512),
nn.Dropout(0.2),
nn.Linear(512 , 256),
nn.Linear(256 , no._of_outputs_classes_for_your_dataset)
)
#computer-vision #using-pretrained-model #data-science #deep-learning #transfer-learning
1667425440
Perl script converts PDF files to Gerber format
Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.
The general workflow is as follows:
Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).
See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.
#Pdf2Gerb config settings:
#Put this file in same folder/directory as pdf2gerb.pl itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;
use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)
##############################################################################################
#configurable settings:
#change values here instead of in main pfg2gerb.pl file
use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call
#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)}Pdf2Gerb.pl ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software. \nGerber files MAY CONTAIN ERRORS. Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG
use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC
use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)
#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1);
#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
.010, -.001, #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
.031, -.014, #used for vias
.041, -.020, #smallest non-filled plated hole
.051, -.025,
.056, -.029, #useful for IC pins
.070, -.033,
.075, -.040, #heavier leads
# .090, -.043, #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
.100, -.046,
.115, -.052,
.130, -.061,
.140, -.067,
.150, -.079,
.175, -.088,
.190, -.093,
.200, -.100,
.220, -.110,
.160, -.125, #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
.090, -.040, #want a .090 pad option, but use dummy hole size
.065, -.040, #.065 x .065 rect pad
.035, -.040, #.035 x .065 rect pad
#traces:
.001, #too thin for real traces; use only for board outlines
.006, #minimum real trace width; mainly used for text
.008, #mainly used for mid-sized text, not traces
.010, #minimum recommended trace width for low-current signals
.012,
.015, #moderate low-voltage current
.020, #heavier trace for power, ground (even if a lighter one is adequate)
.025,
.030, #heavy-current traces; be careful with these ones!
.040,
.050,
.060,
.080,
.100,
.120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);
#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size: parsed PDF diameter: error:
# .014 .016 +.002
# .020 .02267 +.00267
# .025 .026 +.001
# .029 .03167 +.00267
# .033 .036 +.003
# .040 .04267 +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
{
HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects
};
#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
CIRCLE_ADJUST_MINX => 0,
CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
CIRCLE_ADJUST_MAXY => 0,
SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found
};
#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches
#line join/cap styles:
use constant
{
CAP_NONE => 0, #butt (none); line is exact length
CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
};
#number of elements in each shape type:
use constant
{
RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
};
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
our %SHAPELEN =
(
rect => RECT_SHAPELEN,
line => LINE_SHAPELEN,
curve => CURVE_SHAPELEN,
circle => CIRCLE_SHAPELEN,
);
#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions
# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?
#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes.
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes
#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches
# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)
# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time
# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const
use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool
my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time
print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load
#############################################################################################
#junk/experiment:
#use Package::Constants;
#use Exporter qw(import); #https://perldoc.perl.org/Exporter.html
#my $caller = "pdf2gerb::";
#sub cfg
#{
# my $proto = shift;
# my $class = ref($proto) || $proto;
# my $settings =
# {
# $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
# };
# bless($settings, $class);
# return $settings;
#}
#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;
#print STDERR "read cfg file\n";
#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #https://www.perlmonks.org/?node_id=1072691; NOTE: "_OK" skips short/common names
#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }
Author: swannman
Source Code: https://github.com/swannman/pdf2gerb
License: GPL-3.0 license
1657272480
Qu'il s'agisse de Twitter, de Goodreads ou d'Amazon, il n'y a guère d'espace numérique qui ne soit pas saturé d'opinions. Dans le monde d'aujourd'hui, il est crucial pour les organisations d'approfondir ces opinions et d'obtenir des informations sur leurs produits ou services. Cependant, ces données existent en quantités si étonnantes que les évaluer manuellement est une poursuite presque impossible. C'est là qu'intervient une autre aubaine de la science des données : l' analyse des sentiments . Dans cet article, nous allons explorer ce qu'englobe l'analyse des sentiments et les différentes façons de l'implémenter en Python.
L'analyse des sentiments est un cas d'utilisation du traitement du langage naturel (TLN) et relève de la catégorie de la classification de texte . Pour le dire simplement, l'analyse des sentiments consiste à classer un texte en différents sentiments, tels que positif ou négatif, heureux, triste ou neutre, etc. Ainsi, le but ultime de l'analyse des sentiments est de déchiffrer l'humeur, l'émotion ou le sentiment sous-jacent d'un texte. Ceci est également connu sous le nom d' Opinion Mining .
Voyons comment une recherche rapide sur Google définit l'analyse des sentiments :
Eh bien, maintenant, je suppose que nous sommes quelque peu habitués à ce qu'est l'analyse des sentiments. Mais quelle est sa signification et comment les organisations en bénéficient-elles ? Essayons d'explorer la même chose avec un exemple. Supposons que vous démarriez une entreprise qui vend des parfums sur une plateforme en ligne. Vous proposez une large gamme de parfums et bientôt les clients commencent à affluer. Après un certain temps, vous décidez de changer la stratégie de prix des parfums - vous envisagez d'augmenter les prix des parfums populaires et en même temps d'offrir des remises sur les parfums impopulaires. . Maintenant, afin de déterminer quels parfums sont populaires, vous commencez à parcourir les avis des clients sur tous les parfums. Mais tu es coincé ! Ils sont tellement nombreux que vous ne pouvez pas tous les parcourir en une seule vie. C'est là que l'analyse des sentiments peut vous sortir de l'impasse.
Vous rassemblez simplement tous les avis en un seul endroit et y appliquez une analyse des sentiments. Ce qui suit est une représentation schématique de l'analyse des sentiments sur les critiques de trois parfums de parfums - Lavande, Rose et Citron. (Veuillez noter que ces avis peuvent avoir des fautes d'orthographe, de grammaire et de ponctuation, comme dans les scénarios du monde réel)
A partir de ces résultats, nous pouvons clairement voir que :
Fragrance-1 (Lavande) a des critiques très positives de la part des clients, ce qui indique que votre entreprise peut augmenter ses prix compte tenu de sa popularité.
Il se trouve que Fragrance-2 (Rose) a une vision neutre parmi le client, ce qui signifie que votre entreprise ne doit pas modifier ses prix .
Fragrance-3 (Citron) a un sentiment global négatif qui lui est associé - votre entreprise devrait donc envisager d'offrir une remise pour équilibrer la balance.
Ce n'était qu'un exemple simple de la façon dont l'analyse des sentiments peut vous aider à mieux comprendre vos produits/services et aider votre organisation à prendre des décisions.
Nous venons de voir comment l'analyse des sentiments peut donner aux organisations des informations qui peuvent les aider à prendre des décisions basées sur les données. Examinons maintenant d'autres cas d'utilisation de l'analyse des sentiments.
Python est l'un des outils les plus puissants lorsqu'il s'agit d'effectuer des tâches de science des données - il offre une multitude de façons d'effectuer une analyse des sentiments . Les plus populaires sont enrôlés ici:
Plongeons-les profondément un par un.
Remarque : Aux fins des démonstrations des méthodes 3 et 4 (utilisation de modèles basés sur la vectorisation de sacs de mots et utilisation de modèles basés sur LSTM) , l'analyse des sentiments a été utilisée. Il comprend plus de 5000 extraits de texte étiquetés comme positifs, négatifs ou neutres. Le jeu de données est sous licence Creative Commons.
Text Blob est une bibliothèque Python pour le traitement du langage naturel. L'utilisation de Text Blob pour l'analyse des sentiments est assez simple. Il prend le texte en entrée et peut renvoyer la polarité et la subjectivité en sortie.
La polarité détermine le sentiment du texte. Ses valeurs se situent dans [-1,1] où -1 dénote un sentiment très négatif et 1 dénote un sentiment très positif.
La subjectivité détermine si une entrée de texte est une information factuelle ou une opinion personnelle. Sa valeur est comprise entre [0,1] où une valeur plus proche de 0 dénote une information factuelle et une valeur plus proche de 1 dénote une opinion personnelle.
Mise en place :
pip install textblob
Importer un blob de texte :
from textblob import TextBlob
Implémentation de code pour l'analyse des sentiments à l'aide de Text Blob :
L'écriture de code pour l'analyse des sentiments à l'aide de TextBlob est assez simple. Importez simplement l'objet TextBlob et transmettez le texte à analyser avec les attributs appropriés comme suit :
from textblob import TextBlob
text_1 = "The movie was so awesome."
text_2 = "The food here tastes terrible."#Determining the Polarity
p_1 = TextBlob(text_1).sentiment.polarity
p_2 = TextBlob(text_2).sentiment.polarity#Determining the Subjectivity
s_1 = TextBlob(text_1).sentiment.subjectivity
s_2 = TextBlob(text_2).sentiment.subjectivityprint("Polarity of Text 1 is", p_1)
print("Polarity of Text 2 is", p_2)
print("Subjectivity of Text 1 is", s_1)
print("Subjectivity of Text 2 is", s_2)
Production:
Polarity of Text 1 is 1.0
Polarity of Text 2 is -1.0
Subjectivity of Text 1 is 1.0
Subjectivity of Text 2 is 1.0
VADER (Valence Aware Dictionary and sEntiment Reasoner) est un analyseur de sentiments basé sur des règles qui a été formé sur le texte des médias sociaux. Tout comme Text Blob, son utilisation en Python est assez simple. Nous verrons son utilisation dans l'implémentation du code avec un exemple dans un moment.
Installation:
pip install vaderSentiment
Importation de la classe SentimentIntensityAnalyzer depuis Vader :
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
Code pour l'analyse des sentiments à l'aide de Vader :
Tout d'abord, nous devons créer un objet de la classe SentimentIntensityAnalyzer ; alors nous devons passer le texte à la fonction polarity_scores() de l'objet comme suit :
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
sentiment = SentimentIntensityAnalyzer()
text_1 = "The book was a perfect balance between wrtiting style and plot."
text_2 = "The pizza tastes terrible."
sent_1 = sentiment.polarity_scores(text_1)
sent_2 = sentiment.polarity_scores(text_2)
print("Sentiment of text 1:", sent_1)
print("Sentiment of text 2:", sent_2)
Sortie :
Sentiment of text 1: {'neg': 0.0, 'neu': 0.73, 'pos': 0.27, 'compound': 0.5719}
Sentiment of text 2: {'neg': 0.508, 'neu': 0.492, 'pos': 0.0, 'compound': -0.4767}
Comme nous pouvons le voir, un objet VaderSentiment renvoie un dictionnaire de scores de sentiment pour le texte à analyser.
Dans les deux approches discutées jusqu'à présent, c'est-à-dire Text Blob et Vader, nous avons simplement utilisé des bibliothèques Python pour effectuer une analyse des sentiments. Nous allons maintenant discuter d'une approche dans laquelle nous formerons notre propre modèle pour la tâche. Les étapes impliquées dans l'analyse des sentiments à l'aide de la méthode de vectorisation du sac de mots sont les suivantes :
Code pour l'analyse des sentiments à l'aide de l'approche de vectorisation du sac de mots :
Pour créer un modèle d'analyse des sentiments à l'aide de l'approche de vectorisation BOW, nous avons besoin d'un ensemble de données étiqueté. Comme indiqué précédemment, l'ensemble de données utilisé pour cette démonstration a été obtenu auprès de Kaggle. Nous avons simplement utilisé le vectoriseur de comptage de sklearn pour créer le BOW. Ensuite, nous avons formé un classificateur Multinomial Naive Bayes, pour lequel un score de précision de 0,84 a été obtenu.
L'ensemble de données peut être obtenu à partir d' ici .
#Loading the Dataset
import pandas as pd
data = pd.read_csv('Finance_data.csv')
#Pre-Prcoessing and Bag of Word Vectorization using Count Vectorizer
from sklearn.feature_extraction.text import CountVectorizer
from nltk.tokenize import RegexpTokenizer
token = RegexpTokenizer(r'[a-zA-Z0-9]+')
cv = CountVectorizer(stop_words='english',ngram_range = (1,1),tokenizer = token.tokenize)
text_counts = cv.fit_transform(data['sentences'])
#Splitting the data into trainig and testing
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(text_counts, data['feedback'], test_size=0.25, random_state=5)
#Training the model
from sklearn.naive_bayes import MultinomialNB
MNB = MultinomialNB()
MNB.fit(X_train, Y_train)
#Caluclating the accuracy score of the model
from sklearn import metrics
predicted = MNB.predict(X_test)
accuracy_score = metrics.accuracy_score(predicted, Y_test)
print("Accuracuy Score: ",accuracy_score)
Sortie :
Accuracuy Score: 0.9111675126903553
Le classificateur formé peut être utilisé pour prédire le sentiment de n'importe quelle entrée de texte donnée.
Bien que nous ayons pu obtenir un score de précision décent avec la méthode de vectorisation du sac de mots, il se peut qu'elle ne donne pas les mêmes résultats lorsqu'il s'agit d'ensembles de données plus volumineux. Cela donne lieu à la nécessité d'utiliser des modèles basés sur l'apprentissage en profondeur pour la formation du modèle d'analyse des sentiments.
Pour les tâches NLP, nous utilisons généralement des modèles basés sur RNN car ils sont conçus pour traiter des données séquentielles. Ici, nous allons former un modèle LSTM (Long Short Term Memory) en utilisant TensorFlow avec Keras . Les étapes pour effectuer une analyse des sentiments à l'aide de modèles basés sur LSTM sont les suivantes :
Code pour l'analyse des sentiments à l'aide d'une approche de modèle basée sur LSTM :
Ici, nous avons utilisé le même jeu de données que celui que nous avons utilisé dans le cas de l'approche BOW. Une précision d'entraînement de 0,90 a été obtenue.
#Importing necessary libraries
import nltk
import pandas as pd
from textblob import Word
from nltk.corpus import stopwords
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
from keras.models import Sequential
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from sklearn.model_selection import train_test_split
#Loading the dataset
data = pd.read_csv('Finance_data.csv')
#Pre-Processing the text
def cleaning(df, stop_words):
df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x.lower() for x in x.split()))
# Replacing the digits/numbers
df['sentences'] = df['sentences'].str.replace('d', '')
# Removing stop words
df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x for x in x.split() if x not in stop_words))
# Lemmatization
df['sentences'] = df['sentences'].apply(lambda x: ' '.join([Word(x).lemmatize() for x in x.split()]))
return df
stop_words = stopwords.words('english')
data_cleaned = cleaning(data, stop_words)
#Generating Embeddings using tokenizer
tokenizer = Tokenizer(num_words=500, split=' ')
tokenizer.fit_on_texts(data_cleaned['verified_reviews'].values)
X = tokenizer.texts_to_sequences(data_cleaned['verified_reviews'].values)
X = pad_sequences(X)
#Model Building
model = Sequential()
model.add(Embedding(500, 120, input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(704, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(352, activation='LeakyReLU'))
model.add(Dense(3, activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam', metrics = ['accuracy'])
print(model.summary())
#Model Training
model.fit(X_train, y_train, epochs = 20, batch_size=32, verbose =1)
#Model Testing
model.evaluate(X_test,y_test)
Les modèles basés sur les transformateurs sont l'une des techniques de traitement du langage naturel les plus avancées. Ils suivent une architecture basée sur l'encodeur-décodeur et utilisent les concepts d'auto-attention pour donner des résultats impressionnants. Bien que l'on puisse toujours construire un modèle de transformateur à partir de zéro, c'est une tâche assez fastidieuse. Ainsi, nous pouvons utiliser des modèles de transformateurs pré-formés disponibles sur Hugging Face . Hugging Face est une communauté d'IA open source qui propose une multitude de modèles pré-formés pour les applications NLP. Ces modèles peuvent être utilisés tels quels ou être affinés pour des tâches spécifiques.
Installation:
pip install transformers
Importation de la classe SentimentIntensityAnalyzer depuis Vader :
import transformers
Code pour l'analyse des sentiments à l'aide de modèles basés sur Transformer :
Pour effectuer une tâche à l'aide de transformateurs, nous devons d'abord importer la fonction de pipeline à partir des transformateurs. Ensuite, un objet de la fonction pipeline est créé et la tâche à effectuer est passée en argument (c'est-à-dire l'analyse des sentiments dans notre cas). Nous pouvons également spécifier le modèle que nous devons utiliser pour effectuer la tâche. Ici, puisque nous n'avons pas mentionné le modèle à utiliser, le mode distillery-base-uncased-finetuned-sst-2-English est utilisé par défaut pour l'analyse des sentiments. Vous pouvez consulter la liste des tâches et des modèles disponibles ici .
from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
data = ["It was the best of times.", "t was the worst of times."]
sentiment_pipeline(data)Output:[{'label': 'POSITIVE', 'score': 0.999457061290741}, {'label': 'NEGATIVE', 'score': 0.9987301230430603}]
À cette époque où les utilisateurs peuvent exprimer leurs points de vue sans effort et où les données sont générées en superflu en quelques fractions de secondes seulement - tirer des enseignements de ces données est vital pour que les organisations prennent des décisions efficaces - et l'analyse des sentiments s'avère être la pièce manquante du puzzle !
Nous avons maintenant couvert en détail ce qu'implique exactement l'analyse des sentiments et les différentes méthodes que l'on peut utiliser pour l'exécuter en Python. Mais ce n'étaient que quelques démonstrations rudimentaires - vous devez sûrement aller de l'avant et jouer avec les modèles et les essayer sur vos propres données.
Source : https://www.analyticsvidhya.com/blog/2022/07/sentiment-analysis-using-python/
1657276560
无论您说的是 Twitter、Goodreads 还是亚马逊——几乎没有一个数字空间不充满人们的意见。在当今世界,组织挖掘这些意见并获得有关其产品或服务的见解至关重要。然而,这些数据以如此惊人的数量存在,以至于手动测量它几乎是不可能的追求。这就是数据科学的另一个好处 —— 情绪分析。在本文中,我们将探讨情感分析包含的内容以及在 Python 中实现它的各种方法。
情感分析是自然语言处理 (NLP)的一个用例,属于文本分类的范畴。简而言之,情感分析涉及将文本分类为各种情感,如正面或负面、快乐、悲伤或中性等。因此,情感分析的最终目标是破译一个潜在的情绪、情绪或情绪。文本。这也称为意见挖掘。
让我们看看快速谷歌搜索如何定义情绪分析:
好吧,现在我想我们已经有点习惯了情绪分析是什么。但它的意义是什么?组织如何从中受益?让我们尝试用一个例子来探索一下。假设您创办了一家在在线平台上销售香水的公司。你推出了种类繁多的香水,很快顾客就蜂拥而至。一段时间后,你决定改变香水的定价策略——你计划提高流行香水的价格,同时为不受欢迎的香水提供折扣. 现在,为了确定哪些香水受欢迎,您开始查看所有香水的客户评论。但是你被困住了!它们是如此之多,以至于您无法在一生中将它们全部看完。这就是情绪分析可以让你摆脱困境的地方。
您只需将所有评论收集在一个地方并对其应用情绪分析。以下是对三种香水——薰衣草、玫瑰和柠檬的评论的情感分析示意图。(请注意,这些评论可能有不正确的拼写、语法和标点符号,就像在现实世界中一样)
从这些结果中,我们可以清楚地看到:
Fragrance-1(薰衣草)得到了客户的高度好评,这表明贵公司可以根据其受欢迎程度提高其价格。
Fragrance-2 (Rose)恰好在客户中持中立态度,这意味着贵公司不应改变其定价。
Fragrance-3(柠檬)具有与之相关的整体负面情绪 - 因此,您的公司应考虑为其提供折扣以平衡规模。
这只是一个简单的示例,说明情绪分析如何帮助您深入了解您的产品/服务并帮助您的组织做出决策。
我们刚刚看到了情绪分析如何为组织提供洞察力,帮助他们做出数据驱动的决策。现在,让我们来看看更多情感分析的用例。
在执行数据科学任务时,Python 是最强大的工具之一——它提供了多种执行 情感分析的方法。这里列出了最受欢迎的:
让我们一一深入了解它们。
注意:为了演示方法 3 和 4(使用基于词向量化的模型和使用基于 LSTM 的模型)的情感分析。它包含 5000 多个标记为正面、负面或中性的文本摘录。该数据集位于知识共享许可下。
Text Blob 是一个用于自然语言处理的 Python 库。使用 Text Blob 进行情绪分析非常简单。它将文本作为输入,并可以返回极性和主观性作为输出。
极性决定了文本的情绪。它的值位于 [-1,1] 中,其中 -1 表示高度负面的情绪,1 表示高度正面的情绪。
主观性决定了文本输入是事实信息还是个人观点。它的值介于 [0,1] 之间,其中接近 0 的值表示一条事实信息,接近 1 的值表示个人意见。
安装:
pip install textblob
导入文本块:
from textblob import TextBlob
使用文本 Blob 进行情感分析的代码实现:
使用 TextBlob 编写情绪分析代码相当简单。只需导入 TextBlob 对象并使用适当的属性传递要分析的文本,如下所示:
from textblob import TextBlob
text_1 = "The movie was so awesome."
text_2 = "The food here tastes terrible."#Determining the Polarity
p_1 = TextBlob(text_1).sentiment.polarity
p_2 = TextBlob(text_2).sentiment.polarity#Determining the Subjectivity
s_1 = TextBlob(text_1).sentiment.subjectivity
s_2 = TextBlob(text_2).sentiment.subjectivityprint("Polarity of Text 1 is", p_1)
print("Polarity of Text 2 is", p_2)
print("Subjectivity of Text 1 is", s_1)
print("Subjectivity of Text 2 is", s_2)
输出:
Polarity of Text 1 is 1.0
Polarity of Text 2 is -1.0
Subjectivity of Text 1 is 1.0
Subjectivity of Text 2 is 1.0
VADER(Valence Aware Dictionary and sEntiment Reasoner)是一个基于规则的情感分析器,已经在社交媒体文本上进行了训练。就像 Text Blob 一样,它在 Python 中的使用非常简单。稍后我们将通过一个示例来了解它在代码实现中的用法。
安装:
pip install vaderSentiment
从 Vader 导入 SentimentIntensityAnalyzer 类:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
使用 Vader 进行情绪分析的代码:
首先,我们需要创建一个 SentimentIntensityAnalyzer 类的对象;然后我们需要将文本传递给对象的 polar_scores() 函数,如下所示:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
sentiment = SentimentIntensityAnalyzer()
text_1 = "The book was a perfect balance between wrtiting style and plot."
text_2 = "The pizza tastes terrible."
sent_1 = sentiment.polarity_scores(text_1)
sent_2 = sentiment.polarity_scores(text_2)
print("Sentiment of text 1:", sent_1)
print("Sentiment of text 2:", sent_2)
输出:
Sentiment of text 1: {'neg': 0.0, 'neu': 0.73, 'pos': 0.27, 'compound': 0.5719}
Sentiment of text 2: {'neg': 0.508, 'neu': 0.492, 'pos': 0.0, 'compound': -0.4767}
正如我们所见,VaderSentiment 对象返回要分析的文本的情绪分数字典。
在目前讨论的两种方法中,即 Text Blob 和 Vader,我们只是使用 Python 库来执行情绪分析。现在我们将讨论一种方法,在该方法中,我们将为该任务训练我们自己的模型。使用词袋向量化方法执行情感分析的步骤如下:
使用词袋向量化方法进行情感分析的代码:
要使用 BOW 矢量化方法构建情绪分析模型,我们需要一个标记数据集。如前所述,用于此演示的数据集是从 Kaggle 获得的。我们简单地使用了 sklearn 的计数向量器来创建 BOW。之后,我们训练了一个多项朴素贝叶斯分类器,其准确度得分为 0.84。
数据集可以从这里获得。
#Loading the Dataset
import pandas as pd
data = pd.read_csv('Finance_data.csv')
#Pre-Prcoessing and Bag of Word Vectorization using Count Vectorizer
from sklearn.feature_extraction.text import CountVectorizer
from nltk.tokenize import RegexpTokenizer
token = RegexpTokenizer(r'[a-zA-Z0-9]+')
cv = CountVectorizer(stop_words='english',ngram_range = (1,1),tokenizer = token.tokenize)
text_counts = cv.fit_transform(data['sentences'])
#Splitting the data into trainig and testing
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(text_counts, data['feedback'], test_size=0.25, random_state=5)
#Training the model
from sklearn.naive_bayes import MultinomialNB
MNB = MultinomialNB()
MNB.fit(X_train, Y_train)
#Caluclating the accuracy score of the model
from sklearn import metrics
predicted = MNB.predict(X_test)
accuracy_score = metrics.accuracy_score(predicted, Y_test)
print("Accuracuy Score: ",accuracy_score)
输出:
Accuracuy Score: 0.9111675126903553
经过训练的分类器可用于预测任何给定文本输入的情绪。
虽然我们能够使用词袋矢量化方法获得不错的准确度分数,但在处理更大的数据集时可能无法产生相同的结果。这就需要使用基于深度学习的模型来训练情感分析模型。
对于 NLP 任务,我们通常使用基于 RNN 的模型,因为它们旨在处理顺序数据。在这里,我们将使用TensorFlow和Keras训练一个 LSTM(长短期记忆)模型。使用基于 LSTM 的模型执行情感分析的步骤如下:
使用基于 LSTM 的模型方法进行情感分析的代码:
在这里,我们使用了与 BOW 方法相同的数据集。获得了 0.90 的训练准确度。
#Importing necessary libraries
import nltk
import pandas as pd
from textblob import Word
from nltk.corpus import stopwords
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
from keras.models import Sequential
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from sklearn.model_selection import train_test_split
#Loading the dataset
data = pd.read_csv('Finance_data.csv')
#Pre-Processing the text
def cleaning(df, stop_words):
df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x.lower() for x in x.split()))
# Replacing the digits/numbers
df['sentences'] = df['sentences'].str.replace('d', '')
# Removing stop words
df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x for x in x.split() if x not in stop_words))
# Lemmatization
df['sentences'] = df['sentences'].apply(lambda x: ' '.join([Word(x).lemmatize() for x in x.split()]))
return df
stop_words = stopwords.words('english')
data_cleaned = cleaning(data, stop_words)
#Generating Embeddings using tokenizer
tokenizer = Tokenizer(num_words=500, split=' ')
tokenizer.fit_on_texts(data_cleaned['verified_reviews'].values)
X = tokenizer.texts_to_sequences(data_cleaned['verified_reviews'].values)
X = pad_sequences(X)
#Model Building
model = Sequential()
model.add(Embedding(500, 120, input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(704, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(352, activation='LeakyReLU'))
model.add(Dense(3, activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam', metrics = ['accuracy'])
print(model.summary())
#Model Training
model.fit(X_train, y_train, epochs = 20, batch_size=32, verbose =1)
#Model Testing
model.evaluate(X_test,y_test)
基于 Transformer 的模型是最先进的自然语言处理技术之一。它们遵循基于编码器-解码器的架构,并采用自我注意的概念来产生令人印象深刻的结果。虽然总是可以从头开始构建变压器模型,但这是一项相当乏味的任务。因此,我们可以使用Hugging Face上可用的预训练变压器模型。Hugging Face 是一个开源 AI 社区,为 NLP 应用程序提供大量预训练模型。这些模型可以原样使用,也可以针对特定任务进行微调。
安装:
pip install transformers
从 Vader 导入 SentimentIntensityAnalyzer 类:
import transformers
使用基于 Transformer 的模型进行情绪分析的代码:
要使用转换器执行任何任务,我们首先需要从转换器导入管道功能。然后,创建管道函数的对象并将要执行的任务作为参数传递(即在我们的案例中进行情感分析)。我们还可以指定我们需要用来执行任务的模型。这里,由于我们没有提到要使用的模型,所以默认使用 distillery-base-uncased-finetuned-sst-2-English 模式进行情感分析。您可以在此处查看可用任务和模型的列表。
from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
data = ["It was the best of times.", "t was the worst of times."]
sentiment_pipeline(data)Output:[{'label': 'POSITIVE', 'score': 0.999457061290741}, {'label': 'NEGATIVE', 'score': 0.9987301230430603}]
在这个用户可以毫不费力地表达他们的观点并且在几分之一秒内生成多余的数据的时代——从这些数据中获得洞察力对于组织做出有效决策至关重要——而情绪分析被证明是拼图中缺失的部分!
到目前为止,我们已经非常详细地介绍了情感分析的确切含义以及可以用来在 Python 中执行它的各种方法。但这些只是一些基本的演示——你一定要继续摆弄模型,并在你自己的数据上进行尝试。
资料来源:https ://www.analyticsvidhya.com/blog/2022/07/sentiment-analysis-using-python/
1657268760
Quer você fale de Twitter, Goodreads ou Amazon – dificilmente existe um espaço digital não saturado com as opiniões das pessoas. No mundo de hoje, é crucial que as organizações se aprofundem nessas opiniões e obtenham insights sobre seus produtos ou serviços. No entanto, esses dados existem em quantidades tão surpreendentes que medi-los manualmente é uma busca quase impossível. É aqui que mais um benefício da Data Science entra em jogo – Análise de Sentimentos . Neste artigo, exploraremos o que a análise de sentimentos abrange e as várias maneiras de implementá-la em Python.
A Análise de Sentimento é um caso de uso do Processamento de Linguagem Natural (NLP) e se enquadra na categoria de classificação de texto . Simplificando, a Análise de Sentimentos envolve a classificação de um texto em vários sentimentos, como positivo ou negativo, Feliz, Triste ou Neutro, etc. texto. Isso também é conhecido como Mineração de Opinião .
Vejamos como uma rápida pesquisa no Google define a Análise de Sentimento:
Bem, agora acho que estamos um pouco acostumados com o que é a análise de sentimentos. Mas qual é o seu significado e como as organizações se beneficiam dele? Vamos tentar explorar o mesmo com um exemplo. Suponha que você inicie uma empresa que vende perfumes em uma plataforma online. Você coloca uma grande variedade de fragrâncias por aí e logo os clientes começam a aparecer. Depois de algum tempo, você decide mudar a estratégia de preços dos perfumes - você planeja aumentar os preços das fragrâncias populares e, ao mesmo tempo, oferecer descontos nas impopulares . Agora, para determinar quais fragrâncias são populares, você começa a analisar as avaliações dos clientes de todas as fragrâncias. Mas você está preso! Eles são tantos que você não pode passar por todos eles em uma vida. É aqui que a análise de sentimentos pode tirá-lo do poço.
Você simplesmente reúne todas as avaliações em um só lugar e aplica a análise de sentimentos a elas. A seguir, uma representação esquemática da análise de sentimentos nas resenhas de três fragrâncias de perfumes – Lavanda, Rosa e Limão. (Observe que essas revisões podem ter ortografia, gramática e pontuação incorretas, como nos cenários do mundo real)
A partir desses resultados, podemos ver claramente que:
Fragrance-1 (Lavender) tem avaliações altamente positivas dos clientes, o que indica que sua empresa pode aumentar seus preços devido à sua popularidade.
Fragrance-2 (Rose) tem uma perspectiva neutra entre o cliente, o que significa que sua empresa não deve alterar seus preços .
O Fragrance-3 (Lemon) tem um sentimento geral negativo associado a ele – portanto, sua empresa deve considerar oferecer um desconto para equilibrar a balança.
Este foi apenas um exemplo simples de como a análise de sentimentos pode ajudá-lo a obter insights sobre seus produtos/serviços e ajudar sua organização a tomar decisões.
Acabamos de ver como a análise de sentimentos pode capacitar as organizações com insights que podem ajudá-las a tomar decisões baseadas em dados. Agora, vamos dar uma olhada em mais alguns casos de uso de análise de sentimentos.
O Python é uma das ferramentas mais poderosas quando se trata de realizar tarefas de ciência de dados — ele oferece várias maneiras de realizar análises de sentimentos . Os mais populares estão listados aqui:
Vamos mergulhar fundo neles um por um.
Nota: Para fins de demonstração dos métodos 3 e 4 (Usando Modelos Baseados em Vetorização Bag of Words e Usando Modelos Baseados em LSTM) foi utilizada a análise de sentimentos . Compreende mais de 5.000 excretos de texto rotulados como positivos, negativos ou neutros. O conjunto de dados está sob a licença Creative Commons.
Text Blob é uma biblioteca Python para processamento de linguagem natural. Usar o Text Blob para análise de sentimentos é bastante simples. Ele recebe texto como entrada e pode retornar polaridade e subjetividade como saída.
A polaridade determina o sentimento do texto. Seus valores estão em [-1,1] onde -1 denota um sentimento altamente negativo e 1 denota um sentimento altamente positivo.
A subjetividade determina se uma entrada de texto é uma informação factual ou uma opinião pessoal. O seu valor situa-se entre [0,1] onde um valor mais próximo de 0 denota uma informação factual e um valor mais próximo de 1 denota uma opinião pessoal.
Instalação :
pip install textblob
Importando Blob de Texto:
from textblob import TextBlob
Implementação de código para análise de sentimento usando blob de texto:
Escrever código para análise de sentimentos usando TextBlob é bastante simples. Basta importar o objeto TextBlob e passar o texto a ser analisado com os devidos atributos da seguinte forma:
from textblob import TextBlob
text_1 = "The movie was so awesome."
text_2 = "The food here tastes terrible."#Determining the Polarity
p_1 = TextBlob(text_1).sentiment.polarity
p_2 = TextBlob(text_2).sentiment.polarity#Determining the Subjectivity
s_1 = TextBlob(text_1).sentiment.subjectivity
s_2 = TextBlob(text_2).sentiment.subjectivityprint("Polarity of Text 1 is", p_1)
print("Polarity of Text 2 is", p_2)
print("Subjectivity of Text 1 is", s_1)
print("Subjectivity of Text 2 is", s_2)
Resultado:
Polarity of Text 1 is 1.0
Polarity of Text 2 is -1.0
Subjectivity of Text 1 is 1.0
Subjectivity of Text 2 is 1.0
O VADER (Valence Aware Dictionary and sEntiment Reasoner) é um analisador de sentimentos baseado em regras que foi treinado em texto de mídia social. Assim como o Text Blob, seu uso em Python é bastante simples. Veremos seu uso na implementação de código com um exemplo daqui a pouco.
Instalação:
pip install vaderSentiment
Importando a classe SentimentIntensityAnalyzer do Vader:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
Código para análise de sentimentos usando o Vader:
Primeiramente, precisamos criar um objeto da classe SentimentIntensityAnalyzer; então precisamos passar o texto para a função polarity_scores() do objeto da seguinte forma:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
sentiment = SentimentIntensityAnalyzer()
text_1 = "The book was a perfect balance between wrtiting style and plot."
text_2 = "The pizza tastes terrible."
sent_1 = sentiment.polarity_scores(text_1)
sent_2 = sentiment.polarity_scores(text_2)
print("Sentiment of text 1:", sent_1)
print("Sentiment of text 2:", sent_2)
Saída :
Sentiment of text 1: {'neg': 0.0, 'neu': 0.73, 'pos': 0.27, 'compound': 0.5719}
Sentiment of text 2: {'neg': 0.508, 'neu': 0.492, 'pos': 0.0, 'compound': -0.4767}
Como podemos ver, um objeto VaderSentiment retorna um dicionário de pontuações de sentimento para o texto a ser analisado.
Nas duas abordagens discutidas até agora, ou seja, Text Blob e Vader, simplesmente usamos bibliotecas Python para realizar a análise de sentimentos. Agora discutiremos uma abordagem na qual treinaremos nosso próprio modelo para a tarefa. As etapas envolvidas na análise de sentimentos usando o método Bag of Words Vectorization são as seguintes:
Código para análise de sentimentos usando a abordagem de vetorização Bag of Words:
Para construir um modelo de análise de sentimento usando a Abordagem de Vetorização BOW, precisamos de um conjunto de dados rotulado. Como afirmado anteriormente, o conjunto de dados usado para esta demonstração foi obtido do Kaggle. Nós simplesmente usamos o vetorizador de contagem do sklearn para criar o BOW. Após, treinamos um classificador Multinomial Naive Bayes, para o qual foi obtido um escore de precisão de 0,84.
O conjunto de dados pode ser obtido aqui .
#Loading the Dataset
import pandas as pd
data = pd.read_csv('Finance_data.csv')
#Pre-Prcoessing and Bag of Word Vectorization using Count Vectorizer
from sklearn.feature_extraction.text import CountVectorizer
from nltk.tokenize import RegexpTokenizer
token = RegexpTokenizer(r'[a-zA-Z0-9]+')
cv = CountVectorizer(stop_words='english',ngram_range = (1,1),tokenizer = token.tokenize)
text_counts = cv.fit_transform(data['sentences'])
#Splitting the data into trainig and testing
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(text_counts, data['feedback'], test_size=0.25, random_state=5)
#Training the model
from sklearn.naive_bayes import MultinomialNB
MNB = MultinomialNB()
MNB.fit(X_train, Y_train)
#Caluclating the accuracy score of the model
from sklearn import metrics
predicted = MNB.predict(X_test)
accuracy_score = metrics.accuracy_score(predicted, Y_test)
print("Accuracuy Score: ",accuracy_score)
Saída :
Accuracuy Score: 0.9111675126903553
O classificador treinado pode ser usado para prever o sentimento de qualquer entrada de texto.
Embora tenhamos conseguido obter uma pontuação de precisão decente com o método Bag of Words Vectorization, ele pode não produzir os mesmos resultados ao lidar com conjuntos de dados maiores. Isso dá origem à necessidade de empregar modelos baseados em deep learning para o treinamento do modelo de análise de sentimentos.
Para tarefas de PNL, geralmente usamos modelos baseados em RNN, pois são projetados para lidar com dados sequenciais. Aqui, vamos treinar um modelo LSTM (Long Short Term Memory) usando o TensorFlow com Keras . As etapas para realizar a análise de sentimento usando modelos baseados em LSTM são as seguintes:
Código para análise de sentimentos usando abordagem de modelo baseada em LSTM:
Aqui, usamos o mesmo conjunto de dados que usamos no caso da abordagem BOW. Uma precisão de treinamento de 0,90 foi obtida.
#Importing necessary libraries
import nltk
import pandas as pd
from textblob import Word
from nltk.corpus import stopwords
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
from keras.models import Sequential
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from sklearn.model_selection import train_test_split
#Loading the dataset
data = pd.read_csv('Finance_data.csv')
#Pre-Processing the text
def cleaning(df, stop_words):
df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x.lower() for x in x.split()))
# Replacing the digits/numbers
df['sentences'] = df['sentences'].str.replace('d', '')
# Removing stop words
df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x for x in x.split() if x not in stop_words))
# Lemmatization
df['sentences'] = df['sentences'].apply(lambda x: ' '.join([Word(x).lemmatize() for x in x.split()]))
return df
stop_words = stopwords.words('english')
data_cleaned = cleaning(data, stop_words)
#Generating Embeddings using tokenizer
tokenizer = Tokenizer(num_words=500, split=' ')
tokenizer.fit_on_texts(data_cleaned['verified_reviews'].values)
X = tokenizer.texts_to_sequences(data_cleaned['verified_reviews'].values)
X = pad_sequences(X)
#Model Building
model = Sequential()
model.add(Embedding(500, 120, input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(704, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(352, activation='LeakyReLU'))
model.add(Dense(3, activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam', metrics = ['accuracy'])
print(model.summary())
#Model Training
model.fit(X_train, y_train, epochs = 20, batch_size=32, verbose =1)
#Model Testing
model.evaluate(X_test,y_test)
Os modelos baseados em transformadores são uma das técnicas de processamento de linguagem natural mais avançadas. Eles seguem uma arquitetura baseada em Encoder-Decoder e empregam os conceitos de autoatenção para produzir resultados impressionantes. Embora sempre se possa construir um modelo de transformador do zero, é uma tarefa bastante tediosa. Assim, podemos usar modelos de transformadores pré-treinados disponíveis no Hugging Face . Hugging Face é uma comunidade de IA de código aberto que oferece uma infinidade de modelos pré-treinados para aplicativos de PNL. Esses modelos podem ser usados como tal ou podem ser ajustados para tarefas específicas.
Instalação:
pip install transformers
Importando a classe SentimentIntensityAnalyzer do Vader:
import transformers
Código para análise de sentimentos usando modelos baseados em Transformer:
Para executar qualquer tarefa usando transformadores, primeiro precisamos importar a função pipeline dos transformadores. Então, um objeto da função pipeline é criado e a tarefa a ser executada é passada como um argumento (ou seja, análise de sentimento no nosso caso). Também podemos especificar o modelo que precisamos usar para realizar a tarefa. Aqui, como não mencionamos o modelo a ser usado, o modo destilaria-base-uncased-finetuned-sst-2-English é usado por padrão para análise de sentimentos. Você pode conferir a lista de tarefas e modelos disponíveis aqui .
from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
data = ["It was the best of times.", "t was the worst of times."]
sentiment_pipeline(data)Output:[{'label': 'POSITIVE', 'score': 0.999457061290741}, {'label': 'NEGATIVE', 'score': 0.9987301230430603}]
Nesta era em que os usuários podem expressar seus pontos de vista sem esforço e os dados são gerados em superfluidade em apenas frações de segundos - extrair insights desses dados é vital para as organizações tomarem decisões eficientes - e a Análise de Sentimentos prova ser a peça que faltava no quebra-cabeça!
Até agora, cobrimos em detalhes o que exatamente envolve a análise de sentimentos e os vários métodos que podemos usar para realizá-la em Python. Mas essas foram apenas algumas demonstrações rudimentares - você certamente deve ir em frente e mexer nos modelos e testá-los em seus próprios dados.
Fonte: https://www.analyticsvidhya.com/blog/2022/07/sentiment-analysis-using-python/
1657276440
Cho dù bạn nói về Twitter, Goodreads hay Amazon - hầu như không có một không gian kỹ thuật số nào không bão hòa với ý kiến của mọi người. Trong thế giới ngày nay, điều quan trọng là các tổ chức phải tìm hiểu kỹ những ý kiến này và có được những hiểu biết sâu sắc về sản phẩm hoặc dịch vụ của họ. Tuy nhiên, dữ liệu này tồn tại với số lượng đáng kinh ngạc đến mức việc đánh giá nó theo cách thủ công là một mục tiêu không thể theo đuổi tiếp theo. Đây là nơi mà một lợi ích khác của Khoa học dữ liệu đến - Phân tích cảm xúc . Trong bài viết này, chúng ta sẽ khám phá phân tích cảm xúc bao gồm những gì và các cách khác nhau để triển khai nó trong Python.
Phân tích cảm xúc là một trường hợp sử dụng của Xử lý ngôn ngữ tự nhiên (NLP) và thuộc phạm trù phân loại văn bản . Nói một cách đơn giản, Phân tích cảm xúc bao gồm việc phân loại một văn bản thành nhiều cảm xúc khác nhau, chẳng hạn như tích cực hoặc tiêu cực, Vui vẻ, Buồn bã hoặc Trung lập, v.v. Vì vậy, mục tiêu cuối cùng của phân tích tình cảm là giải mã tâm trạng, cảm xúc hoặc tình cảm tiềm ẩn của một chữ. Đây còn được gọi là Khai thác ý kiến .
Hãy cùng chúng tôi xem xét cách tìm kiếm nhanh trên google xác định Phân tích cảm xúc:
Chà, bây giờ tôi đoán chúng ta đã phần nào quen với việc phân tích tình cảm là gì. Nhưng ý nghĩa của nó là gì và các tổ chức thu lợi từ nó như thế nào? Hãy để chúng tôi thử và khám phá điều tương tự với một ví dụ. Giả sử bạn thành lập một công ty bán nước hoa trên nền tảng trực tuyến. Bạn bày bán một loạt các loại nước hoa và chẳng bao lâu sau, khách hàng bắt đầu tràn vào. Sau một thời gian, bạn quyết định thay đổi chiến lược định giá nước hoa - bạn dự định tăng giá các loại nước hoa phổ biến và đồng thời giảm giá cho những loại nước hoa không phổ biến . Bây giờ, để xác định loại nước hoa nào được ưa chuộng, bạn bắt đầu xem xét đánh giá của khách hàng về tất cả các loại nước hoa. Nhưng bạn đang mắc kẹt! Chúng rất nhiều mà bạn không thể trải qua tất cả chúng trong một đời. Đây là nơi mà phân tích tình cảm có thể đưa bạn thoát khỏi hố sâu.
Bạn chỉ cần tập hợp tất cả các đánh giá vào một nơi và áp dụng phân tích cảm tính cho nó. Sau đây là sơ đồ phân tích tình cảm trên các bài đánh giá về ba loại nước hoa - Oải hương, Hoa hồng và Chanh. (Xin lưu ý rằng các bài đánh giá này có thể có lỗi chính tả, ngữ pháp và dấu chấm câu không chính xác như trong các tình huống thực tế)
Từ những kết quả này, chúng ta có thể thấy rõ rằng:
Fragrance-1 (Oải hương) được khách hàng đánh giá rất tích cực , điều này cho thấy công ty của bạn có thể tăng giá do mức độ phổ biến của nó.
Fragrance-2 (Hoa hồng) tình cờ có quan điểm trung lập với khách hàng, điều đó có nghĩa là công ty của bạn không nên thay đổi giá cả .
Fragrance-3 (Lemon) có cảm xúc tiêu cực liên quan đến nó - do đó, công ty của bạn nên xem xét giảm giá cho nó để cân bằng quy mô.
Đây chỉ là một ví dụ đơn giản về cách phân tích tình cảm có thể giúp bạn hiểu rõ hơn về sản phẩm / dịch vụ của mình và giúp tổ chức của bạn đưa ra quyết định.
Chúng ta vừa thấy cách phân tích tình cảm có thể trao quyền cho các tổ chức với những hiểu biết sâu sắc có thể giúp họ đưa ra quyết định dựa trên dữ liệu. Bây giờ, chúng ta hãy đi sâu vào một số trường hợp sử dụng khác của phân tích tình cảm.
Python là một trong những công cụ mạnh mẽ nhất khi thực hiện các nhiệm vụ khoa học dữ liệu - nó cung cấp vô số cách để thực hiện phân tích cảm tính . Những người phổ biến nhất được tranh thủ ở đây:
Hãy đi sâu vào từng cái một.
Lưu ý: Với mục đích chứng minh phương pháp 3 & 4 (Sử dụng mô hình dựa trên hình ảnh hóa từ ngữ và sử dụng mô hình dựa trên LSTM) đã được sử dụng. Nó bao gồm hơn 5000 đoạn văn bản được gắn nhãn là tích cực, tiêu cực hoặc trung tính. Tập dữ liệu nằm trong giấy phép Creative Commons.
Text Blob là một thư viện Python để xử lý ngôn ngữ tự nhiên. Sử dụng Text Blob để phân tích tình cảm khá đơn giản. Nó lấy văn bản làm đầu vào và có thể trả về tính phân cực và tính chủ thể làm đầu ra.
Tính phân cực quyết định tình cảm của văn bản. Giá trị của nó nằm ở [-1,1] trong đó -1 biểu thị tình cảm tiêu cực cao và 1 biểu thị cảm xúc tích cực cao.
Tính chủ quan xác định xem đầu vào văn bản là thông tin thực tế hay là ý kiến cá nhân. Giá trị của nó nằm giữa [0,1] trong đó giá trị gần 0 biểu thị một phần thông tin thực tế và giá trị gần 1 biểu thị ý kiến cá nhân.
Cài đặt :
pip install textblob
Nhập khối văn bản:
from textblob import TextBlob
Triển khai mã để phân tích tình cảm bằng cách sử dụng khối văn bản:
Viết mã để phân tích tình cảm bằng TextBlob khá đơn giản. Chỉ cần nhập đối tượng TextBlob và chuyển văn bản cần phân tích với các thuộc tính thích hợp như sau:
from textblob import TextBlob
text_1 = "The movie was so awesome."
text_2 = "The food here tastes terrible."#Determining the Polarity
p_1 = TextBlob(text_1).sentiment.polarity
p_2 = TextBlob(text_2).sentiment.polarity#Determining the Subjectivity
s_1 = TextBlob(text_1).sentiment.subjectivity
s_2 = TextBlob(text_2).sentiment.subjectivityprint("Polarity of Text 1 is", p_1)
print("Polarity of Text 2 is", p_2)
print("Subjectivity of Text 1 is", s_1)
print("Subjectivity of Text 2 is", s_2)
Đầu ra:
Polarity of Text 1 is 1.0
Polarity of Text 2 is -1.0
Subjectivity of Text 1 is 1.0
Subjectivity of Text 2 is 1.0
VADER (Valence Aware Dictionary và sEntiment Reasoner) là một công cụ phân tích tình cảm dựa trên quy tắc đã được đào tạo về văn bản trên mạng xã hội. Cũng giống như Text Blob, cách sử dụng nó trong Python khá đơn giản. Chúng ta sẽ thấy cách sử dụng của nó trong triển khai mã với một ví dụ sau.
Cài đặt:
pip install vaderSentiment
Nhập lớp SentimentIntensityAnalyzer từ Vader:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
Mã phân tích tình cảm bằng Vader:
Đầu tiên, chúng ta cần tạo một đối tượng của lớp SentimentIntensityAnalyzer; thì chúng ta cần truyền văn bản vào hàm polarity_scores () của đối tượng như sau:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
sentiment = SentimentIntensityAnalyzer()
text_1 = "The book was a perfect balance between wrtiting style and plot."
text_2 = "The pizza tastes terrible."
sent_1 = sentiment.polarity_scores(text_1)
sent_2 = sentiment.polarity_scores(text_2)
print("Sentiment of text 1:", sent_1)
print("Sentiment of text 2:", sent_2)
Đầu ra :
Sentiment of text 1: {'neg': 0.0, 'neu': 0.73, 'pos': 0.27, 'compound': 0.5719}
Sentiment of text 2: {'neg': 0.508, 'neu': 0.492, 'pos': 0.0, 'compound': -0.4767}
Như chúng ta có thể thấy, một đối tượng VaderSentiment trả về một từ điển về điểm tình cảm cho văn bản được phân tích.
Trong hai cách tiếp cận đã thảo luận, tức là Text Blob và Vader, chúng tôi chỉ đơn giản sử dụng các thư viện Python để thực hiện phân tích tình cảm. Bây giờ chúng ta sẽ thảo luận về một cách tiếp cận, trong đó chúng ta sẽ đào tạo mô hình của riêng mình cho nhiệm vụ. Các bước liên quan đến việc thực hiện phân tích tình cảm bằng phương pháp Vectơ hóa Bag of Words như sau:
Mã phân tích tình cảm sử dụng Phương pháp vector hóa Bag of Words:
Để xây dựng một mô hình phân tích tình cảm bằng cách sử dụng Phương pháp Vectơ hóa BOW, chúng ta cần một tập dữ liệu được gắn nhãn. Như đã nêu trước đó, tập dữ liệu được sử dụng cho cuộc trình diễn này đã được lấy từ Kaggle. Chúng tôi chỉ đơn giản sử dụng vectơ đếm của sklearn để tạo BOW. Sau đó, chúng tôi đã đào tạo một bộ phân loại Naive Bayes đa thức, cho điểm chính xác là 0,84.
Tập dữ liệu có thể được lấy từ đây .
#Loading the Dataset
import pandas as pd
data = pd.read_csv('Finance_data.csv')
#Pre-Prcoessing and Bag of Word Vectorization using Count Vectorizer
from sklearn.feature_extraction.text import CountVectorizer
from nltk.tokenize import RegexpTokenizer
token = RegexpTokenizer(r'[a-zA-Z0-9]+')
cv = CountVectorizer(stop_words='english',ngram_range = (1,1),tokenizer = token.tokenize)
text_counts = cv.fit_transform(data['sentences'])
#Splitting the data into trainig and testing
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(text_counts, data['feedback'], test_size=0.25, random_state=5)
#Training the model
from sklearn.naive_bayes import MultinomialNB
MNB = MultinomialNB()
MNB.fit(X_train, Y_train)
#Caluclating the accuracy score of the model
from sklearn import metrics
predicted = MNB.predict(X_test)
accuracy_score = metrics.accuracy_score(predicted, Y_test)
print("Accuracuy Score: ",accuracy_score)
Đầu ra :
Accuracuy Score: 0.9111675126903553
Bộ phân loại được đào tạo có thể được sử dụng để dự đoán cảm xúc của bất kỳ đầu vào văn bản nhất định nào.
Mặc dù chúng tôi có thể đạt được điểm chính xác khá với phương pháp Vectơ hóa Bag of Words, nhưng nó có thể không mang lại kết quả tương tự khi xử lý các bộ dữ liệu lớn hơn. Điều này làm phát sinh nhu cầu sử dụng các mô hình dựa trên học tập sâu để đào tạo mô hình phân tích tình cảm.
Đối với các tác vụ NLP, chúng tôi thường sử dụng các mô hình dựa trên RNN vì chúng được thiết kế để xử lý dữ liệu tuần tự. Ở đây, chúng tôi sẽ đào tạo mô hình LSTM (Bộ nhớ ngắn hạn dài hạn) bằng cách sử dụng TensorFlow với Keras . Các bước để thực hiện phân tích tình cảm bằng cách sử dụng các mô hình dựa trên LSTM như sau:
Mã phân tích tình cảm sử dụng phương pháp tiếp cận mô hình dựa trên LSTM:
Ở đây, chúng tôi đã sử dụng cùng một tập dữ liệu như chúng tôi đã sử dụng trong trường hợp của phương pháp BOW. Độ chính xác huấn luyện là 0,90.
#Importing necessary libraries
import nltk
import pandas as pd
from textblob import Word
from nltk.corpus import stopwords
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
from keras.models import Sequential
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Embedding, LSTM, SpatialDropout1D
from sklearn.model_selection import train_test_split
#Loading the dataset
data = pd.read_csv('Finance_data.csv')
#Pre-Processing the text
def cleaning(df, stop_words):
df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x.lower() for x in x.split()))
# Replacing the digits/numbers
df['sentences'] = df['sentences'].str.replace('d', '')
# Removing stop words
df['sentences'] = df['sentences'].apply(lambda x: ' '.join(x for x in x.split() if x not in stop_words))
# Lemmatization
df['sentences'] = df['sentences'].apply(lambda x: ' '.join([Word(x).lemmatize() for x in x.split()]))
return df
stop_words = stopwords.words('english')
data_cleaned = cleaning(data, stop_words)
#Generating Embeddings using tokenizer
tokenizer = Tokenizer(num_words=500, split=' ')
tokenizer.fit_on_texts(data_cleaned['verified_reviews'].values)
X = tokenizer.texts_to_sequences(data_cleaned['verified_reviews'].values)
X = pad_sequences(X)
#Model Building
model = Sequential()
model.add(Embedding(500, 120, input_length = X.shape[1]))
model.add(SpatialDropout1D(0.4))
model.add(LSTM(704, dropout=0.2, recurrent_dropout=0.2))
model.add(Dense(352, activation='LeakyReLU'))
model.add(Dense(3, activation='softmax'))
model.compile(loss = 'categorical_crossentropy', optimizer='adam', metrics = ['accuracy'])
print(model.summary())
#Model Training
model.fit(X_train, y_train, epochs = 20, batch_size=32, verbose =1)
#Model Testing
model.evaluate(X_test,y_test)
Các mô hình dựa trên máy biến áp là một trong những Kỹ thuật Xử lý Ngôn ngữ Tự nhiên tiên tiến nhất. Họ tuân theo kiến trúc dựa trên Bộ mã hóa-Bộ giải mã và sử dụng các khái niệm về sự chú ý của bản thân để mang lại kết quả ấn tượng. Mặc dù người ta luôn có thể xây dựng một mô hình máy biến áp từ đầu, nhưng đó là một công việc khá tẻ nhạt. Do đó, chúng ta có thể sử dụng các mẫu máy biến áp đã được đào tạo trước có sẵn trên Mặt ôm . Hugging Face là một cộng đồng AI mã nguồn mở cung cấp vô số mô hình được đào tạo trước cho các ứng dụng NLP. Các mô hình này có thể được sử dụng như vậy hoặc có thể được tinh chỉnh cho các nhiệm vụ cụ thể.
Cài đặt:
pip install transformers
Nhập lớp SentimentIntensityAnalyzer từ Vader:
import transformers
Mã phân tích tình cảm bằng cách sử dụng các mô hình dựa trên Máy biến áp:
Để thực hiện bất kỳ tác vụ nào sử dụng máy biến áp, trước tiên chúng ta cần nhập chức năng đường ống từ máy biến áp. Sau đó, một đối tượng của hàm đường ống được tạo và nhiệm vụ cần thực hiện được chuyển như một đối số (tức là phân tích cảm tính trong trường hợp của chúng ta). Chúng tôi cũng có thể chỉ định mô hình mà chúng tôi cần sử dụng để thực hiện tác vụ. Ở đây, vì chúng tôi chưa đề cập đến mô hình sẽ được sử dụng, chế độ chưng cất-cơ sở-không phân biệt-finetuned-sst-2-English được sử dụng theo mặc định để phân tích cảm tính. Bạn có thể xem danh sách các nhiệm vụ và mô hình có sẵn tại đây .
from transformers import pipeline
sentiment_pipeline = pipeline("sentiment-analysis")
data = ["It was the best of times.", "t was the worst of times."]
sentiment_pipeline(data)Output:[{'label': 'POSITIVE', 'score': 0.999457061290741}, {'label': 'NEGATIVE', 'score': 0.9987301230430603}]
Trong thời đại này khi người dùng có thể bày tỏ quan điểm của mình một cách dễ dàng và dữ liệu được tạo ra một cách siêu tốc chỉ trong vài giây - việc rút ra thông tin chi tiết từ những dữ liệu đó là điều quan trọng để các tổ chức đưa ra quyết định hiệu quả - và Phân tích cảm xúc chứng tỏ là một mảnh ghép còn thiếu!
Bây giờ chúng ta đã trình bày rất chi tiết về những gì chính xác yêu cầu phân tích cảm xúc và các phương pháp khác nhau mà người ta có thể sử dụng để thực hiện nó trong Python. Nhưng đây chỉ là một số minh chứng thô sơ - bạn chắc chắn phải tiếp tục tìm hiểu các mô hình và thử chúng trên dữ liệu của riêng bạn.
Nguồn: https://www.analyticsvidhya.com/blog/2022/07/sentiment-analysis-using-python/