Python机器学习 Tensorflow + keras 实现CNN

一、实验目的

1. 了解SkLearn Tensorlow使用方法 

2. 了解SkLearn keras使用方法

二、实验工具:

1. SkLearn

三、实验内容 (贴上源码及结果)

 使用Tensorflow对半环形数据集分

#encoding:utf-8import numpy as npfrom sklearn.datasets import make_moonsimport tensorflow as tffrom sklearn.model_selection import train_test_splitfrom tensorflow.keras import layers,Sequential,optimizers,losses, metricsfrom tensorflow.keras.layers import Denseimport matplotlib.pyplot as plt#产生一个半环形数据集X,y= make_moons(200,noise=0.25,random_state=100)#划分训练集和测试集X_train,X_test, y_train, y_test= train_test_split(X, y, test_size=0.25,random_state=2)print(X.shape,y.shape)def make_plot(X,y,plot_name,XX=None, YY=None, preds=None):plt.figure()axes = plt.gca()x_min=X[:,0].min()-1x_max=X[:,0].max()+ 1y_min=X[:,1].min()-1y_max=X[:,1].max()+ 1axes.set_xlim([x_min,x_max])axes.set_ylim([y_min,y_max])axes.set(xlabel="$x 1$",ylabel="$x 2$")if XX is None and YY is None and preds is None:yr = y.ravel()for step in range(X[:,0].size):if yr[step]== 1:plt.scatter(X[step,0],X[step,1],c='b',s=20,edgecolors='none',marker='x')else:plt.scatter(X[step,0],X[step,1],c='r',s=30,edgecolors='none',marker='o')plt.show()else:plt.contour(XX,YY,preds,cmap=plt.cm.spring,alpha=0.8)plt.scatter(X[:, 0], X[:, 1], c = y, s = 20, cmap=plt.cm.Greens, edgecolors = 'k')plt.rcParams['font.sans-serif'] =['SimHei']plt.rcParams['axes.unicode_minus'] = Falseplt.title(plot_name)plt.show()make_plot(X, y, None)# 创建容器model = Sequential()# 创建第一层model.add(Dense(8, input_dim = 2, activation = 'relu'))for _ in range(3):model.add(Dense(32, activation='relu'))# 创建最后一层,激活model.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])history = model.fit(X_train, y_train, epochs = 30, verbose = 1)# 绘制决策曲线x_min = X[:,0].min() - 1x_max = X[:, 0].max() + 1y_min = X[:1].min() - 1y_max = X[:, 1].max() + 1XX, YY = np.meshgrid(np.arange(x_min, x_max, 0.01), np.arange(y_min, y_max, 0.01))Z = np.argmax(model.predict(np.c_[XX.ravel(), YY.ravel()]), axis=-1)preds =Z.reshape(XX.shape)title = "分类结果"make_plot(X_train, y_train, title, XX, YY, preds)

使用VGGNet 识别猫狗

from tensorflow import  keras                                from keras.applications.resnet import ResNet50               from keras.preprocessing import  image# #手写文字识别              from  keras.applications.resnet import preprocess_input,decodimport  numpy as np# #载人 MNIST 数据集                           from PIL import  ImageFont,ImageDraw,Image# #拆分数据集           # (x_train,y_train),(x_test,y_test)= mnist.load_data()      # #将样本进行预处理,并从整数转换为浮点数                                      # x_train,x_test=x_train/255.0,x_test /255.0                img1=r'C:\Users\PDHuang\Downloads\ch11\dog.jpg'# #使用 tf.kerasimg2=r'C:\Users\PDHuang\Downloads\ch11\cat.jpg'# model= tf.keimg3=r'C:\Users\PDHuang\Downloads\ch11\deer.jpg'# tf.keras.laweight_path=r'C:\Users\PDHuang\Downloads\ch11\resnet50_weightimg=image.load_img(img1,target_size=(224,224))#     tf.keras.x=image.img_to_array(img)#     tf.keras.layers.Dense(10,activx=np.expand_dims(x,axis=0)# ])                               x=preprocess_input(x)# #设置模型的优化器和损失函数                        def get_model():# model.compile(optimizer='adam',loss='sparsemodel=ResNet50(weights=weight_path)# #训练并验证模型            print(model.summary())# model.fit(x_train,y_train,epochs=return model# model.evaluate(x_test,y_test,verbose=2)    model=get_model()                                            #预测图片                                                        preds=model.predict(x)                                       #打印出top-5的结果                                                 print('predicted',decode_predictions(preds,top=5)[0])        

