逻辑斯谛回归python 实现鸢尾花分类不导库
时间: 2023-06-12 15:02:29 浏览: 102
好的,我会为您解答。针对您的问题,逻辑斯谛回归实现鸢尾花分类的代码如下:
```python
import csv
# 读取数据
with open('iris.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
rows = [row for row in reader]
x_data = [] # 特征值
y_data = [] # 预测目标
# 将数据转换为数值类型
for row in rows:
x_data.append(list(map(float, row[:-1])))
y_data.append([int(row[-1])])
# 定义模型参数
theta = [[0], [0], [0], [0], [0]]
# 定义sigmoid函数
import math
def sigmoid(z):
return 1 / (1 + math.exp(-z))
# 计算模型预测值
def predict(x, theta):
z = sum([x[i] * theta[i] for i in range(len(x))])
return sigmoid(z)
# 定义模型损失函数
def cost(x_data, y_data, theta):
m = len(x_data)
total_cost = 0
for i in range(m):
h = predict(x_data[i], theta)
total_cost += (-y_data[i][0] * math.log(h) - (1 - y_data[i][0]) * math.log(1 - h))
return total_cost / m
# 计算模型梯度值
def gradient(x_data, y_data, theta):
m = len(x_data)
grad = [0] * len(theta)
for i in range(m):
h = predict(x_data[i], theta)
for j in range(len(grad)):
grad[j] += (h - y_data[i][0]) * x_data[i][j]
for j in range(len(grad)):
grad[j] /= m
return grad
# 模型训练
alpha = 0.1
iter_num = 1000
for i in range(iter_num):
grad = gradient(x_data, y_data, theta)
for j in range(len(theta)):
theta[j] -= alpha * grad[j]
print('iteration: %d cost: %f' % (i, cost(x_data, y_data, theta)))
# 输出模型参数
print('theta:', theta)
```
注:需准备一个名为 iris.csv 的数据文件,示例数据如下:
```
5.1,3.5,1.4,0.2,0
4.9,3.0,1.4,0.2,0
4.7,3.2,1.3,0.2,0
4.6,3.1,1.5,0.2,0
```
该代码实现了逻辑斯谛回归模型对鸢尾花数据集进行分类,不使用任何第三方库。
阅读全文