zoukankan      html  css  js  c++  java
  • 小象机器学习(邹博老师)学习笔记

    一、线性回归

    1. 基本线性回归

    from sklearn.model_selection import train_test_split
    from sklearn.linear_model import LinearRegression
    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
    # print x_train, y_train
    linreg = LinearRegression()
    model = linreg.fit(x_train, y_train)
    # model
    # linreg.coef_
    # linreg.intercept_
    
    y_hat = linreg.predict(np.array(x_test))
    mse = np.average((y_hat - np.array(y_test)) ** 2)  # Mean Squared Error
    rmse = np.sqrt(mse)  # Root Mean Squared Error
    
    t = np.arange(len(x_test))
    plt.plot(t, y_test, 'r-', linewidth=2, label='Test')
    plt.plot(t, y_hat, 'g-', linewidth=2, label='Predict')

     2. CV

    from sklearn.model_selection import train_test_split
    from sklearn.linear_model import Lasso, Ridge
    from sklearn.model_selection import GridSearchCV
    x_train, x_test, y_train, y_test = train_test_split(x, y, random_state=1)
    # print x_train, y_train
    model = Lasso()
    # model = Ridge()
    alpha_can = np.logspace(-3, 2, 10)
    lasso_model = GridSearchCV(model, param_grid={'alpha': alpha_can}, cv=5)
    lasso_model.fit(x, y)
    # lasso_model.best_params_
    # pd.DataFrame(lasso_model.cv_results_)

     3. pipline和meshgrid画图(鸢尾花数据)

    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)   # 测试点
    
    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()
  • 相关阅读:
    C与设计模式---观察者模式
    如何在嵌入式产品中应用键值存储数据库
    Matlab 常用函数小结
    【Qt点滴】游戏2048
    经典ICP算法的问题
    基于矩阵分解的推荐系统实例
    【Qt点滴】UDP协议实例:简易广播实现
    【Qt点滴】:获取本机网络信息
    51单片机:光立方
    STM32单片机:四旋翼飞行器的飞控实现
  • 原文地址:https://www.cnblogs.com/figo-studypath/p/10384652.html
Copyright © 2011-2022 走看看