8.28数模(十法)

1.线性回归

预测一个连续的输出变量

import numpy as np
from sklearn.linear_model import  LinearRegression
np.random.seed(0)
x=np.random.rand(100,1)
y=2+3*x+np.random.rand(100,1)
model=LinearRegression()//创建一个线性回归模型
model. Fit(x,y)//用现在的x,y来给这个模型,让它拟合,从而使之成为一个可以凭借原有数据来预测新数据的模型,不然,则是一个空模型
print(model.coef_)//打印当前模型的系数
print(model. Intercept_)//打印截距项,即常数项
x_new=np.array([[0.5],[1.0]])
y_new=model. Predict(x_new)//通过创建的模型预测新数据
print(y_new)

2.逻辑回归

预测一个离散的输出变量

import numpy as np
from sklearn.linear_model import LogisticRegression#逻辑回归头文件
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# 创建一个随机数据集
np.random.seed(0)
X = np.random.rand(100, 3)
y = np.random.randint(0, 2, 100)

# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
#测试集用来测试模型的准确度,不用来训练模型,相当于没有答案的题,考试
#不然,模型有了这个数据就会加之来进一步拟合
# 创建逻辑回归模型并拟合数据
model = LogisticRegression()#建立了一个逻辑回归的空模型
model.fit(X_train, y_train)#用训练集(不改变的)来训练这个模型
#使之从空模型转变为有参数的模型

# 预测测试集的结果
y_pred = model.predict(X_test)
#通过训练的模型得到的结果
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
#将模型结果与标准答案作比对,得当前模型的准确度
print('Accuracy:', accuracy)

三、决策树:用于分类和回归问题,通过构建一个树状结构来做出决策

四、支持向量机:用于分类和回归问题,通过找到一个最优的分离超平面来进行分类

from sklearn.datasets import load_iris
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split

# 载入数据集
iris = load_iris()

# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2, random_state=42)
#大部分用来训练,让模型拟合数据,小部分用来测试,测试模型的拟合程度与合理性
# 创建 SVM 分类器并拟合数据
clf = SVC(kernel='linear', C=1.0, random_state=42)
#kernel表示核函数,上句建立了一个核函数为线性核的SVM分类器,
clf.fit(X_train, y_train)
#用训练集的数据来训练这个SVM
# 预测测试集的结果
y_pred = clf.predict(X_test)

# 计算分类器在测试集上的准确率
accuracy = clf.score(X_test, y_test)
print("Accuracy: {:.2f}%".format(accuracy * 100))

五、聚类:用于将数据集中的数据分为不同的组。

七、遗传算法:用于寻找优化问题的最优解。
遗传算法是一种模仿自然选择和遗传机制的优化算法,主要用于求解最优化问题。它模拟了生物进化过程中的遗传、交叉和变异过程,通过不断地进化优秀的个体,逐渐搜索到全局最优解。

遗传算法的基本流程如下:

1.初始化种群:随机生成一组个体作为种群。
2.评价适应度:对每个个体进行适应度评价,通常使用目标函数计算个体的适应度
3.选择操作:根据每个个体的适应度,选择一部分个体作为父代,用于产生下一代。
4.交叉操作:对父代个体进行交叉操作,产生新的个体。
5.变异操作:对新的个体进行变异操作,产生更多的多样性。
6.评价新个体:对新的个体进行适应度评价。
7.判断终止条件:如果满足终止条件,则输出最优解;否则返回第3步

import random
 
# 目标函数:f(x) = x^2
def objective_function(x):
    return x ** 2
 
# 生成随机个体
def generate_individual():
    return random.uniform(-10, 10)
 
# 计算个体适应度
def calculate_fitness(individual):
    return 1 / (1 + objective_function(individual))
 
# 选择操作
def selection(population):
    fitnesses = [calculate_fitness(individual) for individual in population]
    total_fitness = sum(fitnesses)
    probabilities = [fitness / total_fitness for fitness in fitnesses]
    selected = random.choices(population, weights=probabilities, k=len(population))
    return selected
 
# 交叉操作
def crossover(individual1, individual2):
    alpha = random.uniform(0, 1)
    new_individual1 = alpha * individual1 + (1 - alpha) * individual2
    new_individual2 = alpha * individual2 + (1 - alpha) * individual1
    return new_individual1, new_individual2
 
# 变异操作
def mutation(individual):
    new_individual = individual + random.uniform(-1, 1)
    return new_individual
 
