菜鸟小笔记————sklearn.linear_model里的线性回归和逻辑二分类小实验

from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import SGDRegressor, LinearRegression, LogisticRegression
from sklearn.metrics import mean_squared_error, classification_report

import numpy as np
def linearreg():
    #obtain data
    data = load_boston()
    #split
    x_train, x_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.25)
    # print(x_train.shape)
    #target 特征值和目标值矩阵形状不一样,创建两个
    std_x = StandardScaler()
    x_train = std_x.fit_transform(x_train.reshape(-1,1))
    x_test = std_x.fit_transform(x_test.reshape(-1, 1))
    std_y = StandardScaler()
    y_train = std_y.fit_transform(y_train.reshape(-1,1))
    y_test = std_y.fit_transform(y_test.reshape(-1,1))
    #转换器、estimator要求数据必须为二维形状,因此使用reshape更改形状
    #reshape(a, b) a行b列, reshape(c,-1) 只能矩阵/数组, c行,d列(-1表示自动计算)
    #
    #
    #estimator
    #正规方程
    lr = LinearRegression()
    print(x_train.shape, y_train.shape, x_test.shape)
    lr.fit(x_train.reshape(379,13), y_train)
    print(lr.coef_)
    y_predict = std_y.inverse_transform(lr.predict(x_test.reshape(-1,13)))
    print(y_predict)
    #梯度下降
    sgd = SGDRegressor()
    sgd.fit(x_train.reshape(379,13), y_train)
    print(sgd.coef_)
    y_sgd_predict = std_y.inverse_transform(sgd.predict(x_test.reshape(-1,13)))
    print(y_sgd_predict)
    print(y_predict.shape, y_sgd_predict.shape)
    error1 = mean_squared_error(std_y.inverse_transform(y_test), y_predict)
    error2 = mean_squared_error(std_y.inverse_transform(y_test), y_sgd_predict)
    print(error1, error2
    return None
import pandas as pd
import numpy as np
def mylogistic():
    #读取数据
    column = ['Sample code number','Clump Thickness', 'Uniformity of Cell Size','Uniformity of Cell Shape','Marginal Adhesion', 'Single Epithelial Cell Size','Bare Nuclei','Bland Chromatin','Normal Nucleoli','Mitoses','Class']
    data = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data", names=column)
    print(data)
    #缺失值处理
    print(data.isnull().sum())
    data = data.replace(to_replace='?', value=np.nan)
    data = data.dropna()
    #数据分割
    x_train, x_test, y_train, y_test = train_test_split(data[column[1:10]], data[column[10]], test_size=0.25)
    #标准化处理
    std = StandardScaler()
    x_test = std.fit_transform(x_test)
    #模型拟合
    lr = LogisticRegression(C=1.0)
    lr.fit(x_train, y_train)
    print(lr.coef_)
    print(lr.score())
    print(classification_report(y_train, y_test, labels=[2, 4], target_names=["良性", "恶性"]))


    return None
if __name__ == "__main__":
    # linearreg()
    mylogistic()
上一篇:线性回归(Linear Regression)


下一篇:jquey中swing与linear动画切换属相: