机器学习编程作业-神经网络

神经网络

  • 作业说明
  • 复习
  • 任务一:估计马疝病的死亡率
  • 任务二:新闻分类
  • 任务三:对电影评论分类

作业说明

任务一:估计马疝病的死亡率。训练集在horseColicTraining.txt中,有299个样本,每个样本21个特征,最后一列为样本类别标签。测试集在horseColicTest.txt中,有69个样本,最后一列用来计算错误率。训练集和测试集中有些特征缺失的样本可以直接补0,标签缺失的直接舍弃。需要用逻辑回归的方式实现预测。
任务二:新闻分类。训练集和测试集都是dat文件,需要使用pickle包进行读取。然后提取TF-IDF特征用于训练。
任务三:对电影评论分类。数据集和之前贝叶斯的数据集相同。数据处理方式也相同。只需要用神经网络的方式训练即可。

复习

神经网络可以有很多层,但是每一层都必须有个激活函数的东西,没有激活函数,再怎么叠层数最终还是线性回归,激活函数就是用来增加非线性性的东西。常用的激活函数就是sigmoid函数。
此外,神经网络的训练,权重参数的更新是通过前向传播和后向传播配合梯度下降实现的,这里需要仔细研究一下

任务一:估计马疝病的死亡率

机器学习的各种算法在sklearn库中都有对应的函数。逻辑回归也能在这个库中找到使用方法。调库就是比手撕简单得多。
似乎只需要一个这样的函数就能完成任务了。。。

def colicSklearn(train_set, train_lables, test_set, test_lables):

    classifier = LogisticRegression(solver='liblinear', max_iter=10).fit(train_set, train_lables)
    test_accurcy = classifier.score(test_set, test_lables)
    error_rate = 1 - test_accurcy
    print('错误率', error_rate)

当然也可以用之前手撕逻辑回归,用自己写的梯度下降搞。梯度下降我当时是参考了别人的,就不贴了

任务二:新闻分类

TF-IDF特征也是通过sklearn库的sklearn. feature_extraction.text中的TfidfVectorizer来完成。处理代码已经给出,只需要照葫芦画瓢把训练集和测试集都处理好,然后用sklearn.neural_network的MLPClassifier进行训练就好了。

def data_init():
    # 读取dat文件
    f = open('test/test_texts.dat', 'rb')
    test_texts = pickle.load(f)
    f.close()
    f = open('train/train_texts.dat', 'rb')
    train_texts = pickle.load(f)
    f.close()
    # 数据预处理
    vectorizer = TfidfVectorizer(max_features=10000)
    vectors_test = vectorizer.fit_transform(test_texts)
    vectors_train = vectorizer.fit_transform(train_texts)
    features_train = csr_matrix(vectors_train).toarray()
    features_test = csr_matrix(vectors_test).toarray()
    # 读取数据标签
    f = open('train/train_labels.txt', 'r')
    train_labels = np.loadtxt('train/train_labels.txt', delimiter='\n')
    train_labels = list(train_labels)
    f.close()
    print('数据处理完成')
    return features_train, features_test, train_labels


def mpl_classfier(features_train, features_test, train_labels):
    x_train, x_test, y_train, y_test = train_test_split(features_train, train_labels, test_size=0.2)
    clf = MLPClassifier().fit(x_train, y_train)
    print('模型训练完成')
    train_accuracy = clf.score(x_test, y_test)
    train_error_rate = 1 - train_accuracy
    print('训练集精度{},错误率{}'.format(train_accuracy, train_error_rate))
    predict = clf.predict(features_test)
    print(predict)
    f = open('test/test_labels.txt', 'w')
    for i in predict:
        s = str(i) + '\n'
        f.write(s)
    f.close()

任务三:对电影评论分类

数据处理用之前几次作业的处理方式就好,然后神经网络的训练就用sklearn.neural_network的MLPClassifier就好,代码不贴了

你可能感兴趣的:(机器学习,机器学习,神经网络)