简体   繁体   English

Numpy TypeError 必须是整数,而不是元组

[英]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).出于这个原因,我首先从文件中取出数据并将每一行与这个 txt 分开,然后根据“,”将其拆分,然后将它们放入我的数组(数据)中。 After that i converted that array to numPy array and shuffle it randomly.之后我将该数组转换为 numPy 数组并随机洗牌。 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:您必须将 np.array 的结果分配给一个变量,它不会更改参数 matrix_data:

matrix_data = np.array(matrix_data)

Your code failes because you still have a list and not a numpy datastructure.您的代码失败,因为您仍然有一个列表而不是一个 numpy 数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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