当前位置: 首页>>代码示例>>Python>>正文


Python linear_model.Perceptron类代码示例

本文整理汇总了Python中sklearn.linear_model.Perceptron的典型用法代码示例。如果您正苦于以下问题:Python Perceptron类的具体用法?Python Perceptron怎么用?Python Perceptron使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Perceptron类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run

    def run(self):
        """
        Пуск задачи
        """
        train_data = pd.read_csv(self.param.get('train'))
        test_data = pd.read_csv(self.param.get('test'))
        X_train = train_data[['1', '2']]
        y_train = train_data['0']

        X_test = test_data[['1', '2']]
        y_test = test_data['0']


        if self.param.get('scale') is True:

            scaler = StandardScaler()
            X_train = scaler.fit_transform(X_train)

            X_test = scaler.transform(X_test)

        perceptron = Perceptron(random_state=241)
        perceptron.fit(X_train, y_train)

        predictions = perceptron.predict(X_test)

        accuracy = accuracy_score(y_test, predictions)
        with self.output().open('w') as output:
            output.write(str(accuracy))
开发者ID:AndrewKhodyakov,项目名称:mlearning_tasks,代码行数:28,代码来源:couresera_course.py

示例2: PerceptronClassifier

class PerceptronClassifier(AbstractSKLearnClassifier):

    def __init__(self):
        AbstractSKLearnClassifier.__init__(self)
        self.model = False

    def set_label_encoder(self, labels):
        AbstractSKLearnClassifier.set_label_encoder(self, labels)

    def return_label_encoding(self, labels):
        return AbstractSKLearnClassifier.return_label_encoding(self, labels)

    def train_classifier(self, trainvectors, labels, alpha='1.0', iterations=10, jobs=1, v=2):
        iterations = int(iterations)
        jobs = int(jobs)
        if alpha == 'search':
            paramsearch = GridSearchCV(estimator=Perceptron(), param_grid=dict(alpha=numpy.linspace(0,2,20)[1:],n_iter=[iterations]), n_jobs=jobs)
            paramsearch.fit(trainvectors,labels)
            alpha = paramsearch.best_estimator_.alpha
        else:
            alpha = float(alpha)
        self.model = Perceptron(alpha=alpha,n_iter=iterations,n_jobs=jobs)
        self.model.fit(trainvectors, labels)

    def return_classifier(self):
        return self.model
    
    def return_model_insights(self,vocab=False):
        model_insights = []
        return model_insights
开发者ID:LanguageMachines,项目名称:quoll,代码行数:30,代码来源:classifier.py

示例3: ClassificationPLA

class ClassificationPLA(ClassficationBase.ClassificationBase):
    def __init__(self, isTrain, isOutlierRemoval=0):
        super(ClassificationPLA, self).__init__(isTrain, isOutlierRemoval)

        # data preprocessing
        self.dataPreprocessing()

        # PLA object
        self.clf = Perceptron()


    def dataPreprocessing(self):
        # deal with unbalanced data
        self.dealingUnbalancedData()

        # Standardization
        #self.Standardization()



    def training(self):
        # train the K Nearest Neighbors model
        self.clf.fit(self.X_train, self.y_train.ravel())

    def predict(self):
        # predict the test data
        self.y_pred = self.clf.predict(self.X_test)

        # print the error rate
        self.y_pred = self.y_pred.reshape((self.y_pred.shape[0], 1))
        err = 1 - np.sum(self.y_test == self.y_pred) * 1.0 / self.y_pred.shape[0]
        print "Error rate: {}".format(err)
开发者ID:lujunzju,项目名称:AirTicketPredicting,代码行数:32,代码来源:ClassificationPLA.py

示例4: percep

def percep(X_tr, y_tr, X_te):
    clf = Perceptron(n_iter = 1000)
    X_tr_aug = add_dummy_feature(X_tr)
    X_te_aug = add_dummy_feature(X_te)
    clf.fit(X_tr_aug, y_tr)
    y_pred = clf.predict(X_te_aug)
    return y_pred
