ML入门1
ML入門1
記錄我看黑馬三天入門ML的第一天,看完黑馬,準(zhǔn)備再去啃西瓜書!
一.數(shù)據(jù)集使用
先要安裝sklearn相關(guān)的庫,我pycharm配置的是anaconda的環(huán)境,所以直接在anaconda中配置了sklearn的庫。sklearn包含的算法有:Classification(分類)、Regression(回歸)、Clustering(聚類)、Dimensionality redution(降維)、Model selection(模型選擇) 、Preprocessing(特征工程)
1.數(shù)據(jù)集的讀取
加載獲取小規(guī)模數(shù)據(jù)集,數(shù)據(jù)包含在datasets中。
sklearn.datasets.load_*();獲得大規(guī)模數(shù)據(jù)集,數(shù)據(jù)需要從網(wǎng)上下載,函數(shù)第一個參數(shù)是data_home,表示數(shù)據(jù)集下載目錄,有默認(rèn)值。
sklearn.datasets.fetch_*(data_home)例:獲取鳶尾花數(shù)據(jù)集(返回的是字典)
import sklearn def dataset_demo():from sklearn import datasets#獲取數(shù)據(jù)集iris=sklearn.datasets.load_iris()print("鳶尾花數(shù)據(jù)集:\n",iris)print("查看數(shù)據(jù)集描述:\n",iris["DESCR"])return None dataset_demo()#返回的是字典2.數(shù)據(jù)集的返回值
讀取數(shù)據(jù)集以后可以詳細(xì)觀看。
load和fetch返回的數(shù)據(jù)類型是datasets.base.Bunch(字典格式)
(1)data:特征數(shù)據(jù)數(shù)組,是[n_samples*n_features]的二維numpy.ndarray數(shù)組
(2)target:標(biāo)簽數(shù)組,是n_samples的一維numpy.ndarray數(shù)組
(3)DESCR:數(shù)據(jù)描述
(4)feature_names:特征名
(5)target_names:標(biāo)簽名
3.數(shù)據(jù)集的劃分
訓(xùn)練數(shù)據(jù):用于訓(xùn)練,構(gòu)建模型
測試數(shù)據(jù):模型檢驗(yàn),用于評估模型是否有效,占數(shù)據(jù)集20%~30%
數(shù)據(jù)的劃分api
def train_test_split(*arrays,test_size=None,train_size=None,random_state=None,shuffle=True,stratify=None):"""Split arrays or matrices into random train and test subsets子集合Quick utility that wraps input validation and``next(ShuffleSplit().split(X, y))`` and application to input datainto a single call for splitting (and optionally subsampling) data in aoneliner.Read more in the :ref:`User Guide <cross_validation>`.Parameters----------*arrays : sequence of indexables with same length / shape[0]Allowed inputs are lists, numpy arrays, scipy-sparsematrices or pandas dataframes.test_size : float or int, default=NoneIf float, should be between 0.0 and 1.0 and represent the proportionof the dataset to include in the test split. If int, represents theabsolute number of test samples. If None, the value is set to thecomplement of the train size. If ``train_size`` is also None, it willbe set to 0.25.train_size : float or int, default=NoneIf float, should be between 0.0 and 1.0 and represent theproportion of the dataset to include in the train split. Ifint, represents the absolute number of train samples. If None,the value is automatically set to the complement of the test size.random_state : int, RandomState instance or None, default=NoneControls the shuffling applied to the data before applying the split.Pass an int for reproducible output across multiple function calls.See :term:`Glossary <random_state>`.shuffle : bool, default=TrueWhether or not to shuffle the data before splitting. If shuffle=Falsethen stratify must be None.stratify : array-like, default=NoneIf not None, data is split in a stratified fashion, using this asthe class labels.Read more in the :ref:`User Guide <stratification>`.Returns-------splitting : list, length=2 * len(arrays)List containing train-test split of inputs... versionadded:: 0.16If the input is sparse, the output will be a``scipy.sparse.csr_matrix``. Else, output type is the same as theinput type.Examples-------->>> import numpy as np>>> from sklearn.model_selection import train_test_split>>> X, y = np.arange(10).reshape((5, 2)), range(5)>>> Xarray([[0, 1],[2, 3],[4, 5],[6, 7],[8, 9]])>>> list(y)[0, 1, 2, 3, 4]>>> X_train, X_test, y_train, y_test = train_test_split(... X, y, test_size=0.33, random_state=42)...>>> X_trainarray([[4, 5],[0, 1],[6, 7]])>>> y_train[2, 0, 3]>>> X_testarray([[2, 3],[8, 9]])>>> y_test[1, 4]>>> train_test_split(y, shuffle=False)[[0, 1, 2], [3, 4]]"""4.特征工程
(1)為什么需要特征工程(Feature Engineering)
數(shù)據(jù)和特征決定了機(jī)器學(xué)習(xí)的上限,而模型和算法只是逼近這個上限而已
(2) 什么是特征工程
特征工程是使用專業(yè)背景知識和技巧處理數(shù)據(jù),使得特征能在機(jī)器學(xué)習(xí)算法上發(fā)揮更好的作用的過程。會直接影響機(jī)器學(xué)習(xí)的效果。
(3)特征工程的位置與數(shù)據(jù)處理的比較
pandas:一個數(shù)據(jù)讀取非常方便以及基本的處理格式的工具。用于數(shù)據(jù)清洗、數(shù)據(jù)處理
sklearn:對特征的處理提供了強(qiáng)大的接口。用于特征工程
特征抽取/特征提取/特征值化,特征預(yù)處理,特征降維
(4)特征抽取/特征提取/特征值化
學(xué)習(xí)目標(biāo):
應(yīng)用DictVectorizer實(shí)現(xiàn)對類別特征數(shù)值化、離散化
應(yīng)用CountVectorizer實(shí)現(xiàn)對文本特征數(shù)值化
應(yīng)用TfidfVectorizer實(shí)現(xiàn)對文本特征數(shù)值化
說出兩種文本特征提取方式的區(qū)別
無應(yīng)用
(5)為什么要特征提取?什么是特征提取?
用機(jī)器學(xué)習(xí)算法對數(shù)據(jù)集進(jìn)行學(xué)習(xí),機(jī)器學(xué)習(xí)算法實(shí)際上一些統(tǒng)計(jì)方法(數(shù)學(xué)公式),是不能處理字符串、文本、圖像的,需要轉(zhuǎn)換為可用于機(jī)器學(xué)習(xí)的數(shù)字特征。
- 字典特征提取(特征離散化)
- 文本特征提取
- 圖像特征提取(深度學(xué)習(xí) )
(6)特征提取API
sklearn.feature_extractionThe sklearn.feature_extraction module deals with feature extraction from raw data. It currently includes methods to extract features from text and images.
字典特征提取
作用:對字典數(shù)據(jù)進(jìn)行特征值化
1 API
sklearn.feature_extraction.DictVectorizer(*, dtype=<class 'numpy.float64'>, separator='=', sparse=True, sort=True)- 將特征值映射列表轉(zhuǎn)換為向量
- 該轉(zhuǎn)換器將特征名稱到特征值的映射列表(類似字典的對象)轉(zhuǎn)換為 Numpy 數(shù)組或 scipy.sparse 矩陣,以便與scikit-learn 估計(jì)器一起使用。
- 當(dāng)特征值是字符串時(shí),此轉(zhuǎn)換器將執(zhí)行二進(jìn)制 one-hot(又名 one-of-K)編碼:為該特征可以采用的每個可能的字符串值構(gòu)造一個布爾值特征(為了公平)。例如,可以采用值“ham”和“spam”的特征“f”將成為輸出中的兩個特征,一個表示“f=ham”,另一個表示“f=spam”。
- 如果特征值是一個序列或一組字符串,則此轉(zhuǎn)換器將迭代這些值并計(jì)算每個字符串值的出現(xiàn)次數(shù)。
- 但是,請注意,當(dāng)特征值為字符串類型時(shí),此轉(zhuǎn)換器只會執(zhí)行二進(jìn)制 one-hot 編碼。
- 如果分類特征表示為數(shù)值,例如 int 或字符串的可迭代,則可以使用 DictVectorizer OneHotEncoder來完成二進(jìn)制
one-hot 編碼。 - 樣本(映射)中未出現(xiàn)的特征將在結(jié)果數(shù)組/矩陣中具有零值。
- 返回一個稀疏矩陣(sparse),只顯示非0值
應(yīng)用場景:
(1)pclass,sex 數(shù)據(jù)集類別特征較多
=>將數(shù)據(jù)集特征轉(zhuǎn)換為字典類型
=>DictVectorizer轉(zhuǎn)換
(2)數(shù)據(jù)集本身就是字典類型
直接抽取
文本特征提取
作用:對文本數(shù)據(jù)進(jìn)行特征值化
sklearn.feature_extraction.text.CountVectorizer(*, input='content', encoding='utf-8', decode_error='strict', strip_accents=None, lowercase=True, preprocessor=None, tokenizer=None, stop_words=None停用詞, token_pattern='(?u)\b\w\w+\b', ngram_range=(1, 1), analyzer='word', max_df=1.0, min_df=1, max_features=None, vocabulary=None, binary=False, dtype=<class 'numpy.int64'>)停用詞指的是在特征提取的時(shí)候,不提取的詞。
關(guān)鍵詞:在某一個類別文章中,出現(xiàn)很多,在其他類別文章中,出現(xiàn)很少。
Tf-idf文本特征提取
(1)TF-IDF主要思想:如果某個詞或短語在一篇文章中出現(xiàn)概率較高,并且在其他文章中很少出現(xiàn),則認(rèn)為此詞或者是短語具有良好的類別區(qū)分能力,適合用來分類。
(2)TF-IDF作用:用以評估一個字詞對于一個文件集或一個語料庫中的其中一份文件的重要程度。
(3)TD——詞頻=詞語出現(xiàn)次數(shù)/總詞數(shù)
(4)IDF——逆向文檔頻率=lg(總文件數(shù)目/包含該詞語文件數(shù)目)
例:
1000篇文章——語料庫
100篇文章——“非常”
10篇文章——“經(jīng)濟(jì)”
兩篇文章:
文章A(100詞):10次“經(jīng)濟(jì)” TF—IDF:0.12=0.2
TF:10/100 =0.1 IDF:lg(1000/10)=2
文章B(100詞):10次“非常” TF—IDF:0.11=0.1
TF:10/100 =0.1 IDF:lg(1000/100)=1
故而“經(jīng)濟(jì)”對語料庫中的文章分類更重要(個人覺得在一篇文章內(nèi)比較覺得比較好)
API
sklearn.feature_extraction.text.TfidVectorize(stop_words = None...)- 返回詞權(quán)重矩陣
- TfidVectorizerfit_transform(X)
- X:文本或者包含文本字符串的可迭代對象
- 返回值:返回sparse矩陣
- TfidVectorizer.inverse_transform(X)
- X:array數(shù)組或者sparse矩陣
- 返回值:轉(zhuǎn)換之前的數(shù)據(jù)格式
- TfidVectorizer.get_feature_names()
- 返回值:單詞列表
5.特征預(yù)處理
(1)什么是特征預(yù)處理?
通過一些轉(zhuǎn)換函數(shù)將特征數(shù)據(jù)轉(zhuǎn)換成更適合算法模型的特征數(shù)據(jù)過程
(2)包含內(nèi)容
- 數(shù)值型數(shù)據(jù)的無量綱化
- 歸一化
- 標(biāo)準(zhǔn)化
(3)為什么要對數(shù)據(jù)進(jìn)行歸一化,標(biāo)準(zhǔn)化?
特征預(yù)處理API
sklearn.preprocessing歸一化
(1)定義
通過對原始數(shù)據(jù)進(jìn)行變換把數(shù)據(jù)映射到(默認(rèn)為[0,1]之間)
(2)計(jì)算
X1 = (x - min)/(max-min)
X2 = X1*(mx - mi)+ mi
=>mx,mi分別為指定區(qū)間值,默認(rèn)mx為1,mi為0
歸一化 API
sklearn.preprocessing.MinMaxScaier(feature_range =(0,1)...)- feature_ranges默認(rèn)在[0,1]之間,可以自己設(shè)置
- .MinMaxScaier.fit_transform(X)
- X:numpy array格式的數(shù)據(jù)[n_samples,n_features]
- 返回值:轉(zhuǎn)換后形狀相同的array
(3)歸一化的缺點(diǎn)
歸一化方式,魯棒性較差,一般在精確的小數(shù)據(jù)場景使用,因?yàn)闅w一化在計(jì)算時(shí)候使用了max與min,如果最大值和最小值是異常值的話,那么數(shù)據(jù)的歸一化就會出現(xiàn)問題。
標(biāo)準(zhǔn)化
(1)定義
通過對原始數(shù)據(jù)進(jìn)行變化,把數(shù)據(jù)變換到均值為0,標(biāo)準(zhǔn)差為1的范圍內(nèi)。
(2)計(jì)算
X1 = (x-mean(均值))/β(標(biāo)準(zhǔn)差)
標(biāo)準(zhǔn)化API
sklearn.preprocessing.StandardScaler()- StandardScaler.fit_transform(X)
- X:numpy array格式數(shù)據(jù)
- 返回值:形狀相同的array
(3)適用于對大數(shù)據(jù)的處理,如果出現(xiàn)異常點(diǎn),少量異常點(diǎn)對均值與標(biāo)準(zhǔn)差影響不大
總結(jié)
- 上一篇: Bootstrap框架使用(安装,全局样
- 下一篇: go集成gin+swagger