I get this error: Traceback (most recent call last): File…
- User
I get this error: Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Experimental-Learning\main-.py", line 76, in output_vector += time_vector[j] * weights_time_output[j] ValueError: operands could not be broadcast together with shapes (38,) (10,) (38,) When i run this code: import numpy as np import matplotlib.pyplot as plt
Define the neural network architecture
input_neurons = 100
time_neurons = 40 output_neurons = 10Initialize the weights randomly as numpy arrays
weights_input_time = np.random.rand(input_neurons, time_neurons) weights_time_output = np.random.rand(time_neurons, output_neurons)
Initialize output_vector to match the number of output_neurons:
output_vector = np.zeros(output_neurons)
Define the training data
sentences = ["I love Pizza !", "The earth is round.", "Winter is a brand old time.", "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z"]
Define the training parameters
learning_rate = 0.1 epochs = 100
Lists to store the loss and accuracy values for plotting
loss_values = [] accuracy_values = []
def one_hot_encode(word, word_to_index, vocabulary_size): word_vec = np.zeros(vocabulary_size) word_vec[word_to_index[word]] = 1 return word_vec
def one_hot_decode(word_vec, index_to_word): max_index = np.argmax(word_vec) return index_to_word[max_index]
Function to predict the next word
def predict_next_word(input_word, time_vector, weights_time_output, word_to_index, index_to_word): input_vector = one_hot_encode(input_word, word_to_index, vocabulary_size)
# Calculate the output vector output_vector = np.zeros(vocabulary_size) for j in range(time_neurons): output_vector += time_vector[j] * weights_time_output[j] # Get the predicted next word predicted_word = one_hot_decode(output_vector, index_to_word) return predicted_wordCreate a list of all words
all_words = set(word for sentence in sentences for word in sentence.split())
Create a word to index mapping and index to word mapping
word_to_index = {word: i for i, word in enumerate(all_words)} index_to_word = {i: word for word, i in word_to_index.items()} vocabulary_size = len(word_to_index)
Training loop
for epoch in range(epochs): total_loss = 0 correct_predictions = 0
for sentence in sentences: words = sentence.split() time_vector = np.zeros(time_neurons) for i in range(len(words) - 1): input_vector = one_hot_encode(words[i], word_to_index, vocabulary_size) target_vector = one_hot_encode(words[i + 1], word_to_index, vocabulary_size) # Calculate the output vector output_vector = np.zeros(vocabulary_size) for j in range(time_neurons): # Update each element in time_vector time_vector[j] = time_vector[j] + 1 # Perform dot product with weights_time_output[j] output_vector += time_vector[j] * weights_time_output[j] predicted_word = one_hot_decode(output_vector, index_to_word) if predicted_word == words[i+1]: correct_predictions += 1 loss = np.sum((output_vector - target_vector) ** 2) total_loss += loss # Weight update for j in range(time_neurons): # Update the j-th row of weights based on the gradient weights_time_output[j] -= learning_rate * (output_vector - target_vector) * time_vector[j] # Handle prediction for last word # Ensure time_vector and last_output are numpy arrays last_output = np.zeros(vocabulary_size) for j in range(time_neurons): # last_output should not use input_vector since it’s already one-hot encoded last_output += time_vector[j] * weights_time_output[j] # Final prediction and weight update final_target_vector = one_hot_encode(words[-1], word_to_index, vocabulary_size) loss = np.sum((last_output - final_target_vector) ** 2) total_loss += loss for j in range(time_neurons): weights_time_output[j] -= learning_rate * (last_output - final_target_vector) * time_vector[j] # Calculate overall metrics average_loss = total_loss / len(sentences) accuracy = correct_predictions / (len(sentences) * (len(words) - 1)) # Store loss and accuracy loss_values.append(average_loss) accuracy_values.append(accuracy) print(f"Epoch {epoch+1}/{epochs} - Loss: {average_loss:.4f} - Accuracy: {accuracy:.4f}") - Assistant
The error you are experiencing is related to a mismatch in array shapes when trying to perform element-wise multiplication. The error message indicates that the operation is trying to broadcast arrays of different shapes, specifically
(38,)and(10,), which cannot be done directly.In your code, the issue likely stems from this line within the
predict_next_wordfunction:output_vector += time_vector[j] * weights_time_output[j]Here,
time_vector[j]is a scalar, whileweights_time_output[j]is a 1-D array with the number of elements equal to (which is 10 in your case). You're trying to multiply a scalar with an array and then add the resulting array to , which has a shape of , and it appears that is 38. - User
- Assistant
- User
Add a function to load the training sentences from a txt file
- Assistant
- User
This error always occurs: Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Experimental-Learning\main-2.py", line 60, in error = target_vector - output_vector ValueError: operands could not be broadcast together with shapes (15,) (10,)
- Assistant
The
ValueError: operands could not be broadcast together with shapes (15,) (10,)error message indicates that you are trying to perform an operation on two arrays (specifically subtraction in this case) that have incompatible shapes. This means you have a mismatch between your and . - User
- Assistant
The problem lies in how you set
output_neurons. Theoutput_neuronsshould exactly match thevocabulary_sizewithout any addition or subtraction, as each output neuron corresponds to a word in the vocabulary. By settingoutput_neuronstovocabulary_size + 1, you artificially introduced another output neuron that doesn't correspond to a word in the vocabulary, leading to the broadcasting error when trying to perform the subtractionerror = target_vector - output_vector.Here's how you can fix the
output_neuronsvariable assignment and prevent the broadcasting error:# Update output_neurons to match the vocabulary size output_neurons = vocabulary_size # Reinitialize the weights to match the new output_neurons weights_input_time = np.random.rand(input_neurons, time_neurons) weights_time_output = np.random.rand(time_neurons, output_neurons)Now the rest of the code should work with
target_vectorandoutput_vectorhaving matching shapes, and the subtraction should work without broadcasting errors. Make sure to remove the you added because should be exactly equal to . - User
After making the change, i get this error now: vocabulary = 17 Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Experimental-Learning\main-2.py", line 66, in time_vector += weights_input_time[np.argmax(input_vector)] # Emulate time context update IndexError: index 11 is out of bounds for axis 0 with size 10
- Assistant
The
IndexErroryou're encountering indicates that you are trying to use an index that is outside the bounds of theweights_input_timearray.The issue is with this line:
time_vector += weights_input_time[np.argmax(input_vector)]The
weights_input_timearray has a shape(input_neurons, time_neurons), which in your current setup equals(10, 15). When you callnp.argmax(input_vector), you can get an index that ranges from0tovocabulary_size - 1. Since your vocabulary size is 17, the index can be larger than the shape ofweights_input_timealong the first dimension (which only goes up to 9 because of zero-indexing).To fix this issue, you should ensure the first dimension of
weights_input_timematches thevocabulary_size. Theinput_neuronsvariable therefore should be set to the : - User
- Assistant
- User
Give me code to create a proper transformer model using only numpy, this is an experiment only, so i need a lot of data for my paper to document my findings with experimenting with different neural network layers, sizes, activations, sequence window and more
- Assistant
- User
If it is too difficult without a ML framework you can use Pytorch, "CPU" only
- Assistant
- User
Add code to plot loss over epoch and accuracy over epoch in separate plots using matplotlib
- Assistant
- User
- Assistant
- User
Traceback (most recent call last): File "c:\Users\Dell-PC\Desktop\Projets\Experimental-Learning\main-3.py", line 54, in tokenizer = SimpleTokenizer("vocab.txt") # Your vocab file with list of words TypeError: SimpleTokenizer() takes no arguments
- Assistant
Apologies for the confusion—the
SimpleTokenizerneeds to be initialized with parameters. I should have included the__init__parameters inside the class but seems to have missed out. Let me correct that for you. Here's the updated code: - User
- Assistant
The error you're experiencing is occurring because when you attempt to use , the key does not exist yet in the dictionary. To fix this, you should add the token to the vocabulary when you initialize the .
- User
Give me code to test the Transformer
- Assistant
- User
Add a function to create the vocab.txt automatically
- Assistant