import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt # 加载 iris 数据 iris = load_iris() # 只选取两个特征和两个类别进行二分类 X = iris.data[(iris.target==0)|(iris.target==1), :2] y = iris.target[(iris.target==0)|(iris.target==1)] # 将标签转化为 0 和 1 y[y==0] = -1 # 将数据集分为训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 实现逻辑回归算法 class LogisticRegression: def __init__(self, lr=0.01, num_iter=100000, fit_intercept=True, verbose=False): self.lr = lr self.num_iter = num_iter self.fit_intercept = fit_intercept self.verbose = verbose def __add_intercept(self, X): intercept = np.ones((X.shape[0], 1)) return np.concatenate((intercept, X), axis=1) def __sigmoid(self, z): return 1 / (1 + np.exp(-z)) def __loss(self, h, y): return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean() def fit(self, X, y): if self.fit_intercept: X = self.__add_intercept(X) # 初始化参数 self.theta = np.zeros(X.shape[1]) for i in range(self.num_iter): # 计算梯度 z = np.dot(X, self.theta) h = self.__sigmoid(z) gradient = np.dot(X.T, (h - y)) / y.size # 更新参数 self.theta -= self.lr * gradient # 打印损失函数 if self.verbose and i % 10000 == 0: z = np.dot(X, self.theta) h = self.__sigmoid(z) loss = self.__loss(h, y) print(f"Loss: {loss} \t") def predict_prob(self, X): if self.fit_intercept: X = self.__add_intercept(X) return self.__sigmoid(np.dot(X, self.theta)) def predict(self, X, threshold=0.5): return self.predict_prob(X) >= threshold # 训练模型 model = LogisticRegressio
时间: 2023-12-17 07:04:31 浏览: 45
n()
model.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = model.predict(X_test)
# 计算准确率
accuracy = np.sum(y_pred == y_test) / y_test.shape[0]
print(f"Accuracy: {accuracy}")
# 可视化
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred)
plt.show()
请问这段代码实现了什么功能?
相关问题
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split啥意思
这些程序是用来实现一个基于鸢尾花数据集的机器学习任务。具体来说,该程序使用load_iris函数加载鸢尾花数据集,并使用train_test_split函数将数据集随机划分为训练集和测试集,以便进行模型训练和评估。另外,还使用了numpy和matplotlib.pyplot库进行数据处理和可视化。但是,该程序并没有使用任何算法或模型来进行分类或回归任务。
import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sklearn.datasets import load_boston from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn import metrics from sklearn import preprocessing
你给出的是 Python 的代码,我看到你正在使用一些流行的 Python 库,如 NumPy、matplotlib、pandas 和 seaborn,以及一些机器学习相关的库,如 scikit-learn。这些库都是非常有用的,能够帮助你进行数据分析、可视化和建模。在这段代码中,你还导入了波士顿房价数据集(load_boston),并使用 train_test_split 函数将数据集拆分为训练集和测试集。然后,你使用线性回归模型(LinearRegression)对数据进行拟合,并使用 metrics 库中的一些函数来评估模型的性能。最后,你使用 preprocessing 库对数据进行标准化处理。这些步骤都是非常常见的机器学习流程中的一部分,用于数据预处理、建模和评估。