【问题标题】:TypeError: only size-1 arrays can be converted to Python scalars keep arrivingTypeError:只有大小为 1 的数组可以转换为 Python 标量不断到达
【发布时间】:2020-08-09 10:24:49
【问题描述】:

我一直面临这个错误,我读过一些有相同错误的案例,我尝试将每个列表转换为一个 numpy 数组,但它仍然不起作用。

这个错误到底是什么意思?

TypeError                                 Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-4-b5b54f6e1f9e> in <module>
     69 
     70     model = LogisticRegression(eta = 0.01, n_iterations = 1000, lamb = 100)
---> 71     model.fit(x_train, y_train)
     72     ypre = model.predict(x_test)
     73     print(ypre)

<ipython-input-4-b5b54f6e1f9e> in fit(self, x, y)
     29             t = (hx - y)
     30 
---> 31             s = self.cal_s(t, x, row, column)
     32             gradient_w = np.sum(s, 0) / row * self.eta
     33             gradient_b = np.sum(t, 0) / row * self.eta

<ipython-input-4-b5b54f6e1f9e> in cal_s(self, t, x, row, colum)
     17         for i in range(0,row):
     18             for j in range(0, colum):
---> 19                 s[i][j] = t[i] * x[i][j]
     20         return s
     21 

ValueError: setting an array element with a sequence.

我哪里做错了?我该如何解决?

该功能在我导入一些 csv 文件之前工作。(我以前使用 np.random.rand 来概括它)

这是我的代码:

import numpy as np

class LogisticRegression:
    def __init__(self, eta, n_iterations, lamb):
        self.w = np.zeros(30) #theta
        self.b = 0 #theta 0
        self.eta = eta #Learing rate
        self.n_iterations = n_iterations #times for iterations
        self.lamb = lamb #
        self.r = (1 - lamb * self.eta / np.size(self.w, 0))

    def logistic(self, x):
        return 1.0/(1 + np.exp(-x))

    def cal_s(self, t, x, row, colum):
        s = np.zeros([row, colum], dtype=float)
        for i in range(0,row):
            for j in range(0, colum):
                s[i][j] = t[i] * x[i][j]
        return s

    def fit(self, x, y):
        itr = 0
        row, column = np.shape(x)
        print('number of instance', row)
        while itr <= self.n_iterations:
            fx = np.dot(self.w, x.T)
            hx = self.logistic(fx)
            t = (hx - y)

            s = self.cal_s(t, x, row, column)
            gradient_w = np.sum(s, 0) / row * self.eta
            gradient_b = np.sum(t, 0) / row * self.eta
            self.w = self.w * self.r - gradient_w
            self.b -= gradient_b
            itr += 1

    def predict(self, x_test):
        ypre = np.dot(self.w, x_test.T) + self.b
        temp = ypre >= 0
        yp = temp.astype(int)
        return yp

if __name__ == '__main__':
    import matplotlib.pyplot as plt
    import csv

    with open('X_train.csv', newline='') as xTrain:

        xtrain = csv.reader(xTrain, delimiter=',')
        x_train = list(xtrain)
        x_train = np.array(x_train)
        x_train = x_train.astype(np.float)

    with open('Y_train.csv', newline='') as yTrain:

        ytrain = csv.reader(yTrain, delimiter=',')
        y_train = list(ytrain)
        y_train = np.array(y_train)
        y_train = y_train.astype(np.float)

    with open('x_test.csv', newline='') as xTest:

        xtest = csv.reader(xTest, delimiter=',')
        x_test = list(xtest)
        x_test = np.array(x_test)
        x_test = x_test.astype(np.float)

    model = LogisticRegression(eta = 0.01, n_iterations = 1000, lamb = 100)
    model.fit(x_train, y_train)
    ypre = model.predict(x_test)
    print(ypre)

【问题讨论】:

  • 可以查看line19中涉及的变量类型吗?

标签: python arrays numpy


【解决方案1】:

首先,二维数组的首选索引是s[i,j]

s 是一个二维数组。看起来x 具有相同的形状;我不能肯定地说,但我怀疑t 也是二维的。否则 t[i] 将是一个标量,并且分配将起作用。该错误告诉我们t[i]*x[i,j] 是一个“序列”,很可能是一个数组。但是s[i,j] 只能接受一个标量,一个数字。

   s = np.zeros([row, colum], dtype=float)
    for i in range(0,row):
        for j in range(0, colum):
            s[i, j] = t[i] * x[i, j]
    return s

根据t的形状,这个赋值大概可以写成

   s = t * x          # or
   s = t[:,None] * x

但是标题显示了一个不同的错误,关于一个应该是标量的参数,一个单一的数字。相反,你给它一个包含多个元素的数组。您没有显示该错误的回溯。

在调试numpy代码时,要详细注意所有数组的shape(以及type和dtype)。您应该知道代码中每个点的预期内容,并准备好检查这些知识。猜测会产生错误。

【讨论】:

  • s = t * x 不工作,因为 t 是 (500, 500) 而 x 是 (500, 30) s = t[:,None] * x 仍然不工作,形状t 变为 (500,1,500) ValueError: 操作数不能与形状一起广播 (500,1,500) (500,30)
  • 嗯嗯!您如何期望将 (500,500) 乘以 (500,30) 并生成 (500,500) 数组?你不能迭代地做到这一点,你也不能用整个阵列广播来做。就像我写的那样,您必须密切注意数组形状。
  • 抱歉我的解释不好。我的意思是 t(500,500) 是一个意想不到的结果,t 应该是 (500,)。为此,我需要先改变 y 的形状。 y 的原始形状是 (500,1),我使用 numpy.ravel 将其更改为 (500,)。它现在应该可以工作了。但我面临另一个溢出错误: D:\anaconda3\lib\site-packages\ipykernel_launcher.py:13: RuntimeWarning: overflow 在 exp del sys.path[0]
猜你喜欢
  • 2021-10-17
  • 2018-07-22
  • 2021-06-24
  • 1970-01-01
  • 2023-01-14
  • 1970-01-01
  • 2019-06-19
  • 2021-12-19
  • 1970-01-01
相关资源
最近更新 更多