使用深度学习进行手写数字识别

#手写文字识别                                    import tensorflow as tf                    #载人 MNIST 数据集                              mnist= tf.keras.datasets.mnist             #拆分数据集                                     (x_train,y_train),(x_test,y_test)= mnist.lo#将样本进行预处理,并从整数转换为浮点数                       x_train,x_test=x_train/255.0,x_test /255.0#使用 tf.keras.Sequential将模型的各层堆看,并设置参数      model= tf.keras.models.Sequential([        tf.keras.layers.Flatten(input_shape=(28tf.keras.layers.Dense(128,activation='rtf.keras.layers.Dropout(0.2),          tf.keras.layers.Dense(10,activation='so])                                         #设置模型的优化器和损失函数                             model.compile(optimizer='adam',loss='sparse#训练并验证模型                                   model.fit(x_train,y_train,epochs=5)        model.evaluate(x_test,y_test,verbose=2)    

使用Tensorflow + keras 实现人脸识别

from os import listdirimport numpy as npfrom PIL import Imageimport cv2from spyder.plugins.findinfiles.widgets.combobox import FILE_PATHfrom tensorflow.keras.models import Sequential, load_modelfrom tensorflow.keras.layers import Dense, Activation, Convolution2D,MaxPooling2D,Flattenfrom sklearn.model_selection import train_test_splitfrom tensorflow.python.keras.utils import np_utils#读取人脸图片数据def img2vector(fileNamestr):#创建向量returnVect=np.zeros((57,47))image = Image.open(fileNamestr).convert('L')img=np.asarray(image).reshape(57,47)return img#制作人脸数据集def GetDataset(imgDataDir):print('| Step1 |: Get dataset...')imgDataDir='C:/Users/PDHuang/Downloads/ch11/faces_4/'FileDir=listdir(imgDataDir)m= len(FileDir)imgarray=[]hwLabels=[]hwdata=[]#逐个读取文件for i in range(m):#提取子目录className=isubdirName='C:/Users/PDHuang/Downloads/ch11/faces_4/'+str(FileDir[i])+'/'fileNames= listdir(subdirName)lenFiles=len(fileNames)#提取文件名for j in range(lenFiles):fileNamestr=subdirName+fileNames[j]hwLabels.append(className)imgarray=img2vector(fileNamestr)hwdata.append(imgarray)hwdata= np.array(hwdata)return hwdata,hwLabels,6# CNN 模型类class MyCNN(object):FILE_PATH= 'C:/Users/PDHuang/Downloads/ch11/face_recognition.h5'picHeight=57picwidth=47#模型存储/读取目录#模型的人脸图片长47,宽57def __init__(self):self.model = None#获取训练数据集def read_trainData(self,dataset):self.dataset=dataset#建立 Sequential模型,并赋予参数def build_model(self):print('| step2 |:Init CNN model...')self.model=Sequential()print('self.dataset.x train.shape[1:]',self.dataset.X_train.shape[1:])self.model.add(Convolution2D(filters=32,kernel_size=(5,5),padding='same',#dim ordering='th',input_shape=self.dataset.X_train.shape[1:]))self.model.add(Activation('relu'))self.model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='same'))self.model.add(Convolution2D(filters=64,kernel_size=(5,5),padding='same'))self.model.add(Activation('relu'))self.model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),padding='same'))self.model.add(Flatten())self.model.add(Dense(512))self.model.add(Activation('relu'))self.model.add(Dense(self.dataset.num_classes))self.model.add(Activation('softmax'))self.model.summary()# 模型训练def train_model(self):print('| Step3 l: Train CNN model...')self.model.compile(optimizer='adam', loss='categorical_crossentropy',metrics = ['accuracy'])# epochs:训练代次;batch size:每次训练样本数self.model.fit(self.dataset.X_train, self.dataset.Y_train, epochs=10,batch_size=20)def evaluate_model(self):loss, accuracy = self.model.evaluate(self.dataset.X_test, self.dataset.Y_test)print('|Step4|:Evaluate performance...')print('=------=---------------------=----')print('Loss Value is:', loss)print('Accuracy Value is :', accuracy)def save(self, file_path = FILE_PATH):print('| Step5 l: Save model...')self.model.save(file_path)print('Model',file_path, 'is successfully saved.')def predict(self, input_data):prediction = self.model.predict(input_data)return prediction#建立一个用于存储和格式化读取训练数据的类class DataSet(object):def __init__(self, path):self.num_classes = Noneself.X_train = Noneself.X_test = Noneself.Y_train = Noneself.Y_test = Noneself.picwidth=47self.picHeight=57self.makeDataSet(path)#在这个类初始化的过程中读取path下的训练数据def makeDataSet(self, path):#根据指定路径读取出图片、标签和类别数imgs,labels,classNum = GetDataset(path)#将数据集打乱随机分组X_train,X_test,y_train,y_test= train_test_split(imgs, labels, test_size=0.2,random_state=1)#重新格式化和标准化X_train=X_train.reshape(X_train.shape[0],1,self.picHeight, self.picwidth)/255.0X_test=X_test.reshape(X_test.shape[0],1,self.picHeight, self.picwidth)/255.0X_train=X_train.astype('float32')X_test=X_test.astype('float32')#将labels 转成 binary class matricesY_train=np_utils.to_categorical(y_train, num_classes=classNum)Y_test =np_utils.to_categorical(y_test,num_classes=classNum)#将格式化后的数据赋值给类的属性上self.X_train=X_trainself.X_test=X_testself.Y_train= Y_trainself.Y_test = Y_testself.num_classes=classNum#人脸图片目录dataset= DataSet('C:/Users/PDHuang/Downloads/ch11/faces_4/')model = MyCNN()model.read_trainData(dataset)model.build_model()model.train_model()model.evaluate_model()model.save()import osimport cv2import numpy as npfrom tensorflow.keras.models import load_modelhwdata =[]hwLabels =[]classNum = 0picHeight=57picwidth=47#人物标签(编号 0~5)#图像高度#图像宽度#根据指定路径读取出图片、标签和类别数hwdata,hwLabels,classNum= GetDataset('C:/Users/PDHuang/Downloads/ch11/faces_4/')#加载模型if os.path.exists('face recognition.h5'):model= load_model('face recognition.h5')else:print('build model first')#加载待判断图片photo= cv2.imread('C:/Users/PDHuang/Downloads/ch11/who.jpg')#待判断图片调整resized_photo=cv2.resize(photo,(picHeight, picwidth)) #调整图像大小recolord_photo=cv2.cvtColor(resized_photo, cv2.COLOR_BGR2GRAY)#将图像调整成灰度图recolord_photo= recolord_photo.reshape((1,1,picHeight,picwidth))recolord_photo= recolord_photo/255#人物预测print('| Step3 |:Predicting......')result = model.predict(recolord_photo)max_index=np.argmax(result)#显示结果print('The predict result is Person',max_index+ 1)cv2.namedWindow("testperson",0);cv2.resizeWindow("testperson",300,350);cv2.imshow('testperson',photo)cv2.namedWindow("PredictResult",0);cv2.resizeWindow("PredictResult",300,350);cv2.imshow("predictResult",hwdata[max_index * 10])#print(resultrile)k= cv2.waitKey(0)#按Esc 键直接退出if k == 27:cv2.destroyWindow()

