【ML_Algorithm 1】线性回归(Linear Regression)——算法推导及代码实现

::::::::线性回归::::::::

       第一式

                  第二式

从式一到式二,需要添加一个 x_{0} 项,其中 x_{0} 为 x_{0} = 1 的常数量。只是为了容易写成代码而已。


真实值=预测值+误差(误差是独立且具有相同的分布,通常认为服从均值为0的方差为 \theta ^{2} 的高斯分布。)

此式意思是要找到一个θ值使得该θ与x的组合完之后,使得组合值接近y真实值的概率最大化。


为了使得概率最大,我们用到了似然函数

我们所希望的到的L(θ)的值是越大越好——代表了所有的y(i)与其真实值都是尽可能相等的。击球什么样的θ可以使得L(θ)的整体值是最大的。

 

  • 为了使得求解变得简单一些,我们引入对数似然函数  l(θ) = ln L(θ) 

  • 牢记,咱们要求的是似然函数L(θ)的值尽可能大,也就是使对数似然函数l(θ)的最大值,通过化简的到上式,所以咱们要做的就是使右式J(θ)值最小。!

  • 关于J(θ)的求解:

(上面第二步是对 θ 求偏导操作,矩阵求导不做解释,不过可以从上图看出一二)


#以下代码是对以上原理的简单应用。目前我的环境尚未搭建妥当,所以还没有去跑代码,先码在这里,等之后参考

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets

class LinearRegression():
    def __init__(self):
        self.w = None
    def fit(self,X,y):
        #训练阶段
        #Insert constant ones for bias weights
        print (X.shape)
        #x0 = 1 
        X=np.insert(X,0,1,axis=1)
        print (X.shape)
        #对X的转置取逆操作。
        X_ = np.linalg.iniv(X.T.dot(X))
        self.w = X_.dot(X.T).dot(y)
    def predict(self,X):
        #测试阶段
        #Insert constant ones for bias weights
        X = np.insert(X,0,1,axis=1)
        y_pred = X.dot(self.w)
        return y_pred

def mean_squared_error(y_true, ypred):
    mse = np.mean(np.power(y_true - y_pred, 2))
    return mse


def main():
    #Load the diabetes dataset
    diabetes = datasets.load_diabetes()
    
    #Use only one feature
    X = diabetes.data[:, np.newaxis, 2]
    print(X.shape)
    
    #Split the data into training/testing sets
    x_train, x_test = X[:-20],X[-20:]
    
    #Split the targets into training/testing sets
    y_train, y_test = diabetes.target[:-20], diabetes.target[-20:]
    
    clf = LinearRegression()
    clf.fit(x_train, y_train)
    y_pred = clf.predict(x_test)
    
    #Print the mean squared error
    print ("Mean Souared Error:"mean_squared_error(y_test, y_pred))
    
    #Plot the results
    plt.scatter(x_test[:,0], y_test, color='black')
    plt.plot(x_test[:,0], y_pred, color='blue',linewidth=3)
    plt.show()

 

参考:

唐_机器学习

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
# Machine learning algorithms A collection of minimal and clean implementations of machine learning algorithms. ### Why? This project is targeting people who want to learn internals of ml algorithms or implement them from scratch. The code is much easier to follow than the optimized libraries and easier to play with. All algorithms are implemented in Python, using numpy, scipy and autograd. ### Implemented: * [Deep learning (MLP, CNN, RNN, LSTM)](mla/neuralnet) * [Linear regression, logistic regression](mla/linear_models.py) * [Random Forests](mla/ensemble/random_forest.py) * [Support vector machine (SVM) with kernels (Linear, Poly, RBF)](mla/svm) * [K-Means](mla/kmeans.py) * [Gaussian Mixture Model](mla/gaussian_mixture.py) * [K-nearest neighbors](mla/knn.py) * [Naive bayes](mla/naive_bayes.py) * [Principal component analysis (PCA)](mla/pca.py) * [Factorization machines](mla/fm.py) * [Restricted Boltzmann machine (RBM)](mla/rbm.py) * [t-Distributed Stochastic Neighbor Embedding (t-SNE)](mla/tsne.py) * [Gradient Boosting trees (also known as GBDT, GBRT, GBM, XGBoost)](mla/ensemble/gbm.py) * [Reinforcement learning (Deep Q learning)](mla/rl) ### Installation cd MLAlgorithms pip install scipy numpy pip install . ### How to run examples without installation cd MLAlgorithms python -m examples.linear_models ### How to run examples within Docker cd MLAlgorithms docker build -t mlalgorithms . docker run --rm -it mlalgorithms bash python -m examples.linear_models ### Contributing Your contributions are always welcome! Feel free to improve existing code, documentation or implement new algorithm. Please open an issue to propose your changes if they big are enough.
银行家算法是一种避免死锁的方法,它将资源请求看作是一个系统状态,并通过安全性算法来确定是否应该分配资源。下面是一个简单的实现代码及注释,以及流程图。 ```python # 定义可用资源的数量 available = [3, 3, 2] # 定义进程数和资源数 n_processes = 5 n_resources = 3 # 定义每个进程已分配的资源数量 allocation = [[0, 1, 0], [2, 0, 0], [3, 0, 2], [2, 1, 1], [0, 0, 2]] # 定义每个进程还需要的资源数量 need = [[7, 4, 3], [1, 2, 2], [6, 0, 0], [0, 1, 1], [4, 3, 1]] # 定义一个标记列表,标记每个进程是否可以完成 finish = [False] * n_processes # 定义一个安全序列列表,用于存储安全序列 safe_sequence = [] # 定义一个函数,用于判断是否存在安全序列 def is_safe(): # 复制可用资源列表 work = available[:] # 遍历每个进程 for i in range(n_processes): # 如果当前进程未完成且所需资源小于等于可用资源 if not finish[i] and all(need[i][j] <= work[j] for j in range(n_resources)): # 将该进程标记为完成 finish[i] = True # 将已分配资源加回可用资源列表中 work = [work[j] + allocation[i][j] for j in range(n_resources)] # 添加当前进程到安全序列中 safe_sequence.append(i) # 重新遍历所有进程 return is_safe() # 如果所有进程都完成了,返回True return all(finish) # 如果存在安全序列,打印出安全序列 if is_safe(): print("安全序列为:", safe_sequence) else: print("不存在安全序列") ``` 流程图如下: ![银行家算法流程图](banker_algorithm.png) 首先定义了可用资源数量、进程数和资源数、已分配的资源数量、还需要的资源数量等变量。然后定义了一个函数is_safe(),用于判断是否存在安全序列。在该函数中,遍历每个进程,如果当前进程未完成且所需资源小于等于可用资源,则将该进程标记为完成,将已分配资源加回可用资源列表中,添加当前进程到安全序列中,重新遍历所有进程。如果所有进程都完成了,则返回True。最后,如果存在安全序列,打印出安全序列,否则打印出不存在安全序列。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值