0
0
TensorFlowml~10 mins

K-fold cross-validation in TensorFlow - Interactive Code Practice

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

Complete the code to import the KFold class from scikit-learn.

TensorFlow
from sklearn.model_selection import [1]
Drag options to blanks, or click blank then click option'
AGridSearchCV
Btrain_test_split
Ccross_val_score
DKFold
Attempts:
3 left
💡 Hint
Common Mistakes
Using train_test_split instead of KFold
Importing cross_val_score instead of KFold
2fill in blank
medium

Complete the code to create a KFold object with 5 splits and shuffling enabled.

TensorFlow
kf = KFold(n_splits=[1], shuffle=True, random_state=42)
Drag options to blanks, or click blank then click option'
A5
B10
C1
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Using 1 split which disables cross-validation
Using too few splits like 3 which is less common
3fill in blank
hard

Fix the error in the loop to correctly split data indices using KFold.

TensorFlow
for train_index, [1] in kf.split(X):
Drag options to blanks, or click blank then click option'
Aval_index
Btest_index
Csplit_index
Dindex
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'val_index' which is not returned by kf.split
Using a single variable instead of two
4fill in blank
hard

Fill both blanks to create training and testing sets from data arrays X and y.

TensorFlow
X_train, y_train = X[[1]], y[[1]]
X_test, y_test = X[[2]], y[[2]]
Drag options to blanks, or click blank then click option'
Atrain_index
Btest_index
Cval_index
Dsplit_index
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same index for both training and testing
Using undefined variables like val_index
5fill in blank
hard

Fill all three blanks to compile accuracy scores for each fold using a TensorFlow model.

TensorFlow
accuracies = []
for train_idx, test_idx in kf.split(X):
    X_train, y_train = X[[1]], y[[1]]
    X_test, y_test = X[[2]], y[[2]]
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(10, activation='relu', input_shape=(X.shape[1],)),
        tf.keras.layers.Dense(1, activation='sigmoid')
    ])
    model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
    model.fit(X_train, y_train, epochs=5, verbose=0)
    loss, acc = model.evaluate(X_test, y_test, verbose=0)
    accuracies.append(acc)
print(f"Average accuracy: {sum(accuracies)/len(accuracies):.2f}")
Drag options to blanks, or click blank then click option'
Atrain_idx
Btest_idx
Cval_idx
Dsplit_idx
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing train and test indices
Appending loss instead of accuracy