开发者ID:wenzhengong,项目名称:salary,代码行数:7,代码来源:main.py

示例5: PERCEPTRON

def PERCEPTRON(data_train, data_train_vectors, data_test_vectors, **kwargs):
    # Implementing classification model- using Perceptron
    clf_p =  Perceptron()
    clf_p.fit(data_train_vectors, data_train.target)
    y_pred = clf_p.predict(data_test_vectors)
    
    return y_pred
开发者ID:RaoUmer,项目名称:docs_classification,代码行数:7,代码来源:ml_docs_classification_2.py

示例6: Perceptron_1

def Perceptron_1(train_predictors,test_predictors,train_target,test_target):
    clf = Perceptron()
    clf.fit(train_predictors,train_target)
    predicted = clf.predict(test_predictors)
    accuracy = accuracy_score(test_target, predicted)
    print "Accuracy for Linear Model Perceptron: "+str(accuracy)
    return accuracy,predicted  
开发者ID:ineilm,项目名称:BountyApp,代码行数:7,代码来源:Models.py

示例7: perceptron_histo

def perceptron_histo():
    "Interprétation des images comme histogrammes de couleurs et classification via le Perceptron"
    alphas = np.arange(0.01,1.01,0.1)
    best=np.zeros(4)
    
    _, data, target, _ = utils.chargementHistogrammesImages(mer,ailleurs,1,-1)
    X_train,X_test,Y_train,Y_test=train_test_split(data,target,test_size=0.3,random_state=random.seed())
    
    
    for iterations in range(1,5):
        for a in alphas:
            start_time = time.time()
            
            p = Perceptron(alpha=a, n_iter=iterations, random_state=random.seed(), n_jobs=-1)
            
            x1=np.array(X_train)
            x2=np.array(X_test)
            
            p.fit(X=x1, y=Y_train)
            score = p.score(x2,Y_test)
            
            end_time = time.time()
            if score>best[0]:
                best[0] = score
                best[1] = a
                best[2] = iterations
                best[3] = end_time-start_time
        
    print("| Perceptron simple               | V.Histo    | alpha={:1.2f} iterations={:1.0f}            | {:10.3f}ms | {:1.3f} |".format(best[1],best[2],best[3]*1000,best[0]))
开发者ID:laiaga,项目名称:TPSM1,代码行数:29,代码来源:classification_images.py

示例8: perceptron_vecteur

def perceptron_vecteur():
    "Interprétation des images comme vecteurs de pixels et classification via le Perceptron"
    alphas = np.arange(0.01,1.01,0.1)
    best=np.zeros(5)
    
    for npix in range(50,200,50):
        _, data, target, _ = utils.chargementVecteursImages(mer,ailleurs,1,-1,npix)
        X_train,X_test,Y_train,Y_test=train_test_split(data,target,test_size=0.3,random_state=random.seed())
        
        
        for iterations in range(1,5):
            for a in alphas:
                start_time = time.time()
                
                p = Perceptron(alpha=a, n_iter=iterations, random_state=random.seed(), n_jobs=-1)
                
                #X_train, etc, sont des tableaux à 3 dimensiosn par défaut, (93,1,30000) par exemple, qu'il faut remmener en 2 dimensions
                x1=np.array(X_train)
                x1 = np.reshape(x1, (x1.shape[0],x1.shape[2]))
                x2=np.array(X_test)
                x2 = np.reshape(x2, (x2.shape[0],x2.shape[2]))
                
                p.fit(X=x1, y=Y_train)
                score = p.score(x2,Y_test)
                
                end_time = time.time()
                if score>best[0]:
                    best[0] = score
                    best[1] = a
                    best[2] = iterations
                    best[3] = end_time-start_time
                    best[4] = npix
        
    print("| Perceptron simple              | V.Pix {:4.0f} | alpha={:1.2f} iterations={:1.0f}              | {:10.3f}ms | {:1.3f} |".format(best[4],best[1],best[2],best[3]*1000,best[0]))
开发者ID:laiaga,项目名称:TPSM1,代码行数:34,代码来源:classification_images.py

示例9: main

def main():
    iris = load_iris()
    X = iris.data[:, (2, 3)]  # 花弁の長さ、花弁の幅
    y = (iris.target == 0.).astype(np.int32)
    perceptron_classifier = Perceptron(random_state=42)
    perceptron_classifier.fit(X, y)
    y_prediction = perceptron_classifier.predict([[2, 0.5]])
    print(y_prediction)
开发者ID:terasakisatoshi,项目名称:PythonCode,代码行数:8,代码来源:linear_regression.py

示例10: perceptron

def perceptron(kf,data,label,k):
	for train, test in kf:
		X_train, X_test, y_train, y_test = data[train,:], data[test,:], label[train], label[test]
		log = Perceptron(penalty="l2", alpha=0.003)
		logit = log.fit(X_train,y_train)
		y_pred =  logit.predict(X_test)
	scores = cross_validation.cross_val_score(log, data, label, cv=k)
	return scores.mean()
开发者ID:ComputationalBiology-CS-CU,项目名称:FMRI-Analysis,代码行数:8,代码来源:classification_methods.py

示例11: solve

def solve(train_set_x, train_set_y, test_set_x, test_set_y):
    clf = Perceptron(random_state=241)
    clf.fit(X=train_set_x, y=train_set_y)
    prediction = clf.predict(test_set_x)

    accuracy = accuracy_score(test_set_y, prediction)

    return accuracy
开发者ID:PavelVinogradov,项目名称:coursera-vvedenie-mashinnoe-obuchenie,代码行数:8,代码来源:w2_l2_t1.py

示例12: train_data_perceptron

def train_data_perceptron( tup, penalty ):

	df, features, label = tup

	percep = Perceptron( penalty = penalty, fit_intercept = True, eta0 = ETA, n_iter = CYCLES, n_jobs = 2 )
	percep.fit( df[features], df[label] )

	return percep
开发者ID:benjamin-limoges,项目名称:Machine_Learning,代码行数:8,代码来源:classify_forest.py

示例13: classify_perceptron

def classify_perceptron():
    print "perceptron"
    (X_train, y_train), (X_test, y_test) = util.load_all_feat()
    print "original X_train shape", X_train.shape
    clf = Perceptron()
    clf.fit(X_train, y_train)
    pred = clf.predict(X_test)
    print "accuracy score:", accuracy_score(y_test, pred)
开发者ID:HunjaeJung,项目名称:imagenet2014-modified,代码行数:8,代码来源:linear_classifier.py

示例14: t1

 def t1():
     from sklearn.linear_model import Perceptron
     X = np.array([[1, 2], [3, 4], [5, 6]])
     y = np.array([0, 1, 0])
     clf = Perceptron()
     clf.fit(X, y)
     predictions = clf.predict(X)
     print(predictions)
开发者ID:wargile,项目名称:ML1,代码行数:8,代码来源:s1-8.py

示例15: get_accuracy

def get_accuracy(_data_train_features, _data_train_labels, _data_test_features, _data_test_labels):
    # Обучите персептрон со стандартными параметрами и random_state=241.
    clf = Perceptron(random_state=241, shuffle=True)
    clf.fit(_data_train_features, numpy.ravel(_data_train_labels))

    # Подсчитайте качество (долю правильно классифицированных объектов, accuracy)
    # полученного классификатора на тестовой выборке.
    predictions = clf.predict(_data_test_features)
    score = accuracy_score(_data_test_labels, predictions)
    return score
开发者ID:aleksaad4,项目名称:ML,代码行数:10,代码来源:task5.py


注:本文中的sklearn.linear_model.Perceptron类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。