Python和C++及MATLAB低温磁态机器学习模型

news2024/10/12 0:55:44

🎯要点

  1. 使用小规模磁态训练模型,并在二维三维爱德华兹-安德森模型上使用四种算法测试:贪婪算法、模拟退火算法、并行回火算法和本模型。
  2. 将磁态基态搜索视为马尔可夫决策过程 (MDP),学习最优策略以累积其最大回报。
  3. 设计图神经网络式编码器表征状态和动作。
  4. 模型求解非确定性多项式时间问题。

🍁磁态分析

  • Python和MATLAB自旋玻璃投资组合神经网络广义方程
    在这里插入图片描述

🍪语言内容分比

在这里插入图片描述
在这里插入图片描述

🍇Python马尔可夫决策过程策略选择

我们将要实现的马尔可夫决策过程是一个离散时间随机控制过程。它提供了一个数学框架,用于在结果部分随机、部分受决策者控制的情况下对决策进行建模。马尔可夫决策过程是一种对顺序决策问题进行建模的工具,其中决策者以顺序方式与环境进行交互。

假设问题是:我们有一个由 12 个状态组成的世界,1 个障碍初始状态(状态 5)和 2 个结束状态(状态 10、11)。对于每个状态,我们都有一个奖励,我们希望找到实施最佳奖励累积的策略。对于每个状态,奖励为 -0.04(r=-0.4)。对于状态 10,奖励为 1,对于结束状态 11,奖励为 -1。
1 4 7 10 2 5 8 11 3 6 9 12 \begin{array}{|l|l|l|l|} \hline 1 & 4 & 7 & 10 \\ \hline 2 & 5 & 8 & 11 \\ \hline 3 & 6 & 9 & 12 \\ \hline \end{array} 123456789101112
对于所处的每一个状态,我们都想找到最好的行动,是向北(N)、向南(S)、向东(E)还是向西(W)走。基本上,我们希望以最短的路到达状态 10。首先,让我们创建一个世界类,它将在我们的世界中用于解决问题。这个对象可以帮助我们声明世界、绘制世界并绘制我们发现的移动世界的策略。方法 plot_world 绘制了我们上面看到的图像,将使用值迭代方法代替策略迭代。

使用策略迭代求解马尔可夫决策过程,其中 γ = 0.9 和 r = 0.04。我们使用均匀随机策略初始化了策略迭代算法。并且分别使用 World 类的绘制值和绘制策略函数,将每次迭代步骤后的值函数和策略绘制成网格世界的两个不同图形,我们得到了以下结果:

初次迭代:网格世界值
− 0.287 − 0.169 0.05 1.0 − 0.354 − 0.479 − 1.0 − 0.402 − 0.451 − 0.524 − 0.696 \begin{array}{|l|l|l|l|} \hline-0.287 & -0.169 & 0.05 & 1.0 \\ \hline-0.354 & & -0.479 & -1.0 \\ \hline-0.402 & -0.451 & -0.524 & -0.696 \\ \hline \end{array} 0.2870.3540.4020.1690.4510.050.4790.5241.01.00.696

二次迭代:

0.509 0.649 0.795 1.0 0.398 0.486 − 1.0 0.291 0.207 0.168 − 0.009 \begin{array}{|l|l|l|c|} \hline 0.509 & 0.649 & 0.795 & 1.0 \\ \hline 0.398 & & 0.486 & -1.0 \\ \hline 0.291 & 0.207 & 0.168 & -0.009 \\ \hline \end{array} 0.5090.3980.2910.6490.2070.7950.4860.1681.01.00.009