使用Tensorflow + keras 实现电影评论情感分类

# 导包import matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport os# 导入tfimport tensorflow as tffrom tensorflow import kerasprint(tf.__version__)print(keras.__version__)# 加载数据集# num_words:只取10000个词作为词表imdb = keras.datasets.imdb(train_x_all, train_y_all),(test_x, test_y)=imdb.load_data(num_words=10000)# 查看数据样本数量print("Train entries: {}, labels: {}".format(len(train_x_all), len(train_y_all)))print("Train entries: {}, labels: {}".format(len(test_x), len(test_y)))print(train_x_all[0])   # 查看第一个样本数据的内容print(len(train_x_all[0]))  # 查看第一个和第二个训练样本的长度,不一致print(len(train_x_all[1]))# 构建字典  两个方法,一个是id映射到字,一个是字映射到idword_index = imdb.get_word_index()word2id = { k:(v+3) for k, v in word_index.items()}word2id['<PAD>'] = 0word2id['START'] = 1word2id['<UNK>'] = 2word2id['UNUSED'] = 3id2word = {v:k for k, v in word2id.items()}def get_words(sent_ids):return ' '.join([id2word.get(i, '?') for i in sent_ids])sent = get_words(train_x_all[0])print(sent)# 句子末尾进行填充train_x_all = keras.preprocessing.sequence.pad_sequences(train_x_all,value=word2id['<PAD>'],padding='post', #pre表示在句子前面填充, post表示在句子末尾填充maxlen=256)test_x = keras.preprocessing.sequence.pad_sequences(test_x,value=word2id['<PAD>'],padding='post',maxlen=256)print(train_x_all[0])print(len(train_x_all[0]))print(len(train_x_all[1]))#模型编写vocab_size = 10000model = keras.Sequential()model.add(keras.layers.Embedding(vocab_size, 16))model.add(keras.layers.GlobalAveragePooling1D())model.add(keras.layers.Dense(16, activation='relu'))model.add(keras.layers.Dense(1, activation='sigmoid'))model.summary()model.compile(optimizer='adam', loss=keras.losses.binary_crossentropy, metrics=['accuracy'])train_x, valid_x = train_x_all[10000:], train_x_all[:10000]train_y, valid_y = train_y_all[10000:], train_y_all[:10000]# callbacks Tensorboard, earlystoping, ModelCheckpoint# 创建一个文件夹,用于放置日志文件logdir = os.path.join("callbacks")if not os.path.exists(logdir):os.mkdir(logdir)output_model_file = os.path.join(logdir, "imdb_model.keras")# 当训练模型到什么程度的时候,就停止执行 也可以直接不用,然后直接训练callbacks = [# 保存的路径(使用TensorBoard就可以用命令,tensorboard --logdir callbacks 来分析结果)keras.callbacks.TensorBoard(logdir),# 保存最好的模型keras.callbacks.ModelCheckpoint(filepath=output_model_file, save_best_only=True),# 当精度连续5次都在1乘以10的-1次方之后停止训练keras.callbacks.EarlyStopping(patience=5, min_delta=1e-3)]history = model.fit(train_x, train_y,epochs=40,batch_size=512,validation_data=(valid_x, valid_y),callbacks = callbacks,verbose=1   # 设置为1就会打印日志到控制台,0就不打印)def plot_learing_show(history):pd.DataFrame(history.history).plot(figsize=(8,5))plt.grid(True)plt.gca().set_ylim(0,1)plt.show()plot_learing_show(history)result = model.evaluate(test_x, test_y)print(result)test_classes_list = model.predict_classes(test_x)print(test_classes_list[1][0])print(test_y[1])

