使用 Python 原生代码复现,多元逻辑回归,并封装成实体类调用自定义函数
时间: 2024-04-12 22:29:53 浏览: 12
当然可以!下面是一个使用Python原生代码复现多元逻辑回归的示例,并封装成实体类以便调用自定义函数的方法:
```python
import numpy as np
class MultinomialLogisticRegression:
def __init__(self, num_classes):
self.num_classes = num_classes
self.weights = None
def train(self, X, y, learning_rate=0.01, num_iterations=1000):
num_samples, num_features = X.shape
self.weights = np.zeros((num_features, self.num_classes))
for i in range(num_iterations):
scores = np.dot(X, self.weights)
probabilities = self.softmax(scores)
error = probabilities - y
gradient = np.dot(X.T, error)
self.weights -= learning_rate * gradient
def predict(self, X):
scores = np.dot(X, self.weights)
probabilities = self.softmax(scores)
return np.argmax(probabilities, axis=1)
def softmax(self, x):
exps = np.exp(x - np.max(x, axis=1, keepdims=True))
return exps / np.sum(exps, axis=1, keepdims=True)
# 示例用法
X_train = np.array([[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]])
y_train = np.array([0, 0, 0, 1, 1, 1])
lr = MultinomialLogisticRegression(num_classes=2)
lr.train(X_train, y_train)
X_test = np.array([[1, 1], [5, 5]])
predictions = lr.predict(X_test)
print(predictions)
```
在上面的示例中,我们定义了一个`MultinomialLogisticRegression`类,该类包含了训练和预测函数。`train`函数用于训练模型,`predict`函数用于预测新样本的类别。
你可以根据自己的需求修改和扩展这个示例,例如添加正则化项、改变学习率等。
希望对你有所帮助!如果有任何疑问,请随时问我。