三次迭代:
0.509 0.649 0.795 1.0 0.398 0.486 − 1.0 0.291 0.207 0.34 0.126 \begin{array}{|l|l|l|l|} \hline 0.509 & 0.649 & 0.795 & 1.0 \\ \hline 0.398 & & 0.486 & -1.0 \\ \hline 0.291 & 0.207 & 0.34 & 0.126 \\ \hline \end{array} 0.5090.3980.2910.6490.2070.7950.4860.341.01.00.126
四次迭代:
0.509 0.649 0.795 1.0 0.398 0.486 − 1.0 0.296 0.253 0.344 0.129 \begin{array}{|l|l|l|l|} \hline 0.509 & 0.649 & 0.795 & 1.0 \\ \hline 0.398 & & 0.486 & -1.0 \\ \hline 0.296 & 0.253 & 0.344 & 0.129 \\ \hline \end{array} 0.5090.3980.2960.6490.2530.7950.4860.3441.01.00.129

我们可以看到,经过 4 次迭代后我们得到了解,并且我们可以看到与上一次迭代相比,每次迭代的进展情况。如果使用值迭代,应该得到与策略迭代算法相同的结果。

世界类:

import numpy as np
import matplotlib.pyplot as plt

class World:

    def __init__(self):

        self.nRows = 3
        self.nCols = 4
        self.stateObstacles = [5]
        self.stateTerminals = [10, 11]
        self.nStates = 12
        self.nActions = 4

    def _plot_world(self):

        nStates = self.nStates
        nRows = self.nRows
        nCols = self.nCols
        stateObstacles = self.stateObstacles
        stateTerminals = self.stateTerminals
        coord = [[0, 0], [nCols, 0], [nCols, nRows], [0, nRows], [0, 0]]
        xs, ys = zip(*coord)
        plt.plot(xs, ys, "black")
        for i in stateObstacles:
            (I, J) = np.unravel_index(i, shape=(nRows, nCols), order='F')
            coord = [[J, nRows - I],
                     [J + 1, nRows - I],
                     [J + 1, nRows - I + 1],
                     [J, nRows - I + 1],
                     [J, nRows - I]]
            xs, ys = zip(*coord)
            plt.fill(xs, ys, "0.5")
            plt.plot(xs, ys, "black")
        for ind, i in enumerate(stateTerminals):
            (I, J) = np.unravel_index(i, shape=(nRows, nCols), order='F')
            coord = [[J, nRows - I],
                     [J + 1, nRows - I],
                     [J + 1, nRows - I + 1],
                     [J, nRows - I + 1],
                     [J, nRows - I]]
            xs, ys = zip(*coord)
            plt.fill(xs, ys, "0.8")
            plt.plot(xs, ys, "black")
        plt.plot(xs, ys, "black")
        X, Y = np.meshgrid(range(nCols + 1), range(nRows + 1))
        plt.plot(X, Y, 'k-')
        plt.plot(X.transpose(), Y.transpose(), 'k-')

    @staticmethod
    def _truncate(n, decimals=0):
        multiplier = 10 ** decimals
        return int(n * multiplier) / multiplier

    def plot(self):
        nStates = self.nStates
        nRows = self.nRows
        nCols = self.nCols
        self._plot_world()
        states = range(1, nStates + 1)
        k = 0
        for i in range(nCols):
            for j in range(nRows, 0, -1):
                plt.text(i + 0.5, j - 0.5, str(states[k]), fontsize=26, horizontalalignment='center', verticalalignment='center')
                k += 1
        plt.title('MDP gridworld', size=16)
        plt.axis("equal")
        plt.axis("off")
        plt.show()

    def plot_value(self, valueFunction):

        nRows = self.nRows
        nCols = self.nCols
        stateObstacles = self.stateObstacles
        self._plot_world()
        k = 0
        for i in range(nCols):
            for j in range(nRows, 0, -1):
                if k + 1 not in stateObstacles:
                    plt.text(i + 0.5, j - 0.5, str(self._truncate(valueFunction[k], 3)), fontsize=26, horizontalalignment='center', verticalalignment='center')
                k += 1
        plt.title('MDP gridworld', size=16)
        plt.axis("equal")
        plt.axis("off")
        plt.show()

    def plot_policy(self, policy):

        nStates = self.nStates
        nActions = self.nActions
        nRows = self.nRows
        nCols = self.nCols
        stateObstacles = self.stateObstacles
        stateTerminals = self.stateTerminals
        policy = policy.reshape(nRows, nCols, order="F").reshape(-1, 1)
        X, Y = np.meshgrid(range(nCols + 1), range(nRows + 1))
        X1 = X[:-1, :-1]
        Y1 = Y[:-1, :-1]
        X2 = X1.reshape(-1, 1) + 0.5
        Y2 = np.flip(Y1.reshape(-1, 1)) + 0.5
        X2 = np.kron(np.ones((1, nActions)), X2)
        Y2 = np.kron(np.ones((1, nActions)), Y2)
        mat = np.cumsum(np.ones((nStates, nActions)), axis=1).astype("int64")
        if policy.shape[1] == 1:
            policy = (np.kron(np.ones((1, nActions)), policy) == mat)
        index_no_policy = stateObstacles + stateTerminals
        index_policy = [item - 1 for item in range(1, nStates + 1) if item not in index_no_policy]
        mask = policy.astype("int64") * mat
        mask = mask.reshape(nRows, nCols, nCols)
        X3 = X2.reshape(nRows, nCols, nActions)
        Y3 = Y2.reshape(nRows, nCols, nActions)
        alpha = np.pi - np.pi / 2 * mask
        self._plot_world()
        for ii in index_policy:
            ax = plt.gca()
            j = int(ii / nRows)
            i = (ii + 1 - j * nRows) % nCols - 1
            index = np.where(mask[i, j] > 0)[0]
            h = ax.quiver(X3[i, j, index], Y3[i, j, index], np.cos(alpha[i, j, index]), np.sin(alpha[i, j, index]), 0.3)
        states = range(1, nStates + 1)
        k = 0
        for i in range(nCols):
            for j in range(nRows, 0, -1):
                plt.text(i + 0.25, j - 0.25, str(states[k]), fontsize=16, horizontalalignment='right', verticalalignment='bottom')
                k += 1
        plt.axis("equal")
        plt.axis("off")
        plt.show()

主程度:

from World import World
import numpy as np
import pandas as pd
import copy


def construct_p(world, p=0.8, step=-0.04):

    nstates = world.get_nstates()
    nrows = world.get_nrows()
    obsacle_index = world.get_stateobstacles()
    terminal_index = world.get_stateterminals()
    bad_index = obsacle_index + terminal_index
    rewards = np.array([step] * 4 + [0] + [step] * 4 + [1, -1] + [step])
    actions = ["N", "S", "E", "W"]
    transition_models = {}
    for action in actions:
        transition_model = np.zeros((nstates, nstates))
        for i in range(1, nstates + 1):
            if i not in bad_index:
                if action == "N":
                    if i + nrows <= nstates and (i + nrows) not in obsacle_index:
                        transition_model[i - 1][i + nrows - 1] += (1 - p) / 2
                    else:
                        transition_model[i - 1][i - 1] += (1 - p) / 2
                    if 0 < i - nrows <= nstates and (i - nrows) not in obsacle_index:
                        transition_model[i - 1][i - nrows - 1] += (1 - p) / 2
                    else:
                        transition_model[i - 1][i - 1] += (1 - p) / 2
                    if (i - 1) % nrows > 0 and (i - 1) not in obsacle_index:
                        transition_model[i - 1][i - 1 - 1] += p
                    else:
                        transition_model[i - 1][i - 1] += p
                if action == "S":
                    if i + nrows <= nstates and (i + nrows) not in obsacle_index:
                        transition_model[i - 1][i + nrows - 1] += (1 - p) / 2
                    else:
                        transition_model[i - 1][i - 1] += (1 - p) / 2
                    if 0 < i - nrows <= nstates and (i - nrows) not in obsacle_index:
                        transition_model[i - 1][i - nrows - 1] += (1 - p) / 2
                    else:
                        transition_model[i - 1][i - 1] += (1 - p) / 2
                    if 0 < i % nrows and (i + 1) not in obsacle_index and (i + 1) <= nstates:
                        transition_model[i - 1][i + 1 - 1] += p
                    else:
                        transition_model[i - 1][i - 1] += p
                if action == "E":
                    if i + nrows <= nstates and (i + nrows) not in obsacle_index:
                        transition_model[i - 1][i + nrows - 1] += p
                    else:
                        transition_model[i - 1][i - 1] += p
                    if 0 < i % nrows and (i + 1) not in obsacle_index and (i + 1) <= nstates:
                        transition_model[i - 1][i + 1 - 1] += (1 - p) / 2
                    else:
                        transition_model[i - 1][i - 1] += (1 - p) / 2
                    if (i - 1) % nrows > 0 and (i - 1) not in obsacle_index:
                        transition_model[i - 1][i - 1 - 1] += (1 - p) / 2
                    else:
                        transition_model[i - 1][i - 1] += (1 - p) / 2
                if action == "W":
                    if 0 < i - nrows <= nstates and (i - nrows) not in obsacle_index:
                        transition_model[i - 1][i - nrows - 1] += p
                    else:
                        transition_model[i - 1][i - 1] += p
                    if 0 < i % nrows and (i + 1) not in obsacle_index and (i + 1) <= nstates:
                        transition_model[i - 1][i + 1 - 1] += (1 - p) / 2
                    else:
                        transition_model[i - 1][i - 1] += (1 - p) / 2
                    if (i - 1) % nrows > 0 and (i - 1) not in obsacle_index:
                        transition_model[i - 1][i - 1 - 1] += (1 - p) / 2
                    else:
                        transition_model[i - 1][i - 1] += (1 - p) / 2
            elif i in terminal_index:
                transition_model[i - 1][i - 1] = 1
        transition_models[action] = pd.DataFrame(transition_model, index=range(1, nstates + 1), columns=range(1, nstates + 1))

    return transition_models, rewards