使用Tensorflow + keras 解决 回归问题预测汽车燃油效率

# 导包import matplotlib as mplimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport osimport pathlibimport seaborn as sns# 导入tfimport tensorflow as tffrom tensorflow import kerasprint(tf.__version__)print(keras.__version__)# 加载数据集dataset_path = keras.utils.get_file('auto-mpg.data',"http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data")print(dataset_path)# 使用pandas导入数据集column_names = ['MPG', 'Cylinders', 'Displacement', 'Horsepower', 'Weight', 'Acceleration', 'Model Year', 'Origin']raw_dataset = pd.read_csv(dataset_path, names=column_names, na_values='?', comment='\t',sep=' ', skipinitialspace=True)dataset = raw_dataset.copy()print(dataset.tail())# 数据清洗print(dataset.isna().sum())dataset = dataset.dropna()print(dataset.isna().sum())# 将origin转换成one-hot编码origin = dataset.pop('Origin')dataset['USA'] = (origin == 1) * 1.0dataset['Europe'] = (origin == 2) * 1.0dataset['Japan'] = (origin == 3) * 1.0print(dataset.tail())# 拆分数据集 拆分成训练集和测试集train_dataset = dataset.sample(frac=0.8, random_state=0)test_dataset = dataset.drop(train_dataset.index)# 总体数据统计train_stats = train_dataset.describe()train_stats.pop("MPG")train_stats = train_stats.transpose()print(train_stats)# 从标签中分类特征train_labels = train_dataset.pop('MPG')test_labels = test_dataset.pop('MPG')print(train_labels[0])# 数据规范化def norm(x):return (x - train_stats['mean']) / train_stats['std']norm_train_data = norm(train_dataset)norm_test_data = norm(test_dataset)# 构建模型def build_model():model = keras.Sequential([keras.layers.Dense(512, activation='relu', input_shape=[len(train_dataset.keys())]),keras.layers.Dense(256, activation='relu'),keras.layers.Dense(128, activation='relu'),keras.layers.Dense(64, activation='relu'),keras.layers.Dense(1)])optimizer = keras.optimizers.RMSprop(0.001)model.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse'])return model# 构建防止过拟合的模型,加入正则项L1和L2def build_model2():model = keras.Sequential([keras.layers.Dense(512, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.001),input_shape=[len(train_dataset.keys())]),keras.layers.Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.001)),keras.layers.Dense(128, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.001)),keras.layers.Dense(64, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.001)),keras.layers.Dense(1)])optimizer = keras.optimizers.RMSprop(0.001)model.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse'])return model# 构建防止过拟合的模型,加入正则项L1def build_model3():model = keras.Sequential([keras.layers.Dense(512, activation='relu', kernel_regularizer=keras.regularizers.l1(0.001),input_shape=[len(train_dataset.keys())]),keras.layers.Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l1(0.001)),keras.layers.Dense(128, activation='relu', kernel_regularizer=keras.regularizers.l1(0.001)),keras.layers.Dense(64, activation='relu', kernel_regularizer=keras.regularizers.l1(0.001)),keras.layers.Dense(1)])optimizer = keras.optimizers.RMSprop(0.001)model.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse'])return model# 构建防止过拟合的模型,加入正则项L2def build_model4():model = keras.Sequential([keras.layers.Dense(512, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001),input_shape=[len(train_dataset.keys())]),keras.layers.Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001)),keras.layers.Dense(128, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001)),keras.layers.Dense(64, activation='relu', kernel_regularizer=keras.regularizers.l2(0.001)),keras.layers.Dense(1)])optimizer = keras.optimizers.RMSprop(0.001)model.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse'])return model# 构建模型 使用dropout来防止过拟合def build_model5():model = keras.Sequential([keras.layers.Dense(512, activation='relu', input_shape=[len(train_dataset.keys())]),keras.layers.Dropout(0.5),keras.layers.Dense(256, activation='relu'),keras.layers.Dropout(0.5),keras.layers.Dense(128, activation='relu'),keras.layers.Dropout(0.5),keras.layers.Dense(64, activation='relu'),keras.layers.Dropout(0.5),keras.layers.Dense(1)])optimizer = keras.optimizers.RMSprop(0.001)model.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse'])return model# 构建模型  使用正则化L1和L2以及dropout来预测def build_model6():model = keras.Sequential([keras.layers.Dense(512, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.001),input_shape=[len(train_dataset.keys())]),keras.layers.Dropout(0.5),keras.layers.Dense(256, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.001)),keras.layers.Dropout(0.5),keras.layers.Dense(128, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.001)),keras.layers.Dropout(0.5),keras.layers.Dense(64, activation='relu', kernel_regularizer=keras.regularizers.l1_l2(0.001)),keras.layers.Dropout(0.5),keras.layers.Dense(1)])optimizer = keras.optimizers.RMSprop(0.001)model.compile(loss='mse', optimizer=optimizer, metrics=['mae', 'mse'])return modelmodel = build_model()model.summary()early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=200)# 模型训练history = model.fit(norm_train_data, train_labels, epochs=1000, validation_split=0.2, verbose=0, callbacks=[early_stop])def plot_history(history):hist = pd.DataFrame(history.history)hist['epoch'] = history.epochplt.figure()plt.xlabel('Epoch')plt.ylabel('Mean Abs ERROR [PMG]')plt.plot(hist['epoch'], hist['mae'], label='Train Error')plt.plot(hist['epoch'], hist['val_mae'], label='Val Error')plt.ylim([0, 5])plt.legend()plt.figure()plt.xlabel('Epoch')plt.ylabel('Mean Squaree ERROR [PMG]')plt.plot(hist['epoch'], hist['mse'], label='Train Error')plt.plot(hist['epoch'], hist['val_mse'], label='Val Error')plt.ylim([0, 20])plt.legend()plt.show()plot_history(history)# 看下测试集合的效果loss, mae, mse = model.evaluate(norm_test_data, test_labels, verbose=2)print(loss)print(mae)print(mse)# 做预测test_preditions = model.predict(norm_test_data)test_preditions = test_preditions.flatten()plt.scatter(test_labels, test_preditions)plt.xlabel('True Values [MPG]')plt.ylabel('Predictios [MPG]')plt.axis('equal')plt.axis('square')plt.xlim([0, plt.xlim()[1]])plt.ylim([0, plt.ylim()[1]])_ = plt.plot([-100, 100], [-100, 100])# 看一下误差分布error = test_preditions - test_labelsplt.hist(error, bins=25)plt.xlabel("Prediction Error [MPG]")_ = plt.ylabel('Count')

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/18571.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Dynadot API调整一览

