由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

Python Machine Learning

Codes
PDF (English)

  1. sudo pip3.7 install -i https://pypi.tuna.tsinghua.edu.cn/simple sklearn
  2. sudo pip3.7 install -i https://pypi.tuna.tsinghua.edu.cn/simple xgboost
  1. from sklearn.datasets import load_iris
  2. import xgboost as xgb
  3. from xgboost import plot_importance
  4. from matplotlib import pyplot as plt
  5. from sklearn.model_selection import train_test_split
  6. ## read in the iris data
  7. iris = load_iris()
  8. X = iris.data
  9. y = iris.target
  10. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1234565)
  11. params = {
  12. 'booster': 'gbtree',
  13. 'objective': 'multi:softmax',
  14. 'num_class': 3,
  15. 'gamma': 0.1,
  16. 'max_depth': 6,
  17. 'lambda': 2,
  18. 'subsample': 0.7,
  19. 'colsample_bytree': 0.7,
  20. 'min_child_weight': 3,
  21. 'silent': 1,
  22. 'eta': 0.1,
  23. 'seed': 1000,
  24. 'nthread': 4,
  25. }
  26. plst = params.items()
  27. dtrain = xgb.DMatrix(X_train, y_train)
  28. num_rounds = 500
  29. model = xgb.train(plst, dtrain, num_rounds)
  30. ## 对测试集进行预测
  31. dtest = xgb.DMatrix(X_test)
  32. ans = model.predict(dtest)
  33. ## 计算准确率
  34. cnt1 = 0
  35. cnt2 = 0
  36. for i in range(len(y_test)):
  37. if ans[i] == y_test[i]:
  38. cnt1 += 1
  39. else:
  40. cnt2 += 1
  41. print("Accuracy: %.2f %% " % (100 * cnt1 / (cnt1 + cnt2)))
  42. ## 显示重要特征
  43. plot_importance(model)
  44. plt.show()

Enjoy~

本文由Python腳本GitHub/語雀自動更新

由於語法渲染問題而影響閱讀體驗, 請移步博客閱讀~
本文GitPage地址

GitHub: Karobben
Blog:Karobben
BiliBili:史上最不正經的生物狗