2017-08-18 10 views
0

私は、機械学習をPythonで学習し始めました。numpy.dot()はTypeErrorを返します: 'float'型のnon-intでシーケンスを掛けることはできません

TypeError: can't multiply sequence by non-int of type 'float'

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

+0

は正しい寸法の「x」ですか? [documentation](https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.html)を参照してください。 – Carlos

答えて

0

以下の変更が役立ちます。

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] 
+0

'matmul'と' dot'の出力は同じです.. –

+0

'np.dot'は要素ごとの乗算 'np.matmul'は行列の乗算です。ここで、この特殊なケース '(1、n)(n、1)'では、同じものになります。 NOT OTHERWISE –

+0

行列の要素ごとの乗算の次元は同じでなければなりません。 'np.multiply'は要素ごとの乗算です。 (演算子は '*')です。 'np.dot'と' np.matmul'(演算子は '@')の行列乗算の結果は同じです。 –

0

shapexにチェックしてください。

それはaは数ある(a, 1)ある場合は、この使用:それは(1, a)使用この場合には

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

を:

def net_input(self, x): 
    return np.dot(x, self.w_[1:].T) + self.w_[0] 
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) 

を私はfloatのリスト(または配列)と同じエラーが出ます:

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とです、リスト複製。これは数値の乗算ではありません。

これは、エラーメッセージを意味する変数の唯一の組み合わせです。

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) 

が異なるリストから配列を構築した結果だので、このようなエラーに直面した基本的な質問は、 shapeと変数の dtypeものです。

関連する問題