简体   繁体   中英

Numpy TypeError must be integer, not tuple

I want to create a model using logistic regression. For this reason first i take the data from the file and separate each line from this txt and split it according to "," and put them into my array (datum). After that i converted that array to numPy array and shuffle it randomly. But when i slice array into two different piece for testing and training.

This error occured:

Traceback (most recent call last):
  File ".\logisticRegression.py", line 32, in <module>
    training_data = matrix_data[167:,:]
TypeError: list indices must be integers or slices, not tuple

Here is the code that i wrote:

import numpy as np
import matplotlib.pyplot as plt


def load_data(path):
    datum= []
    with open(path) as fp:
        line = fp.readline()
        while line:
            arr_line= line.split(",")
            datum.append(arr_line)
            line=fp.readline()
    return datum

#Sigmoid function
def sigmoid(x):
    return 1/(1+np.exp(-x))

#Loss function
def square_loss(y_pred, target):
    return np.mean(pow(((y_pred - target),2)))

if __name__ == "__main__":
    # load the data from the file
    matrix_data = load_data("all_data.txt")
    np.array(matrix_data)

    np.random.shuffle(matrix_data)

    training_data = matrix_data[167:,:] #These all lines gives error
    test_data = matrix_data[41:,:] #These all lines gives error

    X_tr, y_tr = training_data[:, :-1], training_data[:, -1] #These all lines gives error
    X_te, y_te = test_data[:, :-1], test_data[:, -1] #These all lines gives error
 
    

Note: I searched for this error and i found that the problem is the lack of comma in my array but when i print the array it has comma for each index.

You have to assign the result of np.array to a variable, it doesn't change the argument matrix_data:

matrix_data = np.array(matrix_data)

Your code failes because you still have a list and not a numpy datastructure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM