##载入相关模块
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from collections import Counter
##载入数据
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['label'] = iris.target
df.columns = ['sepal length', 'sepal width', 'petal length', 'petal width', 'label']
##提取特征和样品
#取前面100个数,第一列、第二列和最后一列
data = np.array(df.iloc[:100, [0, 1, -1]])
#最后一个特征作为标签,其他的作为特征
X, y = data[:,:-1], data[:,-1]
#取80%作为训练,20%作为测试
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
载入sklearn中的逻辑回归模块
from sklearn.linear_model import LogisticRegression
模型训练
clf = LogisticRegression(max_iter=200)
clf.fit(X_train, y_train)
输出模型参数
print(clf.coef_, clf.intercept_)
验证算法精度
clf.score(X_test, y_test)
绘制图
x_ponits = np.arange(4, 8)
y_ = -(clf.coef_[0][0]*x_ponits + clf.intercept_)/clf.coef_[0][1]
plt.plot(x_ponits, y_)
plt.plot(X[:50, 0], X[:50, 1], 'bo', color='blue', label='0')
plt.plot(X[50:, 0], X[50:, 1], 'bo', color='orange', label='1')
plt.xlabel('sepal length')
plt.ylabel('sepal width')
plt.legend()