七。自定义数据集 使用tensorflow框架实现逻辑回归并保存模型,然后保存模型后再加载模型进行预测

import tensorflow as tf

import numpy as np

自定义数据集类

class CustomDataset(tf.data.Dataset):

def init(self, x_data, y_data):

self.x_data = tf.convert_to_tensor(x_data, dtype=tf.float32)

self.y_data = tf.convert_to_tensor(y_data, dtype=tf.float32)

def iter(self):

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

yield (self.x_datai, self.y_datai)

逻辑回归模型

class LogisticRegressionModel(tf.keras.Model):

def init(self, input_dim):

super(LogisticRegressionModel, self).init()

self.linear = tf.keras.layers.Dense(1, input_shape=(input_dim,), activation='sigmoid')

def call(self, x):

return self.linear(x)

创建数据集

x_data = np.array(\[1, 2, 3, 4, 5], dtype=np.float32)

y_data = np.array(\[0, 0, 1, 1, 1], dtype=np.float32)

dataset = CustomDataset(x_data, y_data)

创建数据加载器

dataloader = dataset.batch(2).shuffle(100).repeat()

创建模型、损失函数和优化器

model = LogisticRegressionModel(input_dim=1)

loss_object = tf.keras.losses.BinaryCrossentropy()

optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)

训练模型

epochs = 100

for epoch in range(epochs):

for x_batch, y_batch in dataloader:

with tf.GradientTape() as tape:

predictions = model(x_batch)

loss = loss_object(y_batch, predictions)

gradients = tape.gradient(loss, model.trainable_variables)

optimizer.apply_gradients(zip(gradients, model.trainable_variables))

if (epoch+1) % 10 == 0:

print(f'Epoch {epoch+1}/{epochs}, Loss: {loss.numpy():.4f}')

保存模型

model.save('logistic_regression_model.h5')

加载模型

model = tf.keras.models.load_model('logistic_regression_model.h5')

进行预测

x_test = np.array(\[6, 7, 8], dtype=np.float32)

y_pred = model.predict(x_test)

print('预测值:', y_pred)

相关推荐
ikun_文1 分钟前
Django框架路由Router的使用
python·pycharm·django
IvanCodes4 分钟前
Python 基础语法(二):字符串与常用操作
python
昭昭日月明10 分钟前
LangChain 生态:从链到代理,开发者需要掌握的三大核心
python·langchain·agent
Csvn17 分钟前
🐍 Day 8:面向对象编程
后端·python
程序员天天困19 分钟前
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
后端·python·ai编程
alphaTao2 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
苏灿烤鱼2 小时前
当 AI Agent 遇见真实科学环境:深度拆解 Scientific Agent Skills,把"聊天机器人"变成"AI 科学家"
python·开源·agent
张文君2 小时前
ubuntu26.04坏道坏块分区隔离急速版260831-V0.12
linux·python
lupai13 小时前
手机在网状态接口实测效果与质量评估
大数据·python·智能手机·api接口
荷蒲14 小时前
【小白量化Qbuddy】用AI设计miniQMT指标公式计算量化平台
人工智能·python·机器人