Python Forum
Need help with Neural network code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with Neural network code
#1
Hello, I am new in python. Need help with neural network code.

I have data in .xlxs file. Dimensions 7027x65.
This is data file
Data file

First of all I calculate 20% of my data for training my neural network, and set output training array


import pandas as pd
import numpy as np

dataset = pd.read_excel("C:\\Users\\tigra\\Desktop\\1year.xlsx") # nuskaitymas exel failo

# Calculate 20%
dydis=dataset.shape
print('Masyvo dimension: ',dydis)
row=round((dydis[0]*(dydis[1]-1))*0.2/(dydis[0]))
Training_array = dataset.iloc[:,:row]

Training_array_dimensions=Training_array.shape
print('Masyvo dimension: ',Training_array_dimensions)

# input data
inputs = Training_array
outputs = np.array([100])
For prediction I am using other 80% of data

# create two new examples to predict                                   
example = dataset.iloc[:,row:]
example_dimension= example.shape
print('Masyvo dimension: ',example_dimension)
This all the code:
# create NeuralNetwork class
class NeuralNetwork:

    # intialize variables in class
    def __init__(self, inputs, outputs):
        self.inputs  = inputs
        self.outputs = outputs
        # initialize weights as .50 for simplicity
        self.weights = np.full([7027, 1], .50) 
        self.error_history = []
        self.epoch_list = []

    #activation function ==> S(x) = 1/1+e^(-x)
    def sigmoid(self, x, deriv=False):
        if deriv == True:
            return x * (1 - x)
        return 1 / (1 + np.exp(-x))

    # data will flow through the neural network.
    def feed_forward(self):
        self.hidden = self.sigmoid(np.dot(self.inputs, self.weights))

    # going backwards through the network to update weights
    def backpropagation(self):
        self.error  = self.outputs - self.hidden
        delta = self.error * self.sigmoid(self.hidden, deriv=True)
        self.weights += np.dot(self.inputs.T, delta)

    # train the neural net for 25,000 iterations
    def train(self, epochs=25000):
        for epoch in range(epochs):
            # flow forward and produce an output
            self.feed_forward()
            # go back though the network to make corrections based on the output
            self.backpropagation()    
            # keep track of the error history over each epoch
            self.error_history.append(np.average(np.abs(self.error)))
            self.epoch_list.append(epoch)

    # function to predict output on new and unseen input data                               
    def predict(self, new_input):
        prediction = self.sigmoid(np.dot(new_input, self.weights))
        return prediction

# create neural network   
NN = NeuralNetwork(inputs, outputs)
# train neural network
NN.train()

# print the predictions for both examples                                   
print(NN.predict(example), ' - Correct: ')
By running the code I'm get this error:
[Image: view?usp=sharing]

How to fix that? Thanks for your help.
Reply
#2
Please could you post errors as text using error tags, not as an image of an error.
Thank you Smile
Reply
#3
LOAD_GLOBAL(dispatcher), LOAD_FAST(args), LOAD_FAST(kwargs), CALL_FUNCTION_EX{1}, STORE_FAST(relevant_args)
return implement_array_function(
Error:
Exception has occurred: ValueError shapes (7027,13) and (7027,1) not aligned: 13 (dim 1) != 7027 (dim 0) File "<__array_function__ internals>", line 5, in dot File "C:\Users\tigra\Desktop\Untitled-1.py", line 49, in feed_forward self.hidden = self.sigmoid(np.dot(self.inputs, self.weights)) File "C:\Users\tigra\Desktop\Untitled-1.py", line 61, in train self.feed_forward() File "C:\Users\tigra\Desktop\Untitled-1.py", line 80, in <module> NN.train()
implementation, dot, relevant_args, args, kwargs)
Reply
#4
Don't take this wrong - are you supposed to be doing it the hard way, coding each piece when there are fully vetted functions out there to do it? I know sometimes assignments are done that way to try to teach you something special, but for example:
trainval_dataset = df.sample(frac=0.8,random_state=42)
test_dataset = df.drop(trainval_dataset.index)
does your training and testing split, in the usual 80% training and 20% test.

Current problem is with the shapes of your data. Look at the shapes being fed into feedforward.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Develop neural network for consumption function vaibhavpwr101 0 736 Oct-03-2022, 05:29 AM
Last Post: vaibhavpwr101
  Example shalow neural network Malin3k 1 2,277 Apr-22-2021, 04:12 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020