# 遗传算法求解最小值问题
population_size = 100
population = [generate_individual() for i in range(population_size)]
num_generations = 1000
for generation in range(num_generations):
    # 选择操作
    selected_population = selection(population)
    
    # 交叉操作
    offspring_population = []
    for i in range(population_size):
        offspring1, offspring2 = crossover(selected_population[i], selected_population[(i+1) % population_size])
        offspring_population.append(offspring1)
        offspring_population.append(offspring2)
    
    # 变异操作
    for i in range(population_size):
        if random.uniform(0, 1) < 0.1:
            offspring_population[i] = mutation(offspring_population[i])
    
    #

八、粒子群算法:用于寻找优化问题的最优解。
粒子群算法(Particle Swarm Optimization,PSO)是一种基于群体智能的优化算法,通过模拟群体中粒子的移动和群体的信息交流来实现优化目标的搜索。每个粒子在搜索空间中移动,并记录自己的最优位置和群体的最优位置,通过不断地调整自己的位置和速度,逐渐接近最优解。

粒子群算法的基本流程如下:

1.初始化粒子群:随机生成一组粒子的位置和速度。
2.计算适应度值:对每个粒子进行适应度计算,通常使用目标函数计算粒子的适应度。
3.更新个体最优值:将每个粒子的当前位置作为个体最优位置,如果该位置优于个体历史最优位置,则更新个体历史最优位置。
4.更新群体最优值:将所有粒子的个体最优位置作为群体最优位置。
5.更新速度和位置:根据粒子当前位置、速度和群体最优位置,计算新的速度和位置。
6.判断终止条件:如果满足终止条件,则输出最优解;否则返回第2步

import random
 
# 目标函数:f(x) = x^2
def objective_function(x):
    return x ** 2
 
# 生成随机粒子
def generate_particle():
    position = random.uniform(-10, 10)
    velocity = random.uniform(-1, 1)
    return {'position': position, 'velocity': velocity, 'personal_best_position': position, 'personal_best_fitness': objective_function(position)}
 
# 更新个体最优值
def update_personal_best(particle):
    fitness = objective_function(particle['position'])
    if fitness < particle['personal_best_fitness']:
        particle['personal_best_position'] = particle['position']
        particle['personal_best_fitness'] = fitness
 
# 更新群体最优值
def update_global_best(particles):
    global_best_position = particles[0]['personal_best_position']
    global_best_fitness = particles[0]['personal_best_fitness']
    for particle in particles:
        if particle['personal_best_fitness'] < global_best_fitness:
            global_best_position = particle['personal_best_position']
            global_best_fitness = particle['personal_best_fitness']
    return global_best_position, global_best_fitness
 
# 更新速度和位置
def update_velocity_and_position(particle, global_best_position):
    w = 0.5  # 惯性权重
    c1 = 0.5  # 个体学习因子
    c2 = 0.5  # 群体学习因子
    r1 = random.uniform(0, 1)
    r2 = random.uniform(0, 1)
    new_velocity = w * particle['velocity'] + c1 * r1 * (particle['personal_best_position'] - particle['position']) + c2 * r2 * (global_best_position - particle['position'])
    new

九、蚁群算法:用于解决组合优化问题。
蚁群算法(Ant Colony Optimization,ACO)是一种模拟蚂蚁在寻找食物时的行为和信息交流的启发式优化算法。该算法通过模拟蚂蚁的觅食行为,以信息素作为引导信息,通过搜寻路径上信息素的累积来实现最优路径的搜索。

蚁群算法的基本流程如下:

初始化信息素:对每条路径初始化一定量的信息素。
初始化蚂蚁位置:随机分配蚂蚁的起点位置。
选择下一步位置:根据当前位置和信息素分布选择下一步的位置。
更新信息素:根据蚂蚁经过的路径更新信息素。
判断终止条件:如果满足终止条件,则输出最优解;否则返回第3步。
 

import random
 
# 旅行商问题:求解城市之间的最短路径
class TSP:
    def __init__(self, num_cities, distance_matrix):
        self.num_cities = num_cities
        self.distance_matrix = distance_matrix
 
    # 计算路径长度
    def path_length(self, path):
        length = 0
        for i in range(len(path)-1):
            length += self.distance_matrix[path[i]][path[i+1]]
        length += self.distance_matrix[path[-1]][path[0]]
        return length
 
    # 生成随机解
    def random_solution(self):
        path = list(range(self.num_cities))
        random.shuffle(path)
        return path
 
