<jupyter_start><jupyter_text>感知机的朴素实现<jupyter_code>import numpy as np

class Perceptron:
    def __init__(self):
        self._w = self._b = None
        
    def fit(self, x, y, lr=0.01, epoch=1000):
        x, y = np.asarray(x, np.float32), np.asarray(y, np.float32)
        self._w = np.zeros(x.shape[1])
        self._b = 0.
        for _ in range(epoch):
            err = -y * self.predict(x, True)
            idx = np.argmax(err)
            if err[idx] < 0:
                break
            delta = lr * y[idx]
            self._w += delta * x[idx]
            self._b += delta
    
    def predict(self, x, raw=False):
        x = np.asarray(x, np.float32)
        y_pred = x.dot(self._w) + self._b
        if raw:
            return y_pred
        return np.sign(y_pred).astype(np.float32)<jupyter_output><empty_output><jupyter_text>测试<jupyter_code>from Util import gen_two_clusters

x, y = gen_two_clusters()
perceptron = Perceptron()
perceptron.fit(x, y)
print("准确率：{:8.6} %".format((perceptron.predict(x) == y).mean() * 100))<jupyter_output>准确率：    99.0 %<jupyter_text>可视化<jupyter_code>from Util import visualize2d

visualize2d(perceptron, x, y)
visualize2d(perceptron, x, y, True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13947797716150082, 'fraction_numerical': 0.02365415986949429, 'mean_word_length': 2.5360230547550433, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '554868', 'license': 'MIT', 'n_tokens_mistral': 514, 'n_tokens_neox': 496, 'n_words': 90, 'path': 'Notebooks/SVM/zh-cn/Perceptron.ipynb', 'repo_name': 'busyyang/MachineLearning', 'size': '1226'}