from sklearn.datasets import fetch_california_housing from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import tensorflow housing=fetch_california_housing() X_train_full,X_test,y_train_full,y_test=train_test_split(housing.data,housing.target) X_train,X_valid,y_train,y_valid=train_test_split(X_train_full,y_train_full) scaler=StandardScaler()# 归一化和标准化 X_train=scaler.fit_transform(X_train) X_valid=scaler.fit_transform(X_valid) X_test=scaler.fit_transform(X_test) def cnn1(): model = tensorflow.keras.models.Sequential([ # 初始化模型 tensorflow.keras.layers.Dense(30,activation="relu",input_shape=X_train.shape[1:]), tensorflow.keras.layers.Dense(1) ]) return model def cnn2(): # 该模型为深宽神经网络 保存部分数据 input_ = tensorflow.keras.layers.Input(shape=X_train.shape[1:]) hidden1 = tensorflow.keras.layers.Dense(30,activation="relu")(input_) hidden2 = tensorflow.keras.layers.Dense(30, activation="relu")(hidden1) concat = tensorflow.keras.layers.Concatenate()([input_,hidden2]) output = tensorflow.keras.layers.Dense(1)(concat) model = tensorflow.keras.Model(inputs=[input_],outputs=[output]) return model def cnn3(): #深宽神经网络 保存部分特征 input_A = tensorflow.keras.layers.Input(shape=[5],name="wide_input") input_B = tensorflow.keras.layers.Input(shape=[6], name="deep_input") hidden1 = tensorflow.keras.layers.Dense(30, activation="relu")(input_B) hidden2 = tensorflow.keras.layers.Dense(30, activation="relu")(hidden1) concat = tensorflow.keras.layers.concatenate([input_A,hidden2]) output = tensorflow.keras.layers.Dense(1,name="output")(concat) model = tensorflow.keras.Model(inputs=[input_A,input_B],outputs=[output]) return model model=cnn1()#此处修改更换函数 model.compile(loss="mean_squared_error",optimizer="sgd")#设计损失函数和优化器 history=model.fit(X_train,y_train,epochs=20,validation_data=(X_valid,y_valid)) mse_test=model.evaluate(X_test,y_test) X_new=X_test[:3]#进行预测 y_pred=model.predict(X_new)
一些书上简单的代码入门
于 2022-09-27 13:38:19 首次发布