tensorflow模拟仿真

本文介绍如何使用TensorFlow模拟几滴雨水落入方形水池所产生的波动,并演示了如何利用偏微分方程进行仿真模拟的基本步骤。
部署运行你感兴趣的模型镜像
TensorFlow 不仅仅是用来机器学习,它更可以用来模拟仿真。在这里,我们将通过模拟仿真几滴落入一块方形水池的雨点的例子,来引导您如何使用 TensorFlow 中的偏微分方程来模拟仿真的基本使用方法。

参考[url]http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/pdes.html[/url]

[url]https://stackoverflow.com/questions/28237210/image-does-not-display-in-ipython/42567537?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa[/url]
代码运行不了
修改如下


yum install libpng-devel freetype-devel -y
yum install tcl tk tix-devel -y
yum install tk-devel tcl-devel -y
yum -y install tkinter




virtualenv pianweifen

pip install --upgrade pip
#pip-10.0.1
pip install tensorflow
pip install matplotlib
pip install pillow

pip install ipython
pip install scipy



把display(Image(data=f.getvalue()))
改成
scipy.misc.imsave("testimg.jpg", a)
image = PIL.Image.open("testimg.jpg")
image.show()


# encoding: utf-8
#导入模拟仿真需要的库
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#导入可视化需要的库
import PIL.Image
from cStringIO import StringIO
#from io import BytesIO
import scipy.misc
from IPython.display import clear_output, Image, display

def DisplayArray(a, fmt='jpeg', rng=[0,1]):
"""Display an array as a picture."""
a = (a - rng[0])/float(rng[1] - rng[0])*255
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
# f = BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
# display(Image(data=f.getvalue()))
scipy.misc.imsave("testimg.jpg", a)
image = PIL.Image.open("testimg.jpg")
image.show()
#def DisplayArray(a, rng=[0 ,1]):
# plt.ion()
# a = (a - rng[0])/float(rng[1]-rng[0])*255
# a = np.uint8(np.clip(a, 0, 255))
# print(a)
# plt.imshow(a, cmap='gray')
# plt.pause(1)
# plt.close()
sess = tf.InteractiveSession()

def make_kernel(a):
"""Transform a 2D array into a convolution kernel"""
a = np.asarray(a)
a = a.reshape(list(a.shape) + [1,1])
return tf.constant(a, dtype=1)

def simple_conv(x, k):
"""A simplified 2D convolution operation"""
x = tf.expand_dims(tf.expand_dims(x, 0), -1)
y = tf.nn.depthwise_conv2d(x, k, [1, 1, 1, 1], padding='SAME')
return y[0, :, :, 0]

def laplace(x):
"""Compute the 2D laplacian of an array"""
laplace_k = make_kernel([[0.5, 1.0, 0.5],
[1.0, -6., 1.0],
[0.5, 1.0, 0.5]])
return simple_conv(x, laplace_k)

N = 500

# Initial Conditions -- some rain drops hit a pond

# Set everything to zero
u_init = np.zeros([N, N], dtype="float32")
ut_init = np.zeros([N, N], dtype="float32")

# Some rain drops hit a pond at random points
for n in range(40):
a,b = np.random.randint(0, N, 2)
u_init[a,b] = np.random.uniform()

DisplayArray(u_init, rng=[-0.1, 0.1])


]
python hello.py
[img]http://dl2.iteye.com/upload/attachment/0130/0049/ecfe97d0-e884-32f2-af79-ffc3e7cd1cce.png[/img]


完整版还不完美的图片闪现的版本

# encoding: utf-8
#导入模拟仿真需要的库
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#导入可视化需要的库
import PIL.Image
from cStringIO import StringIO
#from io import BytesIO
import scipy.misc
from IPython.display import clear_output, Image, display

def DisplayArray(a, fmt='jpeg', rng=[0,1]):
"""Display an array as a picture."""
a = (a - rng[0])/float(rng[1] - rng[0])*255
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
# f = BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
#display(Image(data=f.getvalue()))
scipy.misc.imsave("testimg.jpg", a)
image = PIL.Image.open("testimg.jpg")
image.show()
sess = tf.InteractiveSession()

def make_kernel(a):
"""Transform a 2D array into a convolution kernel"""
a = np.asarray(a)
a = a.reshape(list(a.shape) + [1,1])
return tf.constant(a, dtype=1)

def simple_conv(x, k):
"""A simplified 2D convolution operation"""
x = tf.expand_dims(tf.expand_dims(x, 0), -1)
y = tf.nn.depthwise_conv2d(x, k, [1, 1, 1, 1], padding='SAME')
return y[0, :, :, 0]

def laplace(x):
"""Compute the 2D laplacian of an array"""
laplace_k = make_kernel([[0.5, 1.0, 0.5],
[1.0, -6., 1.0],
[0.5, 1.0, 0.5]])
return simple_conv(x, laplace_k)

N = 500

# Initial Conditions -- some rain drops hit a pond

# Set everything to zero
u_init = np.zeros([N, N], dtype="float32")
ut_init = np.zeros([N, N], dtype="float32")

# Some rain drops hit a pond at random points
for n in range(40):
a,b = np.random.randint(0, N, 2)
u_init[a,b] = np.random.uniform()

DisplayArray(u_init, rng=[-0.1, 0.1])


eps = tf.placeholder(tf.float32, shape=())
damping = tf.placeholder(tf.float32, shape=())

# Create variables for simulation state
U = tf.Variable(u_init)
Ut = tf.Variable(ut_init)

# Discretized PDE update rules
U_ = U + eps * Ut
Ut_ = Ut + eps * (laplace(U) - damping * Ut)

# Operation to update the state
step = tf.group(
U.assign(U_),
Ut.assign(Ut_))
# Initialize state to initial conditions
tf.initialize_all_variables().run()

# Run 1000 steps of PDE
for i in range(1000):
# Step simulation
step.run({eps: 0.03, damping: 0.04})
# Visualize every 50 steps
if i % 50 == 0:
clear_output()
DisplayArray(U.eval(), rng=[-0.1, 0.1])

您可能感兴趣的与本文相关的镜像

TensorFlow-v2.15

TensorFlow-v2.15

TensorFlow

TensorFlow 是由Google Brain 团队开发的开源机器学习框架,广泛应用于深度学习研究和生产环境。 它提供了一个灵活的平台,用于构建和训练各种机器学习模型

