简体   繁体   English

如何在scikit-learn中的感知器中实现“与”功能

[英]How to implement 'And' function in perceptron in scikit-learn

I am a newbie to machine learning and scikit-learn. 我是机器学习和scikit学习的新手。 I was trying to implement 'and' function in scikit-learn and written a small code as below: 我试图在scikit-learn中实现“和”功能,并编写了一个小代码,如下所示:

import pandas as pd
from pandas import Series,DataFrame
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split

df = DataFrame([[0,0,0],[0,1,0],[1,0,0],[1,1,1]],columns=list('abc'))
X = df[['a','b']]
y=df['c']

scalar_model = StandardScaler()

train_test_split =X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

scalar_model = StandardScaler()

scalar_model.fit(X_train)

X_train_std = scalar_model.transform(X_train)
X_test_std = scalar_model.transform(X_test)

from sklearn.linear_model import Perceptron

#perceptron initialization
ppn = Perceptron(n_iter = 100,eta0=0.1,random_state=0)

#fit the model with standardized data
ppn.fit(X_train_std,y_train)

#make predications
y_pred = ppn.predict(X_test_std)

from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred) * 100
error = (1-accuracy_score(y_test, y_pred))*100


print("Accuracy: {} %".format(accuracy))
print("error: {} %".format(error))

After running the code I am getting the following results: 运行代码后,我得到以下结果:

  Accuracy: 0.0 %
    error: 100.0 %

Here are my questions : 这是我的问题:

  1. why is the perceptron not training after 100 iterations. 为什么感知器在100次迭代后不训练。
  2. I have read from the manual that if weights are not assigned to the features they are automatically assigned. 我从手册中了解到,如果未将权重分配给功能,则会自动分配权重。
  3. If i want to assign the weights to the features randomly in the range of 0 and 1 How can I do that. 如果我想在0和1的范围内为特征随机分配权重,该怎么做。

By splitting your already tiny data set - you don't give Perceptron a chance to learn properly. 通过分割已经很小的数据集-您不会给Perceptron一个适当学习的机会。 Beside that in this case it doesn't make any sense to scale input data set. 除此之外,在这种情况下,缩放输入数据集没有任何意义。

Demo: 演示:

In [257]: ppn.fit(X,y)
Out[257]:
Perceptron(alpha=0.0001, class_weight=None, eta0=0.1, fit_intercept=True,
      max_iter=None, n_iter=100, n_jobs=1, penalty=None, random_state=0,
      shuffle=True, tol=None, verbose=0, warm_start=False)

In [258]: ppn.predict([[1,1], [0,1]])
Out[258]: array([1, 0], dtype=int64)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM