Bird
Raised Fist0
TensorFlowml~10 mins

Sentiment analysis in TensorFlow - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the TensorFlow library.

TensorFlow
import [1] as tf
Drag options to blanks, or click blank then click option'
Atensorflow
Btorch
Cpandas
Dsklearn
Attempts:
3 left
💡 Hint
Common Mistakes
Importing the wrong library like torch or pandas.
Forgetting to alias as tf.
2fill in blank
medium

Complete the code to create a Sequential model for sentiment analysis.

TensorFlow
model = tf.keras.models.Sequential([tf.keras.layers.Embedding(input_dim=10000, output_dim=16), tf.keras.layers.GlobalAveragePooling1D(), tf.keras.layers.Dense([1], activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid')])
Drag options to blanks, or click blank then click option'
A32
B16
C64
D128
Attempts:
3 left
💡 Hint
Common Mistakes
Using output_dim instead of units in Dense layer.
Choosing too small or too large number of units.
3fill in blank
hard

Fix the error in the code to compile the model with the correct loss function for binary sentiment classification.

TensorFlow
model.compile(optimizer='adam', loss='[1]', metrics=['accuracy'])
Drag options to blanks, or click blank then click option'
Acategorical_crossentropy
Bmean_squared_error
Chinge
Dbinary_crossentropy
Attempts:
3 left
💡 Hint
Common Mistakes
Using categorical_crossentropy for binary labels.
Using mean_squared_error which is for regression.
4fill in blank
hard

Fill both blanks to prepare the training data and labels for the model.

TensorFlow
train_data = [1]
train_labels = [2]
Drag options to blanks, or click blank then click option'
Asentences
Blabels
Creviews
Dtargets
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up input data and labels.
Using variable names not defined in context.
5fill in blank
hard

Fill all three blanks to train the model with training data, labels, and set epochs.

TensorFlow
history = model.fit([1], [2], epochs=[3], validation_split=0.2)
Drag options to blanks, or click blank then click option'
Atrain_data
Btrain_labels
C10
Dtest_data
Attempts:
3 left
💡 Hint
Common Mistakes
Using test_data instead of train_data.
Swapping data and labels in fit method.

Practice

(1/5)
1. What is the main goal of sentiment analysis in TensorFlow?
easy
A. To translate text into another language
B. To classify text as positive or negative
C. To generate new text automatically
D. To count the number of words in a sentence

Solution

  1. Step 1: Understand sentiment analysis purpose

    Sentiment analysis is used to find the feeling or opinion in text, usually positive or negative.
  2. Step 2: Match goal with options

    Among the options, only classifying text as positive or negative matches sentiment analysis.
  3. Final Answer:

    To classify text as positive or negative -> Option B
  4. Quick Check:

    Sentiment analysis = classify positive/negative [OK]
Hint: Sentiment analysis = positive or negative text classification [OK]
Common Mistakes:
  • Confusing sentiment analysis with translation
  • Thinking it generates new text
  • Believing it only counts words
2. Which TensorFlow layer is commonly used to convert words into numbers for sentiment analysis?
easy
A. Dense layer
B. Flatten layer
C. Dropout layer
D. Embedding layer

Solution

  1. Step 1: Identify layer for word representation

    Embedding layers convert words into numeric vectors that models can understand.
  2. Step 2: Compare with other layers

    Dense layers are for fully connected neurons, Dropout prevents overfitting, Flatten reshapes data, none convert words to numbers.
  3. Final Answer:

    Embedding layer -> Option D
  4. Quick Check:

    Embedding layer = word to number conversion [OK]
Hint: Embedding layer turns words into numbers for models [OK]
Common Mistakes:
  • Choosing Dense layer for word conversion
  • Confusing Dropout with embedding
  • Using Flatten layer incorrectly
3. What will be the output shape of the embedding layer if input shape is (None, 10) and embedding dimension is 16?
medium
A. (None, 10, 16)
B. (None, 16, 10)
C. (10, 16)
D. (None, 10)

Solution

  1. Step 1: Understand embedding input and output shapes

    Input shape (None, 10) means batch size unknown, sequence length 10. Embedding outputs a vector per word with size 16.
  2. Step 2: Calculate output shape

    Output shape is (batch_size, sequence_length, embedding_dim) = (None, 10, 16).
  3. Final Answer:

    (None, 10, 16) -> Option A
  4. Quick Check:

    Embedding output shape = (batch, seq_len, embed_dim) [OK]
Hint: Embedding output shape = input length x embedding size [OK]
Common Mistakes:
  • Swapping sequence length and embedding dimension
  • Ignoring batch size dimension
  • Confusing input and output shapes
4. Identify the error in this TensorFlow model snippet for sentiment analysis:
model = tf.keras.Sequential([
  tf.keras.layers.Embedding(input_dim=1000, output_dim=16, input_length=10),
  tf.keras.layers.Dense(1, activation='sigmoid')
])
medium
A. Dense layer activation should be 'relu' for binary output
B. Embedding layer input_dim should be output_dim
C. Missing Flatten or GlobalPooling layer before Dense
D. input_length parameter is not allowed in Embedding layer

Solution

  1. Step 1: Analyze model layer sequence

    Embedding outputs 3D tensor (batch, seq_len, embed_dim). Dense expects 2D input, so flattening or pooling is needed.
  2. Step 2: Identify missing layer

    Without Flatten or GlobalPooling, Dense layer will raise shape error.
  3. Final Answer:

    Missing Flatten or GlobalPooling layer before Dense -> Option C
  4. Quick Check:

    Embedding output must be flattened before Dense [OK]
Hint: Add Flatten or pooling before Dense after Embedding [OK]
Common Mistakes:
  • Confusing input_dim and output_dim in Embedding
  • Using wrong activation for binary classification
  • Thinking input_length is invalid parameter
5. You want to improve a sentiment analysis model's accuracy on short reviews. Which approach is best?
hard
A. Increase embedding dimension and add a Bidirectional LSTM layer
B. Reduce embedding dimension and remove all recurrent layers
C. Use only a Dense layer without embedding
D. Train on fewer examples to avoid overfitting

Solution

  1. Step 1: Consider model improvements for short text

    Increasing embedding dimension helps capture more word features; Bidirectional LSTM captures context from both directions.
  2. Step 2: Evaluate other options

    Reducing embedding or removing recurrent layers loses information; training on fewer examples reduces learning quality.
  3. Final Answer:

    Increase embedding dimension and add a Bidirectional LSTM layer -> Option A
  4. Quick Check:

    More embedding + Bidirectional LSTM = better short text accuracy [OK]
Hint: Use bigger embeddings and bidirectional LSTM for short texts [OK]
Common Mistakes:
  • Thinking smaller embeddings improve accuracy
  • Removing recurrent layers harms context understanding
  • Training on fewer examples reduces model learning
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard