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


Python Perceptron.score方法代码示例

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


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

示例1: perceptron_histo

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
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,代码行数:31,代码来源:classification_images.py

示例2: perceptron_vecteur

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
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,代码行数:36,代码来源:classification_images.py

示例3: t

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
    def t():
        # 1
        from pandas import read_csv
        df = read_csv('w2/perceptron-train.csv', header=None)
        dt = read_csv('w2/perceptron-test.csv', header=None)
        yf = df[0]
        xf = df.drop([0], axis=1)
        # print(yf, xf)
        yt = dt[0]
        xt = dt.drop([0], axis=1)
        # print(yt, xt)

        # 2
        from sklearn.linear_model import Perceptron
        clf = Perceptron(random_state=241)
        clf.fit(xf, yf)
        af1 = clf.score(xf, yf)
        at1 = clf.score(xt, yt)
        rf = clf.predict(xf)
        rt = clf.predict(xt)
        # print(list(yf))
        # print(pf)
        # print(list(yt))
        # print(pt)

        # 3
        from sklearn.metrics import accuracy_score
        af = accuracy_score(yf, rf)
        at = accuracy_score(yt, rt)
        print(af, at)
        print(af1, at1)

        # 4
        from sklearn.preprocessing import StandardScaler
        scaler = StandardScaler()
        xfs = scaler.fit_transform(xf)
        xts = scaler.transform(xt)
        clf.fit(xfs, yf)
        afs1 = clf.score(xfs, yf)
        ats1 = clf.score(xts, yt)
        pfs = clf.predict(xfs)
        pts = clf.predict(xts)
        afs = accuracy_score(yf, pfs)
        ats = accuracy_score(yt, pts)
        print(afs, ats)
        print(afs1, ats1)
        pf('5', round(ats - at, 3))
开发者ID:wargile,项目名称:ML1,代码行数:49,代码来源:s1-8.py

示例4: neural_net

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
def neural_net(train, test):
	y = []
	xTrain, yTrain = loadData(train)
	xTest, yTest = loadData(test)
	nN = Perceptron()
	nN.fit(xTrain, yTrain)
	y = nN.predict(xTest)
	testError = 1 - nN.score(xTest, yTest)
	print 'Test error: ' , testError
	return y
开发者ID:rhythm92,项目名称:MachineLearning,代码行数:12,代码来源:number_recognition.py

示例5: neural_net

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
def neural_net(train, test):
    y = []
    trainY, trainX = loadData(train)
    testY, testX = loadData(test)

    neuralNet = Perceptron()
    neuralNet.fit(trainX, trainY)
    y = neuralNet.predict(testX)

    testError = 1 - neuralNet.score(testX, testY)
    print 'Test error: ' + str(testError)
    return y
开发者ID:XiangJi,项目名称:Machine-Learning,代码行数:14,代码来源:number_recognition.py

示例6: test_model

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
def test_model(training_data, testing_data, word2vec_model):
    v = DictVectorizer()
    train_features, train_labels = build_features(training_data, word2vec_model, v, 'train')
    test_features, test_labels = build_features(testing_data, word2vec_model, v)
    
    # create the perceptron model
    model = Perceptron(n_iter = 5)
    # fit the model to the training data
    model.fit(train_features, train_labels)
    # get the accuracy on the testing data
    accuracy = model.score(test_features, test_labels)

    return accuracy
开发者ID:mr-adam-lewis,项目名称:nlp-final-lab,代码行数:15,代码来源:lab10.py

示例7: __Accuracy

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
def __Accuracy(dataDict, parameterDict):
    train_X = dataDict['train_X']
    train_Y = dataDict['train_Y']
    cross_X = dataDict['cross_X']
    cross_Y = dataDict['cross_Y']

    penalty = parameterDict['penalty']
    alpha = parameterDict['alpha']
    fit_intercept = parameterDict['fit_intercept']
    n_iter = parameterDict['n_iter']
    shuffle = parameterDict['shuffle']
    eta0 = parameterDict['eta0']

    clf = Perceptron(penalty=penalty, alpha=alpha, fit_intercept=fit_intercept, n_iter=n_iter, shuffle=shuffle, random_state=1, eta0=eta0, warm_start=False)
    model = clf.fit(train_X, train_Y) # All features must be float.
    accuracy = clf.score(cross_X, cross_Y) # Score=Accuracy=(TP+TN)/(TP+TN+FP+FN)=%Correct

    return accuracy
开发者ID:TBKelley,项目名称:kaggle-allstate-tk,代码行数:20,代码来源:PercepronWeights.py

示例8: main

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
def main( argv ):
	try:
		training_filename  = argv[ 1 ]
		testing_filename = argv[ 2 ]
		output_filename = argv[ 3 ]
	except IndexError:
		print( "Error, usage: \"python3 {} <training> <testing> <output>\"".format( argv[ 0 ] ) ) 
		return

	
	Training_DataFrame = pd.read_csv( training_filename )
	
	X = Training_DataFrame.ix[:,0:-1]
	Y = Training_DataFrame.ix[:,-1]


	Testing_DataFrame = pd.read_csv( testing_filename )
	
	testing_X = Testing_DataFrame.ix[:,0:-1]
	testing_Y = Testing_DataFrame.ix[:,-1]


	'''
		Perceptron
	'''
	from sklearn.linear_model import Perceptron

	# Hyper Parameters:
	alpha 	= 0.0001
	n_iter 	= 20

	# Fit Classifier
	print( "{} Started training".format( str( datetime.now() ) ) )
	P_classifier = Perceptron( alpha = alpha, n_iter = n_iter )
	P_classifier.fit( X, Y )
	print( "{} Stopped training".format( str( datetime.now() ) ) )

	# Report results
	P_score = P_classifier.score( testing_X, testing_Y )

	print( "\nPerceptron Accuracy:", P_score )
开发者ID:CKPalk,项目名称:MachineLearning,代码行数:43,代码来源:perceptron.py

示例9: train

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
def train(a,sizel,intercept):
    d = a.copy()    
    pes = Perceptron(n_jobs=4,n_iter=500,fit_intercept=intercept)
#    d = d.tolist()
    train = d[:len(d)/sizel]
    C = d[len(d)/sizel:]
    train_res = numpy.zeros(shape=(len(train)))#[0.0 for i in range(len(train))]
    C_res = numpy.zeros(shape=(len(C)))#[0.0 for i in range(len(C))]
#    C = [0.0 for i in range(len(C))]
    class_index = len(d[0])-1
    for i in range(len(train)):
        train_res[i] = (train[i][class_index] > 1)# and train[i][class_index] < 16)
        train[i][class_index] = 0        
        C_res[i] = (C[i][class_index]> 1)# and C[i][class_index] < 16)
        C[i][class_index] = 0
    
    pes.fit(train,train_res)
    output = pes.predict(C)
    (falsepr, truepr, thr) = roc_curve(C_res, output, 1)
    area = auc(falsepr, truepr)
    output = pes.score(C,C_res)
    return (output, area)
开发者ID:ks6g10,项目名称:classify,代码行数:24,代码来源:run.py

示例10: StandardScaler

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
#!/usr/bin/env python
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron
import numpy as np

from titanic import answer

if __name__ == '__main__':
    train_data = np.genfromtxt('perceptron-train.csv', delimiter=',')
    test_data = np.genfromtxt('perceptron-test.csv', delimiter=',')

    X_train_data = features = train_data[:, 1:]
    Y_train_data = train_data[:, 0]
    X_test_data = features = test_data[:, 1:]
    Y_test_data = test_data[:, 0]

    scaler = StandardScaler()
    clf = Perceptron(random_state=241)

    clf.fit(X_train_data, Y_train_data)
    scores = clf.score(X_test_data, Y_test_data)
    print(scores.mean())

    X_train_data_scaled = scaler.fit_transform(X_train_data)
    X_test_data_scaled = scaler.transform(X_test_data)

    clf.fit(X_train_data_scaled, Y_train_data)
    scaled_scores = clf.score(X_test_data_scaled, Y_test_data)
    print(scores.mean(), scaled_scores.mean())
    answer(scaled_scores.mean() - scores.mean(), 'feature_normalization.txt')
开发者ID:ANtlord,项目名称:ml-study,代码行数:32,代码来源:feature_normalization.py

示例11: Perceptron

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
X_test = pd.read_csv('perceptron-test.csv', header=None)

y = X_train[X_train.columns[0]]
X_train = X_train.drop(X_train.columns[0], axis=1, inplace=False)
print X_train


clf = Perceptron(random_state=42)
clf.fit(X_train, y)

print clf.predict(X_train)

# 0.34
y1 = X_test[X_test.columns[0]]
X_test = X_test.drop(X_test.columns[0], axis=1, inplace=False)
score = clf.score(X_test, y1)

print score

X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

clf = Perceptron(random_state=42)
clf.fit(X_train_scaled, y)

# 0.89
score_scaled = clf.score(X_test_scaled, y1)
print score_scaled

print (score_scaled - score)
开发者ID:rema7,项目名称:coursera,代码行数:32,代码来源:lesson2.2.py

