【学习笔记】人民邮电出版社《Python机器学习》学习记录。
以下程序调用了机器学习的第三方库scikit-learn,使用该库,方便简洁。
线性回归、逻辑回归、线性分类器的关系:线性回归是回归;逻辑回归是分类,逻辑回归基于线性回归进行分类;线性分类器是以超平面为决策边界的分类器,与线性回归没有必然的关系,线性分类器包括逻辑回归、感知机、SVM(线性核函数)。
import pandas
from pylab import rcParams
rcParams['figure.figsize'] = 10,8
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn import preprocessing
from sklearn import linear_model
import warnings
warnings.filterwarnings('ignore')
titanic_data = pandas.read_csv('E:\\titanic_data.csv') #加载数据,泰坦尼克号数据,标签是幸存与否
titanic_data = titanic_data[['Survived', 'Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Embarked', 'Fare']]
print(titanic_data) #(891, 8)共891条数据、8个属性
#---------特征工程,空值处理----------
print(titanic_data.isnull().any()) #年龄、登船地点有空值,需要进行特征工程
print(titanic_data.isnull().sum()) #空值数量,年龄177个空值;登船地点2个空值
#空值处理策略:用平均值替换空值
titanic_data['Age'].fillna((titanic_data['Age'].mean()), inplace=True)
#空值处理策略:放弃这两条记录,不会对算法有大的影响
titanic_data.dropna(inplace=True)
#---------分割训练数据和测试数据--------
titanic_data_X = titanic_data[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Embarked', 'Fare']]
titanic_data_Y = titanic_data[['Survived']] #类型仍然为DataFrame
x_train, x_test, y_train, y_test = train_test_split(titanic_data_X, titanic_data_Y, test_size=0.2)
#----------特征工程,年龄、票价进行标准化处理-------------
age_scaler = StandardScaler() #Z-Score标准化,均值0,方差1
age_scaler.fit(pandas.DataFrame((x_train['Age']))) #拟合
x_train[['Age']] = age_scaler.transform(x_train[['Age']]) #进行转化
fare_scaler = StandardScaler()
fare_scaler.fit(pandas.DataFrame((x_train['Fare'])))
x_train[['Fare']] = fare_scaler.transform(x_train[['Fare']])
x_train['Sex'] = x_train['Sex'].map({'female': 0, 'male':1}) #性别特征直接转化成0和1
embarked_encoder = preprocessing.LabelEncoder() #标准化标签,标签值转化成(0,1,2)
embarked_encoder.fit(pandas.DataFrame(x_train['Embarked']))
x_train[['Embarked']] = embarked_encoder.transform(x_train[['Embarked']])
#---------相关性分析,删除相关性比较高的列--------
#seaborn.heatmap(x_train.corr()) #协方差热点图
print(x_train.corr()) #打印特征值的协方差矩阵
del x_train['Pclass'] #删除相关性很高的列
x_train_original = x_train
print(x_train)
print(y_train)
x_train = x_train.values
y_train = y_train.values
print(type(y_train))
logRegression = linear_model.LogisticRegression()
logRegression.fit(x_train, y_train)
print('系数:\n', logRegression.coef_)
print('截距:\n', logRegression.intercept_)
#----------对x_test进行同样的特征过程-----------------------
x_test[['Age']] = age_scaler.transform(x_test[['Age']]) #年龄进行转化
x_test[['Fare']] = fare_scaler.transform(x_test[['Fare']])
x_test['Sex'] = x_test['Sex'].map({'female': 0, 'male':1}) #性别特征直接转化成0和1
embarked_encoder = preprocessing.LabelEncoder() #标准化标签,标签值转化成(0,1,2)
embarked_encoder.fit(pandas.DataFrame(x_test['Embarked']))
x_test[['Embarked']] = embarked_encoder.transform(x_test[['Embarked']])
del x_test['Pclass'] #删除相关性很高的列
y_pred = logRegression.predict(x_test) #分类结果
print(y_pred)