def max_action(transition_models, rewards, gamma, s, V, actions, terminal_ind):

    maxs = {key: 0 for key in actions}
    max_a = ""
    action_map = {k: v for k, v in zip(actions, [1, 3, 2, 4])}
    for action in actions:
        if s not in terminal_ind:
            maxs[action] += rewards[s - 1] + gamma * np.dot(transition_models[action].loc[s, :].values, V)
        else:
            maxs[action] = rewards[s - 1]
    maxi = -10 ** 10
    for key in maxs:
        if maxs[key] > maxi:
            max_a = key
            maxi = maxs[key]
    return maxi, action_map[max_a]


def value_iteration(world, transition_models, rewards, gamma=1.0, theta=10 ** -4):

    nstates = world.get_nstates()
    terminal_ind = world.get_stateterminals()
    V = np.zeros((nstates, ))
    P = np.zeros((nstates, 1))
    actions = ["N", "S", "E", "W"]
    delta = theta + 1
    while delta > theta:
        delta = 0
        v = copy.deepcopy(V)
        for s in range(1, nstates + 1):
            V[s - 1], P[s - 1] = max_action(transition_models, rewards, gamma, s, v, actions, terminal_ind)
            delta = max(delta, np.abs(v[s - 1] - V[s - 1]))
    return V, P


def policy_iter(policy, world, transition_models, rewards, gamma=0.9, theta=10 ** -4):

    nstates = world.get_nstates()
    terminal_ind = world.get_stateterminals()

    V = np.zeros((nstates,))
    a = ["N", "S", "E", "W"]
    while True:
        delta = 0

        for s in range(nstates):
            v = 0
 
            for action, action_prob in enumerate(policy[s]):
                action = a[action]

                if s not in terminal_ind:
                    v += rewards[s - 1] + action_prob * gamma * np.dot(transition_models[action].loc[s, :].values, V)
                else:
                    v = rewards[s - 1]
            delta = max(delta, np.abs(v - V[s]))
            V[s] = v
            print (V[s])
        if delta < theta:
            break
    return np.array(V)

👉参阅、更新:计算思维 | 亚图跨际

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2206422.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

从0开始深度学习(9)——softmax回归的逐步实现

