机器学习笔记08-----回归2
1.线性回归补充
图中1,2,3表示拟合的函数的最高次项的阶数。
机器学习的主要挑战是我们的算法必须能够在先前未观测的新输入上表现良好,而不只是在训练集上表现良好。在先前未观测到的输入上表现良好的能力被称为泛
化(generalization)。
通常,我们度量模型在训练集中分出来的测试集(test set)样本上的性能,来评估机器学习模型的泛化误差。
2.logistic回归
利用logistic回归可以做分类。
3.代码示例
#!/usr/bin/python # -*- coding:utf-8 -*- import numpy as np from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt import matplotlib as mpl from sklearn import preprocessing import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline def iris_type(s): it = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} return it[s] if __name__ == "__main__": path = u'8.iris.data' # 数据文件路径 # # 使用sklearn的数据预处理 df = pd.read_csv(path, header=0) x = df.values[:, :-1] y = df.values[:, -1] print('x = \n', x) print('y = \n', y) le = preprocessing.LabelEncoder() le.fit(['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']) print(le.classes_) y = le.transform(y) print('Last Version, y = \n', y) # # 为了可视化,仅使用前两列特征 x = x[:, :2] # print(x) print(y) # # x = StandardScaler().fit_transform(x) # lr = LogisticRegression() # Logistic回归模型 # lr.fit(x, y.ravel()) # 根据数据[x,y],计算回归参数 # # 等价形式 lr = Pipeline([('sc', StandardScaler()), ('clf', LogisticRegression()) ]) lr.fit(x, y.ravel()) # 画图 N, M = 500, 500 # 横纵各采样多少个值 x1_min, x1_max = x[:, 0].min(), x[:, 0].max() # 第0列的范围 x2_min, x2_max = x[:, 1].min(), x[:, 1].max() # 第1列的范围 t1 = np.linspace(x1_min, x1_max, N) t2 = np.linspace(x2_min, x2_max, M) x1, x2 = np.meshgrid(t1, t2) # 生成网格采样点 x_test = np.stack((x1.flat, x2.flat), axis=1) # 测试点 # 无意义,只是为了凑另外两个维度 # x3 = np.ones(x1.size) * np.average(x[:, 2]) # x4 = np.ones(x1.size) * np.average(x[:, 3]) # x_test = np.stack((x1.flat, x2.flat, x3, x4), axis=1) # 测试点 cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FF8080', '#A0A0FF']) cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b']) y_hat = lr.predict(x_test) # 预测值 y_hat = y_hat.reshape(x1.shape) # 使之与输入的形状相同 plt.pcolormesh(x1, x2, y_hat, cmap=cm_light) # 预测值的显示 plt.scatter(x[:, 0], x[:, 1], c=y, edgecolors='k', s=50, cmap=cm_dark) # 样本的显示 plt.xlabel('petal length') plt.ylabel('petal width') plt.xlim(x1_min, x1_max) plt.ylim(x2_min, x2_max) plt.grid() plt.savefig('2.png') plt.show() # 训练集上的预测结果 y_hat = lr.predict(x) y = y.reshape(-1) result = y_hat == y print(y_hat) print(result) acc = np.mean(result) print('准确度: %.2f%%' % (100 * acc))
效果图:
分类:
机器学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2019-04-10 009 Android Fragment实现微信底部导航
2019-04-10 008 Android Fragment原理及应用
2019-04-10 Navicat使用笔记03---Navicat 导出sql文件和导入sql文件