python可视化卷积代码_TensorFlow实现图像卷积并可视化示例

图片尺寸要自己修改。

看起来好像没啥意思,不知道下一步能干什么,先卷了再说。由于weights是随机生成的(tf.random_normal作用:用于从服从指定正太分布的数值中取出随机数),所以每次卷积后的图像会不一样。

代码:

def func19(img_path):

# 读取图片,矩阵化,转换为张量

img_data = cv2.imread(img_path)

img_data = tf.constant(img_data, dtype=tf.float32)

print(img_data.shape)

# 将张量转化为4维

img_data = tf.reshape(img_data, shape=[1, 454, 700, 3])

print(img_data.shape)

# 权重(也叫filter、过滤器)

weights = tf.variable(tf.random_normal(shape=[2, 2, 3, 3] , dtype=tf.float32))

print(weights.shape)

# 卷积

conv = tf.nn.conv2d(img_data, weights, strides=[1, 3, 3, 1], padding='same')

print(conv.shape)

img_conv = tf.reshape(conv, shape=[152, 234, 3])

print(img_conv.shape)

img_conv = tf.nn.relu(img_conv)

with tf.session() as sess:

# 全局初始化

sess.run(tf.global_variables_initializer())

img_conv = sess.run(img_conv)

plt.title('conv')

plt.imshow(img_conv)

plt.show()

return

if __name__ == '__main__':

img_path = r'你的图片路径'

func19(img_path)

原图(尺寸:(454, 700, 3)):

效果(尺寸: (152, 234, 3) ):

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用Python和常见的深度学习库(如TensorFlow或PyTorch)进行二维卷积和t-SNE可视化示例代码: ```python import numpy as np import matplotlib.pyplot as plt from sklearn.manifold import TSNE import tensorflow as tf from tensorflow.keras.datasets import mnist # 加载MNIST数据集 (train_images, _), (_, _) = mnist.load_data() # 数据预处理 train_images = train_images.reshape(train_images.shape[0], 28, 28, 1) train_images = train_images.astype('float32') / 255 # 创建卷积神经网络模型(这里以TensorFlow为例) model = tf.keras.models.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(train_images, np.zeros(len(train_images)), epochs=1, batch_size=64) # 获取卷积层的输出特征 conv_layer = model.layers[0] conv_output = conv_layer.output # 创建新的模型,输出为卷积层的特征 feature_model = tf.keras.models.Model(inputs=model.input, outputs=conv_output) # 提取卷积特征 conv_features = feature_model.predict(train_images) # 使用t-SNE进行降维 tsne = TSNE(n_components=2) tsne_features = tsne.fit_transform(conv_features.reshape(conv_features.shape[0], -1)) # 可视化 plt.scatter(tsne_features[:, 0], tsne_features[:, 1], c='b', marker='o') plt.title('t-SNE Visualization of Convolutional Features') plt.show() ``` 这段代码使用MNIST数据集作为示例数据,创建了一个简单卷积神经网络模型,并提取了卷积层的输出特征。然后使用t-SNE对提取的特征进行降维,并将降维后的特征用散点图进行可视化展示。 请注意,这只是一个示例代码,实际应用中可能需要根据具体任务和数据集进行适当的调整和修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值