关于Dynadot Dynadot是通过ICANN认证的域名注册商&#xff0c;自2002年成立以来&#xff0c;服务于全球108个国家和地区的客户&#xff0c;为数以万计的客户提供简洁&#xff0c;优惠&#xff0c;安全的域名注册以及管理服务。 Dynadot平台操作教程索引&#xff08;包括域名邮…

AI Agent教育行业落地案例

【AI赋能教育】揭秘Duolingo背后的AI Agent&#xff0c;让学习更高效、更有趣&#xff01; ©作者|Blaze 来源|神州问学 引言 随着科技的迅猛发展&#xff0c;人工智能技术已经逐步渗透到我们生活的各个方面。而随着AI技术的广泛应用&#xff0c;教育培训正引领着一场新的…

149.二叉树:二叉树的前序遍历(力扣)

代码解决 这段代码实现了二叉树的前序遍历&#xff0c;前序遍历的顺序是&#xff1a;访问根节点 -> 递归遍历左子树 -> 递归遍历右子树。以下是详细解释&#xff0c;包括各个部分的注释&#xff1a; // 二叉树节点的定义 struct TreeNode {int val; // 节…

php -v在cmd中正常显示 在vscode中却报错

效果展示 原因 在vscode中 终端是 PowerShell PowerShell 默认情况下它不会继承系统的PATH环境变量 解决方案 使用CMD作为终端 打开VSCode设置&#xff08;File > Preferences > Settings 或 Ctrl,&#xff09;。搜索 terminal.integrated.shell.windows。更改其值…

