numpy.dot() 给出 TypeError: 不能将序列乘以类型为 'float' 的非 int



我刚刚开始使用Python学习机器学习。我编写了以下类,该类给出了一个错误:

类型

错误:无法将序列乘以类型为"float"的非 int

class Perceptron(object):
def __init__(self, eta=0.01, n_iter=10):
self.eta = eta                          # Learning Rate
self.n_iter = n_iter                    # Number of iteration over the training dataset
def fit(self, x, y):
self.w_ = np.zeros(1 + x.shape[1])      # Initialize Weights to zero initially                                                # x = {array-like} : shape[no_of_samples, no_of_features]
self.errors_ = []                       # No errors in the beginning of the computation
for _ in range(self.n_iter):
errors = 0
for xi, target in zip(x, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self
def net_input(self, x):
return np.dot(x, self.w_[1:]) + self.w_[0]
def predict(self, x):
return np.where(self.net_input(x) >= 0.0, 1, -1) 

我在 np.dot(( 的 net_input(( 方法中收到错误。 我正在使用以下数据集: https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv

如果您正在从文件鸢尾花中读取训练数据(数据和预测.csv

sepal_length,sepal_width,petal_length,petal_width,species
5.1,3.5,1.4,0.2,setosa
4.9,3,1.4,0.2,setosa

跟:

data = pd.read_csv("iris.csv")

确保将x定义为前四列,否则它将包含最后一列中的字符串:

X = data.iloc[:,0:4]

和预测值:

y = data.iloc[:,5]
y = y.values.reshape(150,1)

以下更改会有所帮助。

def fit(self, x, y):
...
for xi, target in zip(x, y):
update = self.eta * (target - self.predict(xi.reshape(1, x.shape[1]))
...
# Here if you want to implement perceptron, use matmul not dot product
def net_input(self, x):
return np.matmul(x, self.w_[1:]) + self.w_[0]

检查xshape

如果(a, 1)其中a是一个数字,请使用以下命令:

def net_input(self, x):
return np.dot(x.T, self.w_[1:]) + self.w_[0]

如果是(1, a)请使用以下命令:

def net_input(self, x):
return np.dot(x, self.w_[1:].T) + self.w_[0]

我的猜测是x是一个列表的对象dtype数组。

如果我定义一个对象 dtype 数组:

In [45]: x=np.empty((2,),object)
In [46]: x[:]=[[1,2],[3,4]]
In [49]: x
Out[49]: array([list([1, 2]), list([3, 4])], dtype=object)

我在浮点数列表(或数组(中遇到相同的错误:

In [50]: np.dot(x, [1.2,4.5])
...
TypeError: can't multiply sequence by non-int of type 'float'

相反,如果我给它整数,它可以工作 - 有点

In [51]: np.dot(x, [1,2])
Out[51]: [1, 2, 3, 4, 3, 4]

它实际上所做的是[1,2]*1[3,4]*2,列表复制。 这不是数字乘法。

这是唯一有意义的错误消息变量组合。

所以你需要弄清楚为什么x是一个对象数组。 通常,这是从长度不同的列表构建数组的结果

In [54]: x = np.array([[1,2],[3,4,5]])
In [55]: x
Out[55]: array([list([1, 2]), list([3, 4, 5])], dtype=object)

因此,当面对这样的错误时,基本问题是变量的shapedtype是什么。

最新更新