I have a table with columnd ID, Data, and Target. ID is identification number of…
- User
I have a table with columnd ID, Data, and Target. ID is identification number of customer. Data contains a list of Merchant Category Codes for purchases that have been made.Column Target contains the list of Merchant Category Codes for future 10 consecutive purchases. Note that Data contains lists with different number of elements and variable Target contains lists with 10 elements. Write a Python script to predict Target based on Data. Use sequential model. If Target contains more that 10 codes limit they by 10. Use mapk as a measure
def apk(actual, predicted, k=10): if len(predicted) > k: predicted = predicted[:k]
score = 0.0 num_hits = 0.0
for i, p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i+1.0)
if not actual: return 0.0
return score / min(len(actual), k)
def mapk(actual, predicted, k=10): return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)])
See an example ID|Data|Target 1|[5541,5541,6623,7451,2545,5541,5541,6623,7451,2545,6688,6669,66622]|[4125,5541,5541,4125,5541,5541,4125,5541,5541,1478] 2|[5541,5541,6623,7451,5541,6623,7451,2545,6688,6669,66622]|[6125,5541,5541,6125,5541,5541,4125,5541,5541,1478]
Note that the model should predict MCC codes, not probabilities!
- Assistant
To predict the Target column based on the Data column using a sequential model, you can follow these steps:
- Import the required libraries:
import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, Dense- Load the data into variables:
- User
Add the block with checking metrics mapk
- Assistant
To calculate the mean average precision at k (MAP@k) metric, you can use the
mapk()function you provided. Here's how you can incorporate it into the script:def apk(actual, predicted, k=10): if len(predicted) > k: predicted = predicted[:k] score = 0.0 num_hits = 0.0 for i, p in enumerate(predicted): if p in actual and p not in predicted[:i]: num_hits += 1.0 score += num_hits / (i+1.0) if not actual: return 0.0 return score / min(len(actual), k) def mapk(actual, predicted, k=10): return np.mean([apk(a, p, k) for a, p in zip(actual, predicted)]) # Rest of the code... # Predict the Target column for new data new_data = [[5541, 5541, 6623, 7451, 2545, 5541, 5541, 6623, 7451, 2545, 6688, 6669, 66622]] X_new = np.zeros((len(new_data), max_data_length), dtype=int) X_new[0, :len(new_data[0])] = new_data[0] y_pred = model.predict(X_new) predicted_target = np.argmax(y_pred, axis=-1) # Convert predicted_target to the original format predicted_target = [list(map(int, p)) for p in predicted_target] # Calculate MAP@10 for the predicted target and original target data_target = [[4125, 5541, 5541, 4125, 5541, 5541, 4125, 5541, 5541, 1478], [6125, 5541, 5541, 6125, 5541, 5541, 4125, 5541, 5541, 1478]] mapk_score = mapk(data_target, predicted_target, k=10) print("MAP@10 Score:", mapk_score) - User
logits and labels must have the same first dimension, got logits shape [32,10] and labels shape [320] [[{{node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]] [Op:__inference_train_function_38244] The error erases after running model.fit. If you do not understand what the data are, ask questions. Do not provide foolish advices. I lose time and resources due to your recommendations
- Assistant
Apologies for the confusion caused. It appears that the error you encountered is because the shapes of the logits and labels do not match.
To clarify the data and resolve this issue, could you please provide more information about the shape and format of your
X_trainandy_traindata? Additionally, if you could provide details about the desired output format for the predictions (e.g., the shape and format of thepredicted_target), it would be helpful in providing a more accurate solution. - User
Initial data conatins two columns Data and Target. Data contains lists of consecutive MCC-codes. The number of codes in rows is not the same, not constant number. Target contains 10 consecutive MCC codes. I need to train model to predict Target based on Data. The findal metrics is mapk. After training the model, I need to load only Data in model to get 10 MCC codes for each row. I do not need probabilities. I need MCC codes that are always 4 digit-codes
- Assistant
- User
The error is indices[24,0] = 4829 is not in [0, 10) [[{{node sequential_9/embedding_4/embedding_lookup}}]] [Op:__inference_train_function_41538] It appears after running model.fit
- Assistant
Apologies for the confusion. The error indicates that the predicted label index is out of the valid range. This issue might arise if the number of unique classes in the target is different from the expected value.
To address this error, ensure that the number of unique classes (i.e.,
num_classes) matches the number of distinct MCC codes in the target. You can calculate thenum_classesusing thelen()function on the unique values ofy_train_encodedinstead of the originaly_train.Here's an updated code snippet with the correction:
# Calculate the number of unique classes num_classes = len(np.unique(y_train_encoded)) # Build the sequential model model = Sequential() model.add(Embedding(input_dim=num_classes, output_dim=16, input_length=max_data_length)) model.add(LSTM(units=32)) model.add(Dense(units=max_target_length, activation='softmax')) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') # Train the model model.fit(X_train, y_train_encoded, epochs=10, batch_size=32)Please make sure that the number of unique classes () matches the expected number of distinct MCC codes in your target column. This will ensure that the model is correctly trained and avoids the index out of range error.
- User
I do not see any difference
- Assistant
Apologies for the confusion. It seems I made an oversight in my previous response.
To address the error you encountered, you can modify the
num_classesto be the maximum MCC code value plus 1 instead of the number of unique classes. Here's the corrected code snippet:# Calculate the number of classes (maximum MCC code + 1) num_classes = np.max(y_train) + 1 # Build the sequential model model = Sequential() model.add(Embedding(input_dim=num_classes, output_dim=16, input_length=max_data_length)) model.add(LSTM(units=32)) model.add(Dense(units=max_target_length, activation='softmax')) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') # Train the model model.fit(X_train, y_train_encoded, epochs=10, batch_size=32)By using
np.max(y_train) + 1, thenum_classeswill be set to the maximum MCC code value present in the target column, ensuring that the model's embedding layer has the correct number of classes.Please give this updated code a try and let me know if the error persists.
- User
The error is logits and labels must have the same first dimension, got logits shape [32,10] and labels shape [320] [[{{node sparse_categorical_crossentropy/SparseSoftmaxCrossEntropyWithLogits/SparseSoftmaxCrossEntropyWithLogits}}]] [Op:__inference_train_function_48126] Do you still not understand the nature of data?
- Assistant
Apologies for the ongoing confusion. It seems I misunderstood the shape of the target data. To properly address the issue, here's an updated code snippet:
import numpy as np from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, Dense # Load the data into variables data = [ [5541, 5541, 6623, 7451, 2545, 5541, 5541, 6623, 7451, 2545, 6688, 6669, 66622], [5541, 5541, 6623, 7451, 5541, 6623, 7451, 2545, 6688, 6669, 66622] ] target = [ [4125, 5541, 5541, 4125, 5541, 5541, 4125, 5541, 5541, 1478], [6125, 5541, 5541, 6125, 5541, 5541, 4125, 5541, 5541, 1478] ] # Prepare the data for training max_data_length = max(len(seq) for seq in data) max_target_length = 10 X_train = np.zeros((len(data), max_data_length), dtype=int) y_train = np.zeros((len(target), max_target_length), dtype=int) for i, seq in enumerate(data): X_train[i, :len(seq)] = seq for i, seq in enumerate(target): y_train[i, :min(len(seq), max_target_length)] = seq[:max_target_length] # Build the sequential model model = Sequential() model.add(Embedding(max_data_length, 16, input_length=max_data_length)) model.add(LSTM(32)) model.add(Dense(max_target_length, activation='softmax')) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') # Train the model model.fit(X_train, y_train, epochs=10, batch_size=32) # Predict the Target MCC codes for new data new_data = [[5541, 5541, 6623, 7451, 2545, 5541, 5541, 6623, 7451, 2545, 6688, 6669, 66622]] X_new = np.zeros((len(new_data), max_data_length), dtype=int) X_new[0, :len(new_data[0])] = new_data[0] y_pred = model.predict(X_new) # Extract the top-k MCC codes for each row k = 10 predicted_target = [] for pred_row in y_pred: top_k_indices = pred_row.argsort()[-k:][::-1] top_k_codes = [int(index) for index in top_k_indices] predicted_target.append(top_k_codes) print("Predicted Target MCC Codes:", predicted_target)