springboot集成nacos

springboot集成nacos 1.版本2. POM依赖3. nacos服务3.1 下载nacos压缩包3.2 启动nacos 4. yaml配置5.Demo5.1 配置中心简单格式获取方式普通方式还可以再启动类上添加注解完成5.2 获取json格式的demo5.2 自动注册根据yaml配置 1.版本 nacos版本:2.3.2 springboot版本&#xff…

【已解决】使用StringUtils.hasLength参数输入空格仍然添加成功定价为负数仍然添加成功

Bug情景 今天在做功能测试时&#xff0c;发现使用使用StringUtils.hasLength&#xff08;&#xff09;方法以及定价为负数时&#xff0c;添加图书仍然成功 思考过程 0.1 当时在做参数检验时用了spring提供的StringUtils工具包&#xff0c;百度/大数据模型说&#xff1a; 0.2…

Redis:redis基础

Redis Remote Dictionary Service即远程字典服务 一个基于内存的key-value结构数据库,在开发中常常作为缓存存储不经常被改变的数据 基于内存存储,读写性能高 在企业中应用广泛 Redis介绍 用C语言开发的开源高性能键值对数据库,可以达到10w的qps,可以存储丰富的value类型…

【ubuntu20】--- 定时同步文件

在编程的艺术世界里&#xff0c;代码和灵感需要寻找到最佳的交融点&#xff0c;才能打造出令人为之惊叹的作品。而在这座秋知叶i博客的殿堂里&#xff0c;我们将共同追寻这种完美结合&#xff0c;为未来的世界留下属于我们的独特印记。 【Linux命令】--- 多核压缩命令大全&…

