这里是用的鸢尾花数据集进行的运算,然后大家可以修改一下路径
首先是得到参数的代码
import numpy as np
import pandas as pd
def sigmod(x: np.ndarray):
return 1 / (1 + np.exp(-x))
class Net:
def __init__(self, in_feature: int):
self.weights = np.random.rand(in_feature)
self.bias = np.random.rand(1)
self.alpha = 0.05
def forward(self, x: np.ndarray) -> np.ndarray:
return sigmod(x.dot(self.weights) + self.bias)
def grad_w(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:
M, N = x.shape
gw = np.array([sum((self.forward(x[i]) - y[i]) * x[i][j] for i in range(M)) / M for j in range(N)])
return gw[:, 0]
def grad_b(self, x: np.ndarray, y: np.ndarray) -> np.ndarray:
return (self.forward(x) - y).mean()
def update(self, x: np.ndarray, y: np.ndarray):
self.weights -= self.alpha * self.grad_w(x, y)
self.bias -= self.alpha * self.grad_b(x, y)
if __name__ == '__main__':
net = Net(4)
epochs = 100
data = pd.read_excel(r"C:/Users/wxc/PycharmProjects/pythonProject4/机器学习/回归/逻辑回归/train.xlsx")
x = np.array(data.iloc[:, 1:5])
y = np.array(data.iloc[:, 6])
for epoch in range(epochs):
net.update(x, y)
weights = net.weights
bias = net.bias
print('权重', weights)
print('偏置', bias)
得到参数之后可以在进行分类,这里我进行的二分类
import numpy as np
import pandas as pd
data = pd.read_excel(r"C:/Users/wxc/PycharmProjects/pythonProject4/机器学习/回归/逻辑回归/test.xlsx")
x = data.iloc[:, 1:5]
weights = [-0.4095052, -0.70925044, 1.41457683, 0.29889677]
bias = [0.29006966]
z1 = np.dot(x, weights) + bias
sigmoid = 1 / (1 + np.exp(-z1))
for i in sigmoid:
if i > 0.5:
y = 1
else:
y = 0
print(y)
就可以输出了