使用神经网络预测红酒质量
看看这个数据集是不是多分类问题呢?
使用seaborn看看情况。
代码
# -*- coding: utf-8 -*-
# 所需数据请在这里下载:https://video.mugglecode.com/wine_quality.csv
"""
任务:红酒质量预测
"""
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.neural_network import MLPClassifier
DATA_FILE = './data/wine_quality.csv'
def main():
"""
主函数
"""
wine_data = pd.read_csv(DATA_FILE)
# sns.countplot(data=wine_data, x='quality')
# plt.show()
# 数据预处理
wine_data.loc[wine_data['quality'] <= 5, 'quality'] = 0
wine_data.loc[wine_data['quality'] >= 1, 'quality'] = 1
# sns.countplot(data=wine_data, x='quality')
# plt.show()
# 所有列名
all_cols = wine_data.columns.tolist()
# 特征列名称
feat_cols = all_cols[:-1]
# 特征
X = wine_data[feat_cols].values
# 标签
y = wine_data['quality'].values
# 数据集分割
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=10)
# 特征归一化
scaler = MinMaxScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 建立模型
mlp = MLPClassifier(hidden_layer_sizes=(50, 50, 100), activation='relu')
mlp.fit(X_train_scaled, y_train)
accuracy = mlp.score(X_test_scaled, y_test)
print('神经网络模型的预测准确率:{:.2f}%'.format(accuracy * 100))
if __name__ == '__main__':
main()
使用决策树识别鸢尾花
# -*- coding: utf-8 -*-
# 所需数据集请下载:https://video.mugglecode.com/Iris.csv
"""
任务:鸢尾花识别
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
DATA_FILE = './data/Iris.csv'
CATEGRORY_LABEL_DICT = {
'Iris-setosa': 0, # 山鸢尾
'Iris-versicolor': 1, # 变色鸢尾
'Iris-virginica': 2 # 维吉尼亚鸢尾
}
# 使用的特征列
FEAT_COLS = ['SepalLengthCm', 'SepalWidthCm', 'PetalLengthCm', 'PetalWidthCm']
def main():
"""
主函数
"""
iris_data = pd.read_csv(DATA_FILE, index_col='Id')
# 添加label一列作为预测标签
iris_data['Label'] = iris_data['Species'].apply(lambda category_name: CATEGRORY_LABEL_DICT[category_name])
# 4列花的属性作为样本特征
X = iris_data[FEAT_COLS].values
# label列为样本标签
y = iris_data['Label'].values
# 将原始数据集拆分成训练集和测试集,测试集占总样本数的1/3
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=10)
# 构建模型
max_depth_list = [2, 3, 4] #指定决策树的深度
for max_depth in max_depth_list:
dt_model = DecisionTreeClassifier(max_depth=max_depth)
dt_model.fit(X_train, y_train)
train_acc = dt_model.score(X_train, y_train)
test_acc = dt_model.score(X_test, y_test)
print('max_depth', max_depth)
print('训练集上的准确率:{:.2f}%'.format(train_acc * 100))
print('测试集上的准确率:{:.2f}%'.format(test_acc * 100))
print()
if __name__ == '__main__':
main()
如果决策树选择得太深,会造成过拟合
max_depth 2
训练集上的准确率:97.00%
测试集上的准确率:92.00%
max_depth 3
训练集上的准确率:98.00%
测试集上的准确率:92.00%
max_depth 4
训练集上的准确率:100.00%
测试集上的准确率:90.00%
这里选择2、3比较合适。