VM虚拟机共享文件夹fuse: bad mount point `/mnt/hgfs‘: No such file or directory

报错显示挂载点 /mnt/hgfs 不存在&#xff0c;你需要先创建这个目录。可以按照以下步骤进行操作&#xff1a; 创建挂载点目录&#xff1a; sudo mkdir -p /mnt/hgfs 手动挂载共享文件夹&#xff1a; sudo vmhgfs-fuse .host:/ /mnt/hgfs -o allow_other 确保每次启动时自动…

液氮罐内部会污染吗

液氮罐是一种常见的存储液态氮的设备&#xff0c;广泛应用于科研、生物医药、食品冷冻等领域。但是&#xff0c;人们对于液氮罐内部是否会产生污染一直存在疑问。 我们来看液氮罐内部可能的污染源。液氮罐内部主要存在以下几种潜在的污染来源&#xff1a;气体污染、杂质污染、…

C++ | Leetcode C++题解之第117题填充每个节点的下一个右侧节点指针II

题目&#xff1a; 题解&#xff1a; class Solution { public:void handle(Node* &last, Node* &p, Node* &nextStart) {if (last) {last->next p;} if (!nextStart) {nextStart p;}last p;}Node* connect(Node* root) {if (!root) {return nullptr;}Node *…

推券客CMS淘宝优惠券网站源码

推券客CMS淘宝优惠券网站源码是一个以PHPMySQL进行开发的PHP淘宝客优惠券网站。支持电脑站、手机站以及微信公众号查券。支持多级代理返利和阿里妈妈最新的渠道管理等功能。 五大优势 一、全开源 推券客cms网站程序数据库完全开源,目前市场上基本都是以下2种淘宝客系统 第一…

LeetCode - 双指针(Two Pointers) 算法集合 [对撞指针、快慢指针、滑动窗口、双链遍历]

欢迎关注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://spike.blog.csdn.net/article/details/139270999 双指针算法是一种常见且灵活的技巧&#xff0c;通过使用两个指针协同完成任务。这些指针可以指向不同的元素&#xff0c;具体应用取决于…

什么是勒索软件

什么是勒索软件 勒索软件又称勒索病毒&#xff0c;是一种特殊的恶意软件&#xff0c;又被归类为“阻断访问式攻击”&#xff08;denial-of-access attack&#xff09;&#xff0c;与其他病毒最大的不同在于攻击手法以及中毒方式。勒索软件的攻击方式是将受害者的电脑锁起来或者…

Spring Boot中如何查询PGSQL分表后的数据

数据库用的pgsql&#xff0c;在表数据超过100w条的时候执行定时任务进行了分表&#xff0c;分表后表名命名为原的表名后面拼接时间&#xff0c;如原表名是card_device_trajectory_info&#xff0c;分表后拼接时间后得到card_device_trajectory_info_20240503&#xff0c;然后分…

ubuntu使用oh my zsh美化终端

ubuntu使用oh my zsh美化终端 文章目录 ubuntu使用oh my zsh美化终端1. 安装zsh和oh my zsh2. 修改zsh主题3. 安装zsh插件4. 将.bashrc移植到.zshrcReference 1. 安装zsh和oh my zsh 首先安装zsh sudo apt install zsh然后查看本地有哪些shell可以使用 cat /etc/shells 将默…

使用nexus搭建的nodejs私库,定期清理无用的npm组件,彻底释放磁盘空间

一、背景 昨天我们整理了一篇关于docker私库&#xff0c;如何定期清理以释放磁盘空间的文章。 虽然也提及了npm前端应用的组件该如何定期清理的&#xff0c;本文是对它作一个补充说明。 前文也看到了&#xff0c;npm组件占用的blob空间为180多GB&#xff0c;急需清理。 二、…

100个 Unity小游戏系列三 -Unity 抽奖游戏专题一 转盘抽奖游戏

一 、效果展示 二、知识点 2.1 布局需要实现功能 1、转动的根目录为itemSpinRoot 2、创建对应的item 3、每个item转动的角度 2.2 代码 public class WheelDialog : UIBase{[SerializeField] Button btnClick;[SerializeField] Button btnClose;[SerializeField] Sprite[] ite…

哪有异地组网的工具?

不同地区的电脑与电脑、设备与设备、电脑与设备之间的信息远程通信&#xff0c;一直是企业和个人面临的难题。通过使用天联组网的解决方案&#xff0c;这个问题将迎刃而解。 天联组网解决方案 天联组网是一种可以实现不同地区之间电脑、设备及其之间的信息远程通信的解决方案。…

Trie字符串统计-java

Trie&#xff0c;又称前缀树或字典树&#xff0c;是一种有序树&#xff0c;用于保存关联数组&#xff0c;其中的键通常是字符串。 目录 前言☀ 一、Trie字符串统计☀ 二、算法思路☀ 1.Trie树定义&#x1f319; 2.变量解释&#x1f319; 3.插入操作&#x1f319; 4.Trie树查找操…