基于python的ansys_基于python的感知机

一、

1、感知机可以描述为一个线性方程,用python的伪代码可表示为:

sum(weight_i * x_i) + bias -> activation  #activation表示激活函数,x_i和weight_i是分别为与当前神经元连接的其它神经元的输入以及连接的权重。bias表示当前神经元的输出阀值(或称偏置)。箭头(->)左边的数据,就是激活函数的输入

2、定义激活函数f:

def func_activator(input_value):

return 1.0 if input_value >= 0.0 else 0.0

二、感知机的构建

class Perceptron(object):

def __init__(self, input_para_num, acti_func):

self.activator = acti_func

self.weights = [0.0 for _ in range(input_para_num)]

def __str__(self):

return 'final weights\n\tw0 = {:.2f}\n\tw1 = {:.2f}\n\tw2 = {:.2f}' \

.format(self.weights[0],self.weights[1],self.weights[2])

def predict(self, row_vec):

act_values = 0.0

for i in range(len(self.weights)):

act_values += self.weights [ i ] * row_vec [ i ]

return self.activator(act_values)

def train(self, dataset, iteration, rate):

for i in range(iteration):

for input_vec_label in dataset:

prediction = self.predict(input_vec_label)

self._update_weights(input_vec_label,prediction, rate)

def _update_weights(self, input_vec_label, prediction, rate):

delta = input_vec_label[-1] - prediction

for i in range(len(self.weights):

self.weights[ i ] += rate * delta * input_vec_label[ i ]

def func_activator(input_value):

return 1.0 if input_value >= 0.0 else 0.0

def get_training_dataset():

dataset = [[-1, 1, 1, 1], [-1, 0, 0, 0], [-1, 1, 0, 0], [-1, 0, 1, 0]]

return dataset

def train_and_perceptron():

p = Perceptron(3, func_activator)

dataset = get_training_dataset()

return p

if __name__ == '__main__':

and_prerception = train_and_perceptron

print(and_prerception)

print('1 and 1 = %d' % and_perception.predict([-1, 1, 1]))

print('0 and 0 = %d' % and_perception.predict([-1, 1, 1]))

print('1 and 0 = %d' % and_perception.predict([-1, 1, 1]))

print('0 and 1 = %d' % and_perception.predict([-1, 1, 1]))

### 使用 PyFluent 进行深度学习开发实践 PyFluent 主要用于计算流体力学(CFD)模拟中的自动化流程、构建自定义工作流程以及创建定制化解决方案[^1]。然而,将 PyFluent 应用于深度学习领域并非其设计初衷;通常情况下,深度学习框架如 TensorFlow 或 PyTorch 更适合此类任务。 尽管如此,在某些特定场景下可以考虑结合 CFD 模拟数据作为输入特征来增强机器学习模型的表现力。下面提供了一个假设性的案例研究,展示如何利用 PyFluent 获取仿真结果并将其转换成可用于训练神经网络的数据集: #### 数据准备阶段 首先安装必要的库: ```bash pip install ansys-fluent-core numpy pandas scikit-learn tensorflow ``` 接着编写 Python 脚本读取 Fluent 输出文件,并提取感兴趣区域内的物理量分布情况: ```python from ansys.fluent.core import launch_fluent, examples import numpy as np import pandas as pd def get_simulation_data(case_file_path): session = launch_fluent(precision="double", processor_count=2) # 加载 case 文件 session.tui.file.read_case(case_file_path) # 执行求解过程... session.solution.initialization.hybrid_initialize() session.mesh.adaptive_refinement.on_demand.refine() # 提取出所需变量值 velocity_magnitude = session.results.graphics.vector.get_vector_plot('Velocity') pressure_distribution = session.field_info().get_field_data(['Pressure']) df = pd.DataFrame({ 'velocity': velocity_magnitude, 'pressure': pressure_distribution['Pressure'] }) return df ``` 此部分代码展示了怎样通过调用 `launch_fluent()` 函数启动 Fluent 实例,并加载指定路径下的 .cas 文件以执行初始化操作。之后获取速度大小与压力场信息保存至 Pandas DataFrame 对象中以便后续处理。 #### 构建预测模型 基于上述获得的CFD数据,现在可以尝试建立简单的回归分析模型来进行某种属性(比如阻力系数Cd)估计: ```python from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense # 假设已存在包含多个样本点及其对应 Cd 的 CSV 文件 dataframe = pd.read_csv('./cd_samples.csv') X = dataframe[['velocity', 'pressure']].values y = dataframe['Cd'].values.reshape(-1, 1) scaler_x = StandardScaler().fit(X) scaled_X = scaler_x.transform(X) model = Sequential([ Dense(64, activation='relu', input_shape=(2,)), Dense(32, activation='relu'), Dense(1), ]) model.compile(optimizer='adam', loss='mean_squared_error') history = model.fit(scaled_X, y, epochs=50, batch_size=8) new_sample = [[...]] # 新测得的速度和压强组合 predicted_cd = model.predict(new_sample)[0][0] print(f'Predicted drag coefficient (Cd): {predicted_cd:.4f}') ``` 这段脚本说明了如何采用 Keras API 定义一个多层感知机架构,并对其进行编译配置。随后使用标准化后的特征向量完成监督式学习任务——即给定一组新的流动条件参数时能够准确预报物体所受空气动力特性之一:阻力系数Cd。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值