示例12: main

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
def main( argv ):

	try:

		input_csv_filename 	  = argv[ 1 ]
		output_csv_filename   = argv[ 2 ]

	except IndexError:
		print( "Error, usage: \"python3 {} <CSV> <output_CSV>\"".format( argv[ 0 ] ) ) 
		return


	''' Cross validation parameters '''
	split_count = 3
	
	import crossValidationGenerator as cvg

	cvg.splitData( input_csv_filename, split_count )

	Y_results 		= getY( input_csv_filename )
	RF_predictions  = []
	P_predictions   = []
	KNN_predictions = []

	for set_idx in range( split_count ):

		print( "\n{} Starting split {}:".format( str( datetime.now() ), set_idx + 1 ) )

		train_filename = "train_split_{}.csv".format( set_idx )
		test_filename  =  "test_split_{}.csv".format( set_idx )


		# Read training data
		train_df = pd.read_csv( train_filename )
		
		X = train_df.ix[:,0:-1]
		Y = train_df.ix[:,-1]


		# Read training data
		test_df = pd.read_csv( test_filename )
		
		test_X = test_df.ix[:,0:-1]
		test_Y = test_df.ix[:,-1]



		''' Random Forest '''
		from sklearn.ensemble import RandomForestClassifier
	
		# Hyper Parameters
		n_estimators = 60


		RF_classifier = RandomForestClassifier (
			n_estimators = n_estimators
		)

		print( "{} | Training Random Forest".format( str( datetime.now() ) ) )
		RF_classifier.fit( X, Y )

		RF_pred = RF_classifier.predict( test_X )
		RF_predictions.extend( RF_pred )

		print( "{} > Random forest completed for split {} with accuracy {}%\n".format( str( datetime.now() ), set_idx + 1, 100 * RF_classifier.score( test_X, test_Y ) ) )



		''' Perceptron '''
		from sklearn.linear_model import Perceptron

		# Hyper Parameters
		alpha  = 0.0001
		n_iter = 20

		
		P_classifier = Perceptron (
			alpha = alpha,
			n_iter = n_iter
		)

		print( "{} | Training Perceptron".format( str( datetime.now() ) ) )
		P_classifier.fit( X, Y )

		P_pred = P_classifier.predict( test_X )
		P_predictions.extend( P_pred )

		print( "{} > Perceptron completed for split {} with accuracy {}%\n".format( str( datetime.now() ), set_idx + 1, 100 * P_classifier.score( test_X, test_Y ) ) )



		''' K-NN '''
		from sklearn.neighbors import KNeighborsClassifier

		# Hyper Parameters
		n_neighbors = 20

		KNN_classifier = KNeighborsClassifier (
			n_neighbors = n_neighbors
		)
#.........这里部分代码省略.........
开发者ID:CKPalk,项目名称:MachineLearning,代码行数:103,代码来源:stacking_predictions.py

示例13: test_perceptron_accuracy

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
def test_perceptron_accuracy():
    for data in (X, X_csr):
        clf = Perceptron(max_iter=100, tol=None, shuffle=False)
        clf.fit(data, y)
        score = clf.score(data, y)
        assert_greater(score, 0.7)
开发者ID:MartinThoma,项目名称:scikit-learn,代码行数:8,代码来源:test_perceptron.py

示例14:

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
knn=KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train,Y_train)
Y_pred=knn.predict(X_test)
acc_knn=round(knn.score(X_train,Y_train)*100,2)
#print(acc_knn)

gaussian=GaussianNB()
gaussian.fit(X_train,Y_train)
Y_pred=gaussian.predict(X_test)
acc_gaussian=round(gaussian.score(X_train,Y_train)*100,2)
#print(acc_gaussian)

perceptron=Perceptron()
perceptron.fit(X_train,Y_train)
Y_pred=perceptron.predict(X_test)
acc_perceptron=round(perceptron.score(X_train,Y_train)*100,2)
#print(acc_perceptron)

linear_svc=LinearSVC()
linear_svc.fit(X_train,Y_train)
Y_pred=linear_svc.predict(X_test)
acc_linear_svc=round(linear_svc.score(X_train,Y_train)*100,2)
#print(acc_linear_svc)

sgd=SGDClassifier()
sgd.fit(X_train,Y_train)
Y_pred=sgd.predict(X_test)
acc_sgd=round(sgd.score(X_train,Y_train)*100,2)
#print(acc_sgd)

decision_tree=DecisionTreeClassifier()
开发者ID:ajithvallabai,项目名称:kaggle_titanic,代码行数:33,代码来源:titanic.py

示例15: Perceptron

# 需要导入模块: from sklearn.linear_model import Perceptron [as 别名]
# 或者: from sklearn.linear_model.Perceptron import score [as 别名]
import numpy as np
from sklearn.linear_model import Perceptron
from sklearn.preprocessing import StandardScaler
import pandas as pd
data_test = pd.read_csv('C:/temp/machine learning/courseraYa/perceptron-test.csv', header=0)
data_train = pd.read_csv('C:/temp/machine learning/courseraYa/perceptron-train.csv', header=0)
y_train = data_train.iloc[:,0] #classes / target values
X_train = data_train.iloc[:,1:] #feaches

y_test = data_test.iloc[:,0] #classes / target values
X_test = data_test.iloc[:,1:] #feaches

clf = Perceptron(random_state=241, shuffle = True)
clf.fit(X_train, y_train)
#predictions = clf.predict(X_test)
acur = clf.score(X_test,y_test)
print(acur)

scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

clf_scaled = Perceptron(random_state=241, shuffle = True)
clf_scaled.fit(X_train_scaled, y_train)
#predictions = clf.predict(X_test)
acur_scaled = clf_scaled.score(X_test_scaled,y_test)
print(acur_scaled)
开发者ID:samoubiza,项目名称:ML,代码行数:29,代码来源:Perceptron.py


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