文章使用Fashion-MNIST数据集&#xff0c;做一次分类识别任务 Fashion-MNIST中包含的10个类别&#xff0c;分别为&#xff1a; t-shirt&#xff08;T恤&#xff09;、trouser&#xff08;裤子&#xff09;、pullover&#xff08;套衫&#xff09;、dress&#xff08;连衣裙&…

SSD |(二)SSD主控

文章目录 &#x1f4da;控制器架构&#x1f407;PCIe和NVMe控制器前端子系统&#x1f407;NAND闪存控制器后端子系统&#x1f407;内存子系统&#x1f407;安全子系统&#x1f407;CPU计算子系统 &#x1f4da;控制器架构 控制器作为一个片上系统&#xff0c;处理来自用户端的…

Linux下的Makefile基本操作

1.Makefile与 make介绍 在Linux中&#xff0c; Makefile 是⼀个⽂件&#xff0c; 令会在当前⽬录下找 make 是⼀个指令&#xff0c;当使⽤ Makefile ⽂件从⽽执⾏内部的内容 2.创建第一个 Makefile并使用make ⾸先&#xff0c;在当前⽬录下创建⼀个makefile文件 接下来在同级…

【小工具分享】下载保存指定网页的所有图片

一、保存百度首页所有的图片 先看一下保存的图片情况 二、思路 1、打开网页 2、获取所有图片 3、依次下载保存图片到指定路径 三、完整代码 from selenium import webdriver from selenium.webdriver.common.by import By b webdriver.Firefox() import urllib.request…

企业如何借力AI,提升人力资源管理的效率完成组织提效变革

大家好&#xff0c;我是Shelly&#xff0c;一个专注于输出AI工具和科技前沿内容的AI应用教练&#xff0c;体验过300款以上的AI应用工具。关注科技及大模型领域对社会的影响10年。关注我一起驾驭AI工具&#xff0c;拥抱AI时代的到来。 企业面临的压力&#xff1a; 在当今这个充…

LeetCode|70.爬楼梯

这道题很像斐波那契数列&#xff0c;但是初始值不同&#xff0c;也有动态规划的解法&#xff0c;但是一开始我想到的是递归写法。现在我们站在第n阶台阶&#xff0c;那么&#xff0c;我们上一步就有两种可能&#xff1a;1、我们从第n-1阶台阶走一步上来的&#xff1b;2、我们从…

商家转账到零钱接口开通

商家想要开通“商家转账到零钱”功能&#xff0c;需要遵循一系列详细步骤和条件&#xff0c;以确保顺利通过审核。以下是开通办法的详解&#xff1a; 申请流程&#xff1a; 主体资格确认&#xff1a;确保申请主体为公司性质&#xff08;有限公司&#xff09;&#xff0c;个体工…

ScribbleDiff:使用涂鸦引导扩散,实现无需训练的文本到图像生成

ScribbleDiff可以通过简单的涂鸦帮助计算机生成图像。比如你在纸上随意画了一些线条&#xff0c;表示你想要的图像的轮廓。ScribbleDiff会利用这些线条来指导图像生成的过程。 首先&#xff0c;它会分析这些涂鸦&#xff0c;确保生成的图像中的对象朝着你画的方向。比如&#…

品民俗、看展演、逛非遗市集……在海淀,重阳节还可以这样过

秋菊溢彩、叠翠鎏金。由北京市海淀区文化和旅游局主办,北京市海淀区文化馆承办,海淀区上庄镇文化活动中心支持的品鉴民俗 巧手绘梦——2024年海淀区重阳节非遗主题文化活动于10月11日在上庄镇市民活动中心顺利举办。海淀非遗传承人以非遗为媒,与地区群众度过了一个温馨、热闹、…

第四次论文问题知识点及问题

1、NP-hard问题 NP-hard&#xff0c;指所有NP问题都能在多项式时间复杂度内归约到的问题。 2、启发式算法 ‌‌启发式算法&#xff08;heuristic algorithm&#xff09;是相对于最优化算法提出的。它是一种基于直观或经验构造的算法&#xff0c;旨在以可接受的花费给出待解决…

