# Perceptron Implementation in Python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.01, n_iterations=1000):
self.learning_rate = learning_rate
self.n_iterations = n_iterations
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
# Initialize weights and bias
self.weights = np.zeros(n_features)
self.bias = 0
# Convert labels to 1 and -1 for binary classification
y_ = np.where(y <= 0, -1, 1)
# Training loop
for _ in range(self.n_iterations):
for idx, x_i in enumerate(X):
linear_output = np.dot(x_i, self.weights) + self.bias
prediction = np.sign(linear_output)
# Update rule
update = self.learning_rate * (y_[idx] - prediction)
self.weights += update * x_i
self.bias += update
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias
return np.sign(linear_output)
# Example usage:
if __name__ == "__main__":
# Sample data
X = np.array([[2.7810836, 2.550537003],
[1.465489372, 2.362125076],
[3.396561688, 4.400293529],
[1.38807019, 1.850220317]])
y = np.array([0, 0, 1, 1])
# Create and train the perceptron
perceptron = Perceptron(learning_rate=0.01, n_iterations=1000)
perceptron.fit(X, y)
# Make predictions
predictions = perceptron.predict(X)
print("Predictions:", predictions)
fit 和 predict。__init__ 方法中,我们设置了学习率 (learning_rate) 和迭代次数 (n_iterations)。同时,权重 (weights) 和偏置 (bias) 被初始化为 None。fit):predict):根据输入数据计算线性输出,并使用符号函数 (np.sign) 得到最终预测结果。希望这段代码和解释对你有帮助!
上一篇:python卸载第三方库
下一篇:python串口发送16进制数据
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站