目录
sklearn官网 (各种算法模块的说明在 Documentation -> API 中可以找到)
1 train_test_split分离训练样本和测试样本
from sklearn.model_selection import
train_test_split
x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.2,
random_state=0)
# 此函数是从数据集中随机分出训练样本、测试样本
# train_data 为样本集
# train_target 为标签集
# test_size 若为小数,代表测试样本的比重,若为整数,代表测试样本的个数
# random_state 随机种子,若为0,每次随机选取不同,若为1,每次随机选取都一样
2 朴素贝叶斯
from sklearn.naive_bayes import
GaussianNB
clf = GaussianNB()
相关的方法:
fit(X, y[, sample_weight]) | Fit Gaussian Naive Bayes according to X, y |
---|---|
get_params([deep]) | Get parameters for this estimator. |
partial_fit(X, y[, classes, sample_weight]) | Incremental fit on a batch of samples. |
predict(X) | Perform classification on an array of test vectors X. |
predict_log_proba(X) | Return log-probability estimates for the test vector X. |
predict_proba(X) | Return probability estimates for the test vector X. |
score(X, y[, sample_weight]) | Returns the mean accuracy on the given test data and labels. |
set_params(**params) | Set the parameters of this estimator. |
3 SVM
from sklearn.model import svm
clf = svm.SVC()
参数:
C | C-SVC的惩罚参数 | C默认值是1.0,C值小,对误分类的惩罚减小,允许容错,泛化能力较强。 |
---|---|---|
kernel | 核函数,默认是rbf | 可以是:‘linear’:线性核函数’poly’; |
多项式核函数 ‘rbf’: | ||
径向核函数/高斯核 ‘sigmoid’: | ||
sigmod核函数 ‘precomputed’: | ||
核矩阵 | ||
degree | 多项式poly函数的维度 | 默认是3,选择其他核函数时会被忽略。 |
gamma | ‘rbf’,‘poly’ 和‘sigmoid’的核函数参数 | 默认是’auto’,一般为样本特征数的倒数,即1/n_features |
coef0 | 核函数的常数项 | 对于‘poly’和 ‘sigmoid’有用 |
probability | 是否采用概率估计 | 默认为False。 这必须在调用fiti()之前启用,并且会使fit()方法速度变慢 |
shrinking | 是否采用shrinking heuristic方法 | 默认为true |
tol | svm停止训练的误差值大小 | 默认为1e-3 |
cache_size | 核函数cache缓存大小 | 默认为200,即200MB |
class_weight | 类别的权重,字典形式传递 | 设置第几类的参数C为weight*C(C-SVC中的C) |
verbose | 允许冗余输出 | 默认为False。一般不用管 |
max_iter | 最大迭代次数 | 默认为-1,表示无限制 |
decision_function_shape | ‘ovo’, ‘ovr’ or None | default=None |
random_state | 数据洗牌时的种子值,int值 |
相关的方法:
fit(X, y[, sample_weight]) | Fit Gaussian Naive Bayes according to X, y |
---|---|
predict(X) | Perform classification on an array of test vectors X. |
score(X, y[, sample_weight]) | Returns the mean accuracy on the given test data and labels. |
decision_function(X) | 返回决策函数 |
4 决策树
from sklearn import tree
clf = tree.DecisionTreeClassifier()
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier(random_state=0,...)
熵的定义:
信息增益:
其中H(D)为某节点的熵,H(D|A)为其子节点的熵用权重求和。决策树的生成,就是按照信息增益最大化的方式递归编制决策树。比如对于某节点,算出剩下所有特征的信息增益,信息增益最大的那个特征作为该节点的决策。
5 K邻近算法
from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=3)
6 adaboost 算法
7 random forest 随机森林算法
8 回归
from sklearn.linear_model import
LinearRegression
reg = LinearRegression()
reg.fit(xxx,xxxx)
print(reg.predict([27)) #查看预测
print(reg.coef_) #查看斜率
print(reg.intercept_) #查看截距,即R平方数+
print(reg.score(xxx, xxx)) #查看准确率
清理异常值的步骤
初次训练 -> 去掉残差较大的数(数量可以为总数的10%) -> 再次训练
9 K均值聚类算法
from sklearn.cluster import KMeans
km = KMeans(n_clusters=2) # 需要自己指定所分的类别个数
km.fit(data)
km.labels_ #输入数据对应的类别
10 特征缩放
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
rescaled_xxx = scaler.fit_transform(xxx) # xxx为二维数组,其实特征缩放就是归一化
value = scaler.transform(xxx) # 在训练后的缩放比例中,转换一个新的数字
11 文本学习
from sklearn.feature_extraction.text
import CountVectorizer
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)
print(vectorizer.get_feature_names())
print(X.toarray())
# 从NLTK中获取停止词:
from nltk.corpus import stopwords
sw = stopwords.words("english") # sw保存了停止词,是个列表
# 用NLTK提取(英语)词干:
from nltk.stem.snowball import SnowballStemmer
stemmer = SnowballStemmer("english")
stemmer.stem("responsiveness") # 会提取出单词respons
# 去掉字符串中的标点符号:
import string
xxx.translate(str.maketrans("", "", string.punctuation))
# 句子拆分成单词:
word = xxx.split(" ")
# 单词(字符串数组)组合成句子:
words = ' '.join(word)