重要函数

正则化:
L1正则化:相当于维度约减,使权重基本为0 截断作用
L2正则化:相当于权重伸缩,使w变小。

特征工程

使用pandas读取数据,构建dataframe,pd.DatetimeIndex()对时间数据进行处理,分离日期和时间,pd.to_datetime()修改时间格式,pd.DatetimeIndex(data.date).dayofweek取星期几的判断,dataFeatureCon.T.to_dict().values() 转换成python中的dict,对连续数据和离散分别处理,用sklearn的preprocessing.StandardScaler().fit()标准化连续数据,用preprocessing.OneHotEncoder().fit()编码离散化数据,最后用np.concatenate()组合连续和离散数据。

import pandas ad pd
data=pd.read_csv(...)
data.head()  #查看数据长啥样
temp=pd.DatetimeIndex(data['datetime'])  #处理时间字段,划分成date和time
data['date'] = temp.date
data['time'] = temp.time
data['hour'] = pd.to_datetime(data.time, format="%H:%M:%S")  #修改时间格式
data['hour'] = pd.Index(data['hour']).hour
# 我们对时间类的特征做处理,产出一个星期几的类别型变量
data['dayofweek'] = pd.DatetimeIndex(data.date).dayofweek
#删除字段 
dataRel = data.drop(['datetime', 'count','date','time','dayofweek'], axis=1)
#pandas的dataframe可以直接转成python中的dict
X_dictCon = dataFeatureCon.T.to_dict().values() 
from sklearn.feature_extraction import DictVectorizer
# 向量化特征
vec = DictVectorizer(sparse = False)
X_vec_con = vec.fit_transform(X_dictCon)
from sklearn import preprocessing
# 标准化连续值数据
scaler = preprocessing.StandardScaler().fit(X_vec_con)
X_vec_con = scaler.transform(X_vec_con)
# one-hot编码离散数据
enc = preprocessing.OneHotEncoder()
enc.fit(X_vec_cat)
X_vec_cat = enc.transform(X_vec_cat).toarray()
import numpy as np
# 组合离散、连续数据
X_vec = np.concatenate((X_vec_con,X_vec_cat), axis=1)
线性回归

由 sklearn.linear_model 模块中的 LinearRegression 类实现回归

构造方法
sklearn.linear_model.LinearRegression(fit_intercept=True #默认值为 True,表示计算随机变量,False 表示不计算随机变量
, normalize=False #默认值为 False, 表示在回归前是否对回归因子 X 进行归一化,True 表示是
, copy_X=True)
属性

coef_ :存储 w1 wp 的值,与x的维度一致
intercept_ : 存储 w0 的值

方法
decision_function(X)#返回 X 的预测值 y 
fit(X,y[,n_jobs]) #拟合模型
get_params([deep]) #获取 LinearRegression 构造方法的参数信息 #同 decision_function
predict(X) #求预测值,同decision_function(X)
score(X,y[,sample_weight]) #得分
set_params(**params) #设置 LinearRegression 构造方法的参数值
逻辑回归

scikit-learn逻辑回归库:http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression

正则化项

from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(6)
XX = poly.fit_transform(data2[:,0:2])

1.定义sigmoid函数

def sigmoid(z):
    return(1 / (1 + np.exp(-z)))

2.定义损失函数

# 定义损失函数
def costFunctionReg(theta, reg, *args):
    m = y.size
    h = sigmoid(XX.dot(theta))
    J = -1.0*(1.0/m)*(np.log(h).T.dot(y)+np.log(1-h).T.dot(1-y)) + (reg/(2.0*m))*np.sum(np.square(theta[1:]))  
    if np.isnan(J[0]):
        return(np.inf)
    return(J[0])

3.求解梯度

#求解梯度
def gradientReg(theta, reg, *args):
    m = y.size
    h = sigmoid(XX.dot(theta.reshape(-1,1)))  
    grad = (1.0/m)*XX.T.dot(h-y) + (reg/m)*np.r_[[[0]],theta[1:].reshape(-1,1)]
    return(grad.flatten())
    initial_theta = np.zeros(XX.shape[1])
costFunctionReg(initial_theta, 1, XX, y)

4.最小化损失函数:

# 最优化 costFunctionReg
res2 = minimize(costFunctionReg, initial_theta, args=(C, XX, y), jac=gradientReg, options={'maxiter':3000})
# 准确率
accuracy = 100.0*sum(predict(res2.x, XX) == y.ravel())/y.size    
SVC
from sklearn import svm
svc = svm.SVC(kernel='linear')#线性核函数
svc.fit(x,y)
svm.LinearSVC()#线性支持向量分类器,对稀疏数据和文本挖掘更快
svc = svm.SVC(kernel='linear', C=1e3)#正则化项,默认为1
svc = svm.SVC(kernel='poly', degree=4)#多项式核函数
svc = svm.SVC(kernel='rbf', gamma=1e2)#径向基函数,也就是高斯核
Netural network
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值