Android 如何实现远程网页控制售卖机出商品:RabbitMQ的对接,如何使用?如何断网重连?连接不上后台的MQ有哪些方面的原因

目录 一、如何实现远程网页控制售卖机出商品&#xff1f; 比如&#xff0c;我们想实现&#xff0c;通过一个网页去控制自动售卖机&#xff08;自动售卖机装有Android系统&#xff0c;装有App&#xff09;出商品&#xff0c;也就是我们熟知的远程控制&#xff0c;不用你人到现场…

搭建电商商城系统各项功能时需要用到的电商API数据采集接口

在搭建电商商城系统时&#xff0c;选择合适的电商API接口至关重要。以下是一些常用的电商API接口提供商及其功能&#xff1a; 常用电商API接口提供商 淘宝开放平台&#xff1a;提供淘宝、天猫、1688等阿里巴巴集团旗下的电商平台接口&#xff0c;用于商品检索、订单管理、物流…

如何把pdf转换成jpg图片?在线pdf转图片,这6种方法很简单!

“如何把pdf转换成jpg图片&#xff1f;”相信很多小伙伴们都有这个疑问。pdf格式是如今在商业和其他正式场合中使用最广泛的文档类型&#xff0c;因为它能以安全且方便的方式共享信息。然而&#xff0c;查看pdf文件通常需要使用一些专业的pdf阅读器&#xff0c;这可能给一些用户…

服务端给客户端push消息的demo的实现流程

摘要&#xff1a; 本示例演示了一个基本的服务端5分钟定时向客户端app推送消息的WebSocket机制。服务端使用WebSocket协议接受客户端的订阅和取消订阅请求&#xff0c;并根据客户端的订阅状态发送实时消息。服务端记录并打印带有时间戳的日志&#xff0c;以监控订阅活动。客户…

python画图|二维动态柱状图输出

【1】引言 在前面的学习过程中&#xff0c;已经探索过二维柱状图和三维柱状图的绘制教程&#xff0c;包括且不限于的文章链接有&#xff1a; python画图|水平直方图绘制_绘制水平直方图-CSDN博客 python画图|3D bar进阶探索_ax.bar3d-CSDN博客 此外也学习了动态的直线输出和…

调用AI 通过相机识别地标

https://www.youtube.com/watch?vViRfnLAR_Uc&listPLQkwcJG4YTCRJxkPPDBcKqDWrfF5qanQs&index3学习视频 TensorFlow Hub 机器学习模型的代码库 找到地标模型 如何在Android上使用ts模型 https://blog.tensorflow.org/2018/03/using-tensorflow-lite-on-android.html…

10.11每日作业

数据表 #include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this);//想要添加某个数据库if(!db.contains("stu.db")){//如果当前对象中没有包含所需数据库&…

dowhy中反驳实验怎么做?

首先&#xff0c;我们打开最新的dowhy版本网站。 https://www.pywhy.org/dowhy/v0.11.1/index.html 我们主要看标题栏的User Guide和Examples就可以了&#xff0c;如果在User Guide 里找不到使用方法&#xff0c;就去Examples里找例子&#xff0c;里面的数据读取修改为自己的数…

HI6338 (DIP-8内置75W方案)

Hi6338 combines a dedicated current mode PWM controller with integrated high voltage power MOSFET.Vcc low startup current and low operating current contribute to a reliable power on startup design with Hi6338. the IC operates in Extended ‘burst mode’ to …

前端的全栈混合之路Meteor篇:分布式数据协议DDP深度剖析

本文属于进阶篇&#xff0c;并不是太适合新人阅读&#xff0c;但纯粹的学习还是可以的&#xff0c;因为后续会实现很多个ddp的版本用于web端、nodejs端、安卓端和ios端&#xff0c;提前预习和复习下。ddp协议是一个C/S架构的协议&#xff0c;但是客户端也同时可以是服务端。 什…