#!/usr/bin/env python # coding: utf-8 # *** # *** # # 计算传播与机器学习 # # *** # *** # # 王成军 # # wangchengjun@nju.edu.cn # # 计算传播网 http://computational-communication.com # ![](./img/machine.jpg) # ## 1、 监督式学习 # # 工作机制: # - 这个算法由一个目标变量或结果变量(或因变量)组成。 # - 这些变量由已知的一系列预示变量(自变量)预测而来。 # - 利用这一系列变量,我们生成一个将输入值映射到期望输出值的函数。 # - 这个训练过程会一直持续,直到模型在训练数据上获得期望的精确度。 # - 监督式学习的例子有:回归、决策树、随机森林、K – 近邻算法、逻辑回归等。 # ## 2、非监督式学习 # # 工作机制: # - 在这个算法中,没有任何目标变量或结果变量要预测或估计。 # - 这个算法用在不同的组内聚类分析。 # - 这种分析方式被广泛地用来细分客户,根据干预的方式分为不同的用户组。 # - 非监督式学习的例子有:关联算法和 K–均值算法。 # ## 3、强化学习 # # 工作机制: # - 这个算法训练机器进行决策。 # - 它是这样工作的:机器被放在一个能让它通过反复试错来训练自己的环境中。 # - 机器从过去的经验中进行学习,并且尝试利用了解最透彻的知识作出精确的商业判断。 # - 强化学习的例子有马尔可夫决策过程。alphago # # > Chess. Here, the agent decides upon a series of moves depending on the state of the board (the environment), and the # reward can be defined as win or lose at the end of the game: # # - 线性回归 # - 逻辑回归 # - 决策树 # - SVM # - 朴素贝叶斯 # --- # - K最近邻算法 # - K均值算法 # - 随机森林算法 # - 降维算法 # - Gradient Boost 和 Adaboost 算法 # # > # 使用sklearn做线性回归 # *** # # 王成军 # # wangchengjun@nju.edu.cn # # 计算传播网 http://computational-communication.com # # 线性回归 # - 通常用于估计连续性变量的实际数值(房价、呼叫次数、总销售额等)。 # - 通过拟合最佳直线来建立自变量X和因变量Y的关系。 # - 这条最佳直线叫做回归线,并且用 $Y= \beta *X + C$ 这条线性等式来表示。 # - 系数 $\beta$ 和 C 可以通过最小二乘法获得 # In[3]: get_ipython().run_line_magic('matplotlib', 'inline') import sklearn from sklearn import datasets from sklearn import linear_model import matplotlib.pyplot as plt from sklearn.metrics import classification_report from sklearn.preprocessing import scale # In[4]: # boston data boston = datasets.load_boston() y = boston.target X = boston.data # In[5]: ' '.join(dir(boston)) # In[6]: boston['feature_names'] # In[7]: import numpy as np import statsmodels.api as sm import statsmodels.formula.api as smf # Fit regression model (using the natural log of one of the regressors) results = smf.ols('boston.target ~ boston.data', data=boston).fit() print(results.summary()) # In[8]: regr = linear_model.LinearRegression() lm = regr.fit(boston.data, y) # In[9]: lm.intercept_, lm.coef_, lm.score(boston.data, y) # In[10]: predicted = regr.predict(boston.data) # In[11]: fig, ax = plt.subplots() ax.scatter(y, predicted) ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4) ax.set_xlabel('$Measured$', fontsize = 20) ax.set_ylabel('$Predicted$', fontsize = 20) plt.show() # ## 训练集和测试集 # In[190]: boston.data # In[12]: from sklearn.cross_validation import train_test_split Xs_train, Xs_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=42) # In[13]: regr = linear_model.LinearRegression() lm = regr.fit(Xs_train, y_train) # In[14]: lm.intercept_, lm.coef_, lm.score(Xs_train, y_train) # In[15]: predicted = regr.predict(Xs_test) # In[16]: fig, ax = plt.subplots() ax.scatter(y_test, predicted) ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4) ax.set_xlabel('$Measured$', fontsize = 20) ax.set_ylabel('$Predicted$', fontsize = 20) plt.show() # # 交叉验证 # # cross-validation # # k-fold CV, the training set is split into k smaller sets (other approaches are described below, but generally follow the same principles). The following procedure is followed for each of the k “folds”: # - A model is trained using k-1 of the folds as training data; # - the resulting model is validated on the remaining part of the data (i.e., it is used as a test set to compute a performance measure such as accuracy). # In[17]: from sklearn.cross_validation import cross_val_score regr = linear_model.LinearRegression() scores = cross_val_score(regr, boston.data , boston.target, cv = 3) scores.mean() # In[18]: help(cross_val_score) # In[21]: scores = [cross_val_score(regr, data_X_scale,\ boston.target,\ cv = int(i)).mean() \ for i in range(3, 50)] plt.plot(range(3, 50), scores,'r-o') plt.show() # In[20]: data_X_scale = scale(boston.data) scores = cross_val_score(regr,data_X_scale, boston.target,\ cv = 7) scores.mean() # # 使用天涯bbs数据 # In[22]: import pandas as pd df = pd.read_csv('../data/tianya_bbs_threads_list.txt', sep = "\t", header=None) df=df.rename(columns = {0:'title', 1:'link', 2:'author',3:'author_page', 4:'click', 5:'reply', 6:'time'}) df[:2] # In[23]: # 定义这个函数的目的是让读者感受到: # 抽取不同的样本,得到的结果完全不同。 def randomSplit(dataX, dataY, num): dataX_train = [] dataX_test = [] dataY_train = [] dataY_test = [] import random test_index = random.sample(range(len(df)), num) for k in range(len(dataX)): if k in test_index: dataX_test.append([dataX[k]]) dataY_test.append(dataY[k]) else: dataX_train.append([dataX[k]]) dataY_train.append(dataY[k]) return dataX_train, dataX_test, dataY_train, dataY_test, # In[25]: import numpy as np # Use only one feature data_X = df.reply # Split the data into training/testing sets data_X_train, data_X_test, data_y_train, data_y_test = randomSplit(np.log(df.click+1), np.log(df.reply+1), 20) # Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(data_X_train, data_y_train) # Explained variance score: 1 is perfect prediction print('Variance score: %.2f' % regr.score(data_X_test, data_y_test)) # In[89]: data_X_train # In[26]: y_true, y_pred = data_y_test, regr.predict(data_X_test) # In[27]: plt.scatter(y_pred, y_true, color='black') plt.show() # In[28]: # Plot outputs plt.scatter(data_X_test, data_y_test, color='black') plt.plot(data_X_test, regr.predict(data_X_test), color='blue', linewidth=3) plt.show() # In[29]: # The coefficients 'Coefficients: \n', regr.coef_ # In[30]: # The mean square error "Residual sum of squares: %.2f" % np.mean((regr.predict(data_X_test) - data_y_test) ** 2) # In[31]: df.click_log = [[np.log(df.click[i]+1)] for i in range(len(df))] df.reply_log = [[np.log(df.reply[i]+1)] for i in range(len(df))] # In[32]: from sklearn.cross_validation import train_test_split Xs_train, Xs_test, y_train, y_test = train_test_split(df.click_log, df.reply_log,test_size=0.2, random_state=0) # Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(Xs_train, y_train) # Explained variance score: 1 is perfect prediction 'Variance score: %.2f' % regr.score(Xs_test, y_test) # In[33]: # Plot outputs plt.scatter(Xs_test, y_test, color='black') plt.plot(Xs_test, regr.predict(Xs_test), color='blue', linewidth=3) plt.show() # In[34]: from sklearn.cross_validation import cross_val_score regr = linear_model.LinearRegression() scores = cross_val_score(regr, df.click_log, \ df.reply_log, cv = 3) scores.mean() # In[35]: regr = linear_model.LinearRegression() scores = cross_val_score(regr, df.click_log, df.reply_log, cv =5) scores.mean() # > # 使用sklearn做logistic回归 # *** # # 王成军 # # wangchengjun@nju.edu.cn # # 计算传播网 http://computational-communication.com # - logistic回归是一个分类算法而不是一个回归算法。 # - 可根据已知的一系列因变量估计离散数值(比方说二进制数值 0 或 1 ,是或否,真或假)。 # - 简单来说,它通过将数据拟合进一个逻辑函数(logistic function)来预估一个事件出现的概率。 # - 因此,它也被叫做逻辑回归。因为它预估的是概率,所以它的输出值大小在 0 和 1 之间(正如所预计的一样)。 # $$odds= \frac{p}{1-p} = \frac{probability\: of\: event\: occurrence} {probability \:of \:not\: event\: occurrence}$$ # $$ln(odds)= ln(\frac{p}{1-p})$$ # $$logit(x) = ln(\frac{p}{1-p}) = b_0+b_1X_1+b_2X_2+b_3X_3....+b_kX_k$$ # ![](./img/logistic.jpg) # In[50]: repost = [] for i in df.title: if u'转载' in i: repost.append(1) else: repost.append(0) # In[51]: data_X = [[df.click[i], df.reply[i]] for i in range(len(df))] data_X[:3] # In[52]: from sklearn.linear_model import LogisticRegression df['repost'] = repost model = LogisticRegression() model.fit(data_X,df.repost) model.score(data_X,df.repost) # In[53]: def randomSplitLogistic(dataX, dataY, num): dataX_train = [] dataX_test = [] dataY_train = [] dataY_test = [] import random test_index = random.sample(range(len(df)), num) for k in range(len(dataX)): if k in test_index: dataX_test.append(dataX[k]) dataY_test.append(dataY[k]) else: dataX_train.append(dataX[k]) dataY_train.append(dataY[k]) return dataX_train, dataX_test, dataY_train, dataY_test, # In[54]: # Split the data into training/testing sets data_X_train, data_X_test, data_y_train, data_y_test = randomSplitLogistic(data_X, df.repost, 20) # Create logistic regression object log_regr = LogisticRegression() # Train the model using the training sets log_regr.fit(data_X_train, data_y_train) # Explained variance score: 1 is perfect prediction 'Variance score: %.2f' % log_regr.score(data_X_test, data_y_test) # In[55]: y_true, y_pred = data_y_test, log_regr.predict(data_X_test) # In[43]: y_true, y_pred # In[44]: print(classification_report(y_true, y_pred)) # In[56]: from sklearn.cross_validation import train_test_split Xs_train, Xs_test, y_train, y_test = train_test_split(data_X, df.repost, test_size=0.2, random_state=42) # In[57]: # Create logistic regression object log_regr = LogisticRegression() # Train the model using the training sets log_regr.fit(Xs_train, y_train) # Explained variance score: 1 is perfect prediction 'Variance score: %.2f' % log_regr.score(Xs_test, y_test) # In[58]: print('Logistic score for test set: %f' % log_regr.score(Xs_test, y_test)) print('Logistic score for training set: %f' % log_regr.score(Xs_train, y_train)) y_true, y_pred = y_test, log_regr.predict(Xs_test) print(classification_report(y_true, y_pred)) # In[59]: logre = LogisticRegression() scores = cross_val_score(logre, data_X, df.repost, cv = 3) scores.mean() # In[60]: logre = LogisticRegression() data_X_scale = scale(data_X) # The importance of preprocessing in data science and the machine learning pipeline I: scores = cross_val_score(logre, data_X_scale, df.repost, cv = 3) scores.mean() # > # 使用sklearn实现贝叶斯预测 # *** # # 王成军 # # wangchengjun@nju.edu.cn # # 计算传播网 http://computational-communication.com # # Naive Bayes algorithm # # It is a classification technique based on Bayes’ Theorem with an assumption of independence among predictors. # # In simple terms, a Naive Bayes classifier assumes that the presence of a particular feature in a class is unrelated to the presence of any other feature. # # why it is known as ‘Naive’? For example, a fruit may be considered to be an apple if it is red, round, and about 3 inches in diameter. Even if these features depend on each other or upon the existence of the other features, all of these properties independently contribute to the probability that this fruit is an apple. # 贝叶斯定理为使用$p(c)$, $p(x)$, $p(x|c)$ 计算后验概率$P(c|x)$提供了方法: # $$ # p(c|x) = \frac{p(x|c) p(c)}{p(x)} # $$ # - P(c|x) is the posterior probability of class (c, target) given predictor (x, attributes). # - P(c) is the prior probability of class. # - P(x|c) is the likelihood which is the probability of predictor given class. # - P(x) is the prior probability of predictor. # ![](./img/Bayes_41.png) # Step 1: Convert the data set into a frequency table # # Step 2: Create Likelihood table by finding the probabilities like: # - p(Overcast) = 0.29, p(rainy) = 0.36, p(sunny) = 0.36 # - p(playing) = 0.64, p(rest) = 0.36 # # Step 3: Now, use Naive Bayesian equation to calculate the posterior probability for each class. The class with the highest posterior probability is the outcome of prediction. # ## Problem: Players will play if weather is sunny. Is this statement is correct? # # We can solve it using above discussed method of posterior probability. # # $P(Yes | Sunny) = \frac{P( Sunny | Yes) * P(Yes) } {P (Sunny)}$ # # Here we have P (Sunny |Yes) = 3/9 = 0.33, P(Sunny) = 5/14 = 0.36, P( Yes)= 9/14 = 0.64 # # Now, $P (Yes | Sunny) = \frac{0.33 * 0.64}{0.36} = 0.60$, which has higher probability. # In[17]: from sklearn import naive_bayes ' '.join(dir(naive_bayes)) # - naive_bayes.GaussianNB Gaussian Naive Bayes (GaussianNB) # - naive_bayes.MultinomialNB([alpha, ...]) Naive Bayes classifier for multinomial models # - naive_bayes.BernoulliNB([alpha, binarize, ...]) Naive Bayes classifier for multivariate Bernoulli models. # In[61]: #Import Library of Gaussian Naive Bayes model from sklearn.naive_bayes import GaussianNB import numpy as np #assigning predictor and target variables x= np.array([[-3,7],[1,5], [1,2], [-2,0], [2,3], [-4,0], [-1,1], [1,1], [-2,2], [2,7], [-4,1], [-2,7]]) Y = np.array([3, 3, 3, 3, 4, 3, 3, 4, 3, 4, 4, 4]) # In[62]: #Create a Gaussian Classifier model = GaussianNB() # Train the model using the training sets model.fit(x[:8], Y[:8]) #Predict Output predicted= model.predict([[1,2],[3,4]]) predicted # # cross-validation # # k-fold CV, the training set is split into k smaller sets (other approaches are described below, but generally follow the same principles). The following procedure is followed for each of the k “folds”: # - A model is trained using k-1 of the folds as training data; # - the resulting model is validated on the remaining part of the data (i.e., it is used as a test set to compute a performance measure such as accuracy). # In[63]: data_X_train, data_X_test, data_y_train, data_y_test = randomSplit(df.click, df.reply, 20) # Train the model using the training sets model.fit(data_X_train, data_y_train) #Predict Output predicted= model.predict(data_X_test) predicted # In[64]: model.score(data_X_test, data_y_test) # In[66]: from sklearn.cross_validation import cross_val_score model = GaussianNB() scores = cross_val_score(model, [[c] for c in df.click],\ df.reply, cv = 7) scores.mean() # > # 使用sklearn实现决策树 # *** # # 王成军 # # wangchengjun@nju.edu.cn # # 计算传播网 http://computational-communication.com # # 决策树 # - 这个监督式学习算法通常被用于分类问题。 # - 它同时适用于分类变量和连续因变量。 # - 在这个算法中,我们将总体分成两个或更多的同类群。 # - 这是根据最重要的属性或者自变量来分成尽可能不同的组别。 # # ![](./img/tree.png) # ![](./img/playtree.jpg) # ## 在上图中你可以看到,根据多种属性,人群被分成了不同的四个小组,来判断 “他们会不会去玩”。 # ### 为了把总体分成不同组别,需要用到许多技术,比如说 Gini、Information Gain、Chi-square、entropy。 # In[67]: from sklearn import tree model = tree.DecisionTreeClassifier(criterion='gini') # In[68]: data_X_train, data_X_test, data_y_train, data_y_test = randomSplitLogistic(data_X, df.repost, 20) model.fit(data_X_train,data_y_train) model.score(data_X_train,data_y_train) # In[69]: # Predict model.predict(data_X_test) # In[70]: # crossvalidation scores = cross_val_score(model, data_X, df.repost, cv = 3) scores.mean() # > # 使用sklearn实现SVM支持向量机 # *** # # 王成军 # # wangchengjun@nju.edu.cn # # 计算传播网 http://computational-communication.com # ![](./img/svm.jpg) # - 将每个数据在N维空间中用点标出(N是你所有的特征总数),每个特征的值是一个坐标的值。 # - 举个例子,如果我们只有身高和头发长度两个特征,我们会在二维空间中标出这两个变量,每个点有两个坐标(这些坐标叫做支持向量)。 # ![](./img/xyplot.png) # - 现在,我们会找到将两组不同数据分开的一条直线。 # - 两个分组中距离最近的两个点到这条线的距离同时最优化。 # ![](./img/sumintro.png) # ## 上面示例中的黑线将数据分类优化成两个小组 # - 两组中距离最近的点(图中A、B点)到达黑线的距离满足最优条件。 # - 这条直线就是我们的分割线。接下来,测试数据落到直线的哪一边,我们就将它分到哪一类去。 # In[71]: from sklearn import svm # Create SVM classification object model=svm.SVC() # In[72]: ' '.join(dir(svm)) # In[73]: data_X_train, data_X_test, data_y_train, data_y_test = randomSplitLogistic(data_X, df.repost, 20) model.fit(data_X_train,data_y_train) model.score(data_X_train,data_y_train) # In[74]: # Predict model.predict(data_X_test) # In[75]: # crossvalidation scores = [] cvs = [3, 5, 10, 25, 50, 75, 100] for i in cvs: score = cross_val_score(model, data_X, df.repost, cv = i) scores.append(score.mean() ) # Try to tune cv # In[76]: plt.plot(cvs, scores, 'b-o') plt.xlabel('$cv$', fontsize = 20) plt.ylabel('$Score$', fontsize = 20) plt.show() # # # > # 泰坦尼克号数据分析 # # 王成军 # # wangchengjun@nju.edu.cn # # 计算传播网 http://computational-communication.com # In[77]: #Import the Numpy library import numpy as np #Import 'tree' from scikit-learn library from sklearn import tree # In[140]: import pandas as pd train = pd.read_csv('../data/tatanic_train.csv', sep = ",") # In[141]: from sklearn.naive_bayes import GaussianNB # In[142]: train["Age"] = train["Age"].fillna(train["Age"].median()) train["Fare"] = train["Fare"].fillna(train["Fare"].median()) # x = [[i] for i in train['Age']] y = train['Age'] y = train['Fare'].astype(int) #y = [[i] for i in y] # In[145]: #Create a Gaussian Classifier model = GaussianNB() # Train the model using the training sets nb = model.fit(x[:80], y[:80]) # nb.score(x, y) # In[135]: help(GaussianNB) # In[ ]: model.fit(x) # In[79]: train.head() # In[80]: train["Age"] = train["Age"].fillna(train["Age"].median()) #Convert the male and female groups to integer form train["Sex"][train["Sex"] == "male"] = 0 train["Sex"][train["Sex"] == "female"] = 1 #Impute the Embarked variable train["Embarked"] = train["Embarked"].fillna('S') #Convert the Embarked classes to integer form train["Embarked"][train["Embarked"] == "S"] = 0 train["Embarked"][train["Embarked"] == "C"] = 1 train["Embarked"][train["Embarked"] == "Q"] = 2 # In[81]: #Create the target and features numpy arrays: target, features_one target = train['Survived'].values features_one = train[["Pclass", "Sex", "Age", "Fare"]].values #Fit your first decision tree: my_tree_one my_tree_one = tree.DecisionTreeClassifier() my_tree_one = my_tree_one.fit(features_one, target) #Look at the importance of the included features and print the score print(my_tree_one.feature_importances_) print(my_tree_one.score(features_one, target)) # In[82]: test = pd.read_csv('../data/tatanic_test.csv', sep = ",") # Impute the missing value with the median test.Fare[152] = test.Fare.median() test["Age"] = test["Age"].fillna(test["Age"].median()) #Convert the male and female groups to integer form test["Sex"][test["Sex"] == "male"] = 0 test["Sex"][test["Sex"] == "female"] = 1 #Impute the Embarked variable test["Embarked"] = test["Embarked"].fillna('S') #Convert the Embarked classes to integer form test["Embarked"][test["Embarked"] == "S"] = 0 test["Embarked"][test["Embarked"] == "C"] = 1 test["Embarked"][test["Embarked"] == "Q"] = 2 # Extract the features from the test set: Pclass, Sex, Age, and Fare. test_features = test[["Pclass","Sex", "Age", "Fare"]].values # Make your prediction using the test set my_prediction = my_tree_one.predict(test_features) # Create a data frame with two columns: PassengerId & Survived. Survived contains your predictions PassengerId =np.array(test['PassengerId']).astype(int) my_solution = pd.DataFrame(my_prediction, PassengerId, columns = ["Survived"]) # In[83]: my_solution[:3] # In[84]: # Check that your data frame has 418 entries my_solution.shape # In[30]: # Write your solution to a csv file with the name my_solution.csv my_solution.to_csv("../data/tatanic_solution_one.csv", index_label = ["PassengerId"]) # In[85]: # Create a new array with the added features: features_two features_two = train[["Pclass","Age","Sex","Fare",\ "SibSp", "Parch", "Embarked"]].values #Control overfitting by setting "max_depth" to 10 and "min_samples_split" to 5 : my_tree_two max_depth = 10 min_samples_split = 5 my_tree_two = tree.DecisionTreeClassifier(max_depth = max_depth, min_samples_split = min_samples_split, random_state = 1) my_tree_two = my_tree_two.fit(features_two, target) #Print the score of the new decison tree print(my_tree_two.score(features_two, target)) # In[86]: # create a new train set with the new variable train_two = train train_two['family_size'] = train.SibSp + train.Parch + 1 # Create a new decision tree my_tree_three features_three = train[["Pclass", "Sex", "Age", \ "Fare", "SibSp", "Parch", "family_size"]].values my_tree_three = tree.DecisionTreeClassifier() my_tree_three = my_tree_three.fit(features_three, target) # Print the score of this decision tree print(my_tree_three.score(features_three, target)) # In[87]: #Import the `RandomForestClassifier` from sklearn.ensemble import RandomForestClassifier #We want the Pclass, Age, Sex, Fare,SibSp, Parch, and Embarked variables features_forest = train[["Pclass", "Age", "Sex", "Fare", "SibSp", "Parch", "Embarked"]].values #Building the Forest: my_forest n_estimators = 100 forest = RandomForestClassifier(max_depth = 10, min_samples_split=2, n_estimators = n_estimators, random_state = 1) my_forest = forest.fit(features_forest, target) #Print the score of the random forest print(my_forest.score(features_forest, target)) #Compute predictions and print the length of the prediction vector:test_features, pred_forest test_features = test[["Pclass", "Age", "Sex", "Fare", "SibSp", "Parch", "Embarked"]].values pred_forest = my_forest.predict(test_features) print(len(test_features)) print(pred_forest[:3]) # In[88]: #Request and print the `.feature_importances_` attribute print(my_tree_two.feature_importances_) print(my_forest.feature_importances_) #Compute and print the mean accuracy score for both models print(my_tree_two.score(features_two, target)) print(my_forest.score(features_two, target)) # # 阅读材料 # 机器学习算法的要点(附 Python 和 R 代码)http://blog.csdn.net/a6225301/article/details/50479672 # # The "Python Machine Learning" book code repository and info resource https://github.com/rasbt/python-machine-learning-book # # An Introduction to Statistical Learning (James, Witten, Hastie, Tibshirani, 2013) : Python code https://github.com/JWarmenhoven/ISLR-python # # BuildingMachineLearningSystemsWithPython https://github.com/luispedro/BuildingMachineLearningSystemsWithPython # # 作业 # https://www.datacamp.com/community/tutorials/the-importance-of-preprocessing-in-data-science-and-the-machine-learning-pipeline-i-centering-scaling-and-k-nearest-neighbours