# 蚂蚁类
class Ant:
    def __init__(self, tsp, alpha, beta, rho):
        self.tsp = tsp
        self.alpha = alpha  # 信息素重要程度因子
        self.beta = beta  # 启发式因子
        self.rho = rho  # 信息素挥发因子
        self.current_city = random.randint(0, tsp.num_cities-1)  # 当前所在城市
        self.visited_cities = [self.current_city]  # 已访问过的城市
        self.path_length = 0  # 路径长度
 
    # 选择下一步城市
    def choose_next_city(self, pheromone_matrix):
        unvisited_cities = list(set(range(self.tsp.num_cities)) - set(self.visited_cities))
        probabilities = [0] * len(unvisited_cities)
        total_pheromone = 0
        for i, city in enumerate(unvisited_cities):
            probabilities[i] = pheromone_matrix[self.current_city][city] ** self.alpha * ((1 / self.tsp.distance_matrix[self.current_city][city]) ** self.beta)
            total_pheromone += probabilities[i]
        if total_pheromone == 0:
            return random.choice(unvisited_cities)
        probabilities = [p / total_pheromone for p in probabilities]
        next_city = random.choices(unvisited_cities, weights=probabilities)[0]
       

十、模拟退火算法:用于在一个大的搜索空间中找到一个最优解。
模拟退火算法(Simulation Annealing,SA)是一种基于概率的全局优化算法,其灵感来源于固体材料在退火过程中的微观状态变化过程。该算法通过一定的概率接受一个劣解以避免陷入局部最优解,并在迭代过程中逐渐降低概率,最终达到全局最优解的目的。

模拟退火算法的基本流程如下:

初始化温度T、初始解x、终止温度Tmin和降温速率α。
迭代直至温度降至Tmin:在当前解x的邻域中随机生成一个新解y。
判断接受概率:计算当前解x和新解y的差值ΔE,如果ΔE<0,则接受新解y;否则以一定概率接受新解y,概率为e^(-ΔE/T)。
降温:通过降温速率α逐渐降低温度T。
返回第2步。
 

import math
import random


# 旅行商问题:求解城市之间的最短路径
class TSP:
    def __init__(self, num_cities, distance_matrix):
        self.num_cities = num_cities
        self.distance_matrix = distance_matrix

    # 计算路径长度
    def path_length(self, path):
        length = 0
        for i in range(len(path) - 1):
            length += self.distance_matrix[path[i]][path[i + 1]]
        length += self.distance_matrix[path[-1]][path[0]]
        return length

    # 生成随机解
    def random_solution(self):#只管生成一种方式
        path = list(range(self.num_cities))
        random.shuffle(path)
        return path

#问题的描述类
#问题的解法类,后者包含于前者,前者里有随机生成一种情况的方法
# 模拟退火类
class SimulatedAnnealing:#退火类里包含问题类
    def __init__(self, tsp, T, Tmin, alpha):
        self.tsp = tsp
        self.T = T  # 初始温度
        self.Tmin = Tmin  # 终止温度
        self.alpha = alpha  # 降温速率

    # 计算接受概率
    def acceptance_probability(self, old_cost, new_cost, T):
        if new_cost < old_cost:
            return 1#肯定是越小越好,
        else:#当完全小于时,即完全接受,概率就是1
            return math.exp(-(new_cost - old_cost) / T)#不然,则计算接受的概率
        #与旧值的差距越小越容易被接受
        #当前温度越小越不容易被接受,即邻近结束时不易被结束新解

    # 迭代求解
    def solve(self):
        current_solution = self.tsp.random_solution()
        current_cost = self.tsp.path_length(current_solution)
        while self.T > self.Tmin:#只要当前温度大于最小温度,就说明还没结束,可以继续
            new_solution = self.tsp.random_solution()#调用解法里的问题类的随机生成函数,生成一种可行的解
            new_cost = self.tsp.path_length(new_solution)#调用解法里的问题类里的计算费用函数,计算这种随机生成的路径的费用
            if self.acceptance_probability(current_cost, new_cost, self.T) > random.random():#当前者概率为1时,即好于现在解的时候,则肯定结束
                #不然则随缘接受
                current_solution = new_solution
                current_cost = new_cost
            self.T *= self.alpha#下降温度
        return current_solution, current_cost
    #总结就是生成的解是随机的
    #接不接受是随缘的,好了就接受,不好就摆,随缘
    #只有生成几次是确定,认为控制的,最后是个什么结果都不好说

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值