<think>我们正在讨论NumPynp.savenp.savez的区别及适用场景。根据引用[1]和引用[2]:-np.save:将单个数组保存到.npy格式的二进制文件中。-np.savez:将多个数组保存到.npz格式的文件中(实际上是一个压缩包,包含多个.npy文件)。-np.savez_compressed:与np.savez类似,但会进行压缩以减小文件大小。区别:1.保存对象数量:-np.save只能保存一个数组。-np.saveznp.savez_compressed可以保存多个数组。2.文件格式:-np.save生成的文件扩展名为.npy。-np.savez生成的文件扩展名为.npz(实际上是一个zip文件,包含多个.npy文件)。3.压缩情况:-np.savenp.savez不压缩(但.npy格式本身是二进制,已经比文本文件小)。-np.savez_compressed会对存储的数组进行压缩,适合大型数组。使用场景:-当你只有一个数组需要保存时,使用np.save(简单直接)。-当有多个数组需要一起保存,并且希望用一个文件存储时,使用np.saveznp.savez_compressed。-如果数组非常大,且希望节省磁盘空间,使用np.savez_compressed。引用说明:-引用[1]提到np.saveznp.savez_compressed的区别,并指出.npz文件本质是压缩包,按键名存储访问。-引用[2]指出np.save是以.npy格式保存单个数组。-引用[3]展示了np.savenp.savez的使用示例。-引用[4]展示了在np.savez中保存字典的例子(注意字典需要设置allow_pickle=True)。回答结构:1.概述两者的主要区别(以对比表格形式呈现,清晰明了)。2.分别介绍两种方法的适用场景。3.给出具体代码示例说明两种方法的用法。4.添加注意事项(例如压缩对性能的影响)。表格设计(Markdown格式):|特性|np.save|np.savez/np.savez_compressed||------------------|---------------------------|---------------------------------------||保存数组数量|单个|多个||文件扩展名|.npy|.npz||是否支持压缩|否|np.savez:否;np.savez_compressed:是||加载方式|np.load直接返回数组|np.load返回类似字典对象,按关键字获取||适用场景|单个数组存储|多个数组的存储和压缩存储|注意:在写代码示例时,要体现:-np.save:保存和加载单个数组。-np.savez:保存多个数组,并展示如何按名称加载。注意事项:-使用np.savez_compressed可以节省磁盘空间,但压缩和解压缩需要时间,因此需要权衡。-对于非常大的数组,压缩可能会显著增加保存和加载的时间,但可以减少I/O时间(因为文件小),实际效果需测试。代码示例:示例1:使用np.save```pythonimportnumpyasnparr=np.array([1,2,3])np.save('single_array.npy',arr)#保存loaded_arr=np.load('single_array.npy')#加载```示例2:使用np.savez(多个数组)```pythonimportnumpyasnpa=np.array([1,2,3])b=np.array([4,5,6])#保存np.savez('multiple_arrays.npz',array1=a,array2=b)#加载withnp.load('multiple_arrays.npz')asdata:a_loaded=data['array1']b_loaded=data['array2']```示例3:使用np.savez_compressed```pythonnp.savez_compressed('compressed_arrays.npz',a=a,b=b)#加载方式与np.savez相同```最后,生成相关问题。</think> ### NumPy `np.save` 与 `np.savez` 的区别及适用场景 `np.save` 和 `np.savez` 是 NumPy 中用于数组保存的核心函数,主要区别体现在 **文件格式、存储机制和适用场景** 上: | **特性** | `np.save` | `np.savez` | `np.savez_compressed` | |------------------|------------------------|------------------------|-----------------------------| | **文件格式** | `.npy` (单文件) | `.npz` (压缩包) | `.npz` (压缩包) | | **存储对象** | **单个数组** | **多个数组** | **多个数组(带压缩)** | | **底层机制** | 原始二进制数据存储 | ZIP压缩包内嵌`.npy`文件 | ZIP压缩包内嵌压缩的`.npy`文件 | | **加载方式** | 直接返回数组对象 | 返回类似字典的对象 | 返回类似字典的对象 | | **主要优势** | 高效I/O,加载速度快 | 多数组统一管理 | 磁盘空间优化 | | **推荐场景** | 单一大型数组存储 | 关联数据集(如模型权重)| 大型数据集长期存储 | #### 详细区别说明 1. **存储机制差异** - `np.save(file, arr)` 将单个数组 `arr` 保存为二进制 `.npy` 文件,格式紧凑无需解压 ```python np.save("single_array.npy", arr) # 保存单个数组 data = np.load("single_array.npy") # 直接加载数组[^2] ``` - `np.savez(file, a=arr1, b=arr2)` 将多个数组打包为 ZIP 格式的 `.npz` 文件,实际包含多个内部 `.npy` 文件 ```python np.savez("multi_data.npz", weights=model_weights, bias=model_bias) data = np.load("multi_data.npz") # 返回NpzFile对象 weights = data["weights"] # 按键名提取[^1] ``` 2. **空间与性能权衡** - `np.savez_compressed` 在 `np.savez` 基础上增加 **DEFLATE 压缩算法**,降低存储空间(尤其适合稀疏矩阵) ```python # 压缩率示例:原始大小1GB的浮点数组可压缩至~300MB np.savez_compressed("compressed.npz", large_arr=big_data) ``` **代价**: 保存/加载时间增加约 20-50%(需 CPU 压缩解压)[^1] 3. **元数据处理** `.npz` 文件通过 **键值对命名** 保留数组语义信息,避免混淆: ```python # 保存时明确命名 np.savez("experiment_data.npz", input_data=X, labels=y, config=params_dict) # 加载时按名称索引 with np.load("experiment_data.npz") as data: X = data["input_data"] # 清晰语义 y = data["labels"] # 避免arr_0/arr_1混乱[^4] ``` #### 适用场景推荐 | **场景** | **推荐函数** | **原因** | |------------------------------|----------------------|--------------------------------------------------------------------------| | 存储单个大型数组(如张量) | `np.save` | 无压缩开销,I/O速度最快 | | 保存模型权重+结构参数 | `np.savez` | 多组件统一存储,加载逻辑清晰 | | 实验数据集(输入+标签) | `np.savez` | 关联数据保持同步,避免文件散落 | | 归档历史数据(需节省空间) | `np.savez_compressed`| 显著减少磁盘占用,尤其适合float32/64数组 | | 内存有限环境加载部分数据 | `.npz` + 延迟加载 | 支持仅加载特定数组(如`data['key']`),避免全量读入[^3] | #### 注意事项 1. 避免键名冲突:`np.savez` 的键名需唯一(如重复则覆盖) 2. 对象序列化:字典等非数组对象需设置 `allow_pickle=True` 3. 路径处理:Windows路径使用 `r"C:\data.npz"` 避免转义问题 --- ### 相关问题 1. 如何在加载`.npz`文件时仅读取特定数组而避免全量加载? 2. 对于超大型数组(>10GB),使用`np.savez`时有哪些性能优化技巧? 3. `np.savez`保存的字典等Python对象在加载时需要注意什么限制? 4. 如何将`.npz`文件集成到PyTorch/TensorFlow的数据加载流程中? 5. 对比`np.savez`和HDF5格式,各自的优劣及适用场景是什么?
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值