Python中使用TensorFlow和CNN进行预测的笔记
看到一个不错的深度学习做预测,在这里分享给大家。
配置环境 deepin 15.3 Anaconda 2.7 pip 清华镜像 tensorflow
%%time
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
%matplotlib inline
import seaborn as sns
import tensorflow as tf
fac = np.load(’/home/big/Quotes/TensorFlow deal with Uqer/fac16.npy’).astype(np.float32)
ret = np.load(’/home/big/Quotes/TensorFlow deal with Uqer/ret16.npy’).astype(np.float32)
#fac = np.load(’/home/big/Quotes/TensorFlow deal with Uqer/fac16.npy’)
#ret = np.load(’/home/big/Quotes/TensorFlow deal with Uqer/ret16.npy’)
Parameters
learning_rate = 0.001 # 学习速率,
training_iters = 20 # 训练次数
batch_size = 1024 # 每次计算数量 批次大小
display_step = 10 # 显示步长
Network Parameters
n_input = 40*17 # 40 天×17 多因子
n_classes = 7 # 根据涨跌幅度分成 7 类别
这里注意要使用 one-hot 格式,也就是如果分类如 3 类 -1,0,1 则需要 3 列来表达这个分类结果, 3 类是-1 0 1 然后是哪类,哪类那一行为 1 否则为 0
dropout = 0.8 # Dropout, probability to keep units
tensorflow 图 Graph 输入 input ,这里的占位符均为输入
x = tf.placeholder(tf.float32, [None, n_input])
y = tf.placeholder(tf.float32, [None, n_classes])
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)
2 层
# 2 层 CNN
def CNN_Net_two(x,weights,biases,dropout=0.8,m=1):
# 将输入张量调整成图片格式
# CNN 图像识别,这里将前 40 天的多因子数据假设成图片数据
x = tf.reshape(x, shape=[-1,40,17,1])
# 卷积层 1
x = tf.nn.conv2d(x, weights['wc1'], strides=[1,m,m,1],padding='SAME')
# x*W + b
x = tf.nn.bias_add(x,biases['bc1'])
# 激活函数
x = tf.nn.relu(x)
# 卷积层 2 感受野 5 5 16 64 移动步长 1
x = tf.nn.conv2d(x, weights['wc2'], strides=[1,m,m,1],padding='SAME')
x = tf.nn.bias_add(x,biases['bc2'])
x = tf.nn.relu(x)
# 全连接层
x = tf.reshape(x,[-1,weights['wd1'].get_shape().as_list()[0]])
x = tf.add(tf.matmul(x,weights['wd1']),biases['bd1'])
x = tf.nn.relu(x)
# Apply Dropout
x = tf.nn.dropout(x,dropout)
# Output, class prediction
x = tf.add(tf.matmul(x,weights['out']),biases['out'])
return x
Store layers weight & bias
weights = {
‘wc1’: tf.Variable(tf.random_normal([5, 5, 1, 16])),
‘wc2’: tf.Variable(tf.random_normal([5, 5, 16, 64])),
# fully connected, 7764 inputs, 1024 outputs
‘wd1’: tf.Variable(tf.random_normal([401764, 1024])),
‘out’: tf.Variable(tf.random_normal([1024, n_classes]))
}
biases = {
‘bc1’: tf.Variable(tf.random_normal([16])),
‘bc2’: tf.Variable(tf.random_normal([64])),
‘bd1’: tf.Variable(tf.random_normal([1024])),
‘out’: tf.Variable(tf.random_normal([n_classes]))
}
3 层
def CNN_Net_three(x,weights,biases,dropout=0.8,m=1):
x = tf.reshape(x, shape=[-1,40,17,1])
# 卷积层 1
x = tf.nn.conv2d(x, weights['wc1'], strides=[1,m,m,1],padding='SAME')
x = tf.nn.bias_add(x,biases['bc1'])
x = tf.nn.relu(x)
# 卷积层 2
x = tf.nn.conv2d(x, weights['wc2'], strides=[1,m,m,1],padding='SAME')
x = tf.nn.bias_add(x,biases['bc2'])
x = tf.nn.relu(x)
# 卷积层 3
x = tf.nn.conv2d(x, weights['wc3'], strides=[1,m,m,1],padding='SAME')
x = tf.nn.bias_add(x,biases['bc3'])
x = tf.nn.relu(x)
# 全连接层
x = tf.reshape(x,[-1,weights['wd1'].get_shape().as_list()[0]])
x = tf.add(tf.matmul(x,weights['wd1']),biases['bd1'])
x = tf.nn.relu(x)
# Apply Dropout
x = tf.nn.dropout(x,dropout)
# Output, class prediction
x = tf.add(tf.matmul(x,weights['out']),biases['out'])
return x
Store layers weight & bias
weights = {
‘wc1’: tf.Variable(tf.random_normal([5, 5, 1, 16])),
‘wc2’: tf.Variable(tf.random_normal([5, 5, 16, 32])),
‘wc3’: tf.Variable(tf.random_normal([5, 5, 32, 64])),
# fully connected, 7764 inputs, 1024 outputs
‘wd1’: tf.Variable(tf.random_normal([401764, 1024])),
‘out’: tf.Variable(tf.random_normal([1024, n_classes]))
}
biases = {
‘bc1’: tf.Variable(tf.random_normal([16])),
‘bc2’: tf.Variable(tf.random_normal([32])),
‘bc3’: tf.Variable(tf.random_normal([64])),
‘bd1’: tf.Variable(tf.random_normal([1024])),
‘out’: tf.Variable(tf.random_normal([n_classes]))
}
%%time
# 模型优化
pred = CNN_Net_two(x,weights,biases,dropout=keep_prob)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
correct_pred = tf.equal(tf.argmax(pred,1),tf.arg_max(y,1))
# tf.argmax(input,axis=None) 由于标签的数据格式是 -1 0 1 3 列,该语句是表示返回值最大也就是 1 的索引,两个索引相同则是预测正确。
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 更改数据格式,降低均值
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# for step in range(300):
for step in range(1):
for i in range(int(len(fac)/batch_size)):
batch_x = fac[i*batch_size:(i+1)*batch_size]
batch_y = ret[i*batch_size:(i+1)*batch_size]
sess.run(optimizer,feed_dict={x:batch_x,y:batch_y,keep_prob:dropout})
if i % 10 ==0:
print(i,'----',(int(len(fac)/batch_size)))
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,y: batch_y,keep_prob: 1.})
print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
"{:.6f}".format(loss) + ", Training Accuracy= " + \
"{:.5f}".format(acc))
print("Optimization Finished!")
sess.close()
5 层
def CNN_Net_five(x,weights,biases,dropout=0.8,m=1):
x = tf.reshape(x, shape=[-1,40,17,1])
# 卷积层 1
x = tf.nn.conv2d(x, weights['wc1'], strides=[1,m,m,1],padding='SAME')
x = tf.nn.bias_add(x,biases['bc1'])
x = tf.nn.relu(x)
# 卷积层 2
x = tf.nn.conv2d(x, weights['wc2'], strides=[1,m,m,1],padding='SAME')
x = tf.nn.bias_add(x,biases['bc2'])
x = tf.nn.relu(x)
# 卷积层 3
x = tf.nn.conv2d(x, weights['wc3'], strides=[1,m,m,1],padding='SAME')
x = tf.nn.bias_add(x,biases['bc3'])
x = tf.nn.relu(x)
# 卷积层 4
x = tf.nn.conv2d(x, weights['wc4'], strides=[1,m,m,1],padding='SAME')
x = tf.nn.bias_add(x,biases['bc4'])
x = tf.nn.relu(x)
# 卷积层 5
x = tf.nn.conv2d(x, weights['wc5'], strides=[1,m,m,1],padding='SAME')
x = tf.nn.bias_add(x,biases['bc5'])
x = tf.nn.relu(x)
# 全连接层
x = tf.reshape(x,[-1,weights['wd1'].get_shape().as_list()[0]])
x = tf.add(tf.matmul(x,weights['wd1']),biases['bd1'])
x = tf.nn.relu(x)
# Apply Dropout
x = tf.nn.dropout(x,dropout)
# Output, class prediction
x = tf.add(tf.matmul(x,weights['out']),biases['out'])
return x
Store layers weight & bias
weights = {
‘wc1’: tf.Variable(tf.random_normal([5, 5, 1, 16])),
‘wc2’: tf.Variable(tf.random_normal([5, 5, 16, 32])),
‘wc3’: tf.Variable(tf.random_normal([5, 5, 32, 64])),
‘wc4’: tf.Variable(tf.random_normal([5, 5, 64, 32])),
‘wc5’: tf.Variable(tf.random_normal([5, 5, 32, 16])),
# fully connected, 7764 inputs, 1024 outputs
‘wd1’: tf.Variable(tf.random_normal([401716, 1024])),
‘out’: tf.Variable(tf.random_normal([1024, n_classes]))
}
biases = {
‘bc1’: tf.Variable(tf.random_normal([16])),
‘bc2’: tf.Variable(tf.random_normal([32])),
‘bc3’: tf.Variable(tf.random_normal([64])),
‘bc4’: tf.Variable(tf.random_normal([32])),
‘bc5’: tf.Variable(tf.random_normal([16])),
‘bd1’: tf.Variable(tf.random_normal([1024])),
‘out’: tf.Variable(tf.random_normal([n_classes]))
}
%%time
# 模型优化
pred = CNN_Net_five(x,weights,biases,dropout=keep_prob)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
correct_pred = tf.equal(tf.argmax(pred,1),tf.arg_max(y,1))
# tf.argmax(input,axis=None) 由于标签的数据格式是 -1 0 1 3 列,该语句是表示返回值最大也就是 1 的索引,两个索引相同则是预测正确。
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# 更改数据格式,降低均值
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for step in range(1):
for i in range(int(len(fac)/batch_size)):
batch_x = fac[i*batch_size:(i+1)*batch_size]
batch_y = ret[i*batch_size:(i+1)*batch_size]
sess.run(optimizer,feed_dict={x:batch_x,y:batch_y,keep_prob:dropout})
print(i,'----',(int(len(fac)/batch_size)))
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,y: batch_y,keep_prob: 1.})
print("Iter " + str(step*batch_size) + ", Minibatch Loss= " + \
"{:.6f}".format(loss) + ", Training Accuracy= " + \
"{:.5f}".format(acc))
print("Optimization Finished!")
sess.close()
优化参数之后准确率大概在 94%+
该作者其他有关机器学习,深度学习方面的文章也推荐给大家,希望对大家有帮助:
Tensorflow 笔记 1 CNN : https://uqer.io/community/share/58637c716a5e6d00522939b7
TensorFlow 笔记 2 双向 LSTM : https://uqer.io/community/share/586a4eb889e3ba004defde4b
TensorFlow 笔记 3 多层 LSTM : https://uqer.io/community/share/586bb68423a7d60052a361f6
三个臭皮匠-集成算法框架上手 : https://uqer.io/community/share/58562a9f6a5e6d0052291ebe
Python中使用TensorFlow和CNN进行预测的笔记
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
# 1. 数据准备
# 假设我们处理的是MNIST手写数字数据集
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# 归一化并调整维度以适应CNN输入
x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype('float32') / 255.0
# 2. 构建CNN模型
model = models.Sequential([
# 第一卷积层
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
# 第二卷积层
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
# 展平层
layers.Flatten(),
# 全连接层
layers.Dense(64, activation='relu'),
# 输出层(10个类别)
layers.Dense(10, activation='softmax')
])
# 3. 编译模型
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 4. 训练模型
model.fit(x_train, y_train,
epochs=5,
batch_size=64,
validation_split=0.2)
# 5. 评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f"测试准确率: {test_acc:.4f}")
# 6. 进行预测
# 对测试集前5个样本进行预测
predictions = model.predict(x_test[:5])
predicted_classes = np.argmax(predictions, axis=1)
print("预测结果:", predicted_classes)
print("实际标签:", y_test[:5])
# 7. 保存模型(可选)
model.save('mnist_cnn_model.h5')
关键点说明:
-
数据预处理:CNN需要4D张量输入(样本数, 高度, 宽度, 通道数),MNIST数据需要从(60000, 28, 28)调整为(60000, 28, 28, 1)
-
模型架构:
- Conv2D:卷积层提取特征
- MaxPooling2D:池化层降低维度
- Flatten:将3D特征图展平为1D向量
- Dense:全连接层进行分类
-
激活函数:
- ReLU:卷积层和全连接层使用,避免梯度消失
- Softmax:输出层使用,将输出转换为概率分布
-
损失函数:sparse_categorical_crossentropy适用于整数标签的多分类问题
-
预测流程:
- model.predict()返回每个类别的概率
- np.argmax()获取概率最高的类别索引
一句话建议: 确保输入数据维度正确,这是CNN模型工作的前提。
顶一下
请问一下,数据集是什么样的呢

