学习Python中记不住的一些函数
1.np.linspace(start, end, num) : 在区间[start, end]均匀取num个点。
2.plt.scatter(x, y) :画二维坐标的散点图
plt.scatter(x, y, c=z, cmap=’bwr’): 画散点图,但是点有类,用于画分类的散点图。
3.数据的逆 X.I, 数组的转置X.T
4.读取CSV文件:
import pandas as pd
df = pd.read_csv('course-5-boston.csv')
df.head() #读取前五行
df.tail() #读取后五行
df.describe() #显示对应数据的平均值,中位数等信息
在df中对数据分为训练集和测试集:
split_num = int(len(df)*0.7)
特征x, features:train_x=features[:split_num], test_x = features[split_num:]
标签y,label:train_y=label[:split_num], test_y=label[split_num:]
5.线性回归模型:
from sklearn.linear_model import **LinearRegression**
model = LinearRegression() # 建立模型
model.fit(train_x, train_y) # 训练模型
model.coef_, model.intercept_ # 输出训练后的模型参数和截距项
preds = model.predict(test_x) # 输入测试集特征进行预测
6.
features = df[['公交','写字楼','医院', '商场', '地铁', '学校', '建造时间', '楼层', '面积']]
target = df['每平米价格']
pd.concat([features, target], axis=1) #对两个进行列拼接,组成一个新的csv格式的文件
7.np.poly1d([a, b, c]) :生成k次的多项式, y=a*x^2+ b*x^1+c
8.
from scipy.optimize import leastsq
#err_func:误差函数 , p_init:参数初始化
parameters = leastsq(err_func, p_init, args=(np.array(x), np.array(y)))
print('Fitting parameters: ', parameters[0])
9.
通过 PolynomialFeatures() 类自动产生多项式特征矩阵,
from sklearn.preprocessing import PolynomialFeatures
PolynomialFeatures(degree: 多项式次数,默认为 2 次多项式
interaction_only: 默认为 False,如果为 True 则产生相互影响的特征集。
include_bias: 默认为 True,包含多项式中的截距项。)
X=[2, -1, 3]
X_reshape = np.array(X).reshape(len(X), 1) # 转换为列向量
PolynomialFeatures(degree=2, include_bias=False).**fit_transform**(X_reshape)
10.
平均绝对误差MAE: from sklearn.metrics import mean_absolute_error
均方误差MSE: from sklearn.metrics import mean_squared_error
11.
make_pipeline 是使用 sklearn 过程中的技巧创新,其可以将一个处理流程封装起来使用。
from sklearn.pipeline import make_pipeline
train_x = train_x.reshape(len(train_x),1)
test_x = test_x.reshape(len(test_x),1)
train_y = train_y.reshape(len(train_y),1)
for m in [3, 4, 5]:
model = make_pipeline(PolynomialFeatures(m, include_bias=False), LinearRegression())
model.fit(train_x, train_y)
pre_y = model.predict(test_x)
print("{} 次多项式回归平均绝对误差: ".format(m), mean_absolute_error(test_y, pre_y.flatten()))
print("{} 次多项式均方根误差: ".format(m), mean_squared_error(test_y, pre_y.flatten()))
print("---")
12.
from matplotlib import pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(16,5))
axes[0].plot(data['btc_market_price'], 'g')
axes[0].set_xlabel('Time')
axes[0].set_ylabel('btc_market_price')
plt.plot(x, mse, 'r')
plt.scatter(x, mse)
plt.title("MSE")
plt.xlabel("N")
plt.ylabel("MSE")
13.岭回归Ridge: L2约束
#数据集的列(特征)数量 > 数据量(行数量),即 XX 不是列满秩。
#数据集列(特征)数据之间存在较强的线性相关性,即模型容易出现过拟合。
sklearn.linear_model.Ridge(alpha=1.0, fit_intercept=True, normalize=False,
copy_X=True, max_iter=None, tol=0.001, solver='auto',
random_state=None)
alpha: 正则化强度,默认为 1.0,对应约束项系数。
fit_intercept: 默认为 True,计算截距项。
normalize: 默认为 False,不针对数据进行标准化处理。
copy_X: 默认为 True,即使用数据的副本进行操作,防止影响原数据。
max_iter: 最大迭代次数,默认为 None。
tol: 数据解算精度。
solver: 根据数据类型自动选择求解器。
random_state: 随机数发生器。
from sklearn.linear_model import Ridge
ridge_model = Ridge(fit_intercept=False) # 参数代表不增加截距项
ridge_model.fit(x, y)
ridge_model.coef_ # 打印模型参数
更改不同的alpha:
ridge = Ridge(alpha=a, fit_intercept=False)
14.Lasso回归: L1约束
sklearn.linear_model.Lasso(alpha=1.0, fit_intercept=True, normalize=False,
precompute=False, copy_X=True, max_iter=1000,
tol=0.0001, warm_start=False, positive=False,
random_state=None, selection='cyclic')
alpha: 正则化强度,默认为 1.0。
fit_intercept: 默认为 True,计算截距项。
normalize: 默认为 False,不针对数据进行标准化处理。
precompute: 是否使用预先计算的 Gram 矩阵来加速计算。
copy_X: 默认为 True,即使用数据的副本进行操作,防止影响原数据。
max_iter: 最大迭代次数,默认为 1000。
tol: 数据解算精度。
warm_start: 重用先前调用的解决方案以适合初始化。
positive: 强制系数为正值。
random_state: 随机数发生器。
selection: 每次迭代都会更新一个随机系数。
15.
e = np.eye(n)
e = np.ones(3),np.ones((3, 4))
e = np.zeros(3), np.ones((2, 3))
16.逻辑回归 Logistic Regression
LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0, fit_intercept=True,
intercept_scaling=1, class_weight=None, random_state=None,
solver='liblinear', max_iter=100, multi_class='ovr',
verbose=0, warm_start=False, n_jobs=1)
介绍其中几个常用的参数,其余使用默认即可:
penalty: 惩罚项,默认为 L2L2 范数。
dual: 对偶化,默认为 False。
tol: 数据解算精度。
fit_intercept: 默认为 True,计算截距项。
random_state: 随机数发生器。
max_iter: 最大迭代次数,默认为 100。
from sklearn.linear_model import LogisticRegression
model = LogisticRegression(tol=0.001, max_iter=10000) # 设置一样的学习率和迭代次数
model.fit(x, y)
model.coef_, model.intercept_
plt.figure(figsize=(10, 6))
plt.scatter(df['X0'],df['X1'], c=df['Y'])
x1_min, x1_max = df['X0'].min(), df['X0'].max(),
x2_min, x2_max = df['X1'].min(), df['X1'].max(),
xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))
grid = np.c_[xx1.ravel(), xx2.ravel()]
probs = (np.dot(grid, model.coef_.T) + model.intercept_).reshape(xx1.shape)
plt.contour(xx1, xx2, probs, levels=[0], linewidths=1, colors='red');
17 数据集的划分:训练集和测试集:
from sklearn.model_selection import train_test_split
feature_data = lilac_data.iloc[:, :-1] #取的范围
label_data = lilac_data['labels']
x_train, x_test, y_train, y_test = train_test_split(feature_data, label_data,
test_size=0.3, random_state=2)
18 np.ceil 取整
np.ceil(20 / 3) = 6.0