2017-02-15 21 views
0

我們有一個關於分類的機器學習項目。起初,我嘗試了一個最簡單的分類器:分類器總是預測+1。 這是我的代碼。使用python進行機器學習熱身

from binary import * 
from numpy import * 
from pylab import * 

import util 
import datasets 
import binary 
import dumbClassifiers 

class AlwaysPredictOne(BinaryClassifier): 
    """ 
    This defines the classifier that always predicts +1. 
    """ 

    def __init__(self, opts): 
     """ 
     do nothing 
     """ 

    def online(self): 
     return False 

    def __repr__(self): 
     return "AlwaysPredictOne" 

    def predict(self, X): 
     return 1  # return our constant prediction 

    def train(self, X, Y): 
     """ 
     do nothing 
     """ 
h = dumbClassifiers.AlwaysPredictOne({}) 

print(h) 

h.train(datasets.TennisData.X, datasets.TennisData.Y) 

h_p = h.predictAll(datasets.TennisData.X) 

print(h_p) 

m = mean((datasets.TennisData.Y > 0) == (h.predictAll(datasets.TennisData.X) > 0)) 
print(m) 

t = mean((datasets.TennisData.Yte > 0) == (h.predictAll(datasets.TennisData.Xte) > 0)) 

print(t) 

那麼結果:

AlwaysPredictOne 
[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] 
0.642857142857 
0.5 

AlwaysPredictOne 

[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] 
0.642857142857 
0.5 

雖然答案是正確的,我的問題是,爲什麼會出現兩次?我的代碼有問題嗎?

+1

如何運行代碼,此處缺少某些內容。 –

+0

我建議用* pass *替換「什麼都不做」評論:爲什麼在有語法時使用評論? – guidot

回答

0

我不確定您的代碼是Ipsis Verbis但是如果您導入的是您將要運行的相同腳本(運行其內容兩次),則會發生這種情況。

一個小例子。比方說,我做了一個名爲example.py文件,並寫入內部的以下內容:

import example 

class Example: 
    def __init__(self): 
     print("Running Example __init__") 

ex = Example() 

注意我是如何導入該文件本身在我的第一個指令?那麼結果如下:

Running Example __init__ 
Running Example __init__ 

從你的對象單獨把你的行書,避免自我進口的,你應該做的罰款。

+0

謝謝!我將它們分開,